caixa_core/aplicacao.rs
1//! Typed Aplicacao — the fourth caixa kind that turns a graph of
2//! Servicos into a single declarative application (mesh).
3//!
4//! See `theory/MESH-COMPOSITION.md` for the design frame: an
5//! Aplicacao composes [`crate::CaixaKind::Servico`] caixas via WIT-typed
6//! `:contratos` (inter-Servico edges), declares mesh-level
7//! `:politicas` (timeouts, retries, breakers, mTLS), pins
8//! `:placement` strategy (single-node / replicated / sharded), and
9//! exposes `:entrada` (gateway).
10//!
11//! ```lisp
12//! (defcaixa
13//! :nome "checkout"
14//! :versao "0.1.0"
15//! :kind Aplicacao
16//! :membros ((:caixa "catalog" :versao "^0.1")
17//! (:caixa "cart" :versao "^0.1")
18//! (:caixa "payment" :versao "^0.2"))
19//! :contratos ((:de "cart" :para "catalog"
20//! :wit "wasi:http/proxy" :endpoint "/products/:id")
21//! (:de "cart" :para "payment"
22//! :wit "wasi:http/proxy" :endpoint "/charge"))
23//! :politicas ((:timeout "30s")
24//! (:retries 3)
25//! (:circuit-breaker (:max-failures 5 :window "60s"))
26//! (:mtls-required t))
27//! :placement (:estrategia replicated
28//! :clusters ("rio" "mar" "plo"))
29//! :entrada (:host "checkout.quero.cloud"
30//! :para "cart"
31//! :paths ("/api/cart" "/api/products")))
32//! ```
33//!
34//! All the typed slots compose with the M2 primitives the Servicos
35//! they reference already declare (`:limits`, `:behavior`,
36//! `:upgrade-from`). The Aplicacao adds the *graph-level*
37//! standardization on top.
38
39use std::time::Duration;
40
41use serde::{Deserialize, Serialize};
42use thiserror::Error;
43
44use crate::supervisor; // we reuse the duration-string codec at module scope
45
46// ── inter-Servico contracts ──────────────────────────────────────────
47
48/// One typed edge in the Aplicacao graph. The build refuses any
49/// contract whose `:de` or `:para` doesn't appear in `:membros`, and
50/// (M3+) cross-checks the `:wit` shape against both Servicos'
51/// declared imports/exports.
52#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
53#[serde(rename_all = "camelCase")]
54pub struct WitContract {
55 /// Caller Servico — must reference an entry in the Aplicacao's
56 /// `:membros`. The Servico's caixa.lisp must declare a matching
57 /// `:capabilities` import for the `:wit` world.
58 pub de: String,
59
60 /// Callee Servico — must reference an entry in `:membros`. The
61 /// Servico must declare a matching `:capabilities` export.
62 pub para: String,
63
64 /// WIT world reference — e.g. `"wasi:http/proxy"`,
65 /// `"wasi:keyvalue/store"`, `"nats:pub-sub"`. Strings for V0;
66 /// M4 promotes these to a typed enum once the WIT registry
67 /// stabilizes in tatara-lisp.
68 pub wit: String,
69
70 /// HTTP endpoint path, present when `:wit` is HTTP-shaped.
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub endpoint: Option<String>,
73
74 /// NATS / event-stream subject, present when `:wit` is pub-sub-shaped.
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub subject: Option<String>,
77
78 /// Key/value or queue slot, present when `:wit` is store-shaped.
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub slot: Option<String>,
81}
82
83/// Canonical lowercase byte-prefix set the substrate's WIT-shape
84/// dispatch routes `wasi:http/*` / `http:*` values through as the
85/// HTTP-shaped arm. The single source of truth every consumer that
86/// classifies a `:wit` value as HTTP-shaped consults —
87/// [`WitContract::is_http`] on the typed contract, the
88/// `AplicacaoSpec::validate` positive-sweep test's payload-dispatch
89/// helper, and every future renderer that routes an L7 emission off a
90/// bare `&str` (the M4 per-edge WIT registry resolver, the future
91/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer). Spelled
92/// exactly as the [`is_wit_world_ref`][iwr] predicate documents the
93/// canonical lowercase prefixes ("`wasi:http/`, `nats:`,
94/// `wasi:keyvalue/`, `kafka:`, `kv:`, `http:`") so drift between the
95/// substrate's accept-set and this crate's dispatch-set is a
96/// build-time compile error (unused-import), not a per-renderer
97/// silent L7-→-L4 demotion at apply time.
98///
99/// [iwr]: crate::render::is_wit_world_ref
100pub const WIT_HTTP_SHAPE_PREFIXES: &[&str] = &["wasi:http/", "http:"];
101
102/// Canonical lowercase byte-prefix set the substrate's WIT-shape
103/// dispatch routes `nats:*` / `kafka:*` values through as the
104/// pub-sub-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
105/// [`WIT_STORE_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
106/// HTTP constant's docstring for the full lift rationale.
107pub const WIT_PUBSUB_SHAPE_PREFIXES: &[&str] = &["nats:", "kafka:"];
108
109/// Canonical lowercase byte-prefix set the substrate's WIT-shape
110/// dispatch routes `wasi:keyvalue/*` / `kv:*` values through as the
111/// key/value-store-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
112/// [`WIT_PUBSUB_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
113/// HTTP constant's docstring for the full lift rationale.
114pub const WIT_STORE_SHAPE_PREFIXES: &[&str] = &["wasi:keyvalue/", "kv:"];
115
116/// True when `wit` — a raw `:contratos :wit` value — starts with any
117/// entry in the `prefixes` accept-set. The single canonical
118/// prefix-driven WIT-shape classification combinator every peer
119/// per-shape predicate ([`wit_shape_is_http`], [`wit_shape_is_pubsub`],
120/// [`wit_shape_is_store`]) routes through, closing the 3-site
121/// duplication of the `PREFIXES.iter().any(|p| wit.starts_with(p))`
122/// combinator the prior open-coded implementations each carried.
123///
124/// A future 4th WIT-shape dispatch arm (a hypothetical `wasi:sockets/*`
125/// / `tcp:*` transport-layer shape, an `oci:*` capability-import
126/// carrier) becomes exactly one new [`WIT_*_SHAPE_PREFIXES`] const +
127/// one new `wit_shape_is_<name>` one-liner routing through this
128/// combinator, not a fourth copy of the `iter().any(starts_with)`
129/// combinator paired to its own prefix-set. Same "one canonical
130/// combinator, thin per-arm projections" discipline the peer
131/// [`WitTarget::payload_pair`] (6788ed6) already established for the
132/// downstream per-arm `(field, payload)` dispatch, extended to the
133/// upstream per-arm `PREFIXES → bool` dispatch.
134///
135/// Declared `pub const fn` — the four peer classifiers
136/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
137/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) route through
138/// this combinator in `const`-eval context, so the raw `&str → bool`
139/// WIT-shape dispatch reaches every substrate-side `const`-context
140/// consumer (the module-scope `const _: () = assert!(…)` canonical-
141/// accept-set + partition-witness pins immediately below the four
142/// peer classifiers, any future M4
143/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
144/// webhook `const fn` per-`:contratos :wit` shape-arm resolver over a
145/// raw &str, any future `const fn` per-`:contratos`-edge WIT-registry
146/// prefix-set overlay resolver over the substrate primitive that fans
147/// on the shape arm at compile time) through the same typed dispatch
148/// on the substrate primitive at const-eval time as at runtime. The
149/// prior `prefixes.iter().any(|p| wit.starts_with(p))` body carried
150/// non-`const` bounds on stable Rust 1.94 (`.iter()` / `.any()` /
151/// `str::starts_with(&str)` via the non-`const` `Pattern` trait); the
152/// new body routes the per-prefix probe through a manual byte-level
153/// `starts_with` loop over the paired `str::as_bytes` (`pub const fn`)
154/// slice projections, dispatching through primitive-`u8` `!=` and
155/// `usize` comparison + `pub const fn` `<[u8]>::len` and const-stable
156/// slice indexing (since Rust 1.79) — every operation `const`-eval-
157/// callable on stable, no iterator methods, no `Pattern` trait.
158#[must_use]
159pub const fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
160 let bytes = wit.as_bytes();
161 let mut i = 0;
162 while i < prefixes.len() {
163 let prefix = prefixes[i].as_bytes();
164 if prefix.len() <= bytes.len() {
165 let mut j = 0;
166 let mut matches = true;
167 while j < prefix.len() {
168 if bytes[j] != prefix[j] {
169 matches = false;
170 break;
171 }
172 j += 1;
173 }
174 if matches {
175 return true;
176 }
177 }
178 i += 1;
179 }
180 false
181}
182
183/// True when `wit` — a raw `:contratos :wit` value — targets an
184/// HTTP-shaped WIT world (starts with any prefix in
185/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
186/// consumer routes L7-HTTP emission through, whether they carry a
187/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
188/// here) or only the raw `wit` string (the positive-sweep test's
189/// payload-dispatch helper, future renderers that classify off a
190/// bare `&str`). Lifting to a free function makes the shape-dispatch
191/// arm reachable without materializing a scratch [`WitContract`] at
192/// every classification point, and pins the six-prefix accept-set at
193/// one place so future additions (e.g. an `"https:"` peer of
194/// `"http:"`) reach every consumer by construction. Routes through
195/// the lifted [`wit_shape_matches`] combinator so the
196/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
197/// canonical primitive, not one open-coded copy per peer arm.
198///
199/// Declared `pub const fn` — routes through the peer `pub const fn`
200/// [`wit_shape_matches`] combinator so every substrate-side
201/// `const`-context WIT-shape-arm-classifier consumer (the module-scope
202/// `const _: () = assert!(…)` canonical-accept-set + partition-witness
203/// pins immediately below, any future M4 admission-webhook
204/// `const fn` per-`:contratos :wit` HTTP-arm resolver over a raw &str)
205/// reaches through the same typed dispatch on the substrate primitive
206/// at const-eval time as at runtime.
207#[must_use]
208pub const fn wit_shape_is_http(wit: &str) -> bool {
209 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES)
210}
211
212/// True when `wit` — a raw `:contratos :wit` value — targets a
213/// pub-sub-shaped WIT world (starts with any prefix in
214/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
215/// [`wit_shape_is_store`] on the shape-dispatch axis; see
216/// [`wit_shape_is_http`] for the lift rationale. Routes through the
217/// lifted [`wit_shape_matches`] combinator.
218///
219/// Declared `pub const fn` — sibling in `const`-eval posture to the
220/// peer [`wit_shape_is_http`] classifier; see that function's `const`
221/// posture-block for the full rationale.
222#[must_use]
223pub const fn wit_shape_is_pubsub(wit: &str) -> bool {
224 wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES)
225}
226
227/// True when `wit` — a raw `:contratos :wit` value — targets a
228/// key/value-store-shaped WIT world (starts with any prefix in
229/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
230/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
231/// [`wit_shape_is_http`] for the lift rationale. Routes through the
232/// lifted [`wit_shape_matches`] combinator.
233///
234/// Declared `pub const fn` — sibling in `const`-eval posture to the
235/// peer [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] classifiers;
236/// see [`wit_shape_is_http`]'s `const` posture-block for the full
237/// rationale.
238#[must_use]
239pub const fn wit_shape_is_store(wit: &str) -> bool {
240 wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES)
241}
242
243/// True when `wit` — a raw `:contratos :wit` value — targets *none* of
244/// the three known payload-shape WIT worlds; the payload-less
245/// capability arm of the 4-way WIT-shape partition on the raw
246/// `:contratos :wit` axis. Peer of [`wit_shape_is_http`] /
247/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] on the shape-
248/// dispatch axis — closes the free-function classifier family the
249/// three payload-arm predicates opened onto the exact-inverse
250/// disjunction of the trio, so any downstream consumer that must
251/// classify a raw `:wit` `&str` onto the payload-less capability arm
252/// (a future substrate-side capability-shape-only emitter — the M4
253/// per-Aplicacao WIT-registry capability-import materializer, the
254/// future `feira app graph --capability` filter, the future per-
255/// cluster capability-scope reconciler that skips L4/L7 emission for
256/// payload-less edges, the future `mesh.pleme.io/v1alpha1/Aplicacao`
257/// CR admission webhook's per-shape histogram) reaches for exactly
258/// one typed dispatch at the substrate primitive rather than an
259/// open-coded per-consumer `!wit_shape_is_http(wit) &&
260/// !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)` triplet
261/// negation — each of which would silently misclassify a future 4th
262/// payload-arm addition (a hypothetical `wasi:sockets/*` transport-
263/// layer shape, an `oci:*` capability-import carrier per the sibling
264/// [`wit_shape_matches`] docstring's trajectory bullet) as
265/// capability without a compile-time signal at the consumer site.
266///
267/// Fourth arm on the free-function WIT-shape-predicate family — closes
268/// the {[`wit_shape_is_http`], [`wit_shape_is_pubsub`],
269/// [`wit_shape_is_store`]} trio into a 4-way partition witness on the
270/// raw `:contratos :wit` `&str` axis, mirroring the paired sibling
271/// [`WitContract`]-surface [`WitContract::is_capability`] predicate and
272/// the post-projection [`WitTarget`]-side
273/// `gen_platform::IsVariant`-derived [`WitTarget::is_capability`]
274/// (7f6aa98 `IsVariant` derive lift on the peer arm-set). Every
275/// [`WitTarget`] variant now carries a matched peer predicate on both
276/// the raw `&str` axis (this function + [`wit_shape_is_http`] /
277/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`]) and the
278/// [`WitContract`] surface (the sibling 4-arm predicate family
279/// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
280/// [`WitContract::is_store`] / [`WitContract::is_capability`]),
281/// pinned in load-bearing by the sibling
282/// [`tests::wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis`]
283/// partition-witness pin and the peer
284/// [`tests::wit_contract_shape_methods_delegate_to_free_functions`]
285/// delegation pin.
286///
287/// Prior to this lift the "not one of the three known payload shapes"
288/// classification only reached the raw `&str` axis by materializing a
289/// scratch [`WitContract`] and delegating through
290/// [`WitContract::is_capability`] — a five-field constructor at every
291/// classification point for a pure `&str → bool` question, and a
292/// dependency on the payload-carrier scalar layout the classifier
293/// does not read. Same "one canonical combinator, thin per-arm
294/// projections" discipline the peer [`wit_shape_is_http`] /
295/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] trio already
296/// established, extended to close the 4-arm partition on the raw
297/// `&str` axis.
298///
299/// Note: purely syntactic classification on the negated `:wit` prefix-
300/// set — unlike [`WitContract::target`], which additionally rejects
301/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
302/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
303/// payload-shape mismatches. An empty or structurally malformed `wit`
304/// string returns `true` here (the prefix set matches nothing), and
305/// the surrounding validate-side gate cascade is where the
306/// [`AplicacaoError::EmptyWit`] / [`AplicacaoError::ContratoWitInvalid`]
307/// diagnostic surfaces — this function is the classifier, not the
308/// validator.
309///
310/// Declared `pub const fn` — closes the 4-arm classifier family's
311/// `const`-eval-surface pass on the payload-less capability arm,
312/// peer of the sibling `pub const fn` [`wit_shape_is_http`] /
313/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] classifiers, so
314/// the raw `&str → bool` WIT-shape partition on the capability arm
315/// reaches every substrate-side `const`-context consumer through one
316/// typed dispatch. See [`wit_shape_is_http`]'s `const` posture-block
317/// for the full rationale.
318#[must_use]
319pub const fn wit_shape_is_capability(wit: &str) -> bool {
320 !wit_shape_is_http(wit) && !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)
321}
322
323// Compile-time pins on the 4-arm WIT-shape classifier family — the
324// module-scope const-eval assertions below trip at caixa-core build
325// time (not test time) if a future edit rewires any of the four
326// classifier's arm-set away from the accept-set MESH-COMPOSITION §II.3
327// pins. Anchor the `const`-eval-surface posture of the four peer
328// classifiers on canonical accept-set samples (one per WIT_*_SHAPE_PREFIXES
329// prefix) plus pairwise-exclusion samples asserting the trio partitions
330// the payload-carrying arm-set and the capability arm carries the
331// complementary payload-less remainder. Any future accidental downgrade
332// of one classifier to non-`const` fails these items at caixa-core build
333// time; any future prefix-set edit that overlaps two arms (e.g. a `kv:`
334// prefix accidentally re-emitted under `WIT_HTTP_SHAPE_PREFIXES`) trips
335// the corresponding partition-witness item. Peer of the sibling M3
336// [`PlacementStrategy::requires_shard_key`] partition pins at
337// aplicacao.rs:5121-5123 on the sibling closed-set typed-enum
338// discriminator axis.
339const _: () = assert!(wit_shape_is_http("wasi:http/proxy"));
340const _: () = assert!(wit_shape_is_http("http:incoming"));
341const _: () = assert!(wit_shape_is_pubsub("nats:events"));
342const _: () = assert!(wit_shape_is_pubsub("kafka:topic"));
343const _: () = assert!(wit_shape_is_store("wasi:keyvalue/store"));
344const _: () = assert!(wit_shape_is_store("kv:cache"));
345const _: () = assert!(wit_shape_is_capability("wasi:filesystem/preopens"));
346const _: () = assert!(wit_shape_is_capability(""));
347// Pairwise-exclusion pins — the three payload-carrying arms are
348// pairwise disjoint on the canonical accept-set samples, and the
349// capability arm is the exact-inverse disjunction of the trio
350// (the free-function classifier family's 4-way partition witness).
351const _: () = assert!(!wit_shape_is_http("nats:events"));
352const _: () = assert!(!wit_shape_is_http("kv:cache"));
353const _: () = assert!(!wit_shape_is_pubsub("wasi:http/proxy"));
354const _: () = assert!(!wit_shape_is_pubsub("wasi:keyvalue/store"));
355const _: () = assert!(!wit_shape_is_store("wasi:http/proxy"));
356const _: () = assert!(!wit_shape_is_store("nats:events"));
357const _: () = assert!(!wit_shape_is_capability("wasi:http/proxy"));
358const _: () = assert!(!wit_shape_is_capability("nats:events"));
359const _: () = assert!(!wit_shape_is_capability("wasi:keyvalue/store"));
360
361impl WitContract {
362 /// Substrate-canonical per-`:contratos` caller-Servico scalar
363 /// accessor every consumer that reads the edge's source endpoint
364 /// keys off — returns the author-declared `:contratos :de`
365 /// byte-string verbatim as a `&str`, borrowed from the typed slot's
366 /// own [`String`] storage.
367 ///
368 /// The `:contratos :de` slot names the caller-side member Servico
369 /// on a typed inter-Servico edge (validated by
370 /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
371 /// Aplicacao declares — a stray `:de` that doesn't name a member is
372 /// [`AplicacaoError::ContratoMemberMissing`], not a silent
373 /// caller-attachment miss at cluster-apply time). Peer of the
374 /// sibling [`WitContract::destination`] accessor on the same
375 /// per-`:contratos` entry — the pair `( source(), destination() )`
376 /// jointly names the typed edge every renderer that fans on the
377 /// caller-callee identity keys off (the
378 /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
379 /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
380 /// map, the per-edge dedup key, the per-edge membership-lookup
381 /// diagnostic).
382 ///
383 /// Prior to this lift the `.de` byte-string was accessed inline at
384 /// four caixa-core sites (the two validate-side membership lookups
385 /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
386 /// tuple's caller-arm at
387 /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
388 /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
389 /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
390 /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
391 /// — five open-coded `.de.as_str()` field-accesses that expressed
392 /// no compile-time link back to the typed slot. A future extension
393 /// of the `:contratos :de` axis to a richer author surface (a
394 /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
395 /// canary flow, a per-cluster caller-alias table the operator pins
396 /// through a future `:placement`-scoped slot, the M4
397 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
398 /// admission-webhook that promotes the scalar to a caller-set
399 /// projection) would have had to be threaded through every
400 /// open-coded copy in lockstep or one consumer would silently
401 /// disagree with the peers on which caller Servico a given edge
402 /// resolves to. Lifting the resolution rule to a typed method on
403 /// the substrate primitive means every downstream caller-facing
404 /// consumer reaches for one typed dispatch — the resolver's
405 /// accept-set migrates as a unit on any future axis addition.
406 ///
407 /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
408 /// (6db982c) accessor on the analogous per-ingress-Servico scalar
409 /// axis — same "one typed dispatch on the substrate primitive,
410 /// thin projections at each consumer" discipline extended onto the
411 /// per-`:contratos` caller-Servico byte-string axis.
412 ///
413 /// Declared `pub const fn` — the body composes exclusively through
414 /// the `pub const fn` [`String::as_str`] projection (const-stable
415 /// since Rust 1.87, well within the workspace MSRV), so every
416 /// downstream `const`-context consumer of the per-`:contratos`
417 /// caller-Servico byte-string reaches through the same substrate-
418 /// primitive dispatch at const-eval time as at runtime. Peer of
419 /// the sibling `pub const fn` [`Self::destination`] /
420 /// [`Self::world_ref`] scalar accessors on the same
421 /// per-`:contratos` byte-string trio (the family closure the
422 /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
423 /// locks load-bearing), and mirror on the method-surface of the
424 /// sibling free-function [`wit_shape_matches`] +
425 /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
426 /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] `const`-
427 /// eval-surface pass (d46420c) on the raw `&str → bool` WIT-shape
428 /// dispatch family.
429 #[must_use]
430 pub const fn source(&self) -> &str {
431 self.de.as_str()
432 }
433
434 /// Substrate-canonical per-`:contratos` callee-Servico scalar
435 /// accessor every consumer that reads the edge's destination
436 /// endpoint keys off — returns the author-declared
437 /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
438 /// from the typed slot's own [`String`] storage.
439 ///
440 /// The `:contratos :para` slot names the callee-side member Servico
441 /// on a typed inter-Servico edge (validated by
442 /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
443 /// Aplicacao declares — a stray `:para` that doesn't name a member
444 /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
445 /// callee-attachment miss at cluster-apply time). Callee-side twin
446 /// of the sibling [`WitContract::source`] accessor — the pair
447 /// jointly names the typed edge every renderer that fans on the
448 /// caller-callee identity keys off, and this accessor is also the
449 /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
450 /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
451 /// composes with `destination()` at every emit site that projects a
452 /// per-edge destination Servico's L4 listener port.
453 ///
454 /// Prior to this lift the `.para` byte-string was accessed inline
455 /// at five sites — four caixa-core (the validate-side membership
456 /// lookup at `!names.contains(c.para.as_str())`, the per-edge
457 /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
458 /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
459 /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
460 /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
461 /// — with no compile-time link back to the typed slot. A future
462 /// extension of the `:contratos :para` axis to a richer author
463 /// surface (a multi-callee weighted-fan-out overlay for canary /
464 /// blue-green routing on typed edges, a per-cluster callee-alias
465 /// table the operator pins through a future `:placement`-scoped
466 /// slot, the M4 CR materializer's per-CR admission-webhook that
467 /// promotes the scalar to a callee-set projection) would have had
468 /// to be threaded through every open-coded copy in lockstep or one
469 /// consumer would silently disagree on which callee Servico a given
470 /// edge resolves to (a per-CNP `endpointSelector` that names a
471 /// different destination than its L4 port resolver reads for, a
472 /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
473 /// as distinct while the adjacency map collapses them, or vice
474 /// versa). Lifting to a typed method on the substrate primitive
475 /// means every downstream callee-facing consumer reaches for one
476 /// typed dispatch.
477 ///
478 /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
479 /// (6db982c) accessor — both name the "destination-Servico
480 /// byte-string" concept on their respective mesh-slot atoms (per-
481 /// ingress apex vs. per-typed-edge callee), and both extend the
482 /// substrate-primitive-owns-the-resolver discipline onto the
483 /// per-slot destination-Servico scalar axis. Composes with
484 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
485 /// emit-side per-edge L4 port reader — the composition
486 /// `spec.port_for_destination(c.destination())` pins the CNP per-
487 /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
488 /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
489 /// `spec.port_for_destination(entrada.destination())`.
490 ///
491 /// Declared `pub const fn` — sibling in `const`-eval posture to the
492 /// peer `pub const fn` [`Self::source`] / [`Self::world_ref`]
493 /// per-`:contratos` byte-string scalar accessors, all three
494 /// projecting through the `pub const fn` [`String::as_str`]
495 /// (const-stable since Rust 1.87). See [`Self::source`] for the
496 /// family-closure rationale.
497 #[must_use]
498 pub const fn destination(&self) -> &str {
499 self.para.as_str()
500 }
501
502 /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
503 /// accessor every consumer that reads the edge's WIT world
504 /// discriminator keys off — returns the author-declared
505 /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
506 /// the typed slot's own [`String`] storage.
507 ///
508 /// The `:contratos :wit` slot names the WIT world the typed edge
509 /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
510 /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
511 /// be a well-shaped WIT world reference via
512 /// [`crate::render::is_wit_world_ref`] and by
513 /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
514 /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
515 /// [`WitContract::source`] / [`WitContract::destination`] accessors
516 /// on the same per-`:contratos` entry — the triple
517 /// `( source(), destination(), world_ref() )` jointly names the
518 /// typed edge every renderer that fans on the caller-callee-shape
519 /// identity keys off (the per-edge dedup key at
520 /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
521 /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
522 /// [`caixa_mesh::cilium_network_policies`], the
523 /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
524 /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
525 /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
526 ///
527 /// Prior to this lift the `.wit` byte-string was accessed inline at
528 /// five sites — three caixa-core (the `WitContract::is_*` shape-
529 /// dispatch predicates' `&self.wit` arg, the validate-side empty
530 /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
531 /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
532 /// printer's `{}` format-slot at `c.wit`) — five open-coded
533 /// `.wit` field-accesses that expressed no compile-time link back to
534 /// the typed slot. A future extension of the `:contratos :wit` axis
535 /// to a richer author surface (an M4 promotion from `String` to a
536 /// typed WIT-world enum once the WIT registry stabilizes in tatara-
537 /// lisp per this struct's own `:wit` field docstring, a per-cluster
538 /// WIT-alias table the operator pins through a future
539 /// `:placement`-scoped slot, a canonicalization pass that lowercases
540 /// `wasi:*` prefixes) would have had to be threaded through every
541 /// open-coded copy in lockstep or one consumer would silently
542 /// disagree with the peers on which WIT shape a given edge resolves
543 /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
544 /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
545 /// empty-check that missed a whitespace-only string a peer accessor
546 /// stripped, or vice versa). Lifting to a typed method on the
547 /// substrate primitive means every downstream WIT-shape-facing
548 /// consumer reaches for one typed dispatch — the resolver's
549 /// accept-set migrates as a unit on any future axis addition.
550 ///
551 /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
552 /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
553 /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
554 /// 6db982c), per-`:membros` [`Membro::nome`] /
555 /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
556 /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
557 /// on the substrate primitive, thin projections at each consumer"
558 /// discipline extended onto the last unlifted per-`:contratos`
559 /// scalar (the WIT-world-reference arm).
560 ///
561 /// [fag]: caixa-feira/src/cmd/app.rs
562 ///
563 /// Declared `pub const fn` — sibling in `const`-eval posture to the
564 /// peer `pub const fn` [`Self::source`] / [`Self::destination`]
565 /// per-`:contratos` byte-string scalar accessors on the trio, and
566 /// the load-bearing enabler for the paired `pub const fn`
567 /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
568 /// [`Self::is_capability`] WIT-shape-predicate family (each
569 /// composes as `wit_shape_is_<arm>(self.world_ref())` and inherits
570 /// the `const`-eval posture by construction once this accessor
571 /// carries it). See [`Self::source`] for the family-closure
572 /// rationale and the paired
573 /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
574 /// for the load-bearing witness.
575 #[must_use]
576 pub const fn world_ref(&self) -> &str {
577 self.wit.as_str()
578 }
579
580 /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
581 /// payload-target scalar accessor every consumer that reads the
582 /// edge's L7 HTTP request path payload keys off — returns the
583 /// author-declared `:contratos :endpoint` byte-string verbatim as
584 /// an `Option<&str>`, borrowed from the typed slot's own
585 /// `Option<String>` storage; `None` when the slot is absent (the
586 /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
587 /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
588 /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
589 /// [`WitTarget::Capability`] edge carries none of the three).
590 ///
591 /// The `:contratos :endpoint` slot carries the HTTP request path
592 /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
593 /// — same shape required of `:entrada :paths`, gated by the shared
594 /// [`crate::render::is_gateway_api_http_path`] predicate) that
595 /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
596 /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
597 /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
598 /// downstream consumer that reads the payload keys off this scalar
599 /// (the [`WitContract::target`] Http-arm payload extraction that
600 /// materializes [`WitTarget::Http { endpoint }`] under the paired
601 /// [`WitTarget::HTTP_FIELD_NAME`] label, the
602 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
603 /// key's endpoint arm that pins the payload as part of the six-tuple
604 /// dedup key alongside the sibling `:subject`/`:slot` arms, the
605 /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
606 /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
607 /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
608 /// emission path that lands the payload verbatim as a Cilium L7
609 /// `path:` rule).
610 ///
611 /// Prior to this lift the `.endpoint` field was accessed inline at
612 /// two production sites in `caixa-core/src/aplicacao.rs` — the
613 /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
614 /// self.endpoint.as_deref();` binding at the top of the method, and
615 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
616 /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
617 /// field-accesses that expressed no compile-time link back to the
618 /// typed slot. A future extension of the `:contratos :endpoint`
619 /// axis to a richer author surface (an M4 promotion from
620 /// `Option<String>` to a typed HTTP path-template enum once the
621 /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
622 /// this struct's own `:wit` field docstring, a per-cluster endpoint-
623 /// alias table the operator pins through a future `:placement`-
624 /// scoped slot, a canonicalization pass that percent-encodes non-
625 /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
626 /// materializer applies per-tenant) would have had to be threaded
627 /// through both open-coded copies in lockstep or the two consumers
628 /// would silently disagree on which HTTP path a given edge resolves
629 /// to — the [`WitContract::target`] payload-extraction reading
630 /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
631 /// the operator-resolved `"/tenant-a/lookup"` would silently split
632 /// the [`WitTarget::Http`]-arm rendered payload from the actual
633 /// dedup-key uniqueness axis, a two-consumer split at the validator
634 /// far from the source `caixa.lisp` with no field naming the
635 /// payload-drift root cause. Lifting the resolution rule to a typed
636 /// method on the substrate primitive means every downstream
637 /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
638 /// L7-payload surface reaches for exactly one typed dispatch — the
639 /// resolver's accept-set migrates as a unit on any future axis
640 /// addition.
641 ///
642 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
643 /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
644 /// accessors on the M3 mesh-slot family — same "one typed dispatch
645 /// on the substrate primitive, thin projections at each consumer"
646 /// discipline extended onto the per-`:contratos` HTTP-shaped
647 /// payload-carrier `Option<String>` optional-scalar axis. First
648 /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
649 /// atom — opens the "optional per-slot payload-carrier scalar"
650 /// projection pattern the sibling per-`:contratos` `:subject` /
651 /// `:slot` future lifts fold on, matching the closed
652 /// per-`:contratos` scalar-value accessor family
653 /// ([`WitContract::source`] / [`WitContract::destination`] /
654 /// [`WitContract::world_ref`]) already lifted onto the mandatory-
655 /// scalar `String` axes. Named `endpoint()` to match the storage
656 /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
657 /// author-facing label const; the accessor's identity name maps
658 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
659 /// docstring already carries.
660 #[must_use]
661 pub const fn endpoint(&self) -> Option<&str> {
662 match &self.endpoint {
663 Some(s) => Some(s.as_str()),
664 None => None,
665 }
666 }
667
668 /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
669 /// payload-target scalar accessor every consumer that reads the
670 /// edge's NATS / Kafka publish subject payload keys off — returns
671 /// the author-declared `:contratos :subject` byte-string verbatim
672 /// as an `Option<&str>`, borrowed from the typed slot's own
673 /// `Option<String>` storage; `None` when the slot is absent (the
674 /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
675 /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
676 /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
677 /// [`WitTarget::Capability`] edge carries none of the three).
678 ///
679 /// The `:contratos :subject` slot carries the NATS / Kafka publish
680 /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
681 /// per-edge target selector — `orders.paid`, `events.>`, whatever
682 /// subject namespace the author names on the pub-sub edge) that
683 /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
684 /// arm's `subject: &'a str` payload when the edge's `:wit` world
685 /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
686 /// downstream consumer that reads the payload keys off this scalar
687 /// (the [`WitContract::target`] PubSub-arm payload extraction that
688 /// materializes [`WitTarget::PubSub { subject }`] under the paired
689 /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
690 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
691 /// key's subject arm that pins the payload as part of the six-tuple
692 /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
693 /// future M4 per-edge WIT registry resolver's pub-sub-arm
694 /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
695 /// materializer's per-edge NATS admission webhook, the future
696 /// caixa-mesh L4 CNP emission path that lands the payload verbatim
697 /// as a NATS subject the operator pins per-CR).
698 ///
699 /// Prior to this lift the `.subject` field was accessed inline at
700 /// two production sites in `caixa-core/src/aplicacao.rs` — the
701 /// [`WitContract::target`] payload-shape dispatch's `let subject =
702 /// self.subject.as_deref();` binding at the top of the method, and
703 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
704 /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
705 /// field-accesses that expressed no compile-time link back to the
706 /// typed slot. A future extension of the `:contratos :subject` axis
707 /// to a richer author surface (an M4 promotion from `Option<String>`
708 /// to a typed NATS-subject-template enum once the WIT registry
709 /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
710 /// struct's own `:wit` field docstring, a per-cluster subject-alias
711 /// table the operator pins through a future `:placement`-scoped
712 /// slot, a canonicalization pass that lowercases / dedupes wildcard
713 /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
714 /// applies per-tenant) would have had to be threaded through both
715 /// open-coded copies in lockstep or the two consumers would silently
716 /// disagree on which NATS subject a given edge resolves to — the
717 /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
718 /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
719 /// resolved `"tenant-a.orders.paid"` would silently split the
720 /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
721 /// key uniqueness axis, a two-consumer split at the validator far
722 /// from the source `caixa.lisp` with no field naming the payload-
723 /// drift root cause. Lifting the resolution rule to a typed method
724 /// on the substrate primitive means every downstream pub-sub-payload-
725 /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
726 /// surface reaches for exactly one typed dispatch — the resolver's
727 /// accept-set migrates as a unit on any future axis addition.
728 ///
729 /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
730 /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
731 /// carrier axis — second `Option<&str>`-return accessor on the
732 /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
733 /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
734 /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
735 /// key/value-store arm as the last unlifted per-`:contratos`
736 /// `Option<String>` axis. Named `subject()` to match the storage
737 /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
738 /// author-facing label const; the accessor's identity name maps
739 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
740 /// docstring already carries.
741 #[must_use]
742 pub const fn subject(&self) -> Option<&str> {
743 match &self.subject {
744 Some(s) => Some(s.as_str()),
745 None => None,
746 }
747 }
748
749 /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
750 /// shaped payload-target scalar accessor every consumer that reads
751 /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
752 /// off — returns the author-declared `:contratos :slot` byte-string
753 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
754 /// own `Option<String>` storage; `None` when the slot is absent
755 /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
756 /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
757 /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
758 /// [`WitTarget::Capability`] edge carries none of the three).
759 ///
760 /// The `:contratos :slot` slot carries the key/value store
761 /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
762 /// arm's per-edge target selector — `carts/{cart_id}`,
763 /// `sessions/{tenant}/{sid}`, whatever key-template the author
764 /// names on the store edge) that [`WitContract::target`] projects
765 /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
766 /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
767 /// accept-set. Every downstream consumer that reads the payload
768 /// keys off this scalar (the [`WitContract::target`] Store-arm
769 /// payload extraction that materializes [`WitTarget::Store { slot }`]
770 /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
771 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
772 /// key's store arm that pins the payload as part of the six-tuple
773 /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
774 /// the future M4 per-edge WIT registry resolver's store-arm
775 /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
776 /// materializer's per-edge key/value admission webhook, the future
777 /// caixa-mesh L4 CNP emission path that lands the payload verbatim
778 /// as a key-template the operator pins per-CR).
779 ///
780 /// Prior to this lift the `.slot` field was accessed inline at two
781 /// production sites in `caixa-core/src/aplicacao.rs` — the
782 /// [`WitContract::target`] payload-shape dispatch's `let slot =
783 /// self.slot.as_deref();` binding at the top of the method, and
784 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
785 /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
786 /// field-accesses that expressed no compile-time link back to the
787 /// typed slot. A future extension of the `:contratos :slot` axis
788 /// to a richer author surface (an M4 promotion from `Option<String>`
789 /// to a typed key-template enum once the WIT registry stabilizes
790 /// key-template parameter shapes in tatara-lisp per this struct's
791 /// own `:wit` field docstring, a per-cluster slot-alias table the
792 /// operator pins through a future `:placement`-scoped slot, a
793 /// canonicalization pass that lowercases the bucket prefix, a
794 /// per-CR fully-qualified rewrite the M4 CR materializer applies
795 /// per-tenant) would have had to be threaded through both
796 /// open-coded copies in lockstep or the two consumers would
797 /// silently disagree on which key-template a given edge resolves
798 /// to — the [`WitContract::target`] payload-extraction reading
799 /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
800 /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
801 /// would silently split the [`WitTarget::Store`]-arm rendered
802 /// payload from the actual dedup-key uniqueness axis, a
803 /// two-consumer split at the validator far from the source
804 /// `caixa.lisp` with no field naming the payload-drift root cause.
805 /// Lifting the resolution rule to a typed method on the substrate
806 /// primitive means every downstream store-payload-facing consumer
807 /// of the Aplicacao's per-`:contratos` payload surface reaches for
808 /// exactly one typed dispatch — the resolver's accept-set migrates
809 /// as a unit on any future axis addition.
810 ///
811 /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
812 /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
813 /// accessors on the M3 mesh-slot payload-carrier axis — third and
814 /// final `Option<&str>`-return accessor on the per-`:contratos`
815 /// mesh-slot atom, closes the last unlifted per-`:contratos`
816 /// `Option<String>` axis and completes the "optional per-slot
817 /// payload-carrier scalar" projection pattern the peer HTTP /
818 /// pub-sub arms established across the three payload-shape
819 /// dispatch arms. Named `slot()` to match the storage field's
820 /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
821 /// author-facing label const; the accessor's identity name maps
822 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
823 /// docstring already carries.
824 #[must_use]
825 pub const fn slot(&self) -> Option<&str> {
826 match &self.slot {
827 Some(s) => Some(s.as_str()),
828 None => None,
829 }
830 }
831
832 /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
833 /// caller-callee-pair accessor every consumer that constructs an
834 /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
835 /// caller-callee pair keys off — returns the author-declared
836 /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
837 /// owned `(String, String)` tuple, projected through the lifted
838 /// [`WitContract::source`] / [`WitContract::destination`] scalar
839 /// accessors so any future rebrand on the caller-arm / callee-arm
840 /// projection axis (an M4 per-cluster caller-alias table the
841 /// operator pins through a future `:placement`-scoped slot, a
842 /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
843 /// a per-`:membros` alias overlay from the future `:membros
844 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
845 /// acknowledges) reaches every diagnostic-construction site by
846 /// construction.
847 ///
848 /// The `(de, para)` pair is the "typed-edge caller-callee identity in
849 /// owned form" primitive every per-`:contratos` diagnostic variant on
850 /// [`AplicacaoError`] carries alongside its payload-shape arm — the
851 /// nine variants [`AplicacaoError::EmptyWit`],
852 /// [`AplicacaoError::ContratoEndpointEmpty`],
853 /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
854 /// [`AplicacaoError::ContratoEndpointInvalid`],
855 /// [`AplicacaoError::ContratoSubjectEmpty`],
856 /// [`AplicacaoError::ContratoSubjectInvalid`],
857 /// [`AplicacaoError::ContratoSlotEmpty`],
858 /// [`AplicacaoError::ContratoSlotInvalid`], and
859 /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
860 /// para: String` field pair the constructor site reads verbatim off
861 /// the [`WitContract`] the diagnostic points at, so a diagnostic
862 /// whose `de:` and `para:` labels silently drift off the source
863 /// caller/callee — a per-cluster caller-alias rewrite that landed on
864 /// one variant's inline `de: c.de.clone()` field access but not on
865 /// its sibling variant's, an accidental swap of the `de:` and `para:`
866 /// arms in a copy-paste of the constructor block — would emit a
867 /// build-time error whose "which caixa is at fault" question the
868 /// operator answers wrongly, far from the source `caixa.lisp`.
869 ///
870 /// Prior to this lift the `(self.de.clone(), self.para.clone())`
871 /// pair was inlined at seven [`WitContract::target`] error-
872 /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
873 /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
874 /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
875 /// the [`AplicacaoError::ContratoSubjectEmpty`] /
876 /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
877 /// the [`AplicacaoError::ContratoSlotEmpty`] /
878 /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
879 /// two [`AplicacaoSpec::validate`] error-construction sites (the
880 /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
881 /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
882 /// insert-first-seen closure) — nine open-coded `.de.clone() +
883 /// .para.clone()` pairs that expressed no compile-time contract that
884 /// the caller-arm and callee-arm arms of the same diagnostic
885 /// construction reach for the same [`WitContract`] instance or that
886 /// the `de:` and `para:` label pair binds to the fields the author
887 /// declared. Any future rebrand on the axis — an M4 per-cluster
888 /// caller/callee-alias rewrite the operator pins through a future
889 /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
890 /// per-CR fully-qualified namespace prefix the M4
891 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
892 /// per-tenant, a canonicalization pass that lowercases the caller +
893 /// callee identifiers post-parse — would have had to be threaded
894 /// through every open-coded copy in lockstep or one variant's
895 /// diagnostic would silently name a different caller/callee pair
896 /// than its peer, silently degrading the "which caixa is at fault"
897 /// self-locating signal every operator-facing typed diagnostic
898 /// exists to carry. Lifting the pair to a typed method on the
899 /// substrate primitive means every downstream diagnostic-construction
900 /// site reaches for exactly one typed dispatch — the resolver's
901 /// projection migrates as a unit on any future axis addition.
902 ///
903 /// Peer of the sibling per-`:contratos` scalar accessor family
904 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
905 /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
906 /// scalar-value axes — first composite-projection accessor on the
907 /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
908 /// form `.clone()` field-accesses that pair the sibling
909 /// caller/callee accessors' `&str`-return borrowed-form outputs onto
910 /// one typed dispatch. Named `edge_pair()` to reflect the identity
911 /// name of the projected tuple (the typed-edge caller-callee pair,
912 /// distinct from the sibling triple-projection
913 /// [`WitContract::edge_triple`] accessor that folds the local `edge`
914 /// closure in [`WitContract::target`] + the paired
915 /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
916 /// site's `(de, para, wit)` triple onto one typed dispatch).
917 #[must_use]
918 pub fn edge_pair(&self) -> (String, String) {
919 (self.source().to_string(), self.destination().to_string())
920 }
921
922 /// Owned form of the `(:contratos :de, :contratos :para, :contratos
923 /// :wit)` triple every per-edge diagnostic constructor that names
924 /// all three axes threads verbatim into its `de:` / `para:` /
925 /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
926 /// / missing-target / invalid-wit / capability-with-payload arms
927 /// (eight sites all shape `let (de, para, wit) = edge();
928 /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
929 /// accessor landed) and the sibling
930 /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
931 /// constructor (which paired `edge_pair()` for the `(de, para)`
932 /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
933 /// typed-dispatch + raw-field-access shape the sibling accessor
934 /// family already flagged as a drift risk). Nine total call sites
935 /// collapse onto this helper.
936 ///
937 /// Lifted with the same one-source-of-truth discipline
938 /// [`WitContract::edge_pair`] carries on the paired
939 /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
940 /// arms compose through the lifted [`WitContract::source`] /
941 /// [`WitContract::destination`] / [`WitContract::world_ref`]
942 /// scalar accessors byte-for-byte (pinned by the paired
943 /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
944 /// composition-pin), so any future rebrand on the per-`:contratos`
945 /// caller / callee / world-ref axis (an M4 per-cluster
946 /// caller/callee-alias rewrite the operator pins through a future
947 /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
948 /// per-CR fully-qualified namespace prefix the M4
949 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
950 /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
951 /// on `source()` / `destination()`, a per-CR canonicalization pass
952 /// that lowercases the WIT world ref post-parse) migrates as a
953 /// single caixa-core edit rather than a coordinated rewrite of
954 /// nine open-coded triple-constructors.
955 ///
956 /// Peer of the sibling per-`:contratos` composite-projection
957 /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
958 /// composite-value axes — closes the last unlifted owned-form
959 /// composite-tuple axis on the per-`:contratos` diagnostic-
960 /// construction surface. Named `edge_triple()` to reflect the
961 /// identity name of the projected tuple (the typed-edge
962 /// caller-callee-wit triple, sibling to the caller-callee-only
963 /// pair `edge_pair()` returns).
964 #[must_use]
965 pub fn edge_triple(&self) -> (String, String, String) {
966 (
967 self.source().to_string(),
968 self.destination().to_string(),
969 self.world_ref().to_string(),
970 )
971 }
972
973 /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
974 /// dedups typed edges keys off — routes through the lifted
975 /// [`WitContract::source`] / [`WitContract::destination`] /
976 /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
977 /// [`WitContract::subject`] / [`WitContract::slot`] scalar
978 /// accessors so the tuple's six arms and the [`ContratoIdentity`]
979 /// type alias's six axes migrate as a unit on any future axis
980 /// addition (adding a seventh field to [`WitContract`] is one
981 /// [`ContratoIdentity`] alias edit + one accessor addition + one
982 /// arm here, not a coordinated rewrite of every open-coded
983 /// six-tuple builder that dedups on the identity axis).
984 ///
985 /// Sibling of [`WitContract::edge_pair`] /
986 /// [`WitContract::edge_triple`] on the composite-projection axis:
987 /// the pair projects the caller-callee axes, the triple extends it
988 /// with the world-ref, this method extends it with the three
989 /// payload-carrier axes. Every projection returns the same six
990 /// scalar accessors' outputs; the three methods differ only in
991 /// which arms they surface.
992 ///
993 /// Declared `pub const fn` — every callee is itself `pub const fn`
994 /// ([`Self::source`] / [`Self::destination`] / [`Self::world_ref`]
995 /// project through `pub const fn` [`String::as_str`], const-stable
996 /// since Rust 1.87; [`Self::endpoint`] / [`Self::subject`] /
997 /// [`Self::slot`] project through the same `String::as_str` under a
998 /// `match &self.<field> { Some(s) => Some(s.as_str()), None => None }`
999 /// arm — the sibling `Option<String> → Option<&str>` shape 0650f64
1000 /// closed the const-eval surface on) and tuple construction from
1001 /// borrowed-reference / `Option`-of-borrowed-reference arms is
1002 /// itself trivially const. The `ContratoIdentity<'_>` alias
1003 /// resolves to a `(&str, &str, &str, Option<&str>, Option<&str>,
1004 /// Option<&str>)` tuple whose every arm is `Copy` — no destructor,
1005 /// no heap allocation, no non-const call folded through the tuple's
1006 /// construction. Sibling in `const`-eval posture to the peer
1007 /// `pub const fn` [`WitContract::is_http`] / [`Self::is_pubsub`] /
1008 /// [`Self::is_store`] / [`Self::is_capability`] WIT-shape-predicate
1009 /// composite-projection family the sibling
1010 /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1011 /// already anchors — this extends the same `const`-eval-surface
1012 /// posture onto the peer six-arm composite-projection axis where
1013 /// the projection surfaces the full identity tuple rather than a
1014 /// per-`(:de, :para, :wit)`-triple boolean shape probe. Pinned load-
1015 /// bearing by
1016 /// [`wit_contract_identity_projection_accessor_is_const_fn`] below
1017 /// (a future accidental downgrade fires E0015 at the wrapper at
1018 /// caixa-core build time).
1019 #[must_use]
1020 pub const fn identity(&self) -> ContratoIdentity<'_> {
1021 (
1022 self.source(),
1023 self.destination(),
1024 self.world_ref(),
1025 self.endpoint(),
1026 self.subject(),
1027 self.slot(),
1028 )
1029 }
1030
1031 /// True when this contract targets an HTTP-shaped WIT world.
1032 ///
1033 /// Declared `pub const fn` — routes through the paired `pub const
1034 /// fn` [`Self::world_ref`] scalar accessor and the substrate's
1035 /// `pub const fn` free-function classifier [`wit_shape_is_http`]
1036 /// (d46420c). Sibling in `const`-eval posture to the peer
1037 /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
1038 /// [`Self::is_capability`] WIT-shape-predicate family; the closed
1039 /// 4-arm partition on the raw `:contratos :wit` axis now carries
1040 /// the same `const`-eval-surface posture as the free-function
1041 /// classifier family it composes through. Pinned load-bearing by
1042 /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
1043 /// test (a future accidental downgrade to non-`const` fires E0015
1044 /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
1045 /// build time).
1046 #[must_use]
1047 pub const fn is_http(&self) -> bool {
1048 wit_shape_is_http(self.world_ref())
1049 }
1050
1051 /// True when this contract targets a pub-sub-shaped WIT world.
1052 ///
1053 /// Declared `pub const fn` — sibling in `const`-eval posture to
1054 /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
1055 /// [`Self::is_capability`] WIT-shape-predicate family. See
1056 /// [`Self::is_http`] for the family-closure rationale.
1057 #[must_use]
1058 pub const fn is_pubsub(&self) -> bool {
1059 wit_shape_is_pubsub(self.world_ref())
1060 }
1061
1062 /// True when this contract targets a key/value-shaped WIT world.
1063 ///
1064 /// Declared `pub const fn` — sibling in `const`-eval posture to
1065 /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
1066 /// [`Self::is_capability`] WIT-shape-predicate family. See
1067 /// [`Self::is_http`] for the family-closure rationale.
1068 #[must_use]
1069 pub const fn is_store(&self) -> bool {
1070 wit_shape_is_store(self.world_ref())
1071 }
1072
1073 /// True when this contract targets *none* of the three known payload-
1074 /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
1075 /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1076 /// open on the [`WitContract`] surface. Returns the exact-inverse
1077 /// disjunction of the peer trio — `true` when none of the three
1078 /// prefix-set predicates matches the raw `:contratos :wit` value; the
1079 /// author-declared WIT world is a pure typed capability edge with no
1080 /// payload selector (the shape [`WitContract::target`] projects onto
1081 /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
1082 /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
1083 ///
1084 /// The `:contratos :wit` shape-space is closed at four arms
1085 /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
1086 /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
1087 /// everything else on the payload-less capability arm), and every
1088 /// downstream consumer that must filter contratos by shape-class
1089 /// keys off the four sibling predicates (the [`WitContract::target`]
1090 /// dispatch's implicit `else` after the three payload-shape arm
1091 /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
1092 /// every future substrate-side capability-shape-only emitter — the
1093 /// M4 per-Aplicacao WIT-registry capability-import materializer, the
1094 /// future `feira app graph --capability` per-Aplicacao capability-
1095 /// column filter, the future per-cluster capability-scope reconciler
1096 /// that skips L4/L7 emission for payload-less edges since Cilium
1097 /// can't introspect WASI capability calls, the future
1098 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1099 /// shape shape-count histogram). Every such consumer reaches for one
1100 /// typed dispatch on the substrate primitive so the "which arm
1101 /// carries the capability-only shape?" answer lives at one caixa-core
1102 /// edit rather than open-coded across per-consumer
1103 /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1104 /// negations, each of which would silently drop a future fourth
1105 /// payload-arm addition without a compile-time signal at the
1106 /// consumer site.
1107 ///
1108 /// Prior to this lift the "not one of the three known payload
1109 /// shapes" classification sat inline at [`WitContract::target`]'s
1110 /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1111 /// [`WitTarget::Capability`] admission arm after the three `if
1112 /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1113 /// { … }` guards) with no named accessor for downstream consumers
1114 /// to reach through. A future substrate-side capability-only
1115 /// filter or a future capability-scope reconciler would have had to
1116 /// re-inline the same triplet negation at every emit site with no
1117 /// compile-time link back to the sibling trio, and a future arm
1118 /// addition (a hypothetical fourth payload-shape prefix set — a
1119 /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1120 /// import carrier per the sibling [`wit_shape_matches`] docstring's
1121 /// trajectory bullet) would land the new predicate on the payload-
1122 /// carrying trio and silently misclassify the new shape as
1123 /// capability at every triplet-negation consumer site, propagating
1124 /// the drift far from the caixa-core prefix-set commit.
1125 ///
1126 /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1127 /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1128 /// trio into a 4-way partition witness on the raw `:contratos :wit`
1129 /// axis, mirroring the paired post-projection [`WitTarget`]
1130 /// `gen_platform::IsVariant`-derived 4-way predicate set
1131 /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1132 /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1133 /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1134 /// arm-set). The two typed axes — pre-projection on the raw
1135 /// `:contratos :wit` string, post-projection on the validated typed
1136 /// view — now carry a matched 4-arm predicate discipline: every
1137 /// arm on the closed [`WitTarget`] set has a peer pre-projection
1138 /// predicate on the [`WitContract`] surface, and any future
1139 /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1140 /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1141 /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1142 /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1143 /// pre-projection axis through a matching peer prefix-set + peer
1144 /// predicate lift by construction — the compile-time exhaustiveness
1145 /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1146 /// the post-projection accessor family stays in sync, and the sibling
1147 /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1148 /// partition-witness pin locks the pre-projection classification in
1149 /// load-bearing so a peer prefix-set addition that widened one arm's
1150 /// accept-set without shrinking the [`Self::is_capability`] accept-set
1151 /// surfaces as a test failure at caixa-core build time rather than a
1152 /// silent per-consumer split at renderer emit time.
1153 ///
1154 /// Composes byte-for-byte through the lifted peer trio
1155 /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1156 /// any future rebrand of any prefix-set const flows through this
1157 /// method by construction without a coordinated per-consumer rewrite
1158 /// (pinned by the sibling
1159 /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1160 /// composition-witness).
1161 ///
1162 /// Note: purely syntactic classification on the `:wit` prefix-set —
1163 /// unlike [`Self::target`], which additionally rejects value-shape-
1164 /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1165 /// package) via [`crate::render::is_wit_world_ref`] and payload-
1166 /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1167 /// structurally malformed returns `true` from `is_capability()` (the
1168 /// prefix set matches nothing), and the surrounding
1169 /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1170 /// is where the [`AplicacaoError::EmptyWit`] /
1171 /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1172 /// predicate is the classifier, not the validator.
1173 ///
1174 /// Declared `pub const fn` — closes the WIT-shape-predicate
1175 /// family's `const`-eval-surface pass at the fourth (payload-less)
1176 /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
1177 /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
1178 /// See [`Self::is_http`] for the family-closure rationale.
1179 #[must_use]
1180 pub const fn is_capability(&self) -> bool {
1181 wit_shape_is_capability(self.world_ref())
1182 }
1183
1184 /// True when this contract's caller equals its callee — a
1185 /// structurally degenerate typed edge that no `:contratos` entry can
1186 /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1187 /// Servico B" is an *inter*-Servico contract between two distinct
1188 /// graph nodes). A Servico contracting with itself resolves to an
1189 /// in-process call the wasm-engine never routes through the mesh at
1190 /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1191 /// per-edge policy can express the intended shape — the pub-sub
1192 /// path silently rendered a self-allow rule that is a no-op (intra-
1193 /// pod traffic bypasses the mesh entirely), and the synchronous
1194 /// paths surfaced as a misleading `ContratoCycle` whose path was
1195 /// `["cart", "cart"]` — framing a self-edge as a multi-node
1196 /// deadlock. Every downstream consumer that must reject the shape
1197 /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1198 /// gate at caixa-core/src/aplicacao.rs:5559, every future
1199 /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1200 /// axis, every future adjacency-graph builder that must skip self-
1201 /// edges rather than fold them into an incidental cycle) now keys
1202 /// off exactly one typed dispatch on the substrate primitive, so
1203 /// any future rebrand on the axis (an M4-typed-caller enum whose
1204 /// identity comparison rule the accessor could route through, an
1205 /// operator-side per-cluster caller/callee-alias table the
1206 /// materializer resolves per-CR before the equality probe, a
1207 /// promotion of the pointwise `==` to a set-membership check once
1208 /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1209 /// so a per-replica self-edge is rejected under the same predicate)
1210 /// migrates as a single caixa-core edit rather than a coordinated
1211 /// rewrite of every downstream self-edge consumer. Composes
1212 /// byte-for-byte through the lifted [`Self::source`] /
1213 /// [`Self::destination`] scalar accessors — the accessor pair every
1214 /// per-`:contratos` scalar-value axis already routes through — so
1215 /// any future rebrand of the underlying `:de` / `:para` storage
1216 /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1217 /// a per-Aplicacao interning arena the M4 CR materializer authors,
1218 /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1219 /// same one body without a coordinated per-consumer rewrite.
1220 ///
1221 /// Sibling in shape to the peer per-`:contratos` shape-predicate
1222 /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1223 /// on the `:wit` world-ref axis — extended onto the per-edge
1224 /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1225 /// partition the WIT-shape-space; `is_self_loop` partitions the
1226 /// caller-callee identity-space. Named `is_self_loop()` to reflect
1227 /// the graph-theoretic identity of the shape (a loop from a graph
1228 /// node to itself, distinct from the sibling multi-node
1229 /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1230 /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1231 /// variant already carrying the term.
1232 ///
1233 /// Declared `pub const fn` — closes the last unlifted per-`:contratos`
1234 /// shape-predicate on the substrate's `const`-eval surface. The peer
1235 /// per-`:contratos` shape-predicate family [`Self::is_http`] /
1236 /// [`Self::is_pubsub`] / [`Self::is_store`] / [`Self::is_capability`]
1237 /// (d46420c / 84c2325 / 279823b) already carries the `pub const fn`
1238 /// posture on the WIT-world-ref classifier axis; this lift extends it
1239 /// onto the peer caller-callee identity-space predicate. The body
1240 /// projects the `:de` / `:para` `String` storage through the sibling
1241 /// `pub const fn` [`Self::source`] / [`Self::destination`] scalar
1242 /// accessors, then compares the resulting `&str` byte-slices under a
1243 /// manual `while`-loop through `str::as_bytes` (`pub const fn`,
1244 /// const-stable since Rust 1.39), primitive-`usize` `!=` on
1245 /// [`<[u8]>::len`], and const-stable slice indexing (since Rust 1.79)
1246 /// — every operation `const`-eval-callable on stable Rust, no
1247 /// iterator methods, no `PartialEq for str` trait dispatch (which
1248 /// remains non-`const` on stable). Mirrors the peer `pub const fn`
1249 /// [`wit_shape_matches`] combinator's manual byte-level `starts_with`
1250 /// loop verbatim on the paired-slice-equality shape. Every downstream
1251 /// substrate-side `const`-context consumer of the per-`:contratos`
1252 /// self-edge partition (a future `const _: () = assert!(…)` module-
1253 /// scope invariant pin over a per-fixture typed [`WitContract`] once
1254 /// the type's carriers admit `const`-context construction, a future
1255 /// M4 admission-webhook `const fn` self-edge resolver, any `const fn`
1256 /// composer that fans on the identity-space partition at compile
1257 /// time) reaches through the same typed dispatch on the substrate
1258 /// primitive at const-eval time as at runtime. Pinned by
1259 /// [`tests::wit_contract_is_self_loop_predicate_is_const_fn`] which
1260 /// witnesses the `const`-eval posture via a `const fn` wrapper so any
1261 /// future accidental downgrade to non-`const` trips at caixa-core
1262 /// build time with E0015 (`cannot call non-const method`), strictly
1263 /// stronger than a runtime `assert!`.
1264 #[must_use]
1265 pub const fn is_self_loop(&self) -> bool {
1266 // Compose through the paired `pub const fn` [`Self::source`] /
1267 // [`Self::destination`] scalar accessors so any future rebrand of
1268 // the underlying `:de` / `:para` storage (a lift from `String` to
1269 // a typed `ServicoName(String)` newtype, a per-Aplicacao interning
1270 // arena the M4 CR materializer authors, a `smol_str::SmolStr`
1271 // inline-buffer swap) flows through the same one body without a
1272 // coordinated per-consumer rewrite. Peer of the sibling
1273 // [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
1274 // [`Self::is_capability`] shape-predicate family — each of which
1275 // composes through the paired [`Self::world_ref`] scalar accessor
1276 // onto the peer `pub const fn` [`wit_shape_is_http`] /
1277 // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
1278 // [`wit_shape_is_capability`] free-function classifier — the same
1279 // "typed dispatch composes with typed dispatch, not raw field
1280 // access" discipline extended onto the caller-callee identity-
1281 // space partition. Pinned by
1282 // [`tests::wit_contract_is_self_loop_routes_through_source_destination_accessors`]
1283 // above.
1284 let a = self.source().as_bytes();
1285 let b = self.destination().as_bytes();
1286 if a.len() != b.len() {
1287 return false;
1288 }
1289 // Manual byte-level equality loop — mirrors the peer
1290 // [`wit_shape_matches`] combinator's manual `starts_with` loop
1291 // verbatim on the paired-slice-equality shape. `PartialEq for
1292 // str` remains non-`const` on stable Rust 1.94 (the `Pattern`
1293 // trait dispatch it routes through is not `const`), so a naive
1294 // `self.source() == self.destination()` body would trip on
1295 // `const`-eval-callability; the byte-slice loop dispatches
1296 // through primitive-`u8` `!=`, primitive-`usize` comparison, and
1297 // const-stable slice indexing (since Rust 1.79) — every
1298 // operation `const`-eval-callable on stable.
1299 let mut i = 0;
1300 while i < a.len() {
1301 if a[i] != b[i] {
1302 return false;
1303 }
1304 i += 1;
1305 }
1306 true
1307 }
1308
1309 /// Typed view of the contract's payload target. Enforces that the
1310 /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1311 /// fields agree, and that each carried value is itself
1312 /// value-shape valid:
1313 ///
1314 /// - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1315 /// non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1316 /// `PathPrefix` invariant — same shape required of `:entrada
1317 /// :paths`)
1318 /// - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1319 /// non-empty (NATS / Kafka publish without a subject is a
1320 /// no-op subscribe, never the author's intent)
1321 /// - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1322 /// non-empty (an empty slot template addresses the bucket
1323 /// root, defeating the per-key isolation the slot exists for)
1324 /// - Anything else ⇒ none of the three; the contract is a pure
1325 /// typed capability edge with no payload selector.
1326 ///
1327 /// Translates the Apollo Federation discipline ("conflicts are
1328 /// errors at compile time, not warnings at runtime";
1329 /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1330 /// a contract whose WIT shape disagrees with its target field, or
1331 /// whose target field carries a value-shape-invalid string, is a
1332 /// build error — not a silent renderer drop. The returned
1333 /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1334 /// non-empty (and absolute, for `Http`); every downstream consumer
1335 /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1336 /// the M4 per-edge policy resolver) can rely on that without
1337 /// re-checking.
1338 pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1339 // Route the HTTP-shaped payload-target extraction through the
1340 // lifted [`WitContract::endpoint`] accessor rather than the raw
1341 // `self.endpoint.as_deref()` field access — the two production
1342 // consumers of the per-`:contratos :endpoint` HTTP-shaped
1343 // payload-carrier scalar (this method's Http-arm payload
1344 // extraction, the [`AplicacaoSpec::validate`] duplicate-
1345 // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1346 // off exactly one typed dispatch on the substrate primitive, so
1347 // any future rebrand on the axis (an M4 per-cluster endpoint-
1348 // alias rewrite, a per-CR fully-qualified path prefix the M4
1349 // materializer applies per-tenant, an M4 promotion from
1350 // `Option<String>` to a typed HTTP path-template enum) migrates
1351 // as a single caixa-core edit rather than a coordinated rewrite
1352 // of the two call sites — peer of the sibling M3 per-`:placement`
1353 // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1354 // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1355 // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1356 let endpoint = self.endpoint();
1357 let subject = self.subject();
1358 // Route the store-arm payload-carrier scalar through the
1359 // lifted [`WitContract::slot`] accessor rather than the raw
1360 // `self.slot.as_deref()` field access — the two production
1361 // consumers of the per-`:contratos :slot` key/value-store-
1362 // shaped payload-carrier scalar (this method's Store-arm
1363 // payload extraction, the [`AplicacaoSpec::validate`]
1364 // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1365 // arm) now key off exactly one typed dispatch on the substrate
1366 // primitive. Closes the last unlifted per-`:contratos`
1367 // `Option<String>` axis, completing the payload-carrier
1368 // accessor family peer of the sibling per-`:contratos`
1369 // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1370 // (90de675) lifts across the HTTP / pub-sub arms.
1371 let slot = self.slot();
1372 // Route the local `(de, para, wit)` triple-projection closure
1373 // through the lifted [`WitContract::edge_triple`] typed accessor
1374 // rather than re-inlining `(self.de.clone(), self.para.clone(),
1375 // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1376 // triple-carrying diagnostic constructors below (wrong-target /
1377 // missing-target on all three payload arms + capability-with-
1378 // payload + invalid-wit) now key off exactly one typed dispatch
1379 // on the substrate-primitive composite projection, sibling to
1380 // the peer [`WitContract::edge_pair`]-routed
1381 // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1382 // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1383 // diagnostic constructors on the same per-`:contratos`
1384 // diagnostic-construction surface.
1385 let edge = || self.edge_triple();
1386
1387 // The `:wit` value drives every downstream dispatch — the
1388 // is_http/is_pubsub/is_store prefix matchers below, the
1389 // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1390 // exclusion. Until this gate landed `target()` accepted any
1391 // non-empty string and silently demoted unrecognized shapes to
1392 // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1393 // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1394 // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1395 // package, the paste-from-binary footgun a multi-line blob
1396 // accidentally landing in the slot, the un-percent-encoded
1397 // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1398 // routing, got L4-only" footgun. Empty is still pre-checked at
1399 // the [`AplicacaoSpec::validate`] call site via the narrower
1400 // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1401 // validate layer); the value-shape gate here picks up the
1402 // structurally-invalid non-empty cases the empty check misses,
1403 // and remains correct under direct `target()` calls outside
1404 // validate (the predicate's defensive empty arm returns a
1405 // parser-shaped reason rather than silently falling through to
1406 // the Capability arm). Same trajectory as c4213a4 (WitContract
1407 // endpoint/subject/slot value-shape gates lifted into
1408 // `target()`) on the peer payload axes.
1409 //
1410 // Routed through the lifted [`WitContract::world_ref`] accessor
1411 // rather than the raw `&self.wit` field access — the two
1412 // production consumers of the per-`:contratos :wit` world-ref
1413 // byte-string on the value-shape axis (this method's invalid-
1414 // wit gate, the [`AplicacaoSpec::validate`] duplicate-
1415 // `:contratos` [`ContratoIdentity`] dedup-key world-ref arm via
1416 // [`WitContract::identity`]) now key off exactly one typed
1417 // dispatch on the substrate primitive, so any future rebrand on
1418 // the axis (an M4 promotion from `String` to a typed WIT
1419 // world-ref enum once the WIT registry stabilizes in
1420 // tatara-lisp, a per-CR canonicalization pass that lowercases
1421 // the WIT world ref post-parse, a promoted `smol_str::SmolStr`
1422 // inline-buffer swap on the storage arm) migrates as a single
1423 // caixa-core edit rather than a coordinated rewrite of the two
1424 // call sites — sibling of the peer [`WitContract::endpoint`] /
1425 // [`WitContract::subject`] / [`WitContract::slot`] accessor-
1426 // routed payload-carrier extractions above on the same
1427 // [`WitContract::target`] body, completing the per-`:contratos`
1428 // scalar-accessor-routing pass at the last unlifted raw-field-
1429 // access site inside `impl WitContract`. Same "typed dispatch
1430 // composes with typed dispatch, not with raw field access"
1431 // discipline the sibling [`WitContract::edge_pair`] /
1432 // [`WitContract::edge_triple`] / [`WitContract::identity`]
1433 // composite-projection accessors and the
1434 // [`WitContract::is_self_loop`] identity-space predicate
1435 // already route through. Pinned by
1436 // [`tests::wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor`].
1437 if let Err(reason) = crate::render::is_wit_world_ref(self.world_ref()) {
1438 let (de, para, wit) = edge();
1439 return Err(AplicacaoError::ContratoWitInvalid {
1440 de,
1441 para,
1442 wit,
1443 reason,
1444 });
1445 }
1446
1447 if self.is_http() {
1448 if subject.is_some() || slot.is_some() {
1449 let (de, para, wit) = edge();
1450 return Err(AplicacaoError::ContratoWrongTarget {
1451 de,
1452 para,
1453 wit,
1454 expected: WitTarget::HTTP_FIELD_NAME,
1455 });
1456 }
1457 let ep = endpoint.ok_or_else(|| {
1458 let (de, para, wit) = edge();
1459 AplicacaoError::ContratoMissingTarget {
1460 de,
1461 para,
1462 wit,
1463 expected: WitTarget::HTTP_FIELD_NAME,
1464 }
1465 })?;
1466 if ep.is_empty() {
1467 let (de, para) = self.edge_pair();
1468 return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
1469 }
1470 if !ep.starts_with('/') {
1471 let (de, para) = self.edge_pair();
1472 return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1473 de,
1474 para,
1475 endpoint: ep.to_string(),
1476 });
1477 }
1478 // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1479 // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1480 // API v1 HTTPPathMatch.value admission grammar with the
1481 // sibling `:entrada :paths` axis. Until this gate landed
1482 // `target()` only refused the empty string + the missing-
1483 // leading-`/` form; a structurally invalid endpoint
1484 // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1485 // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1486 // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1487 // path-traversal segment, the >1024-byte slug) silently
1488 // passed validate and the failure surfaced at apply time
1489 // as a Cilium policy rejection / silent traffic drop, far
1490 // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1491 // grammar `:entrada :paths` already gates (55410e4), now
1492 // shared with `:contratos :endpoint` through the lifted
1493 // `crate::render::is_gateway_api_http_path` predicate.
1494 if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1495 let (de, para) = self.edge_pair();
1496 return Err(AplicacaoError::ContratoEndpointInvalid {
1497 de,
1498 para,
1499 endpoint: ep.to_string(),
1500 reason,
1501 });
1502 }
1503 return Ok(WitTarget::Http { endpoint: ep });
1504 }
1505 if self.is_pubsub() {
1506 if endpoint.is_some() || slot.is_some() {
1507 let (de, para, wit) = edge();
1508 return Err(AplicacaoError::ContratoWrongTarget {
1509 de,
1510 para,
1511 wit,
1512 expected: WitTarget::PUBSUB_FIELD_NAME,
1513 });
1514 }
1515 let s = subject.ok_or_else(|| {
1516 let (de, para, wit) = edge();
1517 AplicacaoError::ContratoMissingTarget {
1518 de,
1519 para,
1520 wit,
1521 expected: WitTarget::PUBSUB_FIELD_NAME,
1522 }
1523 })?;
1524 if s.is_empty() {
1525 let (de, para) = self.edge_pair();
1526 return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1527 }
1528 // The `:subject` lands at runtime as the NATS subject the
1529 // producer publishes to and the consumer subscribes from.
1530 // Until this gate landed `target()` only refused the
1531 // empty string; a structurally invalid subject
1532 // (`"foo..bar"` — empty token between separators,
1533 // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1534 // server's subject parser rejects, `"foo bar"` —
1535 // un-percent-encoded whitespace, `"foo.café"` —
1536 // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1537 // empty leading/trailing tokens, the >256-byte
1538 // paste-from-binary slug) silently passed validate and
1539 // the failure surfaced at runtime as a NATS server-side
1540 // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1541 // a silent message drop, far from the source caixa.lisp.
1542 // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1543 // trajectory `:contratos :endpoint` (4f0390b) and
1544 // `:contratos :wit` (6226bf4) already gate, now shared
1545 // with `:contratos :subject` through the lifted
1546 // `crate::render::is_nats_subject` predicate.
1547 if let Err(reason) = crate::render::is_nats_subject(s) {
1548 let (de, para) = self.edge_pair();
1549 return Err(AplicacaoError::ContratoSubjectInvalid {
1550 de,
1551 para,
1552 subject: s.to_string(),
1553 reason,
1554 });
1555 }
1556 return Ok(WitTarget::PubSub { subject: s });
1557 }
1558 if self.is_store() {
1559 if endpoint.is_some() || subject.is_some() {
1560 let (de, para, wit) = edge();
1561 return Err(AplicacaoError::ContratoWrongTarget {
1562 de,
1563 para,
1564 wit,
1565 expected: WitTarget::STORE_FIELD_NAME,
1566 });
1567 }
1568 let sl = slot.ok_or_else(|| {
1569 let (de, para, wit) = edge();
1570 AplicacaoError::ContratoMissingTarget {
1571 de,
1572 para,
1573 wit,
1574 expected: WitTarget::STORE_FIELD_NAME,
1575 }
1576 })?;
1577 if sl.is_empty() {
1578 let (de, para) = self.edge_pair();
1579 return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1580 }
1581 // Value-shape gate on the third (and last) typed payload
1582 // axis the `WitContract::target` dispatch carries — the
1583 // peer of [`crate::render::is_gateway_api_http_path`] for
1584 // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1585 // for `:subject` (63e18a0). Until this gate landed
1586 // `target()` only refused the empty string; a structurally
1587 // invalid slot (`"check out/$order"` — un-percent-encoded
1588 // whitespace whose runtime behavior varies unpredictably
1589 // across kv backends, `"checkout/\x01order"` — control
1590 // character that Redis admits but corrupts on next read
1591 // and DynamoDB rejects outright, `"chéckout/$order"` —
1592 // un-percent-encoded non-ASCII byte each backend re-encodes
1593 // differently, `"checkout\n/$order"` — embedded newline,
1594 // the 513-byte paste-from-binary slug) silently passed
1595 // validate and surfaced at runtime as a per-backend kv
1596 // write rejection (DynamoDB / etcd) or as a silent
1597 // next-read corruption (Redis-via-RESP3), far from the
1598 // source caixa.lisp with no field naming which `:contratos`
1599 // edge carried the typo. The lifted predicate makes the
1600 // kv-backend intersection-floor a substrate-level
1601 // invariant at validate time, not a runtime "this passed
1602 // validate but the kv backend rejected on first write"
1603 // surprise — closes the typed payload-axis value-shape
1604 // trajectory across all three legs of the four
1605 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1606 // that caixa-mesh + the future kv emitters land in.
1607 if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1608 let (de, para) = self.edge_pair();
1609 return Err(AplicacaoError::ContratoSlotInvalid {
1610 de,
1611 para,
1612 slot: sl.to_string(),
1613 reason,
1614 });
1615 }
1616 return Ok(WitTarget::Store { slot: sl });
1617 }
1618
1619 // Unrecognized WIT world — must not carry any payload target.
1620 if endpoint.is_some() || subject.is_some() || slot.is_some() {
1621 let (de, para, wit) = edge();
1622 return Err(AplicacaoError::ContratoWrongTarget {
1623 de,
1624 para,
1625 wit,
1626 expected: WitTarget::CAPABILITY_EXPECTED,
1627 });
1628 }
1629 Ok(WitTarget::Capability)
1630 }
1631
1632 /// Substrate-canonical post-validation projection of the typed
1633 /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1634 /// downstream of an [`AplicacaoSpec`] that has already crossed the
1635 /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1636 /// [`typed_view`]-shaped entry point that composes `validate` into
1637 /// the projection) reaches through when it needs the typed
1638 /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1639 /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1640 /// coherence for every `:contratos` entry. The peer accessor to the
1641 /// [`Self::target`] `Result`-returning validator on the same
1642 /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1643 /// pre-validation validator that computes the projection *and* raises
1644 /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1645 /// (`:wit`, payload) mismatch; this method is the post-validation
1646 /// projection every downstream consumer reaches through once the
1647 /// pre-validation gate has succeeded.
1648 ///
1649 /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1650 ///
1651 /// Prior to this lift the "call `.target()` then `.expect(…)` with
1652 /// the same message" pattern sat inline at two production sites with
1653 /// no compile-time link between them: the
1654 /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1655 /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1656 /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1657 /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1658 /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1659 /// (`c.target().expect("validated by typed_view").graph_label()`),
1660 /// each open-coding the same `.target().expect("validated by
1661 /// typed_view")` pair with the message spelled twice. A future
1662 /// vocabulary shift on the panic-message axis (a tightening from
1663 /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1664 /// validate"` as the substrate's validator entry-point vocabulary
1665 /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1666 /// panic to a `debug_assert` under a `--release` build profile) would
1667 /// have had to be threaded through both open-coded call sites in
1668 /// lockstep or one consumer would silently disagree with the peer on
1669 /// which invariant the panic message names. Same "same shape written
1670 /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1671 /// discipline the sibling [`Self::edge_pair`] /
1672 /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1673 /// lifts already establish on the paired composite-projection axis;
1674 /// this lift extends it onto the post-validation typed-view axis.
1675 ///
1676 /// Every future downstream consumer of the projected typed view
1677 /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1678 /// CR materializer's per-edge admission webhook, the future
1679 /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1680 /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1681 /// resolver, the future `feira app graph --l7` / `--pubsub` /
1682 /// `--kv` per-shape column emitters) reaches through this one typed
1683 /// dispatch on the substrate primitive rather than an open-coded
1684 /// per-consumer `.target().expect(…)` pair with the message
1685 /// re-inlined. The invariant the accessor's panic path pins — "this
1686 /// call is only reachable after [`AplicacaoSpec::validate`] has
1687 /// succeeded on the containing spec" — is the substrate's answer to
1688 /// give exactly once, at the primitive, not once per consumer.
1689 ///
1690 /// # Panics
1691 ///
1692 /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1693 /// would return an `Err` — i.e. if this contract's
1694 /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1695 /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1696 /// this accessor only from a code path that has already reached the
1697 /// containing [`AplicacaoSpec`] through a validating entry-point
1698 /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1699 /// [`typed_view`] compose, the future M4 CR admission webhook's
1700 /// per-CR validate). Use [`Self::target`] instead on any pre-
1701 /// validation code path.
1702 ///
1703 /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1704 #[must_use]
1705 pub fn target_projected(&self) -> WitTarget<'_> {
1706 self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1707 }
1708
1709 /// Canonical panic message the [`Self::target_projected`]
1710 /// post-validation projection accessor threads through when the
1711 /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1712 /// has succeeded" precondition. Lifted as a `pub const` on the
1713 /// [`WitContract`] surface so the byte-string lives in one place
1714 /// across the substrate — the [`Self::target_projected`] method
1715 /// body, the two prior production call sites' comments now naming
1716 /// the const, and every future consumer that must format-match the
1717 /// panic-message shape (a future test suite that asserts the panic-
1718 /// message byte-string across a fuzzed invalid-contract corpus,
1719 /// a future custom-panic hook in `caixa-operator` that surfaces the
1720 /// message with per-`:contratos` telemetry, the future admission
1721 /// webhook's per-CR validate-error report) reaches through the same
1722 /// canonical `&'static str`. A future rebrand on the panic-message
1723 /// axis (a tightening from `"validated by typed_view"` to `"validated
1724 /// by AplicacaoSpec::validate"` as the substrate's validator
1725 /// entry-point vocabulary sharpens once caixa-core grows a
1726 /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1727 /// [`typed_view`]) lands at one caixa-core edit rather than a
1728 /// coordinated per-consumer sweep — same "one canonical declaration
1729 /// per axis, next to the accessor that reads it" discipline the peer
1730 /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1731 /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1732 /// const family already establishes on the paired per-consumer-axis
1733 /// diagnostic-scalar surface.
1734 pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1735}
1736
1737/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1738/// gate (see [`AplicacaoSpec::validate`]): every field that
1739/// distinguishes one contract from another, in declaration order
1740/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1741/// with equal [`ContratoIdentity`]s are the same typed edge declared
1742/// twice — the graph-edge analogue of duplicate `:membros` /
1743/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1744/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1745/// clippy's `type_complexity` lint (and so a future axis added to
1746/// `WitContract` is one alias edit, not a coordinated rewrite of
1747/// every set instantiation).
1748pub type ContratoIdentity<'a> = (
1749 &'a str,
1750 &'a str,
1751 &'a str,
1752 Option<&'a str>,
1753 Option<&'a str>,
1754 Option<&'a str>,
1755);
1756
1757/// Typed view of a [`WitContract`]'s payload target. Each variant
1758/// carries the field its WIT shape requires; constructing a `Http`
1759/// view without an endpoint is impossible by the type system.
1760///
1761/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1762/// instead of probing `Option<String>` fields one by one — the
1763/// "which payload field is set?" question is answered once, at
1764/// validation time.
1765#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1766pub enum WitTarget<'a> {
1767 /// HTTP-shaped WIT world. Carries the configured request path.
1768 Http { endpoint: &'a str },
1769 /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1770 ///
1771 /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1772 /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1773 /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1774 /// method name byte-identical to the sibling
1775 /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1776 /// arm-discriminator that routes through
1777 /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1778 /// through `matches!` on the variant), so the two arm-discriminator
1779 /// axes — target-side variant-arm and shape-side ref-prefix — reach
1780 /// every downstream consumer through the same `is_pubsub()` name.
1781 #[is_variant(name = "pubsub")]
1782 PubSub { subject: &'a str },
1783 /// Key-value-shaped WIT world. Carries the slot template.
1784 Store { slot: &'a str },
1785 /// A typed capability edge with no payload selector — the WIT
1786 /// world stands on its own (rare; reserved for plain capability
1787 /// imports or M4-and-later WIT worlds we haven't shaped yet).
1788 Capability,
1789}
1790
1791impl<'a> WitTarget<'a> {
1792 /// Canonical author-facing `:contratos` payload field name for the
1793 /// HTTP-shaped arm — the `expected: &'static str` scalar the
1794 /// [`AplicacaoError::ContratoMissingTarget`] /
1795 /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1796 /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1797 /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1798 /// the `feira app graph` verb prints. Peer of
1799 /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1800 /// on the payload-field-name axis; declared as a peer const next
1801 /// to the [`WitTarget::Http`] variant so a future rename on the
1802 /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1803 /// :endpoint …)))` field lands in exactly one place, not scattered
1804 /// across the [`WitContract::target`] gate's six `expected:`
1805 /// literals, the label template, and every downstream consumer
1806 /// that prints a per-arm prefix. Same trajectory as the peer
1807 /// [`WitTarget::label`] lift (174e96a): a single source of truth
1808 /// for the arm's shape, next to the variant declaration.
1809 pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1810 /// Canonical author-facing `:contratos` payload field name for the
1811 /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1812 /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1813 /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1814 pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1815 /// Canonical author-facing `:contratos` payload field name for the
1816 /// key/value-store-shaped arm. Peer of
1817 /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1818 /// on the payload-field-name axis; see
1819 /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1820 pub const STORE_FIELD_NAME: &'static str = "slot";
1821
1822 /// Canonical stable human-readable label the payload-less
1823 /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1824 /// the byte-string every consumer that formats a payload-less
1825 /// typed capability edge as text lands on (the
1826 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1827 /// naming which identical edge was declared twice, the future
1828 /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1829 /// policy resolver's audit view, the operator's mesh-graph audit).
1830 /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1831 /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1832 /// author-facing label-scalar consts — the same
1833 /// "one canonical declaration per arm, next to the variant, so a
1834 /// future rename lands in one place" discipline extended to the
1835 /// payload-less arm. Until this lift landed the byte-string sat
1836 /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1837 /// match arm, once in the pin test asserting the label's
1838 /// [`WitTarget::Capability`] output — with no compile-time link
1839 /// between the two: a rebrand on either side (an operator-facing
1840 /// vocabulary shift, a per-consumer disambiguation like
1841 /// `"(capability — no payload; typed edge only)"`) would silently
1842 /// desynchronize until a downstream consumer surfaced the drift at
1843 /// runtime.
1844 pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1845
1846 /// Canonical `expected:` scalar the
1847 /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1848 /// through for the payload-less [`WitTarget::Capability`] arm — the
1849 /// byte-string authors read as "this WIT world's shape is not one
1850 /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1851 /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1852 /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1853 /// [`Self::STORE_FIELD_NAME`] consts on the
1854 /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1855 /// same "which payload field name goes in the diagnostic" dispatch
1856 /// the three payload-arm consts cover, extended to the payload-less
1857 /// arm. Until this lift landed the byte-string sat twice — once
1858 /// inline in the [`Self::target`] Capability-arm rejection at the
1859 /// production dispatch, once in the pin test asserting the
1860 /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1861 /// no compile-time link between the two: a rebrand on either side
1862 /// (an author-facing vocabulary shift to `"capability"` /
1863 /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1864 /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1865 /// [`WitTarget::Capability`] into per-shape peers) would silently
1866 /// desynchronize until a downstream consumer surfaced the drift at
1867 /// runtime. Same "one canonical declaration per arm, next to the
1868 /// variant, so a future rename lands in one place" discipline the
1869 /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1870 /// established for the payload-less arm's human-readable label
1871 /// axis; this lift extends it onto the peer diagnostic-scalar axis
1872 /// so both halves of the "how does the Capability arm surface at
1873 /// its two consumer axes (human-readable label, wrong-target
1874 /// diagnostic)" pipeline route through peer consts declared next
1875 /// to the variant.
1876 ///
1877 /// Pairwise-distinctness against the three payload-arm scalars
1878 /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1879 /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1880 /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1881 /// test — the 4-way closure of the 3-way
1882 /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1883 /// the `ContratoWrongTarget::expected` axis, matching the peer
1884 /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1885 /// scalar-value distinctness discipline the sibling M3 typed-enum
1886 /// discriminator axis already carries.
1887 pub const CAPABILITY_EXPECTED: &'static str = "none";
1888
1889 /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1890 /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1891 /// as under [`Self::graph_label`] — the sibling
1892 /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1893 /// payload-column axis (the graph verb spells payload-less as
1894 /// `(capability-only)`, distinct from the duplicate-`:contratos`
1895 /// diagnostic's `(capability — no payload)` on the human-readable
1896 /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1897 /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1898 /// family — extends the "one canonical declaration per arm, next to
1899 /// the variant, so a future rename lands in one place" discipline
1900 /// onto the third payload-less-arm consumer axis (`feira app graph`
1901 /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1902 /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1903 /// axis).
1904 ///
1905 /// Until this lift landed the byte-string sat inline in
1906 /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1907 /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1908 /// `"(capability-only)".to_string()` literal, with no compile-time link
1909 /// back to the [`WitTarget::Capability`] variant declaration nor to
1910 /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1911 /// peer consts already carrying the "one canonical declaration per
1912 /// payload-less-arm consumer axis" discipline. A rebrand on either
1913 /// side (the graph verb's operator-facing vocabulary tightening from
1914 /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1915 /// the WIT registry vocabulary sharpens, an M4 split of
1916 /// [`Self::Capability`] into per-shape peers) would silently
1917 /// desynchronize the graph-verb byte-string from the paired
1918 /// per-arm-adjacent const and land two spellings of the same axis in
1919 /// two spots.
1920 pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1921
1922 /// The `(author-facing field name, payload)` pair this typed target
1923 /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1924 /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1925 /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1926 /// [`Self::Store`], `None` for the payload-less
1927 /// [`Self::Capability`] arm.
1928 ///
1929 /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1930 /// (formats `":{field} {payload:?}"` on `Some`, falls to
1931 /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1932 /// (returns the first component) route through, so a future
1933 /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1934 /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1935 /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1936 /// exactly one new match-arm here (a compile-time exhaustiveness
1937 /// error otherwise), not a coordinated three-way rewrite of the
1938 /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1939 /// + every downstream consumer that reaches for the pair.
1940 ///
1941 /// Until this lift landed the three payload arms sat in
1942 /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1943 /// invocations (one per variant, each hand-quoting the paired
1944 /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1945 /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1946 /// "same shape, written N times" duplication THEORY.md §I.3.5
1947 /// ("Generation first, composition second, hand-authoring last;
1948 /// the duplication budget is zero") promotes to a build-time
1949 /// concern, with each per-arm site paired to its own const with no
1950 /// compile-time link between the format template and the arm's
1951 /// payload extraction.
1952 #[must_use]
1953 pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1954 match *self {
1955 WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1956 WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1957 WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1958 WitTarget::Capability => None,
1959 }
1960 }
1961
1962 /// The canonical author-facing `:contratos` payload field name
1963 /// this typed target arm carries (`Http` → `Some("endpoint")`,
1964 /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1965 /// `None` for the payload-less `Capability` arm.
1966 ///
1967 /// Routes through [`Self::payload_pair`] — the single 4-arm
1968 /// dispatch [`Self::label`] also reads — so a future variant
1969 /// addition is one match-arm edit at [`Self::payload_pair`], not a
1970 /// per-consumer rewrite. Same "exhaustive-match at one canonical
1971 /// dispatch, thin projections at each consumer" trajectory the
1972 /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1973 /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1974 #[must_use]
1975 pub const fn field_name(&self) -> Option<&'static str> {
1976 match self.payload_pair() {
1977 Some((f, _)) => Some(f),
1978 None => None,
1979 }
1980 }
1981
1982 /// The underlying scalar the payload-carrying arm carries — the
1983 /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1984 /// subject ([`Self::PubSub`] `:subject`), or slot template
1985 /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1986 /// `&'a str` storage — or `None` on the payload-less
1987 /// [`Self::Capability`] arm.
1988 ///
1989 /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1990 /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1991 /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1992 /// the paired sub-selector axis. Both per-half accessors read from
1993 /// one authoritative match, so a future [`WitTarget`] variant
1994 /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1995 /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1996 /// on [`Self::payload_pair`] and both per-half projections + every
1997 /// downstream consumer picks the new arm up by construction — no
1998 /// coordinated N-way rewrite across the paired accessor dispatches,
1999 /// the [`Self::label`] / [`Self::graph_label`] format templates,
2000 /// and every future WIT-registry-shaped consumer.
2001 ///
2002 /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
2003 /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
2004 /// controller `spec.ref.<field>` axis — same "one paired dispatch,
2005 /// both per-half projections as thin readers, every downstream
2006 /// consumer through the same match" discipline extended onto the
2007 /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
2008 /// gap between the two paired-dispatch surfaces: the peer
2009 /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
2010 /// the first-component projection until this lift; the second-
2011 /// component sibling now sits alongside so both halves reach every
2012 /// future consumer through the same substrate-primitive dispatch.
2013 ///
2014 /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
2015 #[must_use]
2016 pub const fn payload(&self) -> Option<&'a str> {
2017 match self.payload_pair() {
2018 Some((_, p)) => Some(p),
2019 None => None,
2020 }
2021 }
2022
2023 /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
2024 /// consumer that fans on the L7-HTTP-shaped payload keys off —
2025 /// returns the [`Self::Http`]-arm's author-declared request path
2026 /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
2027 /// projected target is [`Self::Http { endpoint }`], `None` on the
2028 /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
2029 /// [`Self::Capability`], each of which carries no HTTP endpoint by
2030 /// definition).
2031 ///
2032 /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
2033 /// `path:` rule payload every substrate-side L7-introspecting
2034 /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
2035 /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
2036 /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
2037 /// on the L7 introspection branch; every peer WIT shape stays
2038 /// L4-only because Cilium can't introspect NATS / key-value / plain
2039 /// capability edges), and every future L7-introspecting consumer
2040 /// of the projected target's HTTP endpoint (the future M4
2041 /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
2042 /// materializer's per-edge L7 admission-webhook overlay, the
2043 /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
2044 /// path bucket-key resolver, the future per-`:contratos`-edge
2045 /// mTLS-required overlay's HTTP-shape scope filter, the future
2046 /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
2047 /// through the same typed dispatch.
2048 ///
2049 /// Prior to this lift the sole production consumer of the projected-
2050 /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
2051 /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
2052 /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
2053 /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
2054 /// }`) — reached the payload through a raw per-arm `if let` pattern-
2055 /// match that expressed no compile-time link back to the substrate
2056 /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
2057 /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
2058 /// scalar accessor on the peer per-`:contratos` raw-field axis but
2059 /// with no post-projection peer on the typed-view surface. A future
2060 /// [`WitTarget`] variant addition that splits [`Self::Http`] into
2061 /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
2062 /// gRPC-shaped worlds per this enum's own docstring at
2063 /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
2064 /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
2065 /// would have had to be threaded through the caixa-mesh L7 emit
2066 /// branch's raw `if let` in lockstep — either coalescing the two
2067 /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
2068 /// emit path per-arm — with no substrate-primitive dispatch making
2069 /// the "which arms count as L7-HTTP-shaped for path-emission
2070 /// purposes" question the substrate's answer to give. Lifting the
2071 /// resolution to a typed method on the substrate primitive means
2072 /// every downstream L7-HTTP-facing consumer of the Aplicacao's
2073 /// projected-target HTTP endpoint reaches for exactly one typed
2074 /// dispatch — the resolver's accept-set migrates as a unit on any
2075 /// future arm-family widening, and the caixa-mesh L7 emit branch
2076 /// reads through the same substrate primitive.
2077 ///
2078 /// Peer of the sibling pre-projection [`WitContract::endpoint`]
2079 /// (7020470) `Option<&str>` scalar accessor on the raw
2080 /// `:contratos :endpoint` field-access axis — same "one typed
2081 /// dispatch on the substrate primitive, thin projections at each
2082 /// consumer" discipline extended onto the peer post-projection typed-
2083 /// view surface (the [`WitContract::endpoint`] pre-projection
2084 /// accessor returns `Some` for any author-declared `:endpoint`
2085 /// value regardless of the paired `:wit` world's HTTP-shape
2086 /// classification — the raw slot before validation crosses it —
2087 /// while this post-projection [`Self::http_endpoint`] accessor
2088 /// returns `Some` iff the target has been projected onto the
2089 /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
2090 /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
2091 /// coherence; the two accessors close the pre-projection /
2092 /// post-projection pair on the HTTP-endpoint axis). Sibling of the
2093 /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
2094 /// the three payload-carrying arms) — extends the per-arm
2095 /// projection family onto the [`Self::Http`] specialization axis
2096 /// that the pan-arm accessor's shape blends into a single arm-
2097 /// agnostic view; paired with [`Self::pubsub_subject`] /
2098 /// [`Self::store_slot`] on the sibling per-arm axes so every
2099 /// per-payload-arm shape carries a named post-projection accessor
2100 /// on the same shape as `http_endpoint`, closing the per-arm-shape
2101 /// accept-set the substrate primitive owns.
2102 #[must_use]
2103 pub const fn http_endpoint(&self) -> Option<&'a str> {
2104 match *self {
2105 WitTarget::Http { endpoint } => Some(endpoint),
2106 WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2107 }
2108 }
2109
2110 /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
2111 /// consumer that fans on the pub-sub-shaped payload keys off —
2112 /// returns the [`Self::PubSub`]-arm's author-declared event-stream
2113 /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
2114 /// the projected target is [`Self::PubSub { subject }`], `None` on
2115 /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
2116 /// [`Self::Capability`], each of which carries no NATS-shaped
2117 /// subject by definition).
2118 ///
2119 /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
2120 /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
2121 /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
2122 /// CR materializer's `spec.subjects[]` projection, the future
2123 /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
2124 /// bucket-key resolver, the future `feira app graph --pubsub`
2125 /// per-Aplicacao subject column, any future substrate-lifted
2126 /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2127 /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2128 /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2129 /// future pub-sub-shape consumer reaches for the same typed
2130 /// dispatch this accessor exposes so the "which arm carries the
2131 /// subject scalar?" answer lives at one caixa-core edit rather
2132 /// than open-coded across per-consumer `if let WitTarget::PubSub
2133 /// { subject } = c.target()…` pattern-matches.
2134 ///
2135 /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2136 /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2137 /// the pre-projection [`WitContract::subject`] scalar accessor on
2138 /// the raw `:contratos :subject` field-access axis — same "one
2139 /// typed dispatch on the substrate primitive, thin projections at
2140 /// each consumer" discipline extended onto the per-arm pub-sub
2141 /// post-projection axis. The pre-projection accessor returns
2142 /// `Some` for any author-declared `:subject` value regardless of
2143 /// the paired `:wit` world's pub-sub-shape classification (the raw
2144 /// slot before validation crosses it); this post-projection
2145 /// accessor returns `Some` iff the target has been projected onto
2146 /// the [`Self::PubSub`] arm, i.e. only after the
2147 /// [`WitContract::target`] gate has admitted the
2148 /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2149 /// the pre-/post-projection pair on the pub-sub-subject axis to
2150 /// match the pair the [`WitContract::endpoint`] +
2151 /// [`Self::http_endpoint`] surfaces already close on the peer
2152 /// HTTP-endpoint axis.
2153 ///
2154 /// Sibling of the unified pan-arm [`Self::payload`]
2155 /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2156 /// extends the per-arm projection family onto the [`Self::PubSub`]
2157 /// specialization axis that the pan-arm accessor's shape blends
2158 /// into a single arm-agnostic view; the pair
2159 /// (`pubsub_subject`, `store_slot`) closes the trio
2160 /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2161 /// payload arm now carries its own per-arm-shape post-projection
2162 /// accessor.
2163 #[must_use]
2164 pub const fn pubsub_subject(&self) -> Option<&'a str> {
2165 match *self {
2166 WitTarget::PubSub { subject } => Some(subject),
2167 WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2168 }
2169 }
2170
2171 /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2172 /// every consumer that fans on the store-shaped payload keys off —
2173 /// returns the [`Self::Store`]-arm's author-declared slot template
2174 /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2175 /// projected target is [`Self::Store { slot }`], `None` on the
2176 /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2177 /// [`Self::Capability`], each of which carries no
2178 /// key/value-store slot by definition).
2179 ///
2180 /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2181 /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2182 /// every future substrate-side store-introspecting per-`(:de,
2183 /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2184 /// namespace / prefix reconciler's per-slot projection, the future
2185 /// per-store-backend routing overlay's slot-shape gate, the future
2186 /// `feira app graph --store` per-Aplicacao slot column, any future
2187 /// substrate-lifted store-shape emitter that reads a projected
2188 /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2189 /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2190 /// Every future store-shape consumer reaches for the same typed
2191 /// dispatch this accessor exposes so the "which arm carries the
2192 /// slot scalar?" answer lives at one caixa-core edit rather than
2193 /// open-coded across per-consumer
2194 /// `if let WitTarget::Store { slot } = c.target()…`
2195 /// pattern-matches.
2196 ///
2197 /// Peer of the sibling [`Self::http_endpoint`] +
2198 /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2199 /// axes and of the pre-projection [`WitContract::slot`] scalar
2200 /// accessor on the raw `:contratos :slot` field-access axis — same
2201 /// "one typed dispatch on the substrate primitive, thin projections
2202 /// at each consumer" discipline extended onto the per-arm store
2203 /// post-projection axis. Closes the pre-/post-projection pair on
2204 /// the store-slot axis to match the pairs the
2205 /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2206 /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2207 /// already close on the peer HTTP-endpoint and pub-sub-subject
2208 /// axes; the substrate-side pre-/post-projection accessor family
2209 /// now spans all three payload arms as a matched trio, so any
2210 /// future arm-shape widening (a `Rest`/`Grpc` split of
2211 /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2212 /// lands one accessor without threading through the sibling
2213 /// pre-projection or the peer per-arm post-projection surfaces a
2214 /// compile-time exhaustiveness error at the substrate primitive,
2215 /// not a silent per-consumer split at renderer emit time.
2216 ///
2217 /// Sibling of the unified pan-arm [`Self::payload`]
2218 /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2219 /// closes the per-arm projection family onto the [`Self::Store`]
2220 /// specialization axis that the pan-arm accessor's shape blends
2221 /// into a single arm-agnostic view. The trio
2222 /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2223 /// pan-arm accept-set on every payload-carrying arm: exactly one
2224 /// per-arm accessor returns `Some(payload)` and the two peers
2225 /// return `None`, and every payload-less [`Self::Capability`]
2226 /// input returns `None` on all three — the partition the sibling
2227 /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2228 /// pin locks in load-bearing.
2229 #[must_use]
2230 pub const fn store_slot(&self) -> Option<&'a str> {
2231 match *self {
2232 WitTarget::Store { slot } => Some(slot),
2233 WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2234 }
2235 }
2236
2237 /// Render this typed target as a stable human-readable label
2238 /// (`:endpoint "/charge"`, `:subject "events.x"`,
2239 /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2240 /// the WIT world is a pure capability edge).
2241 ///
2242 /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2243 /// gate so the diagnostic names *which* identical edge was
2244 /// declared twice (not just which `(de, para, wit)` triple).
2245 /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2246 /// on the payload-carrying arms (`Some((field, payload)) →
2247 /// format!(":{field} {payload:?}")`) and through the lifted
2248 /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2249 /// [`Self::Capability`] arm — so a future variant addition (the
2250 /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2251 /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2252 /// `Queue`-shaped peer) becomes a single new match-arm on
2253 /// [`Self::payload_pair`] rather than a rewrite of this template
2254 /// (and every downstream consumer that reaches for the label
2255 /// shape: the per-edge policy resolver in M4, the `feira app
2256 /// graph` view, the operator's mesh-graph audit). Until this
2257 /// lift landed the three payload arms carried three near-identical
2258 /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2259 /// [`Self::Capability`] arm carried the payload-less byte-string
2260 /// twice (once inline here, once in the pin test) — closing the
2261 /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2262 /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2263 /// / 4a1e490) peer-const lifts already established for the
2264 /// payload-carrying arms.
2265 #[must_use]
2266 pub fn label(&self) -> String {
2267 match self.payload_pair() {
2268 Some((field, payload)) => format!(":{field} {payload:?}"),
2269 None => Self::CAPABILITY_LABEL.to_string(),
2270 }
2271 }
2272
2273 /// Render this typed target as the `feira app graph` per-`:contratos`
2274 /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2275 /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2276 /// payload-less arm).
2277 ///
2278 /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2279 /// on the payload-carrying arms (`Some((field, payload)) →
2280 /// format!("{field}={payload}")`) and through the lifted
2281 /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2282 /// [`Self::Capability`] arm — so a future variant addition
2283 /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2284 /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2285 /// `Queue`-shaped peer) becomes one match-arm edit at
2286 /// [`Self::payload_pair`], propagating through this graph-verb
2287 /// projection at zero call-site cost, sibling to the peer
2288 /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2289 /// same 4-arm dispatch.
2290 ///
2291 /// Until this lift landed the [`caixa-feira`]
2292 /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2293 /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2294 /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2295 /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2296 /// `format!("{}={endpoint}", ...)` template and hard-coding
2297 /// `"(capability-only)"` as a fifth payload-less scalar with no link
2298 /// back to the paired [`WitTarget::Capability`] variant declaration.
2299 /// A future variant addition would have had to be threaded through
2300 /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2301 /// verb's inline match in lockstep or the two projections would
2302 /// silently disagree on the arm-set the graph verb prints — the
2303 /// duplicate-`:contratos` diagnostic reading one shape while the
2304 /// graph verb's payload column silently dropped the new arm to
2305 /// `(capability-only)`. Lifting the graph-verb projection onto the
2306 /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2307 /// the axis: both projections migrate as a unit.
2308 ///
2309 /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2310 /// quoting) shape is graph-verb-canonical — distinct from the
2311 /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2312 /// duplicate-`:contratos` diagnostic seeds (see
2313 /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2314 /// on the payload-less axis for the paired distinction).
2315 #[must_use]
2316 pub fn graph_label(&self) -> String {
2317 match self.payload_pair() {
2318 Some((field, payload)) => format!("{field}={payload}"),
2319 None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2320 }
2321 }
2322}
2323
2324/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2325/// pretty-printed byte-string every consumer that formats a typed
2326/// payload target as user-facing text lands on (the
2327/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2328/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2329/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2330/// graph` per-`:contratos`-edge payload column that reaches the graph
2331/// verb through `format!("{target}")`, the future M4 per-edge policy
2332/// resolver's per-edge audit-log line, the operator's mesh-graph
2333/// per-edge inspection view) reaches for the same lifted
2334/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2335/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2336/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2337/// routes through — extending the three-path-convergence
2338/// (`Debug` for structural inspection, `Display` for user-facing text,
2339/// per-arm typed accessor for the canonical byte-string) discipline the
2340/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2341/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2342/// onto the fourth (and only remaining) typed-shape-discriminator axis
2343/// on the caixa surface.
2344///
2345/// Pre-lift the two paths were structurally independent — every consumer
2346/// reaching for a payload byte-string past the [`WitTarget::label`]
2347/// helper had to pick between three paths ([`WitTarget::label`],
2348/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2349/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2350/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2351/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2352/// that reached for `format!("{target}")` — the canonical shape every
2353/// user-facing pretty-print site on the sibling typed-enum axes already
2354/// uses — would silently land on the `Debug` derive's structural output
2355/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2356/// than the `label()` helper's stable byte-string (`:endpoint
2357/// "/charge"` — the author-facing `:contratos` keyword form) the
2358/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2359/// already threads through. The two spellings would diverge silently in
2360/// every downstream diagnostic / graph / audit line reached through
2361/// `format!` rather than through the `label()` helper. Routing
2362/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2363/// path: every `format!("{v}")` call reaches the same
2364/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2365/// and the duplicate-`:contratos` gate already route through, so a
2366/// future variant addition (the M4-and-later per-edge WIT registry may
2367/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2368/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2369/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2370/// match — rather than fanning out through hand-rolled per-arm
2371/// [`std::fmt::Display`] arms.
2372///
2373/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2374/// is the typed view returned by [`WitContract::target`], not a
2375/// closed-set discriminator enum with a gen-platform Discriminant
2376/// registration, so the `Debug` derive's structural output (which every
2377/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2378/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2379/// shape for structural inspection; `Display` (via `label`) reveals the
2380/// stable author-facing payload projection.
2381///
2382/// Pin tests
2383/// [`tests::wit_target_display_routes_through_label_helper`] and
2384/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2385/// assert the two paths agree byte-for-byte on every variant, so a
2386/// future variant addition or `label()` reimplementation that hand-rolls
2387/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2388/// build error visible at caixa-core test time, not a silent
2389/// per-consumer dispatch miss at diagnostic / audit / graph time.
2390impl std::fmt::Display for WitTarget<'_> {
2391 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2392 f.write_str(&self.label())
2393 }
2394}
2395
2396// ── one Aplicacao member ─────────────────────────────────────────────
2397
2398/// A Servico participating in the Aplicacao. Same shape as
2399/// `crate::supervisor::ChildSpec` but without a restart policy —
2400/// supervision is per-Servico (each member has its own
2401/// `:supervisor`), the Aplicacao orchestrates *placement*.
2402#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2403#[serde(rename_all = "camelCase")]
2404pub struct Membro {
2405 /// Member caixa's `:nome`. Resolves through the same dep
2406 /// resolution path as `crate::dep::Dep`.
2407 pub caixa: String,
2408
2409 /// Semver constraint.
2410 pub versao: String,
2411}
2412
2413impl Membro {
2414 /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2415 /// accessor every consumer that reads the member's Servico identity
2416 /// keys off — returns the author-declared `:membros :caixa`
2417 /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2418 /// own [`String`] storage.
2419 ///
2420 /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2421 /// participating in the Aplicacao — validated by
2422 /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2423 /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2424 /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2425 /// [`validate_no_self_membership`]) — and every downstream consumer
2426 /// that fans on the member's identity keys off this scalar (the
2427 /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2428 /// lookup, the per-`:membros` duplicate gate's dedup key, the
2429 /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2430 /// identity, the self-membership gate, the
2431 /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2432 /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2433 /// CR materializer's per-member resolver).
2434 ///
2435 /// Prior to this lift the `.caixa` byte-string was read inline at
2436 /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2437 /// set collector at
2438 /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2439 /// [`validate_membros`] validation-side member-caixa gate at
2440 /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2441 /// per-member duplicate-gate dedup key at
2442 /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2443 /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2444 /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2445 /// [`validate_no_self_membership`] self-loop gate at
2446 /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2447 /// expressed no compile-time link back to the typed slot. Every
2448 /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2449 /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2450 /// `name:` axis, so a future extension of the `:membros :caixa`
2451 /// axis to a richer author surface — a per-cluster alias table the
2452 /// operator pins through a future `:placement`-scoped slot, a
2453 /// namespace-qualified rewrite the M4 CR materializer applies
2454 /// per-CR, a per-member overlay from the future `:membros
2455 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2456 /// acknowledges — would have had to be threaded through every
2457 /// open-coded copy in lockstep or one consumer would silently
2458 /// disagree with the peers on which caixa a given member resolves
2459 /// to. A member-set lookup that treated the name as `"cart"` while
2460 /// the peer adjacency map treated it as `"tenant-a/cart"` would
2461 /// silently split the `:contratos` membership-lookup diagnostic from
2462 /// the cycle-detector's node identity — a two-consumer split at the
2463 /// validator far from the source `caixa.lisp` with no field naming
2464 /// the identity-drift root cause. Lifting the resolution rule to a
2465 /// typed method on the substrate primitive means every downstream
2466 /// consumer of the Aplicacao's per-`:membros` identity surface
2467 /// reaches for exactly one typed dispatch — the resolver's
2468 /// accept-set migrates as a unit on any future axis addition.
2469 ///
2470 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2471 /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2472 /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2473 /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2474 /// destination-Servico scalar accessors — same "one typed dispatch
2475 /// on the substrate primitive, thin projections at each consumer"
2476 /// discipline extended onto the per-`:membros` member-caixa `:nome`
2477 /// byte-string axis. Named `nome()` to match the tatara-lisp
2478 /// author-surface term the field's docstring already reaches for
2479 /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2480 /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2481 /// already carries — the accessor's name maps directly onto the
2482 /// canonical caixa-identity vocabulary rather than shadowing the
2483 /// field's storage-side `caixa` label.
2484 #[must_use]
2485 pub const fn nome(&self) -> &str {
2486 self.caixa.as_str()
2487 }
2488
2489 /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2490 /// requirement scalar accessor every consumer that reads the
2491 /// member's version pin keys off — returns the author-declared
2492 /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2493 /// from the typed slot's own [`String`] storage.
2494 ///
2495 /// The `:membros :versao` slot carries the Cargo-shaped semver
2496 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2497 /// pins which release of the member-caixa the Aplicacao composes
2498 /// against — the same requirement grammar the peer `:deps :versao`
2499 /// / `:children :versao` axes carry, resolved through the shared
2500 /// [`crate::render::require_valid_versao_requirement`] cascade and
2501 /// the shared [`crate::version::parse_requirement`] parser. Every
2502 /// downstream consumer that fans on the member's version pin keys
2503 /// off this scalar (the [`validate_membros`] per-member requirement
2504 /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2505 /// …)`, the [`feira app graph`] per-member `println!(" - {} {}",
2506 /// m.nome(), m.versao_requirement())` line, every future per-cluster
2507 /// version-lock overlay the operator pins through a future
2508 /// `:placement`-scoped slot, the future
2509 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2510 /// version resolver, the future `feira app deploy` pipeline's
2511 /// per-member lacre BLAKE3-closure lookup).
2512 ///
2513 /// Prior to this lift the `.versao` byte-string was accessed inline
2514 /// at two `&str`-shaped sites — the [`validate_membros`]
2515 /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2516 /// …)` and the `feira app graph` per-member printer's `println!(
2517 /// " - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2518 /// prior to this lift) — two open-coded field-accesses that expressed
2519 /// no compile-time link back to the typed slot. A future extension of
2520 /// the `:membros :versao` axis to a richer author surface (a
2521 /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2522 /// flow, a lacre-projected concrete-version rewrite the operator
2523 /// materializes at CR-admission time, a future `:membros :versao-lock`
2524 /// per-cluster override slot) would have had to be threaded through
2525 /// every open-coded copy in lockstep or one consumer would silently
2526 /// disagree with the peers on which release constraint a given
2527 /// member resolves to. Lifting the resolution rule to a typed method
2528 /// on the substrate primitive means every downstream requirement-
2529 /// facing consumer reaches for exactly one typed dispatch — the
2530 /// resolver's accept-set migrates as a unit on any future axis
2531 /// addition.
2532 ///
2533 /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2534 /// member-caixa `:nome` scalar accessor — the pair
2535 /// `(nome(), versao_requirement())` jointly projects the
2536 /// `(caixa, versao)` field pair every renderer that fans on
2537 /// per-member identity + version pin keys off, closing the last
2538 /// unlifted per-`:membros` scalar axis so every downstream
2539 /// per-`:membros` reader now routes through a typed dispatch on the
2540 /// substrate primitive. Named `versao_requirement()` rather than
2541 /// `versao()` because the field's storage-side `.versao` label is
2542 /// already the author-surface term (`:versao`); the accessor's name
2543 /// carries the semantic role — the semver *requirement* string the
2544 /// shared [`crate::version::parse_requirement`] entry-point consumes
2545 /// — so a raw field access and a typed dispatch read differently at
2546 /// every consumer site.
2547 ///
2548 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2549 /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2550 /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2551 /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2552 /// destination-Servico scalar accessors — same "one typed dispatch
2553 /// on the substrate primitive, thin projections at each consumer"
2554 /// discipline extended onto the per-`:membros` member-`:versao`
2555 /// semver-requirement byte-string axis.
2556 #[must_use]
2557 pub const fn versao_requirement(&self) -> &str {
2558 self.versao.as_str()
2559 }
2560}
2561
2562// ── mesh-level policies ──────────────────────────────────────────────
2563
2564/// Mesh policies that apply to every `:contratos` edge unless
2565/// overridden per-edge in M4. V0 is a single global policy block.
2566#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2567#[serde(rename_all = "camelCase")]
2568pub struct MeshPolicy {
2569 /// Per-call timeout. Authored as a duration string (`"30s"`).
2570 #[serde(
2571 default,
2572 skip_serializing_if = "Option::is_none",
2573 with = "supervisor::duration_codec"
2574 )]
2575 pub timeout: Option<Duration>,
2576
2577 /// Number of retries on transient failure. None = no retries.
2578 #[serde(default, skip_serializing_if = "Option::is_none")]
2579 pub retries: Option<u32>,
2580
2581 /// Circuit breaker config. Trips after N failures within W
2582 /// duration; closes after a cooldown.
2583 #[serde(default, skip_serializing_if = "Option::is_none")]
2584 pub circuit_breaker: Option<CircuitBreaker>,
2585
2586 /// Whether mTLS is required for every contrato. Default: true
2587 /// (sandboxing-by-default; explicit opt-out only).
2588 #[serde(default, skip_serializing_if = "Option::is_none")]
2589 pub mtls_required: Option<bool>,
2590
2591 /// Token-bucket rate limit. Authored as `"100/s"` or
2592 /// `"5000/m"`; stored as `(rate, window)`.
2593 #[serde(
2594 default,
2595 skip_serializing_if = "Option::is_none",
2596 with = "rate_limit_codec"
2597 )]
2598 pub rate_limit: Option<RateLimit>,
2599}
2600
2601impl MeshPolicy {
2602 /// True when no `:politicas` axis carries a value — every field is
2603 /// `None`. The same emptiness contract every other M2/M3 typed
2604 /// surface carries ([`crate::LimitsSpec::is_empty`],
2605 /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2606 /// typed slot onto a cluster artifact key off this predicate to
2607 /// decide "emit the slot" vs "skip the slot entirely", so an
2608 /// authored-but-unset `:politicas (())` round-trips to a rendered
2609 /// artifact that's structurally identical to one that omits the
2610 /// slot. Lifted as a typed predicate (rather than per-renderer
2611 /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2612 /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2613 /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2614 /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2615 /// not a coordinated rewrite of every consumer that's reaching
2616 /// for the emptiness semantic.
2617 #[must_use]
2618 pub const fn is_empty(&self) -> bool {
2619 self.timeout().is_none()
2620 && self.retries().is_none()
2621 && self.circuit_breaker().is_none()
2622 && self.mtls_required().is_none()
2623 && self.rate_limit().is_none()
2624 }
2625
2626 /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
2627 /// per-call-deadline scalar accessor every consumer of the
2628 /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
2629 /// returns the author-declared `:politicas :timeout` typed
2630 /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
2631 /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
2632 /// is `Copy`, so the accessor returns by value; no borrow of
2633 /// `&self` past the call). `None` when the slot is absent (the
2634 /// "cluster default applies — typically the gateway class's
2635 /// implementation-side per-request wall-clock cap" arm caixa-mesh's
2636 /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
2637 /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
2638 /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
2639 /// round-trips to a rendered `HTTPRoute` structurally identical to
2640 /// one that omits the slot).
2641 ///
2642 /// The `:politicas :timeout` slot carries the "no infinite blocking"
2643 /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
2644 /// the typed slot's `Option<Duration>` accept-set (zero-floor
2645 /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
2646 /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
2647 /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
2648 /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
2649 /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
2650 /// Every downstream consumer that reads the per-call cap keys off
2651 /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2652 /// renderers key off to decide "emit :politicas overlay" vs "skip
2653 /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2654 /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
2655 /// fans the deadline into every rule via
2656 /// [`crate::render::single_field_overlay`], the future M4 per-
2657 /// Aplicacao Gateway API reconciler materialization pass, the
2658 /// future per-`:contratos`-edge timeout-override overlay the
2659 /// MESH-COMPOSITION §III.2 roadmap acknowledges).
2660 ///
2661 /// Prior to this lift the `.timeout` field was accessed inline at
2662 /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
2663 /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
2664 /// …)` call — two open-coded field-accesses that expressed no
2665 /// compile-time link back to the typed slot. A future extension of
2666 /// the `:politicas :timeout` axis to a richer author surface — a
2667 /// per-`:contratos`-edge timeout override the operator pins through
2668 /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
2669 /// roadmap acknowledges, a per-cluster timeout-default overlay the
2670 /// M4 CR materializer resolves per-CR, a split of the single
2671 /// per-call `Duration` into a richer `{request, backendRequest}`
2672 /// pair once the Gateway API's per-rule `timeouts` block grows the
2673 /// upstream-facing backendRequest arm alongside the client-facing
2674 /// request arm — would have had to be threaded through both open-
2675 /// coded copies in lockstep or the emptiness predicate and the
2676 /// caixa-mesh emit path would silently disagree on which per-call
2677 /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
2678 /// whose only axis is a `Some :timeout` would satisfy `is_empty()
2679 /// == false` while the renderer's overlay-emit path silently read
2680 /// a drifted other value, or vice versa: an author's `:timeout
2681 /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
2682 /// the emptiness predicate still classified the policy as non-
2683 /// empty, and every `kubectl -n tatara-system get httproute -o yaml
2684 /// | grep -A2 timeouts` audit would land on a route whose author's
2685 /// typed slot value silently vanished at the renderer layer).
2686 /// Lifting the resolution to a typed method on the substrate
2687 /// primitive means every downstream consumer of the Aplicacao's
2688 /// per-`:politicas` deadline surface reaches for exactly one typed
2689 /// dispatch — the resolver's accept-set migrates as a unit on any
2690 /// future axis addition.
2691 ///
2692 /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
2693 /// family (sibling of the peer per-`:politicas`
2694 /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
2695 /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
2696 /// `Option<bool>` accessor — same "one typed dispatch on the
2697 /// substrate primitive, thin projections at each consumer"
2698 /// discipline extended onto the peer per-`:politicas` typed-
2699 /// [`Duration`] optional-scalar axis; closes the "optional per-slot
2700 /// numeric-Copy-T scalar" projection pattern the sibling
2701 /// `Option<u32>` / `Option<bool>` lifts opened, since every
2702 /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
2703 /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
2704 /// than a scalar). Named `timeout()` to match the storage field's
2705 /// name; the accessor's identity maps onto the canonical MESH-
2706 /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
2707 #[must_use]
2708 pub const fn timeout(&self) -> Option<Duration> {
2709 self.timeout
2710 }
2711
2712 /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
2713 /// retry-budget scalar accessor every consumer of the Aplicacao's
2714 /// Gateway API v1.x per-rule retry-cap keys off — returns the
2715 /// author-declared `:politicas :retries` typed `u32` verbatim as an
2716 /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
2717 /// storage (`Option<u32>` is `Copy`, so the accessor returns by
2718 /// value; no borrow of `&self` past the call). `None` when the slot
2719 /// is absent (the "cluster default applies — typically 'no retries
2720 /// beyond a single dispatch attempt'" arm the caixa-mesh
2721 /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2722 /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2723 /// this predicate too, so an authored-but-unset `:politicas
2724 /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2725 /// identical to one that omits the slot).
2726 ///
2727 /// The `:politicas :retries` slot carries the "transient failure
2728 /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2729 /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2730 /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2731 /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2732 /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2733 /// count scalar the caixa-mesh `retry_overlay` builder writes.
2734 /// Every downstream consumer that reads the retry cap keys off this
2735 /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2736 /// renderers key off to decide "emit :politicas overlay" vs "skip
2737 /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2738 /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2739 /// the value into every rule via [`crate::render::single_field_overlay`],
2740 /// the future M4 per-Aplicacao Gateway API reconciler
2741 /// materialization pass, the future per-`:contratos`-edge retry-
2742 /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2743 /// acknowledges).
2744 ///
2745 /// Prior to this lift the `.retries` field was accessed inline at
2746 /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2747 /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2748 /// …)` call — two open-coded field-accesses that expressed no
2749 /// compile-time link back to the typed slot. A future extension of
2750 /// the `:politicas :retries` axis to a richer author surface — a
2751 /// per-`:contratos`-edge retry override the operator pins through a
2752 /// future `:contratos :retries` slot, a per-cluster retry-default
2753 /// overlay the M4 CR materializer resolves per-CR, a promotion of
2754 /// the plain `u32` attempt-count to a richer `{attempts, codes,
2755 /// backoff}` sub-block once the Gateway API grows the peer
2756 /// `retry.codes` / `retry.backoff` axes — would have had to be
2757 /// threaded through both open-coded copies in lockstep or the
2758 /// emptiness predicate and the caixa-mesh emit path would silently
2759 /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2760 /// (a `:politicas` block whose only axis is a `Some :retries` would
2761 /// satisfy `is_empty() == false` while the renderer's overlay-emit
2762 /// path silently read a drifted other value, or vice versa: an
2763 /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2764 /// block while the emptiness predicate still classified the policy
2765 /// as non-empty). Lifting the resolution to a typed method on the
2766 /// substrate primitive means every downstream consumer of the
2767 /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2768 /// one typed dispatch — the resolver's accept-set migrates as a
2769 /// unit on any future axis addition.
2770 ///
2771 /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2772 /// family (sibling of the peer per-`:politicas`
2773 /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2774 /// same "one typed dispatch on the substrate primitive, thin
2775 /// projections at each consumer" discipline extended onto the
2776 /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2777 /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2778 /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2779 /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2780 /// fold on). Named `retries()` to match the storage field's name;
2781 /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2782 /// §III.2 vocabulary the slot's docstring already carries.
2783 #[must_use]
2784 pub const fn retries(&self) -> Option<u32> {
2785 self.retries
2786 }
2787
2788 /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2789 /// enforcement-toggle scalar accessor every consumer of the
2790 /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2791 /// — returns the author-declared `:politicas :mtls-required` typed
2792 /// bool verbatim as an `Option<bool>`, copied out of the typed
2793 /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2794 /// the accessor returns by value; no borrow of `&self` past the
2795 /// call). `None` when the slot is absent (the "cluster default
2796 /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2797 /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2798 /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2799 /// this predicate too, so an authored-but-unset `:politicas
2800 /// (:mtls-required ())` round-trips to a rendered
2801 /// `CiliumNetworkPolicy` structurally identical to one that omits
2802 /// the slot).
2803 ///
2804 /// The `:politicas :mtls-required` slot carries the "explicit opt-
2805 /// out only, sandboxing-by-default" mTLS-enforcement toggle
2806 /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2807 /// `{None, Some(true), Some(false)}` accept-set maps onto the
2808 /// Cilium `authentication.mode` bijection through
2809 /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2810 /// handshake enforced), `Some(false) → "disabled"` (handshake
2811 /// skipped — the debug-edge opt-out), `None` → omit the block
2812 /// (cluster default applies). Every downstream consumer that
2813 /// reads the toggle keys off this scalar (the
2814 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2815 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2816 /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2817 /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2818 /// ingress rule via [`crate::render::single_field_overlay`], the
2819 /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2820 /// materialization pass, the future per-`:contratos`-edge mTLS
2821 /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2822 ///
2823 /// Prior to this lift the `.mtls_required` field was accessed
2824 /// inline at two sites — [`MeshPolicy::is_empty`]'s
2825 /// `self.mtls_required.is_none()` arm and caixa-mesh's
2826 /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2827 /// two open-coded field-accesses that expressed no compile-time
2828 /// link back to the typed slot. A future extension of the
2829 /// `:politicas :mtls-required` axis to a richer author surface —
2830 /// a per-`:contratos`-edge mTLS override the operator pins through
2831 /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2832 /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2833 /// M4 CR materializer resolves per-CR, a three-valued
2834 /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2835 /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2836 /// would have had to be threaded through both open-coded copies in
2837 /// lockstep or the emptiness predicate and the caixa-mesh emit
2838 /// path would silently disagree on which toggle a given
2839 /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2840 /// axis is a `Some`
2841 /// `:mtls-required` would satisfy `is_empty() == false` while the
2842 /// renderer's overlay-emit path silently read a drifted other
2843 /// value, or vice versa). Lifting the resolution to a typed method
2844 /// on the substrate primitive means every downstream consumer of
2845 /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2846 /// for exactly one typed dispatch — the resolver's accept-set
2847 /// migrates as a unit on any future axis addition.
2848 ///
2849 /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2850 /// family (peer of the sibling per-`:placement`
2851 /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2852 /// same "one typed dispatch on the substrate primitive, thin
2853 /// projections at each consumer" discipline extended onto the
2854 /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2855 /// the "optional per-slot Copy-T scalar" projection pattern the
2856 /// sibling per-`:politicas` `:retries` (Option<u32>) /
2857 /// `:timeout` (Option<Duration>) future lifts fold on). Named
2858 /// `mtls_required()` to match the storage field's name; the
2859 /// accessor's identity maps onto the canonical MESH-COMPOSITION
2860 /// §III.2 vocabulary the slot's docstring already carries.
2861 #[must_use]
2862 pub const fn mtls_required(&self) -> Option<bool> {
2863 self.mtls_required
2864 }
2865
2866 /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2867 /// `local_rate_limit`-mesh token-bucket-declaration scalar
2868 /// accessor every consumer of the Aplicacao's per-`:politicas`
2869 /// per-`(rate, window)` rate-limit surface keys off — returns the
2870 /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2871 /// verbatim as an `Option<RateLimit>`, copied out of the typed
2872 /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2873 /// `Copy`, so the accessor returns by value; no borrow of `&self`
2874 /// past the call). `None` when the slot is absent (the "cluster
2875 /// default applies — typically 'no per-Aplicacao rate declaration,
2876 /// gateway-class per-listener default applies'" arm the future
2877 /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2878 /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2879 /// `rate_limit().is_none()` arm reads this predicate too, so an
2880 /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2881 /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2882 /// identical to one that omits the slot).
2883 ///
2884 /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2885 /// token-bucket rate declaration" contract (MESH-COMPOSITION
2886 /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2887 /// (rate lower-bounded by 1 through
2888 /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2889 /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2890 /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2891 /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2892 /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2893 /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2894 /// `:politicas` overlay emits. Every downstream consumer that
2895 /// reads the rate declaration keys off this scalar (the
2896 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2897 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2898 /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2899 /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2900 /// `rl.window` against [`is_canonical_rate_limit_window`], the
2901 /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2902 /// the future per-`:contratos`-edge rate-limit override the
2903 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2904 ///
2905 /// Prior to this lift the `.rate_limit` field was accessed inline
2906 /// at two sites — [`MeshPolicy::is_empty`]'s
2907 /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2908 /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2909 /// field-accesses that expressed no compile-time link back to the
2910 /// typed slot. A future extension of the `:politicas :rate-limit`
2911 /// axis to a richer author surface — a per-`:contratos`-edge
2912 /// rate-limit override the operator pins through a future
2913 /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2914 /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2915 /// the M4 CR materializer resolves per-CR, a promotion of the
2916 /// plain `(rate, window)` scalar pair to a richer
2917 /// `{rate, window, burst, key}` sub-block once Envoy's
2918 /// `local_rate_limit` grows the peer `burst_size` /
2919 /// `descriptor_key` axes — would have had to be threaded through
2920 /// both open-coded copies in lockstep or the emptiness predicate
2921 /// and the validate gate would silently disagree on which rate
2922 /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2923 /// block whose only axis is a `Some :rate-limit` would satisfy
2924 /// `is_empty() == false` while the validate path silently read a
2925 /// drifted other value, or vice versa: an author's
2926 /// `:rate-limit "100/s"` would omit the value-shape gate while the
2927 /// emptiness predicate still classified the policy as non-empty).
2928 /// Lifting the resolution to a typed method on the substrate
2929 /// primitive means every downstream consumer of the Aplicacao's
2930 /// per-`:politicas` rate-limit surface reaches for exactly one
2931 /// typed dispatch — the resolver's accept-set migrates as a unit
2932 /// on any future axis addition.
2933 ///
2934 /// First `Option<Copy-composite-T>`-return accessor on the M3
2935 /// mesh-slot family — closes the last un-lifted per-`:politicas`
2936 /// scalar-value axis. Peer of the sibling per-`:politicas`
2937 /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2938 /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2939 /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2940 /// "one typed dispatch on the substrate primitive, thin
2941 /// projections at each consumer" discipline extended onto the
2942 /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2943 /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2944 /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2945 /// sub-accessors rather than a top-level accessor because
2946 /// consumers reach for the axes not the aggregate). Named
2947 /// `rate_limit()` to match the storage field's name; the
2948 /// accessor's identity maps onto the canonical MESH-COMPOSITION
2949 /// §III.2 vocabulary the slot's docstring already carries.
2950 #[must_use]
2951 pub const fn rate_limit(&self) -> Option<RateLimit> {
2952 self.rate_limit
2953 }
2954
2955 /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2956 /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2957 /// declaration scalar accessor every consumer of the Aplicacao's
2958 /// per-`:politicas` breaker declaration keys off — returns the
2959 /// author-declared `:politicas :circuit-breaker` typed
2960 /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2961 /// copied out of the typed slot's own `Option<CircuitBreaker>`
2962 /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2963 /// by value; no borrow of `&self` past the call). `None` when the
2964 /// slot is absent (the "cluster default applies — typically 'no
2965 /// per-Aplicacao breaker declaration, gateway-class per-listener
2966 /// default applies'" arm the future caixa-mesh
2967 /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2968 /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2969 /// arm reads this predicate too, so an authored-but-unset
2970 /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2971 /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2972 /// that omits the slot).
2973 ///
2974 /// The `:politicas :circuit-breaker` slot carries the
2975 /// "per-Aplicacao consecutive-transient-failure trip declaration"
2976 /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2977 /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2978 /// zero-floor rejected through
2979 /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2980 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2981 /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2982 /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2983 /// canonical-form pinned through
2984 /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2985 /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2986 /// bijection the future `CiliumClusterwideEnvoyConfig`
2987 /// per-`:politicas` overlay emits. Every downstream consumer that
2988 /// reads the breaker declaration keys off this scalar (the
2989 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2990 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2991 /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2992 /// that brackets `cb.max_failures()` against
2993 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2994 /// [`POLICY_BREAKER_WINDOW_MAX`] via
2995 /// [`crate::render::require_positive_canonical_bounded_duration`],
2996 /// the future M4 per-Aplicacao Envoy reconciler materialization
2997 /// pass, the future per-`:contratos`-edge breaker override the
2998 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2999 ///
3000 /// Prior to this lift the `.circuit_breaker` field was accessed
3001 /// inline at two sites — [`MeshPolicy::is_empty`]'s
3002 /// `self.circuit_breaker.is_none()` arm and the
3003 /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
3004 /// bind — two open-coded field-accesses that expressed no
3005 /// compile-time link back to the typed slot. A future extension of
3006 /// the `:politicas :circuit-breaker` axis to a richer author
3007 /// surface — a per-`:contratos`-edge breaker override the operator
3008 /// pins through a future `:contratos :circuit-breaker` slot the
3009 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
3010 /// breaker-default overlay the M4 CR materializer resolves per-CR,
3011 /// a promotion of the plain `(max_failures, window)` scalar pair to
3012 /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
3013 /// sub-block once Envoy's `outlier_detection` grows the peer
3014 /// ejection-percentage / ejection-time axes — would have had to be
3015 /// threaded through both open-coded copies in lockstep or the
3016 /// emptiness predicate and the validate gate would silently
3017 /// disagree on which breaker declaration a given [`MeshPolicy`]
3018 /// resolves to (a `:politicas` block whose only axis is a
3019 /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
3020 /// the validate path silently read a drifted other value, or vice
3021 /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
3022 /// "60s"))` would omit the value-shape gate while the emptiness
3023 /// predicate still classified the policy as non-empty). Lifting
3024 /// the resolution to a typed method on the substrate primitive
3025 /// means every downstream consumer of the Aplicacao's
3026 /// per-`:politicas` breaker surface reaches for exactly one typed
3027 /// dispatch — the resolver's accept-set migrates as a unit on any
3028 /// future axis addition.
3029 ///
3030 /// Second `Option<Copy-composite-T>`-return accessor on the M3
3031 /// mesh-slot family (sibling of the peer per-`:politicas`
3032 /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
3033 /// on the same composite-Copy shape, and of the sibling per-
3034 /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
3035 /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
3036 /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
3037 /// `Option<bool>` accessors on the sibling primitive-Copy axes —
3038 /// same "one typed dispatch on the substrate primitive, thin
3039 /// projections at each consumer" discipline extended onto the last
3040 /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
3041 /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
3042 /// match the storage field's name; the accessor's identity maps
3043 /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3044 /// docstring already carries. Closes the last unlifted
3045 /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
3046 /// reader now routes through a typed dispatch on the substrate
3047 /// primitive.
3048 #[must_use]
3049 pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
3050 self.circuit_breaker
3051 }
3052}
3053
3054#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
3055#[serde(rename_all = "camelCase")]
3056pub struct CircuitBreaker {
3057 pub max_failures: u32,
3058 #[serde(with = "supervisor::duration_codec_required")]
3059 pub window: Duration,
3060}
3061
3062impl CircuitBreaker {
3063 /// Substrate-canonical per-`:politicas :circuit-breaker`
3064 /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
3065 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3066 /// breaker trip-count keys off — returns the author-declared
3067 /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
3068 /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
3069 /// so the accessor returns by value; no borrow of `&self` past the
3070 /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
3071 /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
3072 /// axis; a `CircuitBreaker` past pattern-match is definitionally
3073 /// present, and its `:max-failures` field carries the trip count as a
3074 /// required-axis scalar).
3075 ///
3076 /// The `:politicas :circuit-breaker :max-failures` axis carries the
3077 /// "consecutive-transient-failure trip threshold" contract
3078 /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
3079 /// (zero-floor rejected through
3080 /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3081 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
3082 /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
3083 /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
3084 /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
3085 /// Every downstream consumer that reads the trip threshold keys off
3086 /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3087 /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
3088 /// canonical `require_positive_bounded_u32` helper, the future M4
3089 /// per-Aplicacao Envoy config reconciler materialization pass, the
3090 /// future per-`:contratos`-edge breaker-override overlay the
3091 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3092 ///
3093 /// Prior to this lift the `.max_failures` field was accessed inline
3094 /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
3095 /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
3096 /// open-coded field-access that expressed no compile-time link back
3097 /// to the typed sub-struct axis. A future extension of the
3098 /// `:max-failures` axis to a richer author surface — a
3099 /// per-`:contratos`-edge breaker override the operator pins through a
3100 /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
3101 /// #3 roadmap acknowledges, a per-cluster max-failures-default
3102 /// overlay the M4 CR materializer resolves per-CR, a promotion of the
3103 /// plain `u32` trip count to a richer
3104 /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
3105 /// tuple once Envoy's `outlier_detection` block's peer axes come into
3106 /// scope, a per-Envoy-cluster minimum-request-volume gate before the
3107 /// count arms — would have had to be threaded through every open-
3108 /// coded copy in lockstep or the validate gate and the future M4
3109 /// emit path would silently disagree on which trip threshold a given
3110 /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
3111 /// would satisfy validate while the emit path silently read a drifted
3112 /// other value, or vice versa: a validated typed slot would land at
3113 /// the emit boundary as a no-op breaker whose trip threshold is
3114 /// structurally never reached). Lifting the resolution to a typed
3115 /// method on the substrate primitive means every downstream consumer
3116 /// of the Aplicacao's per-`:politicas :circuit-breaker`
3117 /// trip-threshold surface reaches for exactly one typed dispatch —
3118 /// the resolver's accept-set migrates as a unit on any future axis
3119 /// addition.
3120 ///
3121 /// First sub-struct scalar accessor on the M3 mesh-slot family
3122 /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
3123 /// scalar" projection pattern the sibling `CircuitBreaker::window` /
3124 /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
3125 /// closes the last unlifted per-`:politicas` scalar-value axis after
3126 /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
3127 /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
3128 /// Same "one typed dispatch on the substrate primitive, thin
3129 /// projections at each consumer" discipline the peer
3130 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3131 /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3132 /// [`Membro::versao_requirement`] (a40b0e3),
3133 /// [`Entrada::destination`] (6db982c) accessors carry on their
3134 /// respective per-mesh-slot-atom scalar-value axes, extended onto the
3135 /// per-sub-struct required-`u32` axis. Named `max_failures()` to
3136 /// match the storage field's name; the accessor's identity maps onto
3137 /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3138 /// docstring already carries.
3139 #[must_use]
3140 pub const fn max_failures(&self) -> u32 {
3141 self.max_failures
3142 }
3143
3144 /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
3145 /// Envoy-outlier-detection rolling-observation-interval scalar
3146 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3147 /// breaker rolling-window duration keys off — returns the
3148 /// author-declared `:politicas :circuit-breaker :window` typed
3149 /// `Duration` verbatim, copied out of the typed slot's own
3150 /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
3151 /// by value; no borrow of `&self` past the call). Non-optional (the
3152 /// surrounding `Option<CircuitBreaker>` is the "slot present?"
3153 /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
3154 /// `CircuitBreaker` past pattern-match is definitionally present,
3155 /// and its `:window` field carries the rolling-observation interval
3156 /// as a required-axis scalar).
3157 ///
3158 /// The `:politicas :circuit-breaker :window` axis carries the
3159 /// "consecutive-transient-failure rolling-observation interval"
3160 /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3161 /// `Duration` accept-set (zero-floor rejected through
3162 /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
3163 /// residue rejected through
3164 /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
3165 /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
3166 /// Envoy `outlier_detection.interval` per-cluster
3167 /// ejection-observation-interval scalar (equivalently the future
3168 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3169 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3170 /// consumer that reads the rolling-observation interval keys off
3171 /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3172 /// integer-millisecond canonical-form + cap bracket at
3173 /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
3174 /// [`crate::render::require_positive_canonical_bounded_duration`]
3175 /// helper, the future M4 per-Aplicacao Envoy config reconciler
3176 /// materialization pass, the future per-`:contratos`-edge
3177 /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3178 /// acknowledges).
3179 ///
3180 /// Prior to this lift the `.window` field was accessed inline at
3181 /// one production site — [`AplicacaoSpec::validate_politicas`]'s
3182 /// `require_positive_canonical_bounded_duration(cb.window, …)`
3183 /// call — one open-coded field-access that expressed no compile-
3184 /// time link back to the typed sub-struct axis. A future extension
3185 /// of the `:window` axis to a richer author surface — a
3186 /// per-`:contratos`-edge window override the operator pins through
3187 /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
3188 /// #3 roadmap acknowledges, a per-cluster window-default overlay
3189 /// the M4 CR materializer resolves per-CR, a promotion of the plain
3190 /// `Duration` observation interval to a richer
3191 /// `{interval, base_ejection_time, max_ejection_percent}` tuple
3192 /// once Envoy's `outlier_detection` block's peer axes come into
3193 /// scope, a per-Envoy-cluster minimum-request-volume gate before
3194 /// the window arms — would have had to be threaded through every
3195 /// open-coded copy in lockstep or the validate gate and the future
3196 /// M4 emit path would silently disagree on which observation
3197 /// interval a given [`CircuitBreaker`] resolves to (an author's
3198 /// `:window "60s"` would satisfy validate while the emit path
3199 /// silently read a drifted other value, or vice versa: a validated
3200 /// typed slot would land at the emit boundary as a breaker whose
3201 /// observation window is structurally so wide that no realistic
3202 /// failure-rate shape can trip it). Lifting the resolution to a
3203 /// typed method on the substrate primitive means every downstream
3204 /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3205 /// observation-window surface reaches for exactly one typed
3206 /// dispatch — the resolver's accept-set migrates as a unit on any
3207 /// future axis addition.
3208 ///
3209 /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3210 /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3211 /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3212 /// required-axis, extended onto the per-sub-struct required-`Duration`
3213 /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3214 /// axis. Same "one typed dispatch on the substrate primitive, thin
3215 /// projections at each consumer" discipline the peer
3216 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3217 /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3218 /// [`Membro::versao_requirement`] (a40b0e3),
3219 /// [`Entrada::destination`] (6db982c) accessors carry on their
3220 /// respective per-mesh-slot-atom scalar-value axes, extended onto
3221 /// the per-sub-struct required-`Duration` axis. Named `window()` to
3222 /// match the storage field's name; the accessor's identity maps onto
3223 /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3224 /// docstring already carries.
3225 #[must_use]
3226 pub const fn window(&self) -> Duration {
3227 self.window
3228 }
3229}
3230
3231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3232pub struct RateLimit {
3233 /// Requests per window.
3234 pub rate: u32,
3235 /// Window duration.
3236 pub window: Duration,
3237}
3238
3239impl RateLimit {
3240 /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3241 /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3242 /// every consumer of the Aplicacao's per-`:contratos`-edge
3243 /// rate-limit-bucket capacity keys off — returns the author-declared
3244 /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
3245 /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
3246 /// returns by value; no borrow of `&self` past the call). Non-optional
3247 /// (the surrounding `Option<RateLimit>` is the "slot present?"
3248 /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
3249 /// `RateLimit` past pattern-match is definitionally present, and its
3250 /// `:rate` field carries the token-bucket capacity as a required-axis
3251 /// scalar).
3252 ///
3253 /// The `:politicas :rate-limit` `:rate` axis carries the
3254 /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
3255 /// the typed slot's `u32` accept-set (zero-floor rejected through
3256 /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
3257 /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
3258 /// `local_rate_limit.token_bucket.max_tokens` per-cluster
3259 /// token-bucket-capacity scalar (equivalently the future
3260 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3261 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3262 /// consumer that reads the token-bucket capacity keys off this
3263 /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3264 /// cap bracket that gates on the canonical
3265 /// [`crate::render::require_positive_bounded_u32`] helper, the
3266 /// [`rate_limit_codec::render`] `Duration → unit` projection that
3267 /// emits the `<n>/<s|m|h>` author surface, the future M4
3268 /// per-Aplicacao Envoy config reconciler materialization pass, the
3269 /// future per-`:contratos`-edge rate-limit-override overlay the
3270 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3271 ///
3272 /// Prior to this lift the `.rate` field was accessed inline at three
3273 /// production sites — [`AplicacaoSpec::validate_politicas`]'s
3274 /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
3275 /// [`rate_limit_codec::render`] format-arm arms (canonical-window
3276 /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
3277 /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
3278 /// field-accesses that expressed no compile-time link back to the
3279 /// typed sub-struct axis. A future extension of the `:rate` axis
3280 /// to a richer author surface — a per-`:contratos`-edge rate
3281 /// override the operator pins through a future `:contratos :rate`
3282 /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
3283 /// per-cluster rate-default overlay the M4 CR materializer resolves
3284 /// per-CR, a promotion of the plain `u32` token capacity to a
3285 /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
3286 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3287 /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
3288 /// before the token arms — would have had to be threaded through
3289 /// every open-coded copy in lockstep or the validate gate, the
3290 /// codec's render path, and the future M4 emit path would silently
3291 /// disagree on which token capacity a given [`RateLimit`] resolves
3292 /// to (an author's `:rate-limit "100/s"` would satisfy validate
3293 /// while the render / emit paths silently read a drifted other
3294 /// value, or vice versa: a validated typed slot would land at the
3295 /// emit boundary as a no-op limiter whose token capacity is
3296 /// structurally so high that no realistic per-edge traffic shape
3297 /// can drain it). Lifting the resolution to a typed method on the
3298 /// substrate primitive means every downstream consumer of the
3299 /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
3300 /// reaches for exactly one typed dispatch — the resolver's
3301 /// accept-set migrates as a unit on any future axis addition.
3302 ///
3303 /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
3304 /// in shape to the peer per-`CircuitBreaker`
3305 /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
3306 /// on the peer per-sub-struct required-axis, extended onto the
3307 /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
3308 /// required-axis scalar" projection pattern the sibling
3309 /// [`RateLimit::window`] future lift folds on. Same "one typed
3310 /// dispatch on the substrate primitive, thin projections at each
3311 /// consumer" discipline the peer [`WitContract::source`] /
3312 /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3313 /// (0804823), [`Membro::nome`] (4a32abf),
3314 /// [`Membro::versao_requirement`] (a40b0e3),
3315 /// [`Entrada::destination`] (6db982c),
3316 /// [`CircuitBreaker::max_failures`] (3a74062),
3317 /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3318 /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3319 /// to match the storage field's name; the accessor's identity maps
3320 /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3321 /// docstring already carries.
3322 #[must_use]
3323 pub const fn rate(&self) -> u32 {
3324 self.rate
3325 }
3326
3327 /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3328 /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3329 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3330 /// rate-limit-bucket refill period keys off — returns the
3331 /// author-declared `:politicas :rate-limit` typed `Duration`
3332 /// verbatim, copied out of the typed slot's own `Duration` storage
3333 /// (`Duration` is `Copy`, so the accessor returns by value; no
3334 /// borrow of `&self` past the call). Non-optional (the surrounding
3335 /// `Option<RateLimit>` is the "slot present?" projection at the
3336 /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3337 /// pattern-match is definitionally present, and its `:window`
3338 /// field carries the token-bucket refill period as a required-axis
3339 /// scalar).
3340 ///
3341 /// The `:politicas :rate-limit` `:window` axis carries the
3342 /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3343 /// — the typed slot's `Duration` accept-set (constrained to the
3344 /// three canonical windows `{1s, 60s, 3600s}` the
3345 /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3346 /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3347 /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3348 /// per-cluster token-bucket-refill-period scalar (equivalently the
3349 /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3350 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3351 /// consumer that reads the token-bucket refill period keys off
3352 /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3353 /// canonical-window gate that keys off
3354 /// [`is_canonical_rate_limit_window`], the
3355 /// [`rate_limit_codec::render`] `Duration → unit` projection that
3356 /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3357 /// [`rate_limit_window_unit`] and non-canonical fallback via
3358 /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3359 /// reconciler materialization pass, the future per-`:contratos`-
3360 /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3361 /// roadmap acknowledges).
3362 ///
3363 /// Prior to this lift the `.window` field was accessed inline at
3364 /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3365 /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3366 /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3367 /// error-payload construction on refusal, and the two
3368 /// [`rate_limit_codec::render`] arms
3369 /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3370 /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3371 /// open-coded field-accesses that expressed no compile-time link
3372 /// back to the typed sub-struct axis. A future extension of the
3373 /// `:window` axis to a richer author surface — a per-`:contratos`-
3374 /// edge window override the operator pins through a future
3375 /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3376 /// acknowledges, a per-cluster window-default overlay the M4 CR
3377 /// materializer resolves per-CR, a promotion of the plain
3378 /// `Duration` refill period to a richer
3379 /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3380 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3381 /// axis comes into scope, an addition of a `"d"` day suffix once
3382 /// Envoy's `rate_limit_action` grows daily-bucket support — would
3383 /// have had to be threaded through every open-coded copy in
3384 /// lockstep or the validate gate, the codec's render path, and
3385 /// the future M4 emit path would silently disagree on which
3386 /// refill period a given [`RateLimit`] resolves to (an author's
3387 /// `:rate-limit "100/s"` would satisfy validate while the render
3388 /// / emit paths silently read a drifted other value, or vice
3389 /// versa: a validated typed slot would land at the emit boundary
3390 /// as a limiter whose refill period is structurally so long that
3391 /// no realistic per-edge traffic shape stays inside the token
3392 /// budget). Lifting the resolution to a typed method on the
3393 /// substrate primitive means every downstream consumer of the
3394 /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3395 /// reaches for exactly one typed dispatch — the resolver's
3396 /// accept-set migrates as a unit on any future axis addition.
3397 ///
3398 /// Second sub-struct scalar accessor on the `RateLimit` axis —
3399 /// sibling in shape to the just-landed [`RateLimit::rate`]
3400 /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
3401 /// required-axis, extended onto the per-sub-struct
3402 /// required-`Duration` axis; closes the last unlifted
3403 /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
3404 /// per-sub-struct accessor coverage is now complete across both
3405 /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
3406 /// the substrate primitive, thin projections at each consumer"
3407 /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
3408 /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
3409 /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
3410 /// (7f0fd43), [`WitContract::world_ref`] (0804823),
3411 /// [`Membro::nome`] (4a32abf),
3412 /// [`Membro::versao_requirement`] (a40b0e3),
3413 /// [`Entrada::destination`] (6db982c) accessors carry on their
3414 /// respective per-mesh-slot-atom scalar-value axes. Named
3415 /// `window()` to match the storage field's name; the accessor's
3416 /// identity maps onto the canonical MESH-COMPOSITION §III.2
3417 /// vocabulary the slot's docstring already carries.
3418 #[must_use]
3419 pub const fn window(&self) -> Duration {
3420 self.window
3421 }
3422
3423 /// Recognize this rate-limit's `:window` as a canonical
3424 /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
3425 /// exactly matches one of the three closed-set arm-Durations
3426 /// (`1s` / `60s` / `3600s`), `None` when the window carries a
3427 /// non-canonical magnitude the codec's round-trip would break on
3428 /// (sub-second residue, or a second-magnitude outside the set
3429 /// [`RateLimitUnit::ALL`] enumerates).
3430 ///
3431 /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
3432 /// returns `Some` here — the validate gate's
3433 /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
3434 /// rejects every window this accessor returns `None` on. Downstream
3435 /// consumers past validate (the codec's [`rate_limit_codec::render`]
3436 /// path, the future M4 per-Aplicacao Envoy config reconciler's
3437 /// materialization pass, the future per-`:contratos`-edge rate-limit-
3438 /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3439 /// acknowledges) that read the typed unit off a validated slot can
3440 /// pattern-match on the returned `Some` without re-checking
3441 /// canonicality at the consumer layer — the typed enum surface is
3442 /// the load-bearing carrier of the canonicality invariant.
3443 ///
3444 /// Preferred over the free [`is_canonical_rate_limit_window`]
3445 /// module-private helper at any call site that has the typed
3446 /// [`RateLimit`] in hand (the codec's `render` arm at
3447 /// [`rate_limit_codec::render`], the validate gate's canonical-form
3448 /// arm in [`AplicacaoSpec::validate_politicas`], any future
3449 /// per-`:contratos` edge-override overlay resolver): those consumers
3450 /// reach for the typed enum without going through the
3451 /// `.window()` scalar-projection layer, and get the enum value
3452 /// directly (which the codec's render arm can then format via
3453 /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
3454 /// "typed sub-struct scalar accessor, one dispatch on the substrate
3455 /// primitive" discipline the sibling [`RateLimit::rate`] and
3456 /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
3457 /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
3458 /// projection axis (the third scalar accessor on the [`RateLimit`]
3459 /// axis, first typed-enum-return projection).
3460 ///
3461 /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
3462 /// the canonical [`RateLimitUnit`] arm now carries the same
3463 /// `const`-eval-surface posture the sibling `pub const fn`
3464 /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
3465 /// this typed sub-struct already carry, composing through the
3466 /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
3467 /// reverse-resolver in `const` context. Any downstream substrate-
3468 /// side `const`-context consumer of the typed unit (a module-scope
3469 /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
3470 /// invariant pin on a typed fixture, a future M4 admission-webhook
3471 /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
3472 /// resolver over a typed [`RateLimit`], any future `const fn`
3473 /// per-`:contratos`-edge rate-limit-override overlay resolver over
3474 /// the substrate primitive) now reaches the same typed dispatch on
3475 /// the substrate primitive at const-eval time as at runtime.
3476 ///
3477 /// Pinned load-bearing at the substrate-primitive level by
3478 /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
3479 /// eval-surface pin via `const fn` wrapper).
3480 #[must_use]
3481 pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
3482 RateLimitUnit::from_window(self.window)
3483 }
3484}
3485
3486/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
3487/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
3488/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
3489///
3490/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
3491/// the `:politicas :rate-limit` unit surface reads from
3492/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
3493/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
3494/// [`is_canonical_rate_limit_window`] predicate the
3495/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
3496/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
3497/// projection) now lives inside this typed enum's `match self` arms — a
3498/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
3499/// `rate_limit_action` grows daily-bucket support) is one new variant
3500/// plus the exhaustiveness arms on the four methods, so every consumer
3501/// picks it up by compile-time construction rather than a runtime
3502/// table-scan miss.
3503///
3504/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
3505/// scanned via `find_map` at every projection call — an untyped runtime
3506/// walk that carried no compile-time link between the parse arm's
3507/// accepted suffixes, the render arm's emitted suffixes, and the
3508/// validate gate's accepted windows. A future rate-limit-unit addition
3509/// that landed one row without threading through the other consumers
3510/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3511/// silently split the accepted-set across the three consumers — the
3512/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3513/// for a 24h window that parse can't round-trip, the validate gate
3514/// misses one canonical window. Lifting the pairs onto a typed
3515/// closed-set enum with exhaustive `match` arms makes any such
3516/// half-landed extension a caixa-core build error (the compiler enforces
3517/// arm coverage on every method), not a silent per-consumer drift
3518/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3519/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3520/// [`crate::supervisor::RestartStrategy`],
3521/// [`crate::supervisor::RestartPolicy`],
3522/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3523/// closed-set typed enums carry on their respective closed-set axes —
3524/// extended onto the seventh closed-set typed-enum discriminator axis
3525/// on the caixa typed surface (the `:politicas :rate-limit :window`
3526/// canonical-unit axis).
3527#[derive(
3528 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3529)]
3530pub enum RateLimitUnit {
3531 /// 1-second window — canonical author-surface suffix `"s"`
3532 /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3533 /// with a 1s magnitude.
3534 Second,
3535 /// 1-minute window — canonical author-surface suffix `"m"`
3536 /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3537 /// with a 60s magnitude.
3538 Minute,
3539 /// 1-hour window — canonical author-surface suffix `"h"`
3540 /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3541 /// with a 3600s magnitude.
3542 Hour,
3543}
3544
3545impl RateLimitUnit {
3546 /// Exhaustive iteration surface for every consumer that reads the
3547 /// full canonical-unit set (the byte-parity witness against the
3548 /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3549 /// webhook's accepted-suffix listing in its rejection body, any
3550 /// future round-trip fuzz harness). A future variant addition to
3551 /// [`RateLimitUnit`] extends this slice as a single edit and every
3552 /// consumer picks up the new entry by construction — the compiler-
3553 /// checked exhaustiveness on the sibling method `match` arms is the
3554 /// build-time guarantee that no arm forgets to grow.
3555 pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3556
3557 /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3558 /// string every `<n>/<unit>` rate-limit shape carries after its
3559 /// `/` separator. The single source of truth the codec's parse and
3560 /// render arms both dispatch on: the parse arm matches an incoming
3561 /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3562 /// output; the render arm emits the entry's `as_suffix` verbatim
3563 /// after the rate magnitude.
3564 #[must_use]
3565 pub const fn as_suffix(self) -> &'static str {
3566 match self {
3567 Self::Second => "s",
3568 Self::Minute => "m",
3569 Self::Hour => "h",
3570 }
3571 }
3572
3573 /// Canonical `Duration` for this unit — the token-bucket refill
3574 /// period the [`RateLimit::window`] axis carries when the surrounding
3575 /// slot's `:rate-limit` author surface named this unit.
3576 #[must_use]
3577 pub const fn window(self) -> Duration {
3578 Duration::from_secs(match self {
3579 Self::Second => 1,
3580 Self::Minute => 60,
3581 Self::Hour => 3_600,
3582 })
3583 }
3584
3585 /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3586 /// `None` when `suffix` is outside the closed-set arm-string set
3587 /// [`Self::as_suffix`] emits. The single `str → Self` projection
3588 /// [`rate_limit_codec::parse`] consumes.
3589 #[must_use]
3590 pub fn from_suffix(suffix: &str) -> Option<Self> {
3591 Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3592 }
3593
3594 /// Recognize a canonical rate-limit `Duration` as one of the three
3595 /// arms, or `None` when `window` carries sub-second residue or a
3596 /// second-magnitude outside the closed-set arm-window set
3597 /// [`Self::window`] emits. The single `Duration → Self` projection
3598 /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3599 /// both consume.
3600 ///
3601 /// `pub const fn` — the reverse `Duration → Self` projection now
3602 /// carries the same `const`-eval-surface posture the sibling
3603 /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
3604 /// projection accessors on this closed-set typed enum already
3605 /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
3606 /// typed-`RateLimit`-projection sibling composes through in `const`
3607 /// context. Routes byte-for-byte through the peer `pub const fn`
3608 /// [`Self::window`] canonical-`Duration` projection so any future
3609 /// arm-magnitude edit on the sibling accessor reaches this reverse
3610 /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
3611 /// per-arm probes each dispatch through one `pub const fn` on the
3612 /// substrate primitive rather than a hand-authored per-arm second-
3613 /// magnitude literal that would silently drift on any future
3614 /// [`Self::window`] arm-magnitude edit.
3615 ///
3616 /// Prior to the `const` lift the body dispatched through
3617 /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
3618 /// iterator-driven linear scan whose iterator methods
3619 /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
3620 /// `PartialEq` dispatch each carry non-`const` bounds on stable
3621 /// Rust 1.94, so any downstream substrate-side `const`-context
3622 /// consumer of the reverse resolver (a module-scope
3623 /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
3624 /// invariant pin on a typed fixture, a future M4
3625 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
3626 /// webhook `const fn` per-`:politicas` canonical-window floor over a
3627 /// typed [`RateLimit`] scalar, any future `const fn`
3628 /// per-`:contratos`-edge rate-limit-override overlay resolver over
3629 /// the substrate primitive that wants to fan on the canonical unit
3630 /// at compile time) surfaced as a downstream E0015 far from the
3631 /// resolver's own declaration. The `pub const fn` posture closes
3632 /// the drift structurally at caixa-core build time.
3633 ///
3634 /// Pinned load-bearing at the substrate-primitive level by
3635 /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
3636 /// eval-surface pin via `const fn` wrapper) and
3637 /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
3638 /// (composition-witness pin against the peer `Self::window` scalar
3639 /// dispatch).
3640 #[must_use]
3641 pub const fn from_window(window: Duration) -> Option<Self> {
3642 if window.subsec_nanos() != 0 {
3643 return None;
3644 }
3645 // Route through the peer `pub const fn` [`Self::window`]
3646 // canonical-`Duration` projection so any future arm-magnitude
3647 // edit on the sibling accessor reaches this reverse resolver by
3648 // construction — the per-arm `secs` comparison keys off
3649 // `Duration::as_secs` (`pub const fn`), not a hand-authored
3650 // per-arm second-magnitude literal that would silently drift.
3651 let secs = window.as_secs();
3652 if secs == Self::Second.window().as_secs() {
3653 Some(Self::Second)
3654 } else if secs == Self::Minute.window().as_secs() {
3655 Some(Self::Minute)
3656 } else if secs == Self::Hour.window().as_secs() {
3657 Some(Self::Hour)
3658 } else {
3659 None
3660 }
3661 }
3662
3663 /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3664 /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3665 /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3666 /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3667 /// consumes.
3668 ///
3669 /// The peer `Duration → &'static str` axis folded onto the substrate
3670 /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3671 /// production consumers ([`rate_limit_codec::render`] and
3672 /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3673 /// migrated (61421a6): the free helper's `Duration → &str` projection
3674 /// is now the two-step composition
3675 /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3676 /// reads through the typed accessor. This lift closes the peer
3677 /// `&str → Duration` axis by folding the vestigial module-private
3678 /// `rate_limit_window_from_unit` delegate onto this associated method
3679 /// — the codec's parse arm and every future wire-side consumer of the
3680 /// `&str → Duration` projection (a future admission-webhook that
3681 /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3682 /// before it's promoted to a validated typed slot, a future
3683 /// `feira lint` shape-probe that reads the author-surface bytes
3684 /// verbatim) now reach for exactly one typed dispatch on the
3685 /// substrate primitive.
3686 ///
3687 /// Same "closed-set typed-enum discriminator with canonical
3688 /// projections per axis" discipline the sibling [`Self::as_suffix`]
3689 /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3690 /// methods carry — this associated method closes the fifth (and last
3691 /// unlifted) projection axis on the arm-table, so the closed-set enum
3692 /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3693 /// consumer of the `:politicas :rate-limit :window` axis reaches
3694 /// through. A future rate-limit-unit addition (a `"d"` day suffix
3695 /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3696 /// `"ms"` sub-second window once high-throughput per-edge policies
3697 /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3698 /// variant plus one arm per method — the compiler enforces
3699 /// exhaustiveness on every consumer's `match self` arms and picks
3700 /// the new unit up by construction across all five projections.
3701 #[must_use]
3702 pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3703 Self::from_suffix(suffix).map(Self::window)
3704 }
3705}
3706
3707/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3708/// every consumer that formats a canonical rate-limit unit as user-
3709/// facing text (future M4 admission-webhook rejection bodies naming
3710/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3711/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3712/// codec's parse arm accepts and the render arm emits. Same
3713/// as_str-through-Display convergence discipline the sibling
3714/// [`PlacementStrategy`], [`crate::CaixaKind`],
3715/// [`crate::supervisor::RestartStrategy`], and
3716/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3717impl std::fmt::Display for RateLimitUnit {
3718 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3719 f.write_str(self.as_suffix())
3720 }
3721}
3722
3723/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3724/// validated [`MeshPolicy::timeout`] past
3725/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3726/// (inclusive on both ends, integer-millisecond magnitudes by the
3727/// canonical-form gate immediately preceding).
3728///
3729/// The typed field is `Option<Duration>` (the zero-floor arm
3730/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3731/// `Duration::ZERO`, and the canonical-form arm
3732/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3733/// sub-millisecond residue), so a programmatic struct literal
3734/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3735/// 24h) and the equivalent author-surface form
3736/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3737/// integer-hour magnitude) both round-trip cleanly through serde — a
3738/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3739/// above the documented production-playbook band (Envoy default `15s`,
3740/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3741/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3742/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3743/// at `~3600s`) silently degenerates the mesh-policy contract: the
3744/// per-call deadline is structurally so long that no realistic
3745/// synchronous-`:contratos` traversal can reach it, so the typed slot
3746/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3747/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3748/// blocking" degenerates to a nominal-only contract on the
3749/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3750/// the sibling `:politicas :retries` axis and the
3751/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3752/// `:politicas :circuit-breaker :max-failures` axis — all three close
3753/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3754/// footgun the prior zero-floor-and-canonical-form-only checks left
3755/// open.
3756///
3757/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3758/// shared duration codec emits (`"<n>h"` for any integer-hour
3759/// magnitude) — every value in the canonical authoring form's
3760/// `<integer><unit>` grammar at or below this cap renders to a clean
3761/// canonical string. The cap sits an order of magnitude above every
3762/// documented production-playbook recommendation band (Envoy default
3763/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3764/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3765/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3766/// below the clearly-pathological "effectively no timeout" floor
3767/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3768/// want for a long-running synchronous workflow, but a hard wall above
3769/// which the mesh-level deadline is structurally a non-deadline.
3770/// Lifted as a typed `pub const` so the bound has exactly one source
3771/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3772/// materializer's admission webhook and the caixa-mesh-side
3773/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3774/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3775/// other typed upper bound in this crate carries
3776/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3777/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3778/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3779/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3780pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3781
3782/// Upper-bound ceiling on the `:politicas :retries` axis — every
3783/// validated [`MeshPolicy::retries`] past
3784/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3785///
3786/// The typed slot is `Option<u32>` (`None` = no retries on transient
3787/// failure; `Some(0)` already rejected by the
3788/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3789/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3790/// .. }`) and the equivalent author-surface form
3791/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3792/// serde / the codec — a structurally unbounded `u32` ceiling. The
3793/// runtime substrate that consumes the value (Envoy's
3794/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3795/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3796/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3797/// admission cap is 10) translates a four-billion-retry policy into a
3798/// thundering-herd amplification vector on transient failure — the
3799/// caller's one request fans out to `retries` server-side calls per
3800/// edge per traversal, multiplying load by `(retries+1)^depth` across
3801/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3802/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3803/// invariant on the retry axis; both belong at the typed-slot layer.
3804///
3805/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3806/// upstream mesh-policy schema that documents one) and sits above the
3807/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3808/// every documented production playbook): a value the author can
3809/// plausibly want, but a hard wall above which the policy is
3810/// structurally a footgun. Lifted as a typed `pub const` so the bound
3811/// has exactly one source of truth — a future axis reaching for the
3812/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3813/// materializer's admission webhook, the caixa-mesh-side
3814/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3815/// one place. Same shape every other typed upper bound in this crate
3816/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3817/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3818/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3819/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3820pub const POLICY_RETRIES_MAX: u32 = 10;
3821
3822/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3823/// axis — every validated [`CircuitBreaker::max_failures`] past
3824/// [`AplicacaoSpec::validate_politicas`] lies in
3825/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3826///
3827/// The typed field is `u32` (the zero-floor arm
3828/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3829/// `0` — a breaker that trips on the first call), so a programmatic
3830/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3831/// and the equivalent author-surface form
3832/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3833/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3834/// `max_failures` value far above the documented production-playbook
3835/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3836/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3837/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3838/// typical 5–50) silently disables the breaker's protection role:
3839/// the threshold is structurally so high that no realistic
3840/// failures-per-`:window` traffic shape can reach it, so the breaker
3841/// never trips and the typed slot becomes a no-op carried on every
3842/// emitted Envoy / Cilium L7 overlay. Pairs with the
3843/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3844/// axis — both close the "structurally unbounded `u32` ceiling on a
3845/// typed policy axis" footgun the prior zero-floor-only checks left
3846/// open.
3847///
3848/// The `1000` ceiling sits an order of magnitude above every
3849/// documented upstream production-playbook recommendation band (the
3850/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3851/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3852/// the clearly-pathological "effectively no protection"
3853/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3854/// plausibly want at hyperscale, but a hard wall above which the
3855/// policy is structurally a no-op. Lifted as a typed `pub const` so
3856/// the bound has exactly one source of truth — the future M4
3857/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3858/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3859/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3860/// one place. Same shape every other typed upper bound in this crate
3861/// carries ([`POLICY_RETRIES_MAX`],
3862/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3863/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3864/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3865pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3866
3867/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3868/// every validated [`CircuitBreaker::window`] past
3869/// [`AplicacaoSpec::validate_politicas`] lies in
3870/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3871/// integer-millisecond magnitudes by the canonical-form gate
3872/// immediately preceding).
3873///
3874/// The typed field is `Duration` (the zero-floor arm
3875/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3876/// `Duration::ZERO`, and the canonical-form arm
3877/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3878/// sub-millisecond residue), so a programmatic struct literal
3879/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3880/// and the equivalent author-surface form
3881/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3882/// integer-hour magnitude) both round-trip cleanly through serde — a
3883/// structurally unbounded `Duration` ceiling. A `:window` value far
3884/// above the documented production-playbook band (Hystrix
3885/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3886/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3887/// Istio `outlierDetection.interval` default `10s`, Envoy
3888/// `outlier_detection.interval` default `10s`, AWS App Mesh
3889/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3890/// breaker's role: a rolling-window failure counter whose window is
3891/// hours long is operationally a lifetime counter, the breaker's
3892/// "recent failures" memory is structurally so long that transient
3893/// failures are never forgotten, and the typed slot becomes a no-op
3894/// trigger that trips once and stays tripped for the lifetime of the
3895/// component carried on every emitted Envoy / Cilium L7 overlay.
3896///
3897/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3898/// shared duration codec emits (`"<n>h"` for any integer-hour
3899/// magnitude) — every value in the canonical authoring form's
3900/// `<integer><unit>` grammar at or below this cap renders to a clean
3901/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3902/// cap on the first typed-`Duration` `:politicas` axis: the two
3903/// duration-typed `:politicas` axes now share a single uniform top
3904/// edge so the next typed-slot wiring (the future caixa-mesh
3905/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3906/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3907/// admission webhook) reaches for either field knowing the value is
3908/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3909/// sits two orders of magnitude above every documented upstream
3910/// production-playbook recommendation band (Hystrix / resilience4j /
3911/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3912/// and below the clearly-pathological "rolling window degenerates to
3913/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3914/// author can plausibly want for a very-low-traffic long-tail
3915/// failure-detection window, but a hard wall above which the breaker's
3916/// rolling-window contract is structurally a lifetime-counter contract.
3917/// Lifted as a typed `pub const` so the bound has exactly one source
3918/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3919/// materializer's admission webhook and the caixa-mesh-side
3920/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3921/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3922/// other typed upper bound in this crate carries
3923/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3924/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3925/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3926/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3927/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3928pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3929
3930/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3931/// every validated [`RateLimit::rate`] past
3932/// [`AplicacaoSpec::validate_politicas`] lies in
3933/// `1..=POLICY_RATE_LIMIT_MAX`.
3934///
3935/// The typed field is `u32` (the zero-floor arm
3936/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3937/// zero-rate limit denies every request, the canonical "I forgot
3938/// that 0 means deny-everything" footgun), so a programmatic struct
3939/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3940/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3941/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3942/// round-trip cleanly through serde — a structurally unbounded `u32`
3943/// ceiling. The runtime substrate consuming the value (Envoy's
3944/// `local_rate_limit.token_bucket.max_tokens`, the future
3945/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3946/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3947/// rate-limit into a no-op rate-limiter: the bucket capacity is
3948/// structurally so high no realistic per-edge traffic shape can
3949/// drain it, the limiter never trips, and the typed slot becomes a
3950/// "rate-limit declared, no enforcement" footgun — the canonical
3951/// declared-but-inert shape every other `:politicas` cap arm
3952/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3953/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3954///
3955/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3956/// above every documented upstream production-playbook recommendation
3957/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3958/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3959/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3960/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3961/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3962/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3963/// `u32::MAX`): a value the author can plausibly want at hyperscale
3964/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3965/// /h-window arm), but a hard wall above which the policy is
3966/// structurally a no-op carried verbatim on every emitted Envoy /
3967/// Cilium L7 overlay. The cap brackets all three canonical windows
3968/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3969/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3970/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3971/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3972/// has exactly one source of truth — the future M4
3973/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3974/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3975/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3976/// one place. Same shape every other typed upper bound in this crate
3977/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3978/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3979/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3980/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3981/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3982/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3983pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3984
3985// `:entrada :host` total-length and per-label cap axes route through
3986// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3987// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3988// pair of aplicacao-private aliases the previous `validate_entrada_host`
3989// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3990// = 63`) were structurally the same K8s Gateway API v1 Hostname
3991// admission-schema bounds — the total-length cap on the OpenAPI
3992// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3993// same regex — that the peer axes at the caixa-core::render level pin,
3994// so hoisting both readers onto the shared lifted constants closes the
3995// third-occurrence duplication threshold structurally: the M4
3996// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3997// label validator, the future per-`Certificate` SAN emitter, and every
3998// other per-Gateway-API-Hostname landing site reach the same one place
3999// as the `:entrada :host` gate does — no per-axis alias drift surface
4000// between them, by construction.
4001
4002/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
4003/// extractor expression — the upper bound `validate_placement_shard_key`
4004/// enforces on every well-shaped shard-key past validate. The realistic
4005/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
4006/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
4007/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
4008/// `:placement :affinity` / `:placement :clusters` identifier-shaped
4009/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
4010/// in `:shard-key`" footgun at validate time rather than at the future
4011/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
4012const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
4013
4014/// Reject `:membros :caixa` values the K8s apiserver would refuse at
4015/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4016/// that maps the shared parser-shaped reason into the
4017/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
4018/// is self-locating (the offending `caixa:` is named verbatim) and
4019/// the author can grep their caixa.lisp for `:caixa "<name>"` and
4020/// fix it in one edit. Same diagnostic shape as
4021/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
4022/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
4023fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
4024 // Empty is already gated by `MembroCaixaEmpty` at the call site;
4025 // re-checking here keeps the predicate usable from any future
4026 // call site (the M4 CR materializer) without an empty-check
4027 // footgun. The shared
4028 // [`crate::render::require_valid_dns_1123_label`] helper brackets
4029 // the empty-first + shape cascade every peer name axis
4030 // (`:placement :clusters`, `:placement :affinity`, `:contratos
4031 // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
4032 // `:upgrade-from :module`) routes through, so drift between the
4033 // eight axes' accepted DNS-1123-label sets is structurally
4034 // impossible.
4035 crate::render::require_valid_dns_1123_label(
4036 caixa,
4037 || AplicacaoError::MembroCaixaEmpty,
4038 |reason| AplicacaoError::MembroCaixaInvalid {
4039 caixa: caixa.to_string(),
4040 reason,
4041 },
4042 )
4043}
4044
4045/// Reject `:placement :clusters` entries the K8s apiserver would refuse
4046/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4047/// that maps the shared parser-shaped reason into the
4048/// [`AplicacaoError::PlacementClusterInvalid`] variant.
4049///
4050/// Cluster names land in DNS-1123-label territory across every consumer:
4051/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
4052/// the `lareira-fleet-programs` aggregator applies to scope programs to
4053/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
4054/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
4055/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
4056/// cluster identity the M4 CR materializer round-trips. Each apiserver-
4057/// side schema enforces the DNS-1123 label rule on admission; a
4058/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
4059/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
4060/// mistaken-identity slug) silently passes the prior empty-/duplicate-
4061/// only gate and the failure surfaces as a no-match at filter time —
4062/// the workload doesn't land in the named cluster, with no diagnostic
4063/// naming the offending `:clusters` entry. Lifting the gate to caixa-
4064/// build time mirrors the `:membros :caixa` value-shape trajectory
4065/// (3f9d7a0) on the peer name axis.
4066///
4067/// The diagnostic carries the offending `cluster:` verbatim plus a
4068/// parser-shaped `reason:` naming the specific violation, so the
4069/// author can grep their caixa.lisp for `:clusters` and fix it in
4070/// one edit. Same diagnostic shape as
4071/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
4072fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
4073 // Empty is already gated by `PlacementClusterEmpty` at the call
4074 // site; re-checking here keeps the predicate usable from any
4075 // future call site (the M4 CR materializer's per-cluster validator)
4076 // without an empty-check footgun. Routes through the shared
4077 // [`crate::render::require_valid_dns_1123_label`] gate the peer
4078 // name axes each land on.
4079 crate::render::require_valid_dns_1123_label(
4080 cluster,
4081 || AplicacaoError::PlacementClusterEmpty,
4082 |reason| AplicacaoError::PlacementClusterInvalid {
4083 cluster: cluster.to_string(),
4084 reason,
4085 },
4086 )
4087}
4088
4089/// Reject `:placement :affinity` hints whose shape can never legitimately
4090/// land in any downstream selector or label-keyed routing axis. Thin
4091/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4092/// shared parser-shaped reason into the
4093/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
4094/// diagnostic is self-locating (the offending `:affinity` is named
4095/// verbatim) and the author can grep their caixa.lisp for
4096/// `:affinity "<hint>"` and fix it in one edit.
4097///
4098/// The `:affinity` slot carries a placement-engine hint — canonical
4099/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
4100/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
4101/// compression overlay and the future M4 placement-engine's per-hint
4102/// routing axis. Each downstream consumer (caixa-mesh's
4103/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
4104/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4105/// `spec.placement.affinity` admission rule, the future M4 per-hint
4106/// node-affinity / pod-affinity rule generator keying off the same
4107/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
4108/// selector) requires the value to be a DNS-1123 label — K8s label
4109/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
4110/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
4111/// admission rule the apiserver enforces.
4112///
4113/// Until this gate landed an `:affinity "DataLocality"` (the canonical
4114/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
4115/// Python-module-name leak), `:affinity "data.locality"` (the
4116/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
4117/// `:affinity "data-locality-"` (boundary-hyphen violation),
4118/// `:affinity "data locality"` (paste-from-doc whitespace),
4119/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
4120/// 64-byte over-cap slug silently passed the empty-only check and the
4121/// failure surfaced as a no-match at the M3 Adaptive compression
4122/// overlay's filter time (`placement.affinity` carried a malformed
4123/// value, no node matched, the workload landed on the default
4124/// heuristic) — the canonical "declared-but-inert" footgun mirroring
4125/// the empty-:affinity / empty-shard-key / zero-:politicas /
4126/// empty-:contratos-target gates already close on every other
4127/// declare-but-no-opinion axis. Lifting the rejection to a build-time
4128/// gate closes the fifth typed slot on the Aplicacao surface to land
4129/// on the canonical DNS-1123 label floor (after the four Servico-name
4130/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
4131/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
4132/// b0e8748).
4133///
4134/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
4135/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
4136/// validated values are guaranteed-accepted by the apiserver without
4137/// re-validation at any downstream renderer or admission layer.
4138fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
4139 // Empty is gated separately at the call site for a self-locating
4140 // diagnostic; re-checking here keeps the predicate usable from any
4141 // future call site (the M4 CR materializer's per-affinity
4142 // validator) without an empty-check footgun. Routes through the
4143 // shared [`crate::render::require_valid_dns_1123_label`] gate the
4144 // peer name axes each land on.
4145 crate::render::require_valid_dns_1123_label(
4146 affinity,
4147 || AplicacaoError::PlacementAffinityEmpty,
4148 |reason| AplicacaoError::PlacementAffinityInvalid {
4149 affinity: affinity.to_string(),
4150 reason,
4151 },
4152 )
4153}
4154
4155/// Reject `:placement :shard-key` extractor expressions whose shape can
4156/// never legitimately drive the future M4 Akka-style cluster-sharding
4157/// reconciler's hash-extractor pass. Maps the per-byte / length checks
4158/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
4159/// diagnostic is self-locating (the offending `:shard-key` value is
4160/// named verbatim alongside the parser-shaped reason) and the author can
4161/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
4162/// edit.
4163///
4164/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
4165/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
4166/// expression naming the message property to hash on. The realistic
4167/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
4168/// property name; `$tenantId` — Akka entity-id placeholder;
4169/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
4170/// `${tenant}` — interpolation-style template) all sit in the printable
4171/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
4172/// multi-line blob landing in `:shard-key`, an embedded space from a
4173/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
4174/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
4175/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
4176/// check and the failure surfaces at the future M4 reconciler's hash
4177/// pass as a runtime extractor-evaluation error far from the source
4178/// `caixa.lisp`, with no field naming which member's `:shard-key`
4179/// carried the offending value.
4180///
4181/// The contract — the printable ASCII single-token intersection-floor
4182/// every Akka-style entity-id extractor implementation admits:
4183///
4184/// - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
4185/// peer DNS-1123-label-shaped `:placement :affinity` /
4186/// `:placement :clusters` identifier axes; realistic shard-keys sit
4187/// well under 32 bytes, the cap surfaces paste-from-doc multi-line
4188/// blob footguns at validate time;
4189/// - every byte in the printable ASCII range `0x21..=0x7E` —
4190/// rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
4191/// `"$tenantId\n"` from paste-from-aligned-doc /
4192/// paste-from-shell-heredoc), control characters (`\x00..\x1F`,
4193/// `\x7F` — the canonical "embedded null from a copy-paste-binary
4194/// footgun"), and non-ASCII bytes (`"$tenàntId"` —
4195/// un-Punycode-encoded IDN that round-trips inconsistently across
4196/// NFC/NFD normalization).
4197///
4198/// The accepted set is broader than the DNS-1123 label floor the peer
4199/// `:placement :clusters` / `:placement :affinity` axes use because the
4200/// `:shard-key` value is not a K8s `metadata.name` / label-selector
4201/// landing site; it's an extractor expression the future Akka-style
4202/// reconciler reads as a property reference. The realistic forms
4203/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
4204/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
4205/// but every Akka-style entity-id extractor parses. The
4206/// printable-ASCII-token floor accepts every shape any such extractor
4207/// would accept while rejecting the cross-implementation footguns
4208/// (whitespace breaks token boundaries; non-ASCII round-trips
4209/// inconsistently across YAML emitters and NFC/NFD normalization;
4210/// control characters silently corrupt the next read).
4211///
4212/// Until this gate landed `validate_placement` only refused the
4213/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
4214/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
4215/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
4216/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
4217/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
4218/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
4219/// control character from paste-from-binary, the 64-byte over-cap
4220/// paste-from-doc multi-line slug) silently passed validate. The future
4221/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
4222/// would then surface the malformed value either as a runtime
4223/// extractor-evaluation error (whitespace breaks the extractor's token
4224/// boundary, no match) or as a silently-different shard assignment
4225/// across YAML emitters (non-ASCII normalizes differently between the
4226/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
4227/// parser, the same entity ID maps to two distinct shards on a
4228/// re-render). Lifting the shape gate to caixa-build time makes the
4229/// extractor-floor invariant a structural property of every validated
4230/// `Placement`: every `Sharded` placement past `validate_placement` has
4231/// a `:shard-key` the future M4 reconciler can hash without
4232/// re-validating at the runtime layer.
4233///
4234/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
4235/// [`AplicacaoError::ContratoSubjectInvalid`] /
4236/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
4237/// on the peer `:contratos` payload axes — each lifts the
4238/// runtime-side parser's intersection-floor to a caixa-build-time gate,
4239/// closing the canonical "this passed validate but the runtime parser
4240/// rejected it" surprise.
4241fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
4242 // Empty is gated separately at the call site via the more
4243 // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
4244 // re-checking here keeps the predicate usable from any future call
4245 // site (the M4 CR materializer's per-shard-key validator) without
4246 // an empty-check footgun.
4247 if key.is_empty() {
4248 return Err(AplicacaoError::ShardedKeyEmpty);
4249 }
4250 if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
4251 return Err(AplicacaoError::ShardKeyInvalid {
4252 shard_key: key.to_string(),
4253 reason: format!(
4254 "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
4255 (got {} bytes; realistic Akka-style entity-id extractor expressions \
4256 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
4257 well under 32 bytes, this length suggests a paste-from-doc \
4258 multi-line blob landed in `:shard-key` instead of a single-token \
4259 extractor expression)",
4260 key.len()
4261 ),
4262 });
4263 }
4264 for &b in key.as_bytes() {
4265 if (0x21..=0x7E).contains(&b) {
4266 continue;
4267 }
4268 let reason = if b == b' ' {
4269 "contains a space (Akka-style entity-id extractor expressions are \
4270 single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
4271 whitespace breaks the extractor's token boundary at the runtime layer, \
4272 and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
4273 a multi-token blob in one `:shard-key` slot)"
4274 .to_string()
4275 } else if b == b'\t' {
4276 "contains a tab character (paste-from-aligned-doc footgun; the \
4277 Akka-style entity-id extractor reads `:shard-key` as a single-token \
4278 reference, embedded whitespace breaks the token boundary at the \
4279 runtime hash-extractor pass)"
4280 .to_string()
4281 } else if b == b'\n' || b == b'\r' {
4282 format!(
4283 "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
4284 paste-from-multiline-doc footgun; the Akka-style entity-id \
4285 extractor reads `:shard-key` as a single-token reference, embedded \
4286 newlines either truncate the value at the YAML emitter layer or \
4287 break the token boundary at the runtime hash-extractor pass)"
4288 )
4289 } else if b < 0x20 || b == 0x7F {
4290 format!(
4291 "contains control character 0x{b:02x} (the canonical \
4292 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
4293 control characters silently corrupt round-trip serialization \
4294 across YAML emitters and break the runtime hash-extractor's \
4295 single-token parser)"
4296 )
4297 } else {
4298 format!(
4299 "contains non-ASCII byte 0x{b:02x} (the canonical \
4300 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
4301 inconsistently across NFC/NFD normalization on APFS / ext4 / \
4302 across YAML emitter implementations — the same entity ID can \
4303 silently map to two distinct shards on a re-render. Use a \
4304 printable-ASCII extractor expression like `tenantId`, \
4305 `$tenantId`, or `metadata.tenantId`)"
4306 )
4307 };
4308 return Err(AplicacaoError::ShardKeyInvalid {
4309 shard_key: key.to_string(),
4310 reason,
4311 });
4312 }
4313 Ok(())
4314}
4315
4316/// Reject `:contratos :de` / `:contratos :para` values whose shape
4317/// can never legitimately match a validated `:membros :caixa`. Thin
4318/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4319/// shared parser-shaped reason into the
4320/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4321/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4322/// the offending value verbatim) and the author can grep their
4323/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4324/// one edit.
4325///
4326/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4327/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4328/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4329/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4330/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4331/// un-Punycode-encoded IDN) silently passed the per-axis check and
4332/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4333/// membership lookup — diagnostic-framed as "this caixa is not in
4334/// `:membros`" when the root cause is "this `:de` value is not a
4335/// well-shaped Servico-name identifier and could never legitimately
4336/// match any validated member". Because every `:membros :caixa` is
4337/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4338/// `names` HashSet structurally never contains an empty / malformed
4339/// string, so the membership lookup arm misframes every empty /
4340/// malformed input. Lifting the shape arm ahead of the lookup
4341/// preserves the legitimate `ContratoMemberMissing` arm (a
4342/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4343/// reference) while routing every structurally-impossible-to-match
4344/// input through the narrower self-locating shape diagnostic.
4345///
4346/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4347/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4348/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4349/// to land on the canonical [`crate::render::is_dns_1123_label`]
4350/// floor. The `slot: &'static str` field carries the kebab-case
4351/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4352/// per-callback-slot diagnostic shape and the
4353/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4354/// (85f102c) cross-list-tag pattern.
4355fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4356 // Routes through the shared
4357 // [`crate::render::require_valid_dns_1123_label`] gate the peer
4358 // name axes each land on. The `slot: &'static str` field flows
4359 // through both error variants so the diagnostic names which
4360 // per-edge axis (`:de` vs `:para`) the offending value came from.
4361 crate::render::require_valid_dns_1123_label(
4362 caixa,
4363 || AplicacaoError::ContratoCaixaEmpty { slot },
4364 |reason| AplicacaoError::ContratoCaixaInvalid {
4365 slot,
4366 caixa: caixa.to_string(),
4367 reason,
4368 },
4369 )
4370}
4371
4372/// Reject `:entrada :para` values whose shape can never legitimately
4373/// match a validated `:membros :caixa`. Thin wrapper around
4374/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4375/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4376/// variant, so the diagnostic is self-locating (the offending
4377/// `:entrada :para` value is named verbatim) and the author can grep
4378/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4379///
4380/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4381/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4382/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4383/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4384/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4385/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4386/// silently passed the per-axis check and surfaced as
4387/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4388/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4389/// root cause is "this `:entrada :para` value is not a well-shaped
4390/// Servico-name identifier and could never legitimately match any
4391/// validated member". Because every `:membros :caixa` is shape-
4392/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4393/// `HashSet` structurally never contains an empty / malformed string,
4394/// so the membership lookup arm misframes every empty / malformed
4395/// input. Lifting the shape arm ahead of the lookup preserves the
4396/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4397/// simply isn't in `:membros` — a phantom reference) while routing
4398/// every structurally-impossible-to-match input through the narrower
4399/// self-locating shape diagnostic.
4400///
4401/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4402/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4403/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4404/// fourth and last Aplicacao-level Servico-name reference axis to
4405/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4406/// No `slot: &'static str` field because there is only one axis
4407/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4408/// the simpler shape mirrors [`validate_membro_caixa`] and
4409/// [`validate_placement_cluster`].
4410fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4411 // Empty is gated separately at the call site for a self-locating
4412 // diagnostic; re-checking here keeps the predicate usable from any
4413 // future call site (the M4 CR materializer's per-`:entrada`
4414 // validator) without an empty-check footgun. Routes through the
4415 // shared [`crate::render::require_valid_dns_1123_label`] gate the
4416 // peer name axes each land on.
4417 crate::render::require_valid_dns_1123_label(
4418 para,
4419 || AplicacaoError::EntradaParaEmpty,
4420 |reason| AplicacaoError::EntradaParaInvalid {
4421 para: para.to_string(),
4422 reason,
4423 },
4424 )
4425}
4426
4427/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
4428/// would refuse at admission time. The contract — exactly the regex
4429/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
4430/// and `HTTPRoute.spec.hostnames[]`,
4431/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
4432/// (max length 253; per-label max length 63):
4433///
4434/// - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
4435/// uppercase, no underscore, no Unicode/IDN — IDN must be
4436/// pre-encoded as Punycode `xn--…` by the author);
4437/// - exactly one optional leading wildcard label (`*.`); a wildcard
4438/// in any non-leading label position is rejected;
4439/// - each `.`-separated label is 1..=63 bytes, with non-hyphen
4440/// alphanumeric at both boundaries (no `-foo`, no `foo-`);
4441/// - total length 1..=253 bytes;
4442/// - no IPv4 literal (Gateway API forbids IP literals);
4443/// - no scheme (`https://`, `http://`), no port (`:8080`), no
4444/// whitespace, no path (`/`).
4445///
4446/// Lifted as a typed gate (rather than an inline cascade in
4447/// `validate()`) so the contract lives in one place — every future
4448/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4449/// materializer's host validator, the future per-`:entrada` SAN
4450/// emission for cert-manager Certificates, the multi-`:entrada`
4451/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
4452/// for the same predicate, not its own. Same compounding shape as
4453/// `is_canonical_rate_limit_window` (808017c) and
4454/// [`WitTarget::label`] (previously the free `contrato_target_label`
4455/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
4456/// per-variant label match is compiler-checked-exhaustive).
4457///
4458/// The diagnostic carries the offending `host:` verbatim plus a
4459/// parser-shaped `reason:` naming the specific violation, so the
4460/// author can grep their caixa.lisp for `:host "<host>"` and fix it
4461/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
4462/// (9888b13).
4463fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
4464 // Empty is already gated by `EmptyEntradaHost` at the call site;
4465 // re-checking here keeps the predicate usable from any future
4466 // call site (M4 CR materializer) without an empty-check footgun.
4467 if host.is_empty() {
4468 return Err(AplicacaoError::EmptyEntradaHost);
4469 }
4470 if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
4471 return Err(AplicacaoError::EntradaHostInvalid {
4472 host: host.to_string(),
4473 reason: format!(
4474 "exceeds Gateway API v1 Hostname max length of {cap} bytes \
4475 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
4476 host.len(),
4477 cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
4478 ),
4479 });
4480 }
4481 if host.contains("://") {
4482 return Err(AplicacaoError::EntradaHostInvalid {
4483 host: host.to_string(),
4484 reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
4485 Gateway API takes the bare hostname)"
4486 .to_string(),
4487 });
4488 }
4489 if host.contains('/') {
4490 return Err(AplicacaoError::EntradaHostInvalid {
4491 host: host.to_string(),
4492 reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
4493 matching is in `:entrada :paths`)"
4494 .to_string(),
4495 });
4496 }
4497 // After the `://` scheme-prefix and `/` path arms have ruled out the
4498 // two `:`-bearing shapes the Gateway API actively rejects with
4499 // location-shaped diagnostics, any remaining `:` in the host body is
4500 // either the canonical "I put the port in the `:host` slot"
4501 // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
4502 // slot lives one axis away on the same `:entrada` block) or an
4503 // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
4504 // Hostname forbids identically to the IPv4-literal arm below. Both
4505 // shapes silently fell through the `://` and `/` arms before this
4506 // lift and surfaced as a deep `label "<rest>:<port>" contains
4507 // invalid character ':'` diagnostic from the per-byte loop near the
4508 // bottom of this predicate, which named the offending byte but not
4509 // the canonical authoring fix — for the port case the author has to
4510 // know the `:entrada` block carries a separate `:port u16` slot
4511 // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
4512 // move the value over; for the IPv6 case the author has to know
4513 // Gateway API v1 forbids IP literals across the board. The contract
4514 // doc-comment above already promises "no port (`:8080`)" verbatim
4515 // in the rejected-shape enumeration but the predicate's
4516 // implementation refused the `:` only as a side-effect of the
4517 // per-label `[a-z0-9-]` character-class loop; this arm brings the
4518 // implementation in line with the documented contract by surfacing
4519 // the canonical fix at the top-level shape gate, peer with how the
4520 // `://` arm names the scheme prefix and the `/` arm names the
4521 // `:entrada :paths` axis. Same compounding trajectory the recent
4522 // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
4523 // — the typed slot's rejected set matches the apiserver's rejected
4524 // set, structurally, with a self-locating diagnostic at the
4525 // offending axis instead of a deep parser-shape leak.
4526 if host.contains(':') {
4527 return Err(AplicacaoError::EntradaHostInvalid {
4528 host: host.to_string(),
4529 reason: "must not contain `:` (the port belongs in the `:entrada :port` \
4530 slot — a separate `u16` axis on the same `:entrada` block, \
4531 defaulting to 8080 — not in the host body; drop the `:<port>` \
4532 suffix and author the bare hostname. If you intended an IPv6 \
4533 literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
4534 Hostname forbids IP literals identically to the IPv4-literal \
4535 arm — use a DNS name)"
4536 .to_string(),
4537 });
4538 }
4539 // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
4540 // predicate — the same single source of truth every peer
4541 // ASCII-whitespace scan in caixa-core flows through: the four
4542 // typed-magnitude codec sites (`limits::parse_byte_size` backing
4543 // `:limits :memory`, `limits::parse_duration` backing `:limits
4544 // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
4545 // `aplicacao::rate_limit_codec::parse` backing `:politicas
4546 // :rate-limit`) and the shared duration codec
4547 // (`supervisor::duration_codec::parse`) backing `:supervisor
4548 // :restart-window` / `:politicas :timeout` / `:politicas
4549 // :circuit-breaker :window`. This landing closes the last string-typed
4550 // slot in caixa-core still calling `.bytes().any(|b|
4551 // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
4552 // across every typed slot now shares one predicate, so a future
4553 // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
4554 // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
4555 // deliberately excluded from the peer non-ASCII predicate) can
4556 // extend at this shared site in one edit rather than seven
4557 // independent scans diverging over time. Naming the offending byte
4558 // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
4559 // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
4560 // the offending byte verbatim" discipline every peer codec site
4561 // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4562 // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4563 if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4564 return Err(AplicacaoError::EntradaHostInvalid {
4565 host: host.to_string(),
4566 reason: format!(
4567 "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4568 Hostname is a single-token DNS name — leading, trailing, \
4569 or embedded whitespace breaks the K8s apiserver's Hostname \
4570 regex at admission time; the paste-from-aligned-doc / \
4571 paste-from-shell-history / paste-from-CSV footgun silently \
4572 lands a multi-token blob in `:entrada :host`. Strip every \
4573 whitespace byte and author the bare hostname — space \
4574 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4575 refuse identically)"
4576 ),
4577 });
4578 }
4579 // Peer of the ASCII-whitespace scan above: route the non-ASCII
4580 // subset of Unicode `White_Space` through the shared
4581 // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4582 // single source of truth every peer non-ASCII-whitespace scan in
4583 // caixa-core flows through: `limits::parse_byte_size` (`:limits
4584 // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4585 // `limits::parse_millicores` (`:limits :cpu`),
4586 // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4587 // and `supervisor::duration_codec::parse` (`:supervisor
4588 // :restart-window` / `:politicas :timeout` / `:politicas
4589 // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4590 // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4591 // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4592 // paste-from-web-doc), or an EM-SPACE-split host
4593 // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4594 // survived this predicate's ASCII byte-scan (none of the UTF-8
4595 // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4596 // `u8::is_ascii_whitespace`), then landed on the per-label
4597 // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4598 // predicate with the generic `label "…" must start and end with an
4599 // alphanumeric` diagnostic — a "far from source at build-time"
4600 // leak that names the label-shape violation but not the
4601 // paste-from-typography origin the author actually needs to fix.
4602 // Peer with the four codec sites the 1b75b38 landing pinned: the
4603 // typed slot's diagnostic axis names the offending codepoint
4604 // (`U+XXXX`) verbatim rather than laundering the value through a
4605 // downstream label-shape arm, so the author can grep their
4606 // caixa.lisp for the invisible codepoint at the surfaced position
4607 // rather than eyeball a multi-byte host for embedded NBSP / LINE
4608 // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4609 // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4610 // drift between any two typed-slot sites' non-ASCII-whitespace
4611 // rejection set becomes a single-edit fix at the shared predicate
4612 // rather than N independent inline scans diverging over time, and
4613 // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4614 // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4615 // `char::is_whitespace`" class the peer non-ASCII predicate's
4616 // doc-comment names as the follow-up trajectory) extends at the
4617 // shared predicate in one edit rather than seven.
4618 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4619 return Err(AplicacaoError::EntradaHostInvalid {
4620 host: host.to_string(),
4621 reason: format!(
4622 "contains non-ASCII Unicode whitespace character {ch:?} \
4623 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4624 single-token DNS name limited to `[a-z0-9-]` labels; \
4625 the paste-from-typography footgun silently lands an \
4626 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4627 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4628 `U+3000`, and every other member of the Unicode \
4629 `White_Space` property outside the ASCII byte range) \
4630 in `:entrada :host`, which the K8s apiserver's \
4631 Hostname regex refuses at admission time far from the \
4632 caixa.lisp source line. Strip every non-ASCII \
4633 whitespace character and author the bare hostname \
4634 with only ASCII bytes (write \"checkout.quero.cloud\" \
4635 verbatim)",
4636 codepoint = ch as u32,
4637 ),
4638 });
4639 }
4640
4641 // Strip the optional single leading wildcard label *before* the
4642 // trailing-dot check so the bare `"*."` form surfaces the more
4643 // self-locating "wildcard without domain" diagnostic instead of
4644 // the generic "trailing dot" one.
4645 let (had_wildcard, rest) = match host.strip_prefix("*.") {
4646 Some(r) => (true, r),
4647 None => (false, host),
4648 };
4649 if had_wildcard && rest.is_empty() {
4650 return Err(AplicacaoError::EntradaHostInvalid {
4651 host: host.to_string(),
4652 reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4653 });
4654 }
4655 if rest.contains('*') {
4656 return Err(AplicacaoError::EntradaHostInvalid {
4657 host: host.to_string(),
4658 reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4659 no inner or trailing `*` labels"
4660 .to_string(),
4661 });
4662 }
4663 if rest.ends_with('.') {
4664 return Err(AplicacaoError::EntradaHostInvalid {
4665 host: host.to_string(),
4666 reason: "must not have a trailing `.` (Gateway API hostnames are not \
4667 fully-qualified with a root dot; the apiserver regex rejects \
4668 trailing dots)"
4669 .to_string(),
4670 });
4671 }
4672
4673 // Reject pure IPv4 literals: four dot-separated labels, every
4674 // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4675 // literals as Hostnames.
4676 let labels: Vec<&str> = rest.split('.').collect();
4677 if labels.len() == 4
4678 && labels
4679 .iter()
4680 .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4681 {
4682 return Err(AplicacaoError::EntradaHostInvalid {
4683 host: host.to_string(),
4684 reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4685 literals; use a DNS name)"
4686 .to_string(),
4687 });
4688 }
4689
4690 // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4691 // hyphen, with non-hyphen at both boundaries.
4692 for label in &labels {
4693 if label.is_empty() {
4694 return Err(AplicacaoError::EntradaHostInvalid {
4695 host: host.to_string(),
4696 reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4697 });
4698 }
4699 if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4700 return Err(AplicacaoError::EntradaHostInvalid {
4701 host: host.to_string(),
4702 reason: format!(
4703 "label {label:?} exceeds DNS-1123 label max length of \
4704 {cap} bytes (got {} bytes)",
4705 label.len(),
4706 cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4707 ),
4708 });
4709 }
4710 let bytes = label.as_bytes();
4711 if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4712 return Err(AplicacaoError::EntradaHostInvalid {
4713 host: host.to_string(),
4714 reason: format!(
4715 "label {label:?} must start and end with an alphanumeric \
4716 (no leading or trailing `-`)"
4717 ),
4718 });
4719 }
4720 for &b in bytes {
4721 let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4722 if !valid {
4723 let msg = if b.is_ascii_uppercase() {
4724 format!(
4725 "label {label:?} contains uppercase character {ch:?} \
4726 (Gateway API hostnames are lowercase-only; use {lower:?})",
4727 ch = b as char,
4728 lower = label.to_ascii_lowercase()
4729 )
4730 } else if b == b'_' {
4731 format!(
4732 "label {label:?} contains `_` (Gateway API hostnames \
4733 allow only `[a-z0-9-]`; use `-` instead)"
4734 )
4735 } else {
4736 format!(
4737 "label {label:?} contains invalid character {ch:?} \
4738 (Gateway API hostnames allow only `[a-z0-9-]`)",
4739 ch = b as char
4740 )
4741 };
4742 return Err(AplicacaoError::EntradaHostInvalid {
4743 host: host.to_string(),
4744 reason: msg,
4745 });
4746 }
4747 }
4748 }
4749 Ok(())
4750}
4751
4752/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4753/// would refuse at admission time. Thin wrapper around
4754/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4755/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4756/// variant, preserving the more self-locating
4757/// [`AplicacaoError::EntradaPathEmpty`] /
4758/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4759/// path fails those narrower invariants first.
4760///
4761/// The contract is the canonical HTTP-path grammar — `1..=
4762/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4763/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4764/// whitespace/control/non-ASCII bytes — shared with the
4765/// `:contratos :endpoint` axis through the lifted predicate so drift
4766/// between either landing site and the K8s apiserver-side
4767/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4768/// the predicate, not a per-renderer "this passed validate but failed
4769/// admission" surprise. The diagnostic carries the offending `path:`
4770/// verbatim plus a parser-shaped `reason:` naming the specific
4771/// violation, so the author can grep their caixa.lisp for `:paths`
4772/// and fix it in one edit. Same diagnostic shape as
4773/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4774/// axis.
4775fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4776 // Empty and missing-leading-`/` are already gated at the call
4777 // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4778 // checking here keeps the per-axis narrower diagnostics in force
4779 // when the predicate is reached directly (and `is_gateway_api_http_path`
4780 // itself defends against `bytes[0]`-style indexing on empty
4781 // input).
4782 if path.is_empty() {
4783 return Err(AplicacaoError::EntradaPathEmpty);
4784 }
4785 if !path.starts_with('/') {
4786 return Err(AplicacaoError::EntradaPathNotAbsolute {
4787 path: path.to_string(),
4788 });
4789 }
4790 crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4791 AplicacaoError::EntradaPathInvalid {
4792 path: path.to_string(),
4793 reason,
4794 }
4795 })
4796}
4797
4798mod rate_limit_codec {
4799 // `Duration` is no longer named here — the codec routes through
4800 // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4801 // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4802 // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4803 // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4804 // closed-set enum's arm-table rather than through vestigial free-helper
4805 // delegates.
4806 use super::{RateLimit, RateLimitUnit};
4807 use serde::{Deserialize, Deserializer, Serializer};
4808
4809 pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4810 match v {
4811 Some(rl) => s.serialize_str(&render(*rl)),
4812 None => s.serialize_none(),
4813 }
4814 }
4815
4816 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4817 let opt: Option<String> = Option::deserialize(d)?;
4818 match opt {
4819 None => Ok(None),
4820 Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4821 }
4822 }
4823
4824 fn parse(s: &str) -> Result<RateLimit, String> {
4825 // Whitespace-rejection arm — peer with the leading-`+`
4826 // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4827 // same canonical-form render-determinism axis. Until this gate
4828 // landed the parser silently tolerated leading / trailing /
4829 // internal whitespace via the top-level `s.trim()` and the
4830 // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4831 // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4832 // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4833 // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4834 // serde silently round-tripped to `"100/s"` on the next emit
4835 // (a *different* canonical string) — breaking the THEORY.md
4836 // Part V render-determinism contract on the same
4837 // canonical-form-drift axis the leading-`+` arm below (the
4838 // 4eeae98 predecessor) and the leading-zero arm below (the
4839 // 4f46830 predecessor) already close.
4840 //
4841 // The canonical author shape is `<integer>/<s|m|h>` with no
4842 // whitespace bytes anywhere — every string [`render`] emits
4843 // carries none, so the parser's accepted set must match for
4844 // serialize / deserialize to round-trip losslessly. This gate
4845 // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4846 // `unit.trim()` calls below strict no-ops on the accepted set
4847 // (every byte-position match they would perform is now already
4848 // trimmed away by the accepted set itself), while the arm
4849 // surfaces every rejected whitespace-carrying shape with a
4850 // self-locating diagnostic naming the offending byte and the
4851 // canonical form the author intended, peer with every prior
4852 // canonical-form-drift arm on this codec.
4853 //
4854 // Routed through the lifted
4855 // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4856 // same source of truth the four peer typed-magnitude codec
4857 // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4858 // `limits::parse_millicores`, `supervisor::duration_codec`)
4859 // share. `u8::is_ascii_whitespace()` at the predicate covers
4860 // the five WhatWG-conformant ASCII whitespace bytes (space,
4861 // tab, LF, FF, CR); the "single lifted predicate" discipline
4862 // the peer non-ASCII arm below carries on the strictly-
4863 // complementary Unicode `White_Space` class extends here to
4864 // the ASCII byte set as well.
4865 if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4866 return Err(format!(
4867 "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4868 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4869 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4870 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4871 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4872 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4873 on first serialize — breaking the THEORY.md Part V render-determinism \
4874 contract every typed slot carries. Strip every whitespace byte (write \
4875 `\"100/s\"` verbatim)"
4876 ));
4877 }
4878 // Non-ASCII Unicode `White_Space` arm — the strictly-
4879 // complementary class the ASCII arm above cannot see.
4880 // `str::trim` at the top of every peer codec uses
4881 // `char::is_whitespace` (Unicode `White_Space`, strictly
4882 // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4883 // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4884 // survives the byte-scan (its UTF-8 bytes are not in
4885 // `is_ascii_whitespace`), gets silently stripped by the
4886 // top-level `s.trim()` below, and the value round-trips
4887 // through `render` to a *different* canonical form
4888 // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4889 // render-determinism contract every typed slot carries.
4890 // Closed here (`:politicas :rate-limit`) and at the three
4891 // peer codec sites (`limits::parse_byte_size`,
4892 // `limits::parse_duration`, `supervisor::duration_codec`)
4893 // through the shared
4894 // [`crate::render::find_non_ascii_whitespace_char`] predicate
4895 // — the "single lifted predicate across all four codec sites
4896 // in one follow-up run" the 24a8ad4 commit body's `Forward
4897 // compounding` bullet named as the next compounding step.
4898 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4899 return Err(format!(
4900 "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4901 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4902 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4903 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4904 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4905 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4906 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4907 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4908 silently strips it at parse entry, and the value round-trips through \
4909 `render` to a *different* canonical form (`\"100/s\"`) on first \
4910 serialize — breaking the THEORY.md Part V render-determinism contract \
4911 every typed slot carries. Strip every non-ASCII whitespace character \
4912 (write `\"100/s\"` verbatim with only ASCII bytes)",
4913 cp = ch as u32
4914 ));
4915 }
4916 let s = s.trim();
4917 let (rate_str, unit) = s
4918 .split_once('/')
4919 .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4920 let rate_trim = rate_str.trim();
4921 // The canonical authoring form for `:politicas :rate-limit` is
4922 // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4923 // non-negative integer with no decimal point and no leading
4924 // sign, so the parser's accepted set must match for
4925 // serialize/deserialize to round-trip without canonical-form
4926 // drift. Until this gate landed the parser accepted any
4927 // `u32::from_str`-shaped magnitude — and current Rust
4928 // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4929 // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4930 // serde silently round-tripped to `"100/s"` on the next emit
4931 // (a *different* canonical string) — breaking the THEORY.md
4932 // Part V render-determinism contract on the fifth typed-codec
4933 // surface in caixa-core (peer with the four duration codecs the
4934 // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4935 // already covered: `supervisor::duration_codec` backing three
4936 // typed-duration slots, `limits::parse_duration` backing
4937 // `:limits :wall-clock`, `limits::parse_byte_size` backing
4938 // `:limits :memory`). The fractional / decimal-shaped sibling
4939 // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4940 // existing rejection arm, but the diagnostic is value-laundered
4941 // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4942 // doesn't name the canonical-form remediation or the round-trip
4943 // drift the next emit would produce); this gate lifts the
4944 // fractional arm onto the same canonical-form diagnostic the
4945 // peer codecs carry.
4946 //
4947 // Strict canonical form: every byte of the magnitude is an
4948 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4949 // inputs the gate distinguishes "non-canonical-but-numeric"
4950 // (parses as f64 or i64 — surfaced with a self-locating
4951 // diagnostic naming the canonical authoring form and the
4952 // round-trip drift the rejected shape would produce on first
4953 // serialize) from "garbage" (parses as neither — surfaced with
4954 // the existing narrower `"not a u32"` wording so its
4955 // diagnostic shape remains stable for the parser-shape footgun
4956 // case).
4957 //
4958 // Routed through the lifted
4959 // [`crate::render::is_digit_only_magnitude`] predicate — the
4960 // same source of truth the four peer typed-magnitude codec
4961 // sites share.
4962 let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4963 if !digit_only {
4964 let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4965 if numeric {
4966 return Err(format!(
4967 "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4968 canonical authoring form for `:politicas :rate-limit` is \
4969 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4970 with no decimal point and no leading `+` / `-` sign. A fractional / \
4971 signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4972 through `render` to a *different* canonical form (`\"1/s\"`, \
4973 `\"100/s\"`, parser-reject) on first serialize — breaking the \
4974 THEORY.md Part V render-determinism contract every typed slot \
4975 carries. Pick an integer rate that fits the desired window \
4976 (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4977 ));
4978 }
4979 return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4980 }
4981 // Leading-zero arm — peer with the prior `"+100/s"` arm above
4982 // (4eeae98's predecessor) on the same canonical-form
4983 // render-determinism axis. The digit-only gate accepts
4984 // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4985 // them losslessly (= 100, 0, 7), but `render` emits the
4986 // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4987 // a *different* canonical string on the next emit, breaking
4988 // the THEORY.md Part V render-determinism contract the same
4989 // way `"+100/s"` did before the leading-`+` arm landed. The
4990 // single-byte magnitude `"0"` itself round-trips losslessly
4991 // through `render` (`render(0)` emits `"0/s"`) — the
4992 // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4993 // what refuses rate-zero authoring, so `"0/s"` stays in the
4994 // accepted set at this codec layer and the diagnostic
4995 // partitioning between canonical-form drift (this arm) and
4996 // semantic-zero (the downstream gate) remains stable.
4997 // Peer with the future leading-zero arms on the three peer
4998 // typed-magnitude codecs the trajectory acknowledges:
4999 // `supervisor::duration_codec`, `limits::parse_duration`,
5000 // `limits::parse_byte_size` — each carries the same
5001 // canonical-form-drift class today; this gate lands the
5002 // discipline on the fourth typed-magnitude codec in
5003 // caixa-core first because the peer `"+100/s"` arm above is
5004 // the closest predecessor on the trajectory.
5005 //
5006 // Routed through the lifted
5007 // [`crate::render::is_leading_zero_padded_magnitude`]
5008 // predicate — the same source of truth the four peer
5009 // typed-magnitude codec sites share.
5010 if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
5011 return Err(format!(
5012 "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
5013 canonical authoring form for `:politicas :rate-limit` is \
5014 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
5015 with no leading-zero padding on the magnitude. A leading-zero magnitude \
5016 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
5017 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
5018 first serialize — breaking the THEORY.md Part V render-determinism \
5019 contract every typed slot carries. Strip the leading zeros (write \
5020 `\"100/s\"` instead of `\"0100/s\"`)"
5021 ));
5022 }
5023 // The digit-only gate guarantees every byte is `[0-9]`, and
5024 // the leading-zero arm above guarantees the magnitude is
5025 // either the single byte `"0"` or starts with `[1-9]`, so
5026 // the only way `u32::from_str` can fail here is overflow
5027 // (the magnitude exceeds `u32::MAX`). Surface that with an
5028 // overflow-shaped wording so the diagnostic names the
5029 // offending magnitude verbatim rather than collapsing onto
5030 // the non-canonical arm. Same shape
5031 // `supervisor::duration_codec` (1c55a2a) carries on the peer
5032 // duration-codec axis.
5033 let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
5034 format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
5035 })?;
5036 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
5037 // the closed-set typed enum [`super::RateLimitUnit`]; this parse
5038 // arm reads the `&str → Duration` projection through the
5039 // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5040 // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
5041 // with [`super::RateLimitUnit::window`]) rather than the vestigial
5042 // module-private `rate_limit_window_from_unit` free helper the
5043 // predecessor 61421a6 left as the last unlifted delegate on this
5044 // axis. One typed dispatch on the substrate primitive instead of
5045 // one runtime call through the free-helper delegate; the sole
5046 // production consumer of the `&str → Duration` axis (this parse
5047 // arm) now reaches for exactly one typed method on the closed-set
5048 // enum, sibling to the codec's render arm's
5049 // [`super::RateLimit::canonical_unit`] dispatch on the paired
5050 // `Duration → RateLimitUnit` axis and to the validate gate's
5051 // [`super::RateLimit::canonical_unit`] shape-probe on the
5052 // canonical-window axis. A future rate-limit-unit addition (a
5053 // `"d"` day suffix once Envoy's `rate_limit_action` grows
5054 // daily-bucket support, a `"ms"` sub-second window once
5055 // high-throughput per-edge policies come into scope per
5056 // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
5057 // on the closed-set enum, and the compiler enforces exhaustiveness
5058 // on every consumer's `match self` arms — this parse arm's
5059 // accepted-suffix set, the render arm's emitted-suffix set, the
5060 // validate gate's canonical-window set, and every future
5061 // per-`:contratos`-edge rate-limit-override overlay all pick it up
5062 // by construction.
5063 let unit = unit.trim();
5064 let window = RateLimitUnit::window_from_suffix(unit)
5065 .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
5066 Ok(RateLimit { rate, window })
5067 }
5068
5069 fn render(rl: RateLimit) -> String {
5070 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
5071 // module scope on the closed-set typed enum [`super::RateLimitUnit`];
5072 // this render arm reads the `Duration → RateLimitUnit` projection
5073 // through the substrate primitive [`super::RateLimit::canonical_unit`]
5074 // (returns `None` on every non-canonical window — the sub-second /
5075 // non-`{1, 60, 3600}` shapes the validate gate rejects), then
5076 // formats the returned typed enum through its
5077 // [`std::fmt::Display`] impl (which routes through
5078 // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
5079 // the substrate primitive instead of one runtime `find_map`
5080 // walk through the free-helper delegate chain
5081 // [`super::rate_limit_window_unit`] (the vestigial free helper's
5082 // sole production consumer was this arm; every other consumer of
5083 // the `Duration → unit` axis — the validate gate below and the
5084 // future M4 per-Aplicacao Envoy config reconciler — now reads
5085 // the same typed method).
5086 //
5087 // A future rate-limit-unit addition (a `"d"` day suffix once
5088 // Envoy's `rate_limit_action` grows daily-bucket support) is
5089 // one variant + one arm per method on the closed-set enum, and
5090 // the compiler enforces exhaustiveness on every consumer's
5091 // `match self` arms — the codec's `parse` accepted-suffix set,
5092 // this render arm's emitted-suffix set, the validate gate's
5093 // canonical-window set, and every future per-`:contratos`-edge
5094 // rate-limit-override overlay all pick it up by construction.
5095 if let Some(unit) = rl.canonical_unit() {
5096 format!("{}/{unit}", rl.rate())
5097 } else {
5098 // Defensive fallback for non-canonical windows. Note:
5099 // [`AplicacaoSpec::validate_politicas`] rejects any
5100 // non-canonical `:rate-limit :window` via
5101 // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
5102 // a validated `RateLimit` never reaches this branch. The
5103 // emitted `<n>/<k>s` form is *not* round-trippable through
5104 // [`parse`] (which accepts only the closed-set
5105 // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
5106 // explicit count) — the validate gate is what makes the
5107 // round-trip a structural property; this branch exists only
5108 // so a programmatic non-validated serialize doesn't panic.
5109 format!("{}/{}s", rl.rate(), rl.window().as_secs())
5110 }
5111 }
5112}
5113
5114// ── placement strategy ───────────────────────────────────────────────
5115
5116/// How the Aplicacao distributes across clusters. Three options:
5117///
5118/// - `SingleNode` — one cluster runs the app at a time; takeover on
5119/// death (Erlang/OTP distributed-app semantics).
5120/// - `Replicated` — every named cluster runs an instance (active-active).
5121/// - `Sharded` — entities distribute by hash key across clusters
5122/// (Akka cluster sharding).
5123#[derive(
5124 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
5125)]
5126pub enum PlacementStrategy {
5127 SingleNode,
5128 Replicated,
5129 Sharded,
5130}
5131
5132/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
5133/// distribution-strategy default for the `:placement :estrategia` axis —
5134/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
5135/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
5136/// so every substrate-side consumer that resolves "what
5137/// [`PlacementStrategy`] variant does an author-omitted `:placement
5138/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
5139/// primitive [`PlacementStrategy`].
5140///
5141/// The `:placement :estrategia` default axis has three production
5142/// consumers on the substrate side today: the [`Default for
5143/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
5144/// impl's struct-literal `estrategia` field, and the serde-side
5145/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
5146/// author-omitted `:placement :estrategia` scalar through the [`Default
5147/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
5148/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
5149/// impl and implicit `PlacementStrategy::default()` routes at the sibling
5150/// consumers, with no compile-time link back to the paired
5151/// [`crate::manifest::Caixa::aplicacao_view`] fold's
5152/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
5153/// production consumer that resolves an author-omitted `:placement` slot
5154/// (entirely omitted, not just the `:estrategia` scalar within a declared
5155/// `:placement` block) through [`Placement::default`] which then routes
5156/// through this same discriminator. A future coherent rebrand of the
5157/// `:placement :estrategia` default (a widening to `Sharded` once the
5158/// substrate discovers hash-keyed distribution as the more common
5159/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
5160/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
5161/// names, a per-cluster overlay the operator pins through a future
5162/// `:placement-overrides` slot) would have had to migrate a lifted
5163/// discriminator on one path and open-coded discriminators on the peers
5164/// in lockstep or the four consumers would silently drift out of
5165/// pairing. Lifting the resolution rule to a typed `pub const` on the
5166/// substrate primitive means the M3-mesh-canonical `:placement
5167/// :estrategia` default migrates as one unit on any future axis change.
5168///
5169/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
5170/// §II.2's active-active-across-every-named-cluster arm — the closest
5171/// canonical M3 production reference the substrate carries, matching the
5172/// caixa-mesh default axis every M3 renderer already keys off (a
5173/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
5174/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
5175/// under the substrate's fleet-programs aggregator without an explicit
5176/// `:placement :estrategia` override). The two alternatives the closed
5177/// [`PlacementStrategy::ALL`] accept-set carries
5178/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
5179/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
5180/// Akka-style hash-keyed distribution across clusters,
5181/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
5182/// postures an author declares explicitly, never a posture an omitted
5183/// slot should silently assume.
5184///
5185/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
5186/// exactly one source of truth on the `:placement :estrategia` axis, on
5187/// the same substrate-primitive lift discipline the sibling M2
5188/// per-supervisor default set carries
5189/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
5190/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
5191/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
5192/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
5193/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
5194/// ([`crate::render::DEFAULT_NAMESPACE`],
5195/// [`crate::render::DEFAULT_LIBRARY_NAME`],
5196/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
5197/// the M3 mesh-primitive-defining slot family to converge onto the
5198/// substrate-primitive-lift discipline the M2 supervisor-slot family
5199/// already carries end-to-end.
5200pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
5201
5202impl Default for PlacementStrategy {
5203 fn default() -> Self {
5204 // Route the [`Default for PlacementStrategy`] impl through the
5205 // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5206 // `pub const` rather than a raw `Self::Replicated` arm — one
5207 // source of truth for the M3-mesh-canonical active-active-
5208 // across-every-named-cluster `:placement :estrategia` default
5209 // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5210 // lift discipline the sibling M2 per-supervisor default set
5211 // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5212 // paired halves) carries end-to-end. Pinned by
5213 // `placement_strategy_default_routes_through_lifted_default`.
5214 PLACEMENT_ESTRATEGIA_DEFAULT
5215 }
5216}
5217
5218impl PlacementStrategy {
5219 /// Exhaustive iteration surface for every consumer that reads the
5220 /// full closed-set (the future M4 admission-webhook's accepted-
5221 /// strategy listing in its rejection body, a future `feira app
5222 /// placement --list` CLI-side surfacing of the accepted arm-set,
5223 /// any future round-trip fuzz harness). A future variant addition
5224 /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5225 /// names as a trajectory item) extends this slice as a single edit
5226 /// and every consumer picks up the new entry by construction — the
5227 /// compiler-checked exhaustiveness on the sibling method `match`
5228 /// arms is the build-time guarantee that no arm forgets to grow.
5229 /// Same shape as the sibling closed-set typed enums'
5230 /// [`RateLimitUnit::ALL`] (6bce03d) and
5231 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5232 /// surfaces — the third closed-set typed enum on the caixa surface
5233 /// to converge onto the same discipline.
5234 pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5235
5236 /// Canonical camelCase-schema discriminator scalar this variant
5237 /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5238 /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5239 /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5240 /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5241 /// every substrate consumer that dispatches on the strategy (the
5242 /// `lareira-fleet-programs` aggregator, the future `app-operator`
5243 /// reconciler, the M3 Adaptive compression pass) reads the same
5244 /// byte-string the `Serialize` derive emits — the pin test in
5245 /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5246 /// asserts the two paths agree.
5247 #[must_use]
5248 pub const fn as_str(self) -> &'static str {
5249 match self {
5250 Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
5251 Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
5252 Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
5253 }
5254 }
5255
5256 /// Substrate-canonical reverse projection on the `:placement
5257 /// :estrategia` closed-set axis — parses the camelCase-schema
5258 /// discriminator scalar back to the typed variant, or `None` when
5259 /// `s` is outside the closed-set arm-string set [`Self::as_str`]
5260 /// emits. Dispatches on the same lifted
5261 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5262 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5263 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
5264 /// [`Self::as_str`] emitter walks, so the parse and emit halves of
5265 /// the round-trip migrate through one caixa-core edit on any future
5266 /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
5267 /// §II.5 hint names as a trajectory item lands one variant + one
5268 /// arm per method and the compiler enforces exhaustiveness on every
5269 /// consumer's `match self` arms).
5270 ///
5271 /// Prior to this lift the substrate carried only the forward
5272 /// `Self → &str` projection (the [`Self::as_str`] emitter, the
5273 /// [`std::fmt::Display`] impl routed through it, the `Serialize`
5274 /// derive that emits the same byte-string under
5275 /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
5276 /// consumer that wanted to parse a wire-form strategy scalar had to
5277 /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
5278 /// => …, "Sharded" => …, _ => … }` cascade that expressed no
5279 /// compile-time link back to the typed variant's canonical lifted
5280 /// constant. A future variant rename or a per-arm serde-attribute
5281 /// drift would silently split the wire byte-string one non-serde
5282 /// consumer parsed from the one the emitter wrote, with the
5283 /// failure surfacing at parse time far from the rebrand commit.
5284 ///
5285 /// Same closed-set-reverse-projection discipline the sibling
5286 /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
5287 /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
5288 /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
5289 /// defining `:placement :estrategia` closed-set axis, the third
5290 /// substrate-side closed-set typed enum to converge on the two-way
5291 /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
5292 /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
5293 /// and side-step the [`std::str::FromStr`]-collision clippy
5294 /// (`clippy::should_implement_trait`) the plain `from_str` name
5295 /// carries; a future explicit [`std::str::FromStr`] impl can layer
5296 /// on top by delegating to this canonical arm-dispatch method.
5297 ///
5298 /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
5299 /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
5300 /// picks the diagnostic form appropriate for its use site — a
5301 /// future `feira app placement --set` CLI-side arg-parse that wants
5302 /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
5303 /// Sharded)"` diagnostic builds one on top by iterating
5304 /// [`Self::ALL`], while the future M4 admission-webhook's rejection
5305 /// path folds `None` onto its per-CR structured refusal body.
5306 #[must_use]
5307 pub fn from_wire(s: &str) -> Option<Self> {
5308 match s {
5309 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
5310 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
5311 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5312 _ => None,
5313 }
5314 }
5315
5316 /// Substrate-canonical per-arm predicate naming the cross-slot
5317 /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5318 /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5319 /// consumes the paired [`Placement::shard_key`] axis (and therefore
5320 /// requires — and is the only strategy that permits — a non-empty
5321 /// `:shard-key` on the paired slot). Today the accept-set is the
5322 /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5323 /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5324 /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5325 /// distributed-app takeover — §II.1) and `Replicated` (active-active
5326 /// across every named cluster) have no hash-keyed routing axis to
5327 /// consume the slot and refuse a declared-but-inert `:shard-key`
5328 /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5329 ///
5330 /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5331 /// satisfies `placement.shard_key().is_some() ==
5332 /// placement.estrategia().requires_shard_key()` by construction — the
5333 /// cross-slot partition the pin
5334 /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5335 /// locks load-bearing, so every downstream consumer that reaches for
5336 /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5337 /// CR materializer's per-CR shard-key resolver, the future
5338 /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5339 /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5340 /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5341 /// shard-key requirement probe, a future author-facing tatara-lisp
5342 /// linter that flags `(:placement (:estrategia Replicated :shard-key
5343 /// "tenantId"))` shapes before `feira lint` reaches
5344 /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5345 /// the substrate primitive — the predicate names *the cross-slot
5346 /// invariant*, not the arm identity.
5347 ///
5348 /// Prior to this lift the "does this strategy consume `:shard-key`"
5349 /// classification lived under the `gen_platform::IsVariant`-derived
5350 /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5351 /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5352 /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5353 /// } else { None }` cascade, the
5354 /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5355 /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5356 /// "tenantId".to_string())` cascade, and the
5357 /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5358 /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5359 /// cascade). Each site conflated two semantically distinct questions:
5360 /// "is the variant `Sharded`?" (arm-identity, what
5361 /// [`Self::is_sharded`] answers) and "does the variant consume
5362 /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5363 /// The two questions land on the same three-way answer under today's
5364 /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5365 /// future arm addition that consumed `:shard-key` under a different
5366 /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5367 /// §II.5 roadmap-hint names that hash-partitions across the cluster
5368 /// pool by client-IP hash rather than an author-declared extractor
5369 /// expression, a hypothetical `WeightedShard` variant that carries a
5370 /// shard-key + per-cluster weight table under a promoted M5
5371 /// adaptive-placement engine) or an addition that did *not* consume
5372 /// `:shard-key` on a semantically Sharded-shaped arm would silently
5373 /// split the two questions. Any consumer that read
5374 /// `.is_sharded().then(…)` for the shard-key requirement gate would
5375 /// silently misclassify the new arm as non-consuming — a fixture
5376 /// builder would omit `:shard-key` where the new arm required one and
5377 /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5378 /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5379 /// commit, a future M4 CR materializer would fall through the
5380 /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5381 /// silently emit an empty extractor at the Akka reconciler layer.
5382 ///
5383 /// Lifting the classification as a substrate-primitive method on the
5384 /// closed-set typed enum names the cross-slot invariant on the
5385 /// primitive that owns the partition: every future arm addition
5386 /// declares its `:shard-key` consumption in one place (this predicate's
5387 /// `match self` arm-set), and every downstream consumer that reaches
5388 /// for the paired shape reads through one typed dispatch. Same
5389 /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5390 /// per-arm predicate on the pre-projection WIT-shape axis and the
5391 /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5392 /// paired predicate on the post-projection typed-view axis — a
5393 /// per-arm semantic-classification predicate paired with the
5394 /// arm-identity predicate the derive already emits, closing the drift
5395 /// footgun on the cross-slot invariant axis.
5396 ///
5397 /// Method-named `requires_shard_key` (not `has_shard_key`, not
5398 /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5399 /// invariant reads as "this strategy *requires* the paired
5400 /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5401 /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5402 /// merely omit it. The `has_*` framing would read as an accessor
5403 /// (returning the presence of an already-carried value) rather than a
5404 /// requirement (naming the invariant the paired slot must satisfy).
5405 /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5406 /// shape as the sibling [`WitContract::is_capability`] /
5407 /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5408 /// arm-family, so every consumer reaches for `.requires_shard_key()`
5409 /// as a drop-in replacement for the `.is_sharded()` conflated read
5410 /// without a return-shape migration.
5411 #[must_use]
5412 pub const fn requires_shard_key(self) -> bool {
5413 match self {
5414 Self::Sharded => true,
5415 Self::SingleNode | Self::Replicated => false,
5416 }
5417 }
5418}
5419
5420// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5421// cross-slot-invariant per-arm predicate: the module-scope const-eval
5422// assertions below trip at caixa-core build time (not test time) if a
5423// future edit rewires the predicate's arm-set away from the singleton
5424// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5425// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5426// runtime pin covers the same truth-table with a more descriptive
5427// diagnostic on failure; these const-eval items add a build-time failure
5428// surface strictly stronger than the runtime pin (a downstream renderer's
5429// `const`-context reader that composed against a rebound predicate would
5430// still surface here before the test suite even ran) and side-step the
5431// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5432// would otherwise accumulate on the caixa-core module baseline.
5433const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5434const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5435const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5436
5437/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5438/// the pretty-printed byte-string every consumer that formats the strategy
5439/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5440/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5441/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5442/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5443/// admission-webhook rejection body) reaches for the same lifted
5444/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5445/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5446/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5447/// `Serialize` derive already emits under
5448/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5449/// [`PlacementStrategy::as_str`] helper already returns.
5450///
5451/// Until this lift landed the sibling OTP-shape typed enums —
5452/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5453/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5454/// so [`std::fmt::Display`] routes through the same discriminant string
5455/// the wire format emits) — carried a stable [`std::fmt::Display`]
5456/// surface but [`PlacementStrategy`] did not; every consumer reaching
5457/// for a strategy byte-string past the wire format had to pick between
5458/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5459/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5460/// derive), any two of which a future variant rename or
5461/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5462/// desynchronize — with the failure surfacing as a downstream renderer /
5463/// operator's per-strategy dispatch reading one spelling while the wire
5464/// format emitted another, far from the source rebrand commit and with
5465/// no field naming the drift. Routing `Display` through
5466/// [`PlacementStrategy::as_str`] makes the three paths
5467/// (`Debug` for structural inspection, `Display` for user-facing text,
5468/// `Serialize` for the wire format) converge on the same lifted
5469/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5470/// the diagnostic byte-string, and the pretty-printed byte-string move
5471/// as a single unit through one canonical declaration each, by
5472/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5473/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5474/// closes the third path.
5475///
5476/// Pin tests
5477/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
5478/// and
5479/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
5480/// assert the three paths agree byte-for-byte on every variant, so a
5481/// future variant rename or per-arm serde attribute drift is a build
5482/// error visible at caixa-core test time, not a silent per-consumer
5483/// dispatch miss at apply / reconcile time.
5484impl std::fmt::Display for PlacementStrategy {
5485 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5486 f.write_str(self.as_str())
5487 }
5488}
5489
5490/// Where the Aplicacao runs.
5491#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5492#[serde(rename_all = "camelCase")]
5493pub struct Placement {
5494 /// Distribution strategy.
5495 #[serde(default)]
5496 pub estrategia: PlacementStrategy,
5497
5498 /// Named clusters that host this Aplicacao. Required for
5499 /// `Replicated` and `SingleNode`; for `Sharded` declares the
5500 /// shard pool.
5501 #[serde(default)]
5502 pub clusters: Vec<String>,
5503
5504 /// Optional hint to the placement engine: `"data-locality"`,
5505 /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
5506 #[serde(default, skip_serializing_if = "Option::is_none")]
5507 pub affinity: Option<String>,
5508
5509 /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
5510 #[serde(default, skip_serializing_if = "Option::is_none")]
5511 pub shard_key: Option<String>,
5512}
5513
5514impl Placement {
5515 /// Substrate-canonical per-`:placement` Akka-cluster-sharding
5516 /// `:shard-key` extractor-expression scalar accessor every consumer
5517 /// of the Aplicacao's hash-keyed distribution routing keys off —
5518 /// returns the author-declared `:placement :shard-key` byte-string
5519 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
5520 /// own `Option<String>` storage; `None` when the slot is absent
5521 /// (the canonical shape under `:estrategia Replicated` /
5522 /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
5523 /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
5524 /// partition — `validate` refuses any `Placement` past this call
5525 /// that lands `Some` on a non-`Sharded` strategy or `None` on
5526 /// `Sharded`).
5527 ///
5528 /// The `:placement :shard-key` slot carries the Akka-style
5529 /// cluster-sharding entity-id extractor expression
5530 /// (MESH-COMPOSITION §II.4) — validated by
5531 /// [`validate_placement_shard_key`] to be a non-empty printable-
5532 /// ASCII single-token reference (`tenantId`, `$tenantId`,
5533 /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
5534 /// future M4 Akka-style cluster-sharding reconciler hashes without
5535 /// re-validating at the runtime layer), and every downstream
5536 /// consumer that reads the key keys off this scalar (the
5537 /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
5538 /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5539 /// declared-but-inert refusal diagnostic, the caixa-mesh
5540 /// per-Aplicacao `placement.shardKey` emit path the substrate
5541 /// operator's per-entity hash-routing reader consumes, the future
5542 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5543 /// per-shard-key resolver).
5544 ///
5545 /// Prior to this lift the `.shard_key` field was accessed inline at
5546 /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
5547 /// `Sharded` arm's `match &self.placement.shard_key { None => …,
5548 /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
5549 /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
5550 /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
5551 /// — two open-coded field-accesses that expressed no compile-time
5552 /// link back to the typed slot. A future extension of the
5553 /// `:placement :shard-key` axis to a richer author surface — a
5554 /// per-cluster override the operator pins through a future
5555 /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
5556 /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
5557 /// alias table the M4 CR materializer resolves per-CR, a
5558 /// per-Aplicacao dynamic `:shard-key` derivation the future
5559 /// adaptive placement engine computes from `:affinity` weights —
5560 /// would have had to be threaded through both open-coded copies in
5561 /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
5562 /// arm refusal would silently disagree on which extractor
5563 /// expression a given Placement resolves to. Lifting the resolution
5564 /// rule to a typed method on the substrate primitive means every
5565 /// downstream consumer of the Aplicacao's per-`:placement`
5566 /// hash-key surface reaches for exactly one typed dispatch — the
5567 /// resolver's accept-set migrates as a unit on any future axis
5568 /// addition.
5569 ///
5570 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
5571 /// [`WitContract::destination`] / [`WitContract::world_ref`]
5572 /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
5573 /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
5574 /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
5575 /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
5576 /// typed dispatch on the substrate primitive, thin projections at
5577 /// each consumer" discipline extended onto the per-`:placement`
5578 /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
5579 /// First `Option<&str>`-return accessor on the M3 mesh-slot family
5580 /// — opens the "optional per-slot scalar" projection pattern the
5581 /// sibling per-`:placement` `:affinity`, per-`:politicas`
5582 /// `:rate-limit` future lifts fold on. Named `shard_key()` to
5583 /// match the storage field's name; the accessor's identity name
5584 /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
5585 /// slot's docstring already carries.
5586 #[must_use]
5587 pub const fn shard_key(&self) -> Option<&str> {
5588 match &self.shard_key {
5589 Some(s) => Some(s.as_str()),
5590 None => None,
5591 }
5592 }
5593
5594 /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
5595 /// compression-hint scalar accessor every weighting-consumer of the
5596 /// Aplicacao's per-hint routing surface keys off — returns the
5597 /// author-declared `:placement :affinity` byte-string verbatim as
5598 /// an `Option<&str>`, borrowed from the typed slot's own
5599 /// `Option<String>` storage; `None` when the slot is absent (the
5600 /// canonical shape of an Aplicacao that leaves the compression
5601 /// weighting up to the placement engine's cluster-default arm — no
5602 /// author-authored `data-locality` / `low-latency` / etc. hint
5603 /// biases the routing).
5604 ///
5605 /// The `:placement :affinity` slot carries the M3 Adaptive-
5606 /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
5607 /// by [`validate_placement_affinity`] to be a DNS-1123 label
5608 /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
5609 /// K8s-conformant label-selector shape every apiserver-side pod-
5610 /// affinity / node-affinity materializer already gates on
5611 /// admission), and every downstream consumer that reads the hint
5612 /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
5613 /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
5614 /// `placement.affinity` overlay emit path the substrate operator's
5615 /// per-hint weighting-consumer reads, the future M4
5616 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
5617 /// pod-affinity / node-affinity selector resolver).
5618 ///
5619 /// Prior to this lift the `.affinity` field was accessed inline at
5620 /// the sole caixa-core site — the
5621 /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
5622 /// `if let Some(a) = &self.placement.affinity { …
5623 /// validate_placement_affinity(a)? … }` cascade — one open-coded
5624 /// field-access that expressed no compile-time link back to the
5625 /// typed slot. A future extension of the `:placement :affinity`
5626 /// axis to a richer author surface — a per-cluster override the
5627 /// operator pins through a future `:placement :affinity-overrides`
5628 /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
5629 /// tenant hint alias table the M4 CR materializer resolves per-CR,
5630 /// a per-Aplicacao dynamic `:affinity` derivation the future
5631 /// adaptive placement engine computes from `:clusters` topology —
5632 /// would have had to be threaded through the open-coded copy in
5633 /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
5634 /// materializer reader that landed on the axis, or the per-hint
5635 /// value-shape gate and its downstream weighting consumers would
5636 /// silently disagree on which hint a given Placement resolves to.
5637 /// Lifting the resolution rule to a typed method on the substrate
5638 /// primitive means every downstream consumer of the Aplicacao's
5639 /// per-`:placement` compression-hint surface reaches for exactly
5640 /// one typed dispatch — the resolver's accept-set migrates as a
5641 /// unit on any future axis addition.
5642 ///
5643 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
5644 /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5645 /// optional-scalar axis — same "one typed dispatch on the substrate
5646 /// primitive, thin projections at each consumer" discipline extended
5647 /// onto the per-`:placement` M3-Adaptive-compression-hint
5648 /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5649 /// return accessor on the M3 mesh-slot family; closes the last
5650 /// un-lifted per-`:placement` `Option<String>` axis. Named
5651 /// `affinity()` to match the storage field's name; the accessor's
5652 /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5653 /// vocabulary the slot's docstring already carries.
5654 #[must_use]
5655 pub const fn affinity(&self) -> Option<&str> {
5656 match &self.affinity {
5657 Some(s) => Some(s.as_str()),
5658 None => None,
5659 }
5660 }
5661
5662 /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5663 /// strategy scalar accessor every consumer that dispatches on the
5664 /// Aplicacao's per-cluster distribution shape keys off — returns the
5665 /// author-declared `:placement :estrategia` variant verbatim as a
5666 /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5667 /// `PlacementStrategy` storage.
5668 ///
5669 /// The `:placement :estrategia` slot carries the closed-set
5670 /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5671 /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5672 /// `Replicated` — active-active across every named cluster; `Sharded`
5673 /// — Akka-style hash-keyed entity distribution across the cluster pool
5674 /// per §II.4) that every downstream consumer of the Aplicacao's
5675 /// per-cluster fan-out shape keys off. Validated by
5676 /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5677 /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5678 /// matches!(estrategia, Sharded)` — the cross-slot partition the
5679 /// [`Placement::shard_key`] accessor's docstring pins), and every
5680 /// downstream consumer that reads the strategy keys off this scalar
5681 /// (the [`AplicacaoSpec::validate_placement`]
5682 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5683 /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5684 /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5685 /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5686 /// declared-but-inert refusal's
5687 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5688 /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5689 /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5690 /// emit path the substrate operator's per-strategy fan-out reader
5691 /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5692 /// materializer's per-strategy admission-webhook resolver).
5693 ///
5694 /// Prior to this lift the `.estrategia` field was accessed inline at
5695 /// four sites — the [`AplicacaoSpec::validate_placement`]
5696 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5697 /// `estrategia: self.placement.estrategia`, the same method's
5698 /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5699 /// partition dispatch, the non-`Sharded`-arm
5700 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5701 /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5702 /// per-Aplicacao strategy print line at
5703 /// `println!("… {} …", spec.placement.estrategia, …)`
5704 /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5705 /// expressed no compile-time link back to the typed slot. A future
5706 /// extension of the `:placement :estrategia` axis to a richer author
5707 /// surface (a per-cluster override the operator pins through a future
5708 /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5709 /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5710 /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5711 /// derivation the future adaptive placement engine computes from
5712 /// `:affinity` + `:clusters` topology) would have had to be threaded
5713 /// through every open-coded copy in lockstep — one consumer reading
5714 /// the raw variant while a peer read the operator-resolved variant
5715 /// would silently split the `PlacementWithoutClusters` /
5716 /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5717 /// partition-dispatch input, a two-consumer split at the validator
5718 /// far from the source `caixa.lisp` with no field naming the
5719 /// strategy-drift root cause. Lifting the resolution rule to a typed
5720 /// method on the substrate primitive means every downstream consumer
5721 /// of the Aplicacao's per-`:placement` distribution-strategy surface
5722 /// reaches for exactly one typed dispatch — the resolver's accept-set
5723 /// migrates as a unit on any future axis addition.
5724 ///
5725 /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5726 /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5727 /// same "one typed dispatch on the substrate primitive, thin
5728 /// projections at each consumer" discipline extended onto the
5729 /// per-`:placement` distribution-strategy `Copy`-composite-enum
5730 /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5731 /// family; first `Copy`-return accessor on the M3 mesh-slot
5732 /// `Placement` type — companion to the sibling per-`:placement`
5733 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5734 /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5735 /// optional-scalar axes, closing the last unlifted per-`:placement`
5736 /// scalar-value axis (the closed-set `PlacementStrategy`
5737 /// distribution-strategy discriminator) so every downstream
5738 /// per-`:placement` reader now routes through a typed dispatch on
5739 /// the substrate primitive. Named `estrategia()` to match the storage
5740 /// field's name; the accessor's identity name maps onto the
5741 /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5742 /// already carries. Declared `pub const fn` (matching the peer M3
5743 /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5744 /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5745 /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5746 /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5747 /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5748 /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5749 /// [`RateLimit`] — every one a `pub const fn`) so every future
5750 /// substrate-side `const`-context consumer of the resolved
5751 /// distribution-strategy variant (a `const _: () = assert!(…)`
5752 /// module-scope invariant pin on a per-fixture typed [`Placement`],
5753 /// a future M4 admission-webhook `const fn` resolver over a typed
5754 /// [`Placement`], any `const fn` composer that fans on the strategy
5755 /// at compile time) reaches through the same typed dispatch on the
5756 /// substrate primitive at const-eval time as at runtime. Pinned by
5757 /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
5758 /// const-eval posture at module scope via `const _:() = …` items so
5759 /// any future accidental downgrade to non-`const` trips at caixa-core
5760 /// build time.
5761 #[must_use]
5762 pub const fn estrategia(&self) -> PlacementStrategy {
5763 self.estrategia
5764 }
5765
5766 /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5767 /// per-cluster distribution-target slice accessor every consumer that
5768 /// walks the Aplicacao's declared cluster-pool keys off — returns the
5769 /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5770 /// `&[String]` slice-view, borrowed from the typed slot's own
5771 /// `Vec<String>` storage (a zero-copy slice-view over the same
5772 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5773 /// through). Non-optional: the empty slice is the load-bearing
5774 /// pre-validation sentinel every downstream consumer of the paired
5775 /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5776 /// off — every strategy in the closed
5777 /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5778 /// requires a non-empty list (`SingleNode` / `Replicated` use the
5779 /// list as hosting / takeover candidates per Erlang/OTP distributed-
5780 /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5781 /// shard pool per Akka cluster-sharding convention, §II.4), so the
5782 /// `.is_empty()` probe is the shared pre-condition every
5783 /// [`AplicacaoSpec::validate_placement`] arm heads on.
5784 ///
5785 /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5786 /// 1123-label per-cluster distribution-target list — the same
5787 /// set-not-multiset shape the sibling `:membros :caixa` /
5788 /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5789 /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5790 /// pins the shape). Every downstream consumer that fans on the list
5791 /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5792 /// pre-flight `.is_empty()` probe that trips
5793 /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5794 /// per-cluster value-shape + duplicate-detection fan-out loop, the
5795 /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5796 /// that materializes the list verbatim onto every
5797 /// programs.yaml entry the substrate operator's per-cluster
5798 /// `placement.clusters | contains .Values.cluster` filter reads,
5799 /// the `feira app graph` per-Aplicacao cluster print line, the
5800 /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5801 /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5802 /// placement engine's cluster-topology reader).
5803 ///
5804 /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5805 /// inline at three production sites — the
5806 /// [`AplicacaoSpec::validate_placement`] pre-flight
5807 /// `self.placement.clusters.is_empty()` refusal probe, the same
5808 /// method's per-cluster validate loop's
5809 /// `for c in &self.placement.clusters` traversal head, and the
5810 /// `feira app graph` per-Aplicacao print line's
5811 /// `spec.placement.clusters` `{:?}` formatter argument
5812 /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5813 /// that expressed no compile-time link back to the typed slot. A
5814 /// future extension of the `:placement :clusters` axis to a richer
5815 /// author surface (a per-tenant cluster-pool overlay the operator
5816 /// pins through a future `:placement :clusters-overrides` slot the
5817 /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5818 /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5819 /// the future M5 adaptive-placement engine computes from
5820 /// `:affinity` weights + live cluster-topology probes, a promotion
5821 /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5822 /// partition once the substrate operator's cluster-membership
5823 /// reconciler comes into typed scope) would have had to be threaded
5824 /// through all three open-coded copies in lockstep or one consumer
5825 /// would silently disagree with the peers on which cluster-pool a
5826 /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5827 /// reading the raw slot while the peer per-cluster validate loop
5828 /// read an operator-resolved slot would silently split the paired
5829 /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5830 /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5831 /// input from the pre-flight input, a three-consumer split at the
5832 /// validator and formatter far from the source `caixa.lisp` with
5833 /// no field naming the cluster-pool-drift root cause. Lifting the
5834 /// resolution rule to a typed method on the substrate primitive
5835 /// means every downstream consumer of the Aplicacao's
5836 /// per-`:placement` cluster-pool surface reaches for exactly one
5837 /// typed dispatch — the resolver's accept-set migrates as a unit
5838 /// on any future axis addition.
5839 ///
5840 /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5841 /// slot — sibling to the seed M2
5842 /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5843 /// slice-return accessor on the peer per-`:supervisor` static-
5844 /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5845 /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5846 /// primitive, thin projections at each consumer" discipline. The
5847 /// three peer `Vec`-carry axes still unlifted at the time of this
5848 /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5849 /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5850 /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5851 /// [`crate::UpgradeFromEntry::instructions`]
5852 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5853 /// — inherit this accessor's discipline as future compounding runs
5854 /// migrate their consumers onto the shared slice-return shape.
5855 /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5856 /// type, sibling to the two `Option<&str>`-return
5857 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5858 /// (74ec2d3) accessors and the `Copy`-return
5859 /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5860 /// unlifted per-`:placement` field axis (the `Vec<String>`
5861 /// distribution-target-list carrier) so every downstream
5862 /// per-`:placement` reader now routes through a typed dispatch on
5863 /// the substrate primitive. Named `clusters()` to match the storage
5864 /// field's name verbatim and the tatara-lisp author-surface term
5865 /// (`:clusters`) the field's own docstring already carries; the
5866 /// accessor's identity maps onto the canonical MESH-COMPOSITION
5867 /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5868 /// for. Returns `&[String]` (not `&Vec<String>`) because every
5869 /// downstream consumer of the cluster list treats it as a read-only
5870 /// sequence — the slice-view is the narrowest borrow that supports
5871 /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5872 /// `.len()`) without leaking the backing `Vec`'s
5873 /// grow/push/reserve surface that no consumer of the typed view
5874 /// reaches for (the storage-side `Vec` remains reachable through
5875 /// the `pub clusters` field for the mutation-carrying serde
5876 /// round-trip and per-test fixture-mutation paths).
5877 #[must_use]
5878 pub const fn clusters(&self) -> &[String] {
5879 self.clusters.as_slice()
5880 }
5881}
5882
5883impl Default for Placement {
5884 fn default() -> Self {
5885 Self {
5886 // Route the struct-literal `estrategia` default arm through
5887 // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
5888 // typed `pub const` rather than the transitively-derived
5889 // [`PlacementStrategy::default`] route — one source of truth
5890 // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
5891 // active-active-across-every-named-cluster arm
5892 // (MESH-COMPOSITION §II.2) that both this struct-literal
5893 // altitude and the sibling [`Default for PlacementStrategy`]
5894 // impl already key off through the same substrate primitive.
5895 // Pinned by
5896 // `placement_default_estrategia_routes_through_lifted_default`.
5897 estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
5898 clusters: Vec::new(),
5899 affinity: None,
5900 shard_key: None,
5901 }
5902 }
5903}
5904
5905// ── external entry point ─────────────────────────────────────────────
5906
5907/// External entry point — what an outside caller sees. Renders to a
5908/// Gateway / Ingress + a route to the named member Servico.
5909#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5910#[serde(rename_all = "camelCase")]
5911pub struct Entrada {
5912 /// Public hostname (e.g. `"checkout.quero.cloud"`).
5913 pub host: String,
5914
5915 /// Member Servico the gateway routes to. Must be in `:membros`.
5916 pub para: String,
5917
5918 /// Optional path filter — if set, only matching paths route to
5919 /// this Aplicacao (the rest fall through to other route rules).
5920 #[serde(default)]
5921 pub paths: Vec<String>,
5922
5923 /// Default port on the destination Servico (the trigger.service.port).
5924 #[serde(default = "default_port")]
5925 pub port: u16,
5926}
5927
5928impl Entrada {
5929 /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5930 /// every HTTPRoute-aware renderer keys off — returns the author-
5931 /// declared `:entrada :paths` list verbatim when non-empty, and the
5932 /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5933 /// all fallback otherwise (so an Aplicacao author who declares an
5934 /// external `:entrada` block but no per-path rule surface still
5935 /// gets a route whose sole `HTTPPathMatch` matches every incoming
5936 /// request under the paired
5937 /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5938 ///
5939 /// Prior to this lift the "if `:entrada :paths` is empty use the
5940 /// substrate catch-all; else return each declared path verbatim"
5941 /// cascade lived inline at
5942 /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5943 /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5944 /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5945 /// substrate ships today, with no typed method on the substrate
5946 /// primitive that named the rule. A future path-resolution axis
5947 /// addition — a per-cluster `:entrada :default-path` override the
5948 /// operator pins through a future `:placement`-scoped slot, an
5949 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5950 /// admission-webhook floor that materializes the catch-all before
5951 /// the CR lands, a future per-`:entrada :paths` overlay from a
5952 /// per-cluster policy the future `feira app deploy` pipeline
5953 /// consumes — would have to be threaded through every renderer's
5954 /// inline copy of the cascade in lockstep or one consumer would
5955 /// silently disagree with the peers on which path list a given
5956 /// `:entrada` block resolves to. Lifting the rule to a typed
5957 /// method on the substrate primitive means every downstream
5958 /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5959 /// per-cluster overlay resolver, every future per-Aplicacao
5960 /// snapshot renderer) reaches for exactly one typed dispatch —
5961 /// the resolver's accept-set moves as a unit on any future axis
5962 /// addition.
5963 ///
5964 /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5965 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5966 /// per-`:entrada` scalar-value axes — extends the "one typed
5967 /// dispatch on the substrate primitive, thin projections at each
5968 /// consumer" discipline onto the per-`:entrada` path-list
5969 /// resolution axis every HTTPRoute-aware renderer consumes. Same
5970 /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5971 /// sibling `:politicas` primitive — one typed method on the
5972 /// substrate primitive that names the cascade every renderer
5973 /// otherwise re-inlines.
5974 #[must_use]
5975 pub fn resolved_paths(&self) -> Vec<&str> {
5976 // Route the internal cascade-head + per-entry projection reads
5977 // through the lifted [`Self::paths`] slice accessor rather than
5978 // the raw `self.paths` field access — the substrate-primitive
5979 // per-`:entrada` path-list resolver's two internal reads now
5980 // key off the canonical raw-slot surface every downstream
5981 // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5982 // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5983 // entrada summary line's `{:?}` Debug print) routes through, so
5984 // any future rebrand on the typed slot's raw-slot reader lands
5985 // at exactly one place. Same two-consumer coherence discipline
5986 // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5987 // the peer M3 mesh-slot `Vec<String>`-carry axis.
5988 if self.paths().is_empty() {
5989 vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5990 } else {
5991 self.paths().iter().map(String::as_str).collect()
5992 }
5993 }
5994
5995 /// Substrate-canonical per-`:entrada` DNS-hostname singular
5996 /// accessor every Gateway-API `Listener.hostname` reader keys off
5997 /// — returns the author-declared `:entrada :host` byte-string
5998 /// verbatim as a `&str`, borrowed from the typed slot's own
5999 /// [`String`] storage.
6000 ///
6001 /// Named the "singular" half of the DNS-hostname resolver pair on
6002 /// the substrate primitive: the parent-Gateway per-listener
6003 /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
6004 /// (`Listener.hostname: Option<PreciseHostname>` — at most one
6005 /// hostname per listener), and this accessor is the typed dispatch
6006 /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
6007 /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
6008 /// the per-HTTPRoute `spec.hostnames[]` list axis the same
6009 /// per-Aplicacao ingress-hostname surface projects onto.
6010 ///
6011 /// Prior to this lift the `entrada.host.clone()` byte-string was
6012 /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
6013 /// per-listener singular `hostname:` axis
6014 /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
6015 /// per-HTTPRoute plural `spec.hostnames[]` axis
6016 /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
6017 /// consumers read the same `entrada.host` field but the two-site
6018 /// duplication expressed no compile-time contract that the singular
6019 /// Gateway-listener filter and the plural `HTTPRoute` filter list
6020 /// stay in lockstep on future extensions of the `:entrada` slot to
6021 /// a multi-hostname author surface (an `:entrada :alt-hosts` list
6022 /// overlay, a per-cluster SNI fan-out the operator pins through a
6023 /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
6024 /// Aplicacao` CR materializer's per-listener virtual-host filter
6025 /// admission-webhook overlay). Any such extension would have to be
6026 /// threaded through every renderer's inline copy of the resolution
6027 /// in lockstep or the Gateway listener's `hostname:` filter would
6028 /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
6029 /// — a Gateway-API-conformance divergence whose apply-time symptom
6030 /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
6031 /// `NoMatchingParent` — the API server rejects the route because
6032 /// its `hostnames[]` filter doesn't intersect the parent listener's
6033 /// `hostname` filter) is far from the source `caixa.lisp` and never
6034 /// surfaces in the emitted YAML. Lifting the singular and plural
6035 /// resolvers to typed methods on the substrate primitive means
6036 /// every consumer of the Aplicacao's ingress-hostname surface
6037 /// reaches for exactly one typed dispatch, and the pair-invariant
6038 /// `hostnames() == vec![hostname()]` pinned by the sibling
6039 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
6040 /// keeps the two axes in lockstep by construction.
6041 ///
6042 /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
6043 /// (1449891) path-list resolver on the per-HTTPRoute per-rule
6044 /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
6045 /// the substrate primitive, thin projections at each consumer"
6046 /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6047 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6048 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6049 /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
6050 /// `:entrada` scalar-value + list-value axes.
6051 #[must_use]
6052 pub const fn hostname(&self) -> &str {
6053 self.host.as_str()
6054 }
6055
6056 /// Substrate-canonical per-`:entrada` DNS-hostname plural
6057 /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
6058 /// keys off — returns the singleton `[hostname()]` list under
6059 /// today's single-hostname-per-Aplicacao author surface, and the
6060 /// authoritative multi-hostname list under a future
6061 /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
6062 ///
6063 /// Plural half of the DNS-hostname resolver pair — see the
6064 /// companion [`Entrada::hostname`] docstring for the two-consumer
6065 /// lift + pair-invariant discipline (`hostnames() ==
6066 /// vec![hostname()]`, pinned load-bearing by the sibling
6067 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
6068 /// test).
6069 ///
6070 /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
6071 /// per-`:entrada` plural-list resolver on the per-HTTPRoute
6072 /// per-rule path-list axis — same `Vec<&str>` shape, same
6073 /// substrate-primitive-owns-the-resolver discipline extended to
6074 /// the per-HTTPRoute virtual-host filter-list axis.
6075 #[must_use]
6076 pub fn hostnames(&self) -> Vec<&str> {
6077 vec![self.hostname()]
6078 }
6079
6080 /// Substrate-canonical per-`:entrada` destination-Servico scalar
6081 /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
6082 /// the author-declared `:entrada :para` byte-string verbatim as a
6083 /// `&str`, borrowed from the typed slot's own [`String`] storage.
6084 ///
6085 /// The `:entrada :para` slot names the single member Servico the
6086 /// external Gateway routes to (validated by
6087 /// [`AplicacaoSpec::validate`] to be a
6088 /// [`Membro::caixa`] the Aplicacao declares — a stray
6089 /// `:para` that doesn't name a member is
6090 /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
6091 /// backend-attachment miss at cluster-apply time). Under today's
6092 /// single-destination author surface `:entrada :para` is the ingress
6093 /// apex Servico's canonical identity; under a hypothetical
6094 /// future multi-backend author surface (a `:entrada
6095 /// :split :backends` weighted-fan-out overlay for canary /
6096 /// blue-green traffic-split rollouts, per-path override for
6097 /// path-based per-Servico routing beyond the single-apex model,
6098 /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6099 /// per-CR admission-webhook that promotes the scalar to a
6100 /// weighted list) this accessor is the substrate primitive's typed
6101 /// dispatch every downstream `HTTPRoute`-aware consumer routes
6102 /// through, so the resolution shape migrates as a unit on one
6103 /// caixa-core edit rather than a coordinated rewrite across every
6104 /// renderer's inline field-access.
6105 ///
6106 /// Prior to this lift the `entrada.para` byte-string was accessed
6107 /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
6108 /// `metadata.name` composer's per-destination discriminator arg
6109 /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
6110 /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
6111 /// per-HTTPRoute per-rule `backendRefs[0].name` axis
6112 /// (`entrada.para.clone()`,
6113 /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
6114 /// consumers read the same `entrada.para` field but the two-site
6115 /// duplication expressed no compile-time contract that the HTTPRoute
6116 /// name-discriminator and the per-rule backend name stay in
6117 /// lockstep on future extensions of the `:entrada` slot to a
6118 /// multi-destination author surface. Any such extension would have
6119 /// to be threaded through every renderer's inline copy of the
6120 /// destination projection in lockstep or the HTTPRoute
6121 /// `metadata.name` would silently reference a different destination
6122 /// than its own `backendRefs[]` — an operator-side
6123 /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
6124 /// grep-by-name lookup would land on a route whose `backendRefs[]`
6125 /// silently point at a peer Servico, dropping every external
6126 /// `:entrada` flow at the gateway with the destination-drift root
6127 /// cause invisible in the emitted YAML.
6128 ///
6129 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
6130 /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
6131 /// the per-listener singular / per-HTTPRoute plural filter axes and
6132 /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
6133 /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
6134 /// typed dispatch on the substrate primitive, thin projections at
6135 /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6136 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6137 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6138 /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
6139 /// sibling per-`:entrada` scalar-value + list-value axes — this
6140 /// accessor closes the last unlifted per-`:entrada` scalar axis
6141 /// (the destination-Servico byte-string) so every downstream
6142 /// per-`:entrada` reader now routes through a typed dispatch on
6143 /// the substrate primitive.
6144 #[must_use]
6145 pub const fn destination(&self) -> &str {
6146 self.para.as_str()
6147 }
6148
6149 /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
6150 /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
6151 /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
6152 /// reader keys off — returns the author-declared `:entrada :port`
6153 /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
6154 /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
6155 /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
6156 /// [`AplicacaoError::EntradaPortZero`], not a silent
6157 /// admission-webhook rejection at cluster-apply time).
6158 ///
6159 /// The `:entrada :port` slot carries the destination Servico's
6160 /// canonical in-cluster L4 listener port (`trigger.service.port` on
6161 /// the `pleme-computeunit` library chart), and every downstream
6162 /// consumer that reads the port keys off this scalar (the
6163 /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
6164 /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
6165 /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
6166 /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6167 /// CR materializer's per-Aplicacao gateway port resolver).
6168 ///
6169 /// Prior to this lift the `.port` field was accessed inline at two
6170 /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
6171 /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
6172 /// the [`AplicacaoSpec::port_for_destination`] resolver's
6173 /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
6174 /// open-coded field-accesses that expressed no compile-time link
6175 /// back to the typed slot. A future extension of the `:entrada :port`
6176 /// axis to a richer author surface — a per-cluster override the
6177 /// operator pins through a future `:placement :default-port` slot the
6178 /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
6179 /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
6180 /// heterogeneous listener ports, an M4
6181 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6182 /// admission-webhook floor that promotes the scalar to a
6183 /// per-destination map — would have had to be threaded through both
6184 /// open-coded copies in lockstep or the structural-floor validator
6185 /// and the [`AplicacaoSpec::port_for_destination`] resolver would
6186 /// silently disagree on which port a given [`Entrada`] resolves to.
6187 /// Lifting the resolution rule to a typed method on the substrate
6188 /// primitive means every downstream consumer of the Aplicacao's
6189 /// per-`:entrada` L4-port surface reaches for exactly one typed
6190 /// dispatch — the resolver's accept-set migrates as a unit on any
6191 /// future axis addition.
6192 ///
6193 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
6194 /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
6195 /// accessors on the per-`:entrada` scalar-value axis — same "one
6196 /// typed dispatch on the substrate primitive, thin projections at
6197 /// each consumer" discipline extended onto the per-`:entrada`
6198 /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
6199 /// the M3 mesh-slot `Entrada` type — closes the last unlifted
6200 /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
6201 /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
6202 /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
6203 /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
6204 /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
6205 /// storage field's name; the accessor's identity name maps onto the
6206 /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
6207 /// already carries. Declared `pub const fn` (matching the peer M3
6208 /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6209 /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6210 /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6211 /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6212 /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6213 /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6214 /// [`RateLimit`], and the sibling per-`:placement`
6215 /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
6216 /// enum scalar axis — every one a `pub const fn`) so every future
6217 /// substrate-side `const`-context consumer of the resolved
6218 /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
6219 /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
6220 /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
6221 /// admission-webhook `const fn` per-CR gateway-port floor over a
6222 /// typed [`Entrada`], any `const fn` composer that fans on the port
6223 /// at compile time) reaches through the same typed dispatch on the
6224 /// substrate primitive at const-eval time as at runtime. Pinned by
6225 /// [`entrada_port_accessor_is_const_fn`] which witnesses the
6226 /// const-eval posture at module scope via `const _:() = …` items so
6227 /// any future accidental downgrade to non-`const` trips at caixa-core
6228 /// build time.
6229 #[must_use]
6230 pub const fn port(&self) -> u16 {
6231 self.port
6232 }
6233
6234 /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
6235 /// slice accessor every HTTPRoute-aware renderer keys off when it
6236 /// wants the raw author-declared path-list (not the fallback-
6237 /// applied projection [`Self::resolved_paths`] returns) — returns
6238 /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
6239 /// borrowed from the typed slot's own [`Vec<String>`] storage.
6240 ///
6241 /// Named the "raw slot" half of the per-`:entrada` path-list resolver
6242 /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
6243 /// (1449891) closes the fallback-applying arm every per-Aplicacao
6244 /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
6245 /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
6246 /// catch-all; non-empty slot → per-entry verbatim projection); this
6247 /// accessor closes the raw-slot arm every consumer that must see the
6248 /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
6249 /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
6250 /// not `Err(EntradaPathEmpty)`, so it cannot route through the
6251 /// fallback-applying sibling; the `feira app graph` per-Aplicacao
6252 /// external-gateway summary line's `{:?}` Debug print — which must
6253 /// name the author's declaration, not the substrate's fallback, so
6254 /// an author reading their graph output can grep their caixa.lisp
6255 /// for the exact list they authored) routes through.
6256 ///
6257 /// Prior to this lift the `.paths` field was accessed inline at four
6258 /// production sites: the two internal reads in [`Self::resolved_paths`]
6259 /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
6260 /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
6261 /// value-shape gate's `for p in &e.paths` traversal head, and the
6262 /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
6263 /// Debug print — four open-coded field-accesses that expressed no
6264 /// compile-time link back to the typed slot. A future extension of
6265 /// the `:entrada :paths` axis to a richer author surface — a
6266 /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
6267 /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
6268 /// spec supports through `matches[].method`), a per-path per-header
6269 /// filter overlay (`matches[].headers[]`), a per-cluster override
6270 /// the operator pins through a future `:placement :path-overlay`
6271 /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6272 /// per-CR admission-webhook that normalized the list at admission
6273 /// time — would have had to be threaded through every open-coded
6274 /// copy in lockstep or the validator's per-entry gate would silently
6275 /// disagree with the renderer's per-entry emit on which list a given
6276 /// `:entrada` block resolves to. Lifting the resolution to a typed
6277 /// method on the substrate primitive means every downstream consumer
6278 /// of the Aplicacao's per-`:entrada` path-list surface reaches for
6279 /// exactly one typed dispatch — the resolver's accept-set migrates
6280 /// as a unit on any future axis addition.
6281 ///
6282 /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
6283 /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
6284 /// carry axis — same "one typed dispatch on the substrate primitive,
6285 /// thin projections at each consumer" discipline extended onto the
6286 /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
6287 /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
6288 /// carrier) so every downstream per-`:entrada` reader now routes
6289 /// through a typed dispatch on the substrate primitive. Returns
6290 /// `&[String]` (not `&Vec<String>`) because every downstream consumer
6291 /// treats the list as a read-only sequence — the slice-view is the
6292 /// narrowest borrow that supports every present + roadmapped consumer
6293 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
6294 /// `Vec`'s grow/push/reserve surface that no consumer of the typed
6295 /// view reaches for (the storage-side `Vec` remains reachable through
6296 /// the `pub paths` field for the mutation-carrying serde round-trip
6297 /// and per-test fixture-mutation paths).
6298 #[must_use]
6299 pub const fn paths(&self) -> &[String] {
6300 self.paths.as_slice()
6301 }
6302}
6303
6304/// Canonical default L4 port every typed Servico exposes on its
6305/// in-cluster K8s Service (the `trigger.service.port` axis the
6306/// `pleme-computeunit` library chart emits, the `:entrada :port` author
6307/// surface defaults to when the author omits the slot, and the
6308/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
6309/// `:entrada` block matches the per-`:contratos` destination Servico).
6310/// The single source of truth all three typed-port consumers reach for:
6311///
6312/// - [`Entrada::port`]'s serde default (via the
6313/// [`default_port`] helper this constant feeds); the author surface
6314/// `(:entrada (:host … :para …))` without an explicit `:port` slot
6315/// reads back as a typed [`Entrada`] carrying this exact value;
6316/// - the
6317/// [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6318/// emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6319/// fallback, fired when the typed `:entrada` block doesn't name
6320/// the per-`:contratos` destination Servico — the typed
6321/// `:contratos` graph carries no per-destination port axis (the
6322/// destination port is the destination Servico's
6323/// `lareira-<nome>` chart's `trigger.service.port`, which the
6324/// Aplicacao-level renderer has no visibility into without a
6325/// resolver round-trip), so the renderer falls back to the
6326/// substrate's canonical Servico-port assumption — by
6327/// construction the same value the destination's own
6328/// `pleme-computeunit` chart emits, the same value the
6329/// destination's own typed `:entrada :port` slot defaults to;
6330/// - every future per-Servico renderer the absorption-roadmap
6331/// acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6332/// CR materializer's per-edge port resolver, the future
6333/// per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6334/// emitter's per-route bucket key, the future caixa-otel
6335/// collector-pipeline emitter's per-Servico scrape port).
6336///
6337/// Until this lift landed the value `8080` lived at two production-code
6338/// call-sites: the [`default_port`] helper at
6339/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6340/// and the `.unwrap_or(8080)` literal at
6341/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6342/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6343/// resolver). A future Servico-port rebrand — the substrate moving the
6344/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6345/// gateway grows direct `:80` listeners, to `8443` once the substrate
6346/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6347/// override the operator pins through a future
6348/// `:placement :default-port` slot — without a coordinated edit on
6349/// both sides would silently emit Servicos listening on one port and
6350/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6351/// The CNP's apply-time symptom (the policy is admitted but every L4
6352/// flow on the destination Servico's actual port silently drops because
6353/// it doesn't match the whitelisted port) is far from the rebrand
6354/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6355/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6356/// a shared constant closes the drift footgun structurally — both
6357/// consumers read from the same `u16`, so any rebrand reaches both
6358/// sites by construction.
6359///
6360/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6361/// per-renderer canonical-K8s-axis constant — the namespace string
6362/// and the canonical Servico port both lived as duplicated literals
6363/// across caixa-core / caixa-mesh / caixa-flux before their respective
6364/// lifts. Same "the typed constant lives in one place" discipline the
6365/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6366/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6367/// shared-string axes.
6368///
6369/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6370pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6371
6372/// Structural floor for the typed `:entrada :port` axis — every
6373/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6374/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6375///
6376/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6377/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6378/// interprets as "let the kernel pick a free port at bind time", not a
6379/// well-defined destination the substrate's per-`:entrada` Gateway API
6380/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6381/// carrying `port: 0` degenerates to a nominal-only routing target: the
6382/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6383/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6384/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6385/// at build time rather than at `kubectl apply` time), and the
6386/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6387/// (caixa-mesh/src/lib.rs:2657 through
6388/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6389/// [`Entrada::port`] typed value — silently emits a policy whose
6390/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6391/// actual listener, dropping every L4 flow at the eBPF data plane far
6392/// from the source caixa.lisp with no field naming the port-zero-drift
6393/// root cause.
6394///
6395/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6396/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6397/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6398/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6399/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6400/// well below `u32::MAX` and therefore need explicit typed caps).
6401///
6402/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6403/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6404/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6405/// `:port` inherits through the serde default hook; this constant names
6406/// the accept-set floor every declared port must satisfy. The pair is
6407/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6408/// substrate's default must satisfy its own accept-set floor by
6409/// construction) — a future rebrand that accidentally moved
6410/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6411/// negative-cast typo, a per-cluster override the operator pins through
6412/// a future `:placement :default-port` slot that lands out-of-range)
6413/// would silently invalidate the serde-default emission at every
6414/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6415/// invariant pin
6416/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6417/// closes the drift footgun at caixa-core build time.
6418///
6419/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6420/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6421/// has exactly one source of truth — the future M4
6422/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6423/// gateway resolver, the future per-Servico
6424/// `computeunit.trigger.service.port` renderer's per-CR port-value
6425/// validator, and every downstream test-fixture navigator asserting
6426/// the accept-set floor all read from one place. Same shape every
6427/// other typed bracket-floor / bracket-ceiling in this crate carries
6428/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6429/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6430/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6431/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6432/// [`POLICY_RATE_LIMIT_MAX`]).
6433pub const SERVICO_PORT_MIN: u16 = 1;
6434
6435const fn default_port() -> u16 {
6436 DEFAULT_SERVICO_PORT
6437}
6438
6439// ── the typed view ───────────────────────────────────────────────────
6440
6441/// Typed composition view of the flat Aplicacao slots on
6442/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6443/// validation + downstream renderer consumption.
6444#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6445#[serde(rename_all = "camelCase")]
6446pub struct AplicacaoSpec {
6447 pub membros: Vec<Membro>,
6448 pub contratos: Vec<WitContract>,
6449 pub politicas: MeshPolicy,
6450 pub placement: Placement,
6451 pub entrada: Option<Entrada>,
6452}
6453
6454impl AplicacaoSpec {
6455 /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6456 /// per-Aplicacao member-list slice-return accessor every
6457 /// per-Aplicacao member-list reader keys off — returns the author-
6458 /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6459 /// over the same backing buffer the raw `self.membros.as_slice()`
6460 /// field access borrows from.
6461 ///
6462 /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6463 /// member list — the load-bearing identity of the application graph
6464 /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6465 /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6466 /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6467 /// accessor) with a `:versao` semver-requirement string (through
6468 /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6469 /// and every downstream consumer that fans on the member-set keys
6470 /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6471 /// membership-lookup `HashSet<&str>` seed's collect input, the
6472 /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6473 /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6474 /// per-member DNS-1123 / semver-requirement / duplicate-detection
6475 /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
6476 /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
6477 /// programs.yaml per-`:membros` fan-out emitter's per-entry
6478 /// mapping-composition loop, the `feira app graph` per-Aplicacao
6479 /// member-count print line and per-member tree traversal,
6480 /// every future wasm-operator (M4) per-Aplicacao CR materializer's
6481 /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
6482 /// placement engine's per-member weight-topology reader).
6483 ///
6484 /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
6485 /// inline at six production sites — the [`AplicacaoSpec::validate`]
6486 /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
6487 /// [`AplicacaoSpec::validate_membros`]'s pre-flight
6488 /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
6489 /// probe, the same method's per-member `for m in &self.membros`
6490 /// validate-loop traversal head, the
6491 /// [`AplicacaoSpec::detect_sync_cycles`]'s
6492 /// `for m in &self.membros` adjacency-list seed, the
6493 /// [`caixa_mesh::programs_for_aplicacao`] emitter's
6494 /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
6495 /// paired with the peer `for m in &spec.membros` per-entry fan-out
6496 /// loop, and the `feira app graph` per-Aplicacao print line's
6497 /// `spec.membros.len()` count formatter argument paired with the
6498 /// peer `for m in &spec.membros` per-member tree traversal — six
6499 /// open-coded field-accesses that expressed no compile-time link
6500 /// back to the typed slot. A future extension of the `:membros`
6501 /// axis to a richer author surface (a per-cluster member-set
6502 /// overlay the operator pins through a future
6503 /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
6504 /// roadmap acknowledges, a per-tenant member-alias table the M4
6505 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
6506 /// CR at admission time, a per-Aplicacao dynamic member-set
6507 /// derivation the future adaptive-placement engine computes from
6508 /// weighted membership topology, a promotion of the plain
6509 /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
6510 /// Orleans-style virtual-actor dynamic-membership comes into typed
6511 /// scope) would have had to be threaded through all six open-coded
6512 /// copies in lockstep or one consumer would silently disagree with
6513 /// the peers on which member-set a given Aplicacao resolves to —
6514 /// the `HashSet<&str>` name-set seed reading the raw slot while
6515 /// the peer `.is_empty()` refusal probe read an operator-resolved
6516 /// slot would silently split the `:contratos` membership-lookup
6517 /// input from the pre-flight-refusal input, a six-consumer split
6518 /// at the validator + programs.yaml emitter + graph printer far
6519 /// from the source `caixa.lisp` with no field naming the member-
6520 /// set-drift root cause. Lifting the resolution rule to a typed
6521 /// method on the substrate primitive means every downstream
6522 /// consumer of the Aplicacao's per-`:membros` member-list surface
6523 /// reaches for exactly one typed dispatch — the resolver's accept-
6524 /// set migrates as a unit on any future axis addition.
6525 ///
6526 /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
6527 /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6528 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6529 /// static-child-list `Vec`-carry axis, and to the M3
6530 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6531 /// on the peer per-`:placement` distribution-target-list `Vec`-
6532 /// carry axis. Same "one typed dispatch on the substrate primitive,
6533 /// thin projections at each consumer" discipline. The two peer
6534 /// `Vec`-carry axes still unlifted at the time of this lift —
6535 /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
6536 /// WIT-typed edge list) and
6537 /// [`crate::UpgradeFromEntry::instructions`]
6538 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6539 /// — inherit this accessor's discipline as future compounding runs
6540 /// migrate their consumers onto the shared slice-return shape.
6541 /// First `&[T]`-return accessor on the top-level M3 mesh-slot
6542 /// `AplicacaoSpec` type itself, extending the discipline beyond
6543 /// the inner per-slot types ([`crate::Placement`],
6544 /// [`crate::SupervisorSpec`]) onto the outermost typed composition
6545 /// view every renderer consumes. Named `membros()` to match the
6546 /// storage field's name verbatim and the tatara-lisp author-
6547 /// surface term (`:membros`) the field's own docstring already
6548 /// carries; the accessor's identity maps onto the canonical
6549 /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
6550 /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
6551 /// every downstream consumer of the member list treats it as a
6552 /// read-only sequence — the slice-view is the narrowest borrow
6553 /// that supports every present + roadmapped consumer
6554 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6555 /// backing `Vec`'s grow/push/reserve surface that no consumer of
6556 /// the typed view reaches for (the storage-side `Vec` remains
6557 /// reachable through the `pub membros` field for the mutation-
6558 /// carrying serde round-trip and per-test fixture-mutation paths).
6559 #[must_use]
6560 pub const fn membros(&self) -> &[Membro] {
6561 self.membros.as_slice()
6562 }
6563
6564 /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
6565 /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
6566 /// accessor every per-Aplicacao contract-list reader keys off —
6567 /// returns the author-declared `:contratos` list verbatim as a
6568 /// `&[WitContract]` slice-view over the same backing buffer the raw
6569 /// `self.contratos.as_slice()` field access borrows from.
6570 ///
6571 /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
6572 /// WIT-typed edge list — the load-bearing set of directed edges
6573 /// on the application graph whose nodes are the `:membros` entries
6574 /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
6575 /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
6576 /// six-tuple is the edge identity every downstream duplicate gate
6577 /// keys off). Every per-`:contratos` entry pairs a `:de` source-
6578 /// Servico caller name + a `:para` destination-Servico callee name
6579 /// (through the lifted [`WitContract::source`] +
6580 /// [`WitContract::destination`] (7f0fd43) accessor pair on the
6581 /// caller/callee-Servico axis) with a `:wit` world-reference
6582 /// (through the lifted [`WitContract::world_ref`] (0804823)
6583 /// accessor) and the target-shape-appropriate payload-carrier
6584 /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
6585 /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
6586 /// (ed22b66) accessor on the per-target-shape payload-carrier
6587 /// axis). Every downstream consumer that fans on the edge-set
6588 /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
6589 /// name-set / self-edge / target-shape / dedup fan-out loop, the
6590 /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
6591 /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
6592 /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
6593 /// grouping loop, the `feira app graph` per-Aplicacao contract-
6594 /// count print line and per-contract tree traversal, every future
6595 /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
6596 /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
6597 /// mesh-policy overlay resolver's per-contract typed-edge weight
6598 /// reader).
6599 ///
6600 /// Prior to this lift the `.contratos` `Vec<WitContract>` was
6601 /// accessed inline at four production sites — the
6602 /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
6603 /// per-edge validate-loop traversal head (which drives every
6604 /// per-edge name-set membership lookup, self-edge check,
6605 /// target-shape dispatch, and dedup `HashSet` insert), the
6606 /// [`AplicacaoSpec::detect_sync_cycles`]'s
6607 /// `for c in &self.contratos` adjacency-list seed head (which
6608 /// drives every per-edge sync-vs-pub-sub partition and per-edge
6609 /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
6610 /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
6611 /// `BTreeMap` grouping loop head (which drives every per-CNP
6612 /// fan-out emit), and the `feira app graph` per-Aplicacao print
6613 /// line's `spec.contratos.len()` count formatter argument paired
6614 /// with the peer `for c in &spec.contratos` per-contract tree
6615 /// traversal — four open-coded field-accesses that expressed no
6616 /// compile-time link back to the typed slot. A future extension
6617 /// of the `:contratos` axis to a richer author surface (a
6618 /// per-cluster contract overlay the operator pins through a
6619 /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
6620 /// federation roadmap acknowledges, a per-tenant edge-policy
6621 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6622 /// materializer resolves per-CR at admission time, a per-edge
6623 /// weight scalar the future adaptive-placement engine reads to
6624 /// bias sync-subgraph routing, a promotion of the plain
6625 /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
6626 /// once virtual-actor-style dynamic-edge composition comes into
6627 /// typed scope) would have had to be threaded through all four
6628 /// open-coded copies in lockstep or one consumer would silently
6629 /// disagree with the peers on which edge-set a given Aplicacao
6630 /// resolves to — the validator's per-edge dedup `HashSet` seed
6631 /// reading the raw slot while the peer sync-cycle adjacency-list
6632 /// seed read an operator-resolved slot would silently split the
6633 /// build-time edge-set gate from the runtime deadlock-detection
6634 /// gate, a four-consumer split at the validator, the cycle
6635 /// detector, the CNP emitter, and the graph printer far from
6636 /// the source `caixa.lisp` with no field naming the edge-set-
6637 /// drift root cause. Lifting the resolution rule to a typed method on the
6638 /// substrate primitive means every downstream consumer of the
6639 /// Aplicacao's per-`:contratos` edge-list surface reaches for
6640 /// exactly one typed dispatch — the resolver's accept-set
6641 /// migrates as a unit on any future axis addition.
6642 ///
6643 /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
6644 /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6645 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6646 /// static-child-list `Vec`-carry axis, to the M3
6647 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6648 /// on the peer per-`:placement` distribution-target-list `Vec`-
6649 /// carry axis, and to the immediately-adjacent sibling M3
6650 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
6651 /// the peer per-`:membros` node-list `Vec`-carry axis — the
6652 /// per-`:contratos` edge-list accessor is the natural pair of
6653 /// the per-`:membros` node-list accessor (graph edges over graph
6654 /// nodes; every graph-shaped consumer reads both). Same "one
6655 /// typed dispatch on the substrate primitive, thin projections
6656 /// at each consumer" discipline. The last remaining `Vec`-carry
6657 /// axis still unlifted at the time of this lift —
6658 /// [`crate::UpgradeFromEntry::instructions`]
6659 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
6660 /// list) — inherits this accessor's discipline as future
6661 /// compounding runs migrate its consumers onto the shared slice-
6662 /// return shape. Second `&[T]`-return accessor on the top-level
6663 /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
6664 /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
6665 /// `:contratos` are the two `Vec` fields on the outer typed
6666 /// composition view — `:politicas`, `:placement`, `:entrada` are
6667 /// scalar/option-shaped and already route through their per-slot
6668 /// accessor families). Named `contratos()` to match the storage
6669 /// field's name verbatim and the tatara-lisp author-surface term
6670 /// (`:contratos`) the field's own docstring already carries; the
6671 /// accessor's identity maps onto the canonical MESH-COMPOSITION
6672 /// §III.1 vocabulary the slot's docstring already reaches for.
6673 /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
6674 /// every downstream consumer of the contract list treats it as a
6675 /// read-only sequence — the slice-view is the narrowest borrow
6676 /// that supports every present + roadmapped consumer
6677 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6678 /// backing `Vec`'s grow/push/reserve surface that no consumer of
6679 /// the typed view reaches for (the storage-side `Vec` remains
6680 /// reachable through the `pub contratos` field for the mutation-
6681 /// carrying serde round-trip and per-test fixture-mutation paths).
6682 #[must_use]
6683 pub const fn contratos(&self) -> &[WitContract] {
6684 self.contratos.as_slice()
6685 }
6686
6687 /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
6688 /// per-Aplicacao mesh-policy composite-reference accessor every
6689 /// per-Aplicacao policy-block reader keys off — returns the author-
6690 /// declared `:politicas` composite verbatim as a `&MeshPolicy`
6691 /// reference over the same backing storage the raw `&self.politicas`
6692 /// field access borrows from.
6693 ///
6694 /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
6695 /// mesh-policy composite — the load-bearing container of every
6696 /// mesh-level operational-policy axis every downstream mesh-artifact
6697 /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6698 /// mesh-policy overlay is the single typed surface a
6699 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6700 /// from). Every per-`:politicas` axis threads through a lifted
6701 /// per-slot accessor on the [`MeshPolicy`] type: the
6702 /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6703 /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6704 /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6705 /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6706 /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6707 /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6708 /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6709 /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6710 /// accessor. Every downstream consumer that reaches for a policy
6711 /// axis first passes through this outer accessor onto the composite
6712 /// and then dispatches onto the per-axis accessor — the two-level
6713 /// dispatch means every per-`:politicas` reader now routes through
6714 /// a typed dispatch on the substrate primitive at both altitudes.
6715 ///
6716 /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6717 /// accessed inline at four production sites — the
6718 /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6719 /// &self.politicas;` traversal seed (which drives every per-axis
6720 /// zero-floor + upper-cap + canonical-form bracket dispatch through
6721 /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6722 /// `p.rate_limit()` on the axis-level lifted accessors), the
6723 /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6724 /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6725 /// chain (which drives every per-`(:de, :para)` CNP
6726 /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6727 /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6728 /// timeout + retry overlay emitter's paired
6729 /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6730 /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6731 /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6732 /// open-coded outer-field accesses that expressed no compile-time
6733 /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6734 /// future extension of the `:politicas` outer axis to a richer
6735 /// author surface (a per-cluster policy overlay the operator pins
6736 /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6737 /// §V federation roadmap acknowledges, a per-tenant policy-alias
6738 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6739 /// resolves per-CR at admission time, a per-Aplicacao dynamic
6740 /// policy-composite derivation the future adaptive-placement engine
6741 /// computes from a per-cluster load-topology reader, a promotion of
6742 /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6743 /// partition once virtual-actor-style dynamic-mesh-policy
6744 /// composition comes into typed scope) would have had to be threaded
6745 /// through all four open-coded copies in lockstep or one consumer
6746 /// would silently disagree with the peers on which mesh-policy
6747 /// composite a given Aplicacao resolves to — the validator's
6748 /// per-axis bracket-dispatch seed reading the raw slot while the
6749 /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6750 /// would silently split the build-time policy-shape gate from the
6751 /// runtime CNP-emission gate, a four-consumer split at the
6752 /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6753 /// the source `caixa.lisp` with no field naming the policy-drift
6754 /// root cause. Lifting the resolution rule to a typed method on the
6755 /// substrate primitive means every downstream consumer of the
6756 /// Aplicacao's per-`:politicas` mesh-policy composite surface
6757 /// reaches for exactly one typed dispatch — the resolver's accept-
6758 /// set migrates as a unit on any future axis addition.
6759 ///
6760 /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6761 /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6762 /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6763 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6764 /// close the two `Vec`-carry axes on the outer typed composition
6765 /// view; the outer `:politicas` composite-reference axis is the
6766 /// natural pair to the paired outer `Vec`-carry accessors on the
6767 /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6768 /// emitter reads all four axes as one unit (graph nodes + graph
6769 /// edges + mesh policy + placement pool). Peer to the same
6770 /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6771 /// slot: every M2 `SupervisorSpec`-scoped composite reader
6772 /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6773 /// `restart_window`, `children`) already routes through the M2
6774 /// `SupervisorSpec` accessor family — this lift extends the same
6775 /// "one typed dispatch on the substrate primitive at the outer
6776 /// composition altitude" discipline to the M3 mesh-slot
6777 /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6778 /// remaining peer outer-composite axes still unlifted at the time
6779 /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6780 /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6781 /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6782 /// inherit this accessor's discipline as future compounding runs
6783 /// migrate their consumers onto the shared reference-return shape.
6784 /// Named `politicas()` to match the storage field's name verbatim
6785 /// and the tatara-lisp author-surface term (`:politicas`) the
6786 /// field's own docstring already carries; the accessor's identity
6787 /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6788 /// slot's docstring already reaches for. Returns `&MeshPolicy`
6789 /// (not the owning composite by copy or clone) because every
6790 /// downstream consumer of the mesh-policy composite treats it as a
6791 /// read-only per-axis dispatch source — the reference-view is the
6792 /// narrowest borrow that supports every present + roadmapped
6793 /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6794 /// emptiness probe) without cloning the composite through every
6795 /// consumer's fast path.
6796 #[must_use]
6797 pub const fn politicas(&self) -> &MeshPolicy {
6798 &self.politicas
6799 }
6800
6801 /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6802 /// per-Aplicacao distribution-composite composite-reference accessor
6803 /// every per-Aplicacao placement-block reader keys off — returns the
6804 /// author-declared `:placement` composite verbatim as a `&Placement`
6805 /// reference over the same backing storage the raw `&self.placement`
6806 /// field access borrows from.
6807 ///
6808 /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6809 /// distribution composite — the load-bearing container of every
6810 /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6811 /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6812 /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6813 /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6814 /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6815 /// `:affinity` hint). Every per-`:placement` axis threads through a
6816 /// lifted per-slot accessor on the [`Placement`] type: the
6817 /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6818 /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6819 /// per-cluster distribution-target slice-return accessor, the
6820 /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6821 /// optional-scalar accessor, and the [`Placement::shard_key`]
6822 /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6823 /// downstream consumer that reaches for a placement axis first passes
6824 /// through this outer accessor onto the composite and then dispatches
6825 /// onto the per-axis accessor — the two-level dispatch means every
6826 /// per-`:placement` reader now routes through a typed dispatch on the
6827 /// substrate primitive at both altitudes.
6828 ///
6829 /// Prior to this lift the `.placement` `Placement` composite was
6830 /// accessed inline at three production sites — the
6831 /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6832 /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6833 /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6834 /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6835 /// cluster `.clusters()` validate-loop traversal head, the per-
6836 /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6837 /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6838 /// paired with the shape-gate cascade's `.shard_key()` /
6839 /// `.estrategia()` diagnostic-carry pair), the
6840 /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6841 /// per-entry placement-block emitter's outer
6842 /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6843 /// seed (which fans onto every per-cluster `programs[]` entry as a
6844 /// self-describing distribution overlay the aggregator filters by),
6845 /// and the `feira app graph` per-Aplicacao print line's paired
6846 /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6847 /// then-inner-accessor chains (which drive the human-readable
6848 /// distribution summary of the typed Aplicacao view) — three open-
6849 /// coded outer-field accesses that expressed no compile-time link
6850 /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6851 /// extension of the `:placement` outer axis to a richer author surface
6852 /// (a per-cluster placement overlay the operator pins through a
6853 /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6854 /// federation roadmap acknowledges, a per-tenant placement-alias
6855 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6856 /// resolves per-CR at admission time, a per-Aplicacao dynamic
6857 /// placement-composite derivation the future M5 adaptive-placement
6858 /// engine computes from a per-cluster load-topology reader, a
6859 /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6860 /// partition once Orleans-style virtual-actor dynamic-placement comes
6861 /// into typed scope) would have had to be threaded through all three
6862 /// open-coded copies in lockstep or one consumer would silently
6863 /// disagree with the peers on which placement composite a given
6864 /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6865 /// seed reading the raw slot while the peer
6866 /// `programs_for_aplicacao` emitter read an operator-resolved slot
6867 /// would silently split the build-time distribution-shape gate from
6868 /// the runtime programs.yaml distribution-annotation gate, a three-
6869 /// consumer split at the validator, the programs.yaml emitter, and
6870 /// the `feira app graph` printer far from the source `caixa.lisp`
6871 /// with no field naming the placement-drift root cause. Lifting the
6872 /// resolution rule to a typed method on the substrate primitive
6873 /// means every downstream consumer of the Aplicacao's per-
6874 /// `:placement` distribution composite surface reaches for exactly
6875 /// one typed dispatch — the resolver's accept-set migrates as a unit
6876 /// on any future axis addition.
6877 ///
6878 /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6879 /// `AplicacaoSpec` type itself — sibling to the seed
6880 /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6881 /// composite-reference accessor on the peer per-`:politicas` outer-
6882 /// composite axis, and to the paired slice-return accessors
6883 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6884 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6885 /// the two `Vec`-carry axes on the outer typed composition view; the
6886 /// outer `:placement` composite-reference axis is the natural pair
6887 /// to the peer `:politicas` composite-reference axis on the two
6888 /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6889 /// how-to-run policy overlay, `:placement` carries the where-to-run
6890 /// distribution composite — every whole-Aplicacao mesh-artifact
6891 /// emitter reads both as one unit). Same "one typed dispatch on the
6892 /// substrate primitive, thin projections at each consumer"
6893 /// discipline the peer per-`:politicas` composite-reference axis
6894 /// already routes through. The one remaining outer-composite axis
6895 /// still unlifted at the time of this lift —
6896 /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6897 /// external-gateway composite) — inherits this accessor's discipline
6898 /// as the next compounding run migrates its consumers onto the shared
6899 /// reference-return shape, closing the outer-composite altitude on
6900 /// every M3 mesh-slot axis. Named `placement()` to match the storage
6901 /// field's name verbatim and the tatara-lisp author-surface term
6902 /// (`:placement`) the field's own docstring already carries; the
6903 /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6904 /// vocabulary the slot's docstring already reaches for. Returns
6905 /// `&Placement` (not the owning composite by copy or clone) because
6906 /// every downstream consumer of the placement composite treats it as
6907 /// a read-only per-axis dispatch source — the reference-view is the
6908 /// narrowest borrow that supports every present + roadmapped consumer
6909 /// (per-axis accessor dispatch, serde composite-serialization) without
6910 /// cloning the composite through every consumer's fast path.
6911 #[must_use]
6912 pub const fn placement(&self) -> &Placement {
6913 &self.placement
6914 }
6915
6916 /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6917 /// per-Aplicacao external-gateway composite optional-composite-
6918 /// reference accessor every per-Aplicacao gateway-block reader
6919 /// keys off — returns the author-declared `:entrada` composite
6920 /// verbatim as an `Option<&Entrada>` reference over the same
6921 /// backing storage the raw `self.entrada.as_ref()` field access
6922 /// borrows from, with `None` naming the internal-only mesh shape
6923 /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6924 /// gateway_routes emitter treats as "emit nothing" and the peer
6925 /// `feira app graph` printer treats as "internal-only mesh").
6926 ///
6927 /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6928 /// external-gateway composite — the load-bearing container of
6929 /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6930 /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6931 /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6932 /// hostname axis, §III.4 for the `:para` destination-Servico
6933 /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6934 /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6935 /// axis threads through a lifted per-slot accessor on the
6936 /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6937 /// Gateway-API `Listener.hostname` scalar accessor, the paired
6938 /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6939 /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6940 /// backendRefs destination-Servico scalar accessor, the
6941 /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6942 /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6943 /// scalar accessor. Every downstream consumer that reaches for
6944 /// an entrada axis first passes through this outer accessor onto
6945 /// the composite and then dispatches onto the per-axis accessor
6946 /// — the two-level dispatch means every per-`:entrada` reader
6947 /// now routes through a typed dispatch on the substrate primitive
6948 /// at both altitudes.
6949 ///
6950 /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6951 /// was accessed inline at four production sites — the
6952 /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6953 /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6954 /// (which drives every per-axis refusal on the composite: the
6955 /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6956 /// `EntradaMemberMissing` membership lookup against the
6957 /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6958 /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6959 /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6960 /// per-path shape gate on each entry of `e.paths`), the
6961 /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6962 /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6963 /// composite-projection seed (which drives the destination-
6964 /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6965 /// backendRefs port emitter fans on), the
6966 /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6967 /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6968 /// early-return seed (which drives the "no `:entrada` ⇒ no
6969 /// external artifacts" partition on the whole-Aplicacao Gateway-
6970 /// API emitter's fan-out), and the `feira app graph` per-
6971 /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6972 /// external-gateway summary emitter (which drives the human-
6973 /// readable `entrada: host → para (paths=…, port=…)` /
6974 /// `entrada: (internal-only mesh)` partition on the typed
6975 /// Aplicacao view) — four open-coded outer-field accesses that
6976 /// expressed no compile-time link back to the typed slot at the
6977 /// [`AplicacaoSpec`] altitude. A future extension of the
6978 /// `:entrada` outer axis to a richer author surface (a
6979 /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6980 /// at admission time so an Aplicacao can expose a public-web +
6981 /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6982 /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6983 /// operator can pin a per-cluster hostname override without
6984 /// re-authoring the `caixa.lisp`, a promotion of the plain
6985 /// `Option<Entrada>` to a richer `{single, multi}` partition once
6986 /// the multi-`:entrada` roadmap lands) would have had to be
6987 /// threaded through all four open-coded copies in lockstep or one
6988 /// consumer would silently disagree with the peers on which
6989 /// entrada composite a given Aplicacao resolves to — the
6990 /// validator's per-axis bracket-dispatch seed reading the raw
6991 /// slot while the peer `gateway_routes` emitter read an
6992 /// operator-resolved slot would silently split the build-time
6993 /// gateway-shape gate from the runtime Gateway + HTTPRoute
6994 /// emission gate, a four-consumer split at the validator, the
6995 /// `port_for_destination` L4-port resolver, the `gateway_routes`
6996 /// emitter, and the `feira app graph` printer far from the
6997 /// source `caixa.lisp` with no field naming the entrada-drift
6998 /// root cause. Lifting the resolution rule to a typed method on
6999 /// the substrate primitive means every downstream consumer of
7000 /// the Aplicacao's per-`:entrada` external-gateway composite
7001 /// surface reaches for exactly one typed dispatch — the
7002 /// resolver's accept-set migrates as a unit on any future axis
7003 /// addition.
7004 ///
7005 /// Third and final `&Composite`-return accessor on the top-level
7006 /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
7007 /// unlifted outer-composite axis on the outer typed composition
7008 /// view, sibling to the seed [`AplicacaoSpec::politicas`]
7009 /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
7010 /// accessor on the per-`:politicas` outer-composite axis and to
7011 /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
7012 /// distribution-composite composite-reference accessor on the
7013 /// per-`:placement` outer-composite axis; extends the outer-
7014 /// composite reference-return discipline the two peers already
7015 /// route through onto the last unlifted per-`AplicacaoSpec`
7016 /// outer-composite axis. The `:entrada` outer-composite axis is
7017 /// the natural pair to the two peer outer-composite axes on the
7018 /// three operationally-symmetric M3 mesh-slot outer composites
7019 /// (`:politicas` carries the how-to-run policy overlay,
7020 /// `:placement` carries the where-to-run distribution composite,
7021 /// `:entrada` carries the who-can-reach-it external-gateway
7022 /// composite — every whole-Aplicacao mesh-artifact emitter reads
7023 /// all three as one unit). Same "one typed dispatch on the
7024 /// substrate primitive, thin projections at each consumer"
7025 /// discipline the peer outer-composite axes already route through.
7026 /// Named `entrada()` to match the storage field's name verbatim
7027 /// and the tatara-lisp author-surface term (`:entrada`) the
7028 /// field's own docstring already carries; the accessor's
7029 /// identity maps onto the canonical MESH-COMPOSITION §III.4
7030 /// vocabulary the slot's docstring already reaches for. Returns
7031 /// `Option<&Entrada>` (not the owning composite by copy or
7032 /// clone) because every downstream consumer of the entrada
7033 /// composite treats it as a read-only per-axis dispatch source
7034 /// — the reference-view is the narrowest borrow that supports
7035 /// every present + roadmapped consumer (per-axis accessor
7036 /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
7037 /// port-fallback projection, early-return partition on the
7038 /// `None` arm) without cloning the composite through every
7039 /// consumer's fast path. The `Option` half of the return-type
7040 /// preserves the load-bearing "author-omitted `:entrada` ⇒
7041 /// internal-only mesh" partition (not a default composite the
7042 /// downstream must reject on emptiness) — the accessor projects
7043 /// the raw `Option<Entrada>` slot's presence bit through the
7044 /// reference-return unchanged.
7045 #[must_use]
7046 pub const fn entrada(&self) -> Option<&Entrada> {
7047 self.entrada.as_ref()
7048 }
7049
7050 /// Validate the typed shape:
7051 /// - `:membros` is non-empty; every entry has a non-empty `:caixa`
7052 /// and a non-empty `:versao`; no two entries share the same
7053 /// `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
7054 /// not a multiset)
7055 /// - every `:contratos` :de + :para must be in `:membros`
7056 /// - no `:contratos` edge is a self-edge (`:de == :para`) — a
7057 /// contract is an inter-Servico edge, so a Servico contracting
7058 /// with itself is a build error under every WIT shape
7059 /// (MESH-COMPOSITION §III.1)
7060 /// - no two `:contratos` entries agree on
7061 /// `(de, para, wit, endpoint, subject, slot)` — the typed-graph
7062 /// edges are a set, not a multiset (peer of the `:membros` /
7063 /// `:placement :clusters` / `:entrada :paths` duplicate gates)
7064 /// - `:entrada :para` must be in `:membros`
7065 /// - `:placement Sharded` must declare `:shard-key` (non-empty);
7066 /// `:placement Replicated`/`SingleNode` must NOT declare
7067 /// `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
7068 /// consumes it (MESH-COMPOSITION §II.4), and the typed partition
7069 /// between strategy and shard-key is symmetric: every validated
7070 /// `Placement` has `shard_key.is_some()` iff `estrategia ==
7071 /// Sharded`
7072 /// - every `:placement` strategy must declare ≥1 `:clusters` entry —
7073 /// `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
7074 /// the shard pool (MESH-COMPOSITION §III.1)
7075 /// - every `:clusters` entry is non-empty and unique
7076 /// - `:placement :affinity`, when set, is non-empty
7077 /// - the synchronous-`:contratos` subgraph is acyclic
7078 /// (MESH-COMPOSITION §III.3)
7079 /// - every declared `:politicas` value is operationally meaningful
7080 /// (zero timeout, zero retries, zero breaker thresholds, zero rate
7081 /// limit are all build errors — MESH-COMPOSITION §V CSE invariants;
7082 /// omit the field instead to express "no policy on this axis")
7083 pub fn validate(&self) -> Result<(), AplicacaoError> {
7084 self.validate_membros()?;
7085 let names: std::collections::HashSet<&str> =
7086 self.membros().iter().map(Membro::nome).collect();
7087
7088 // Identity key for the typed-edge duplicate gate below: every
7089 // field that distinguishes one contract from another. Two
7090 // entries that agree on all six are *the same edge declared
7091 // twice*, the typed-graph analogue of duplicate `:membros` /
7092 // `:placement :clusters` / `:entrada :paths` entries (which
7093 // are already build errors at this layer). Rejecting it at the
7094 // validate gate closes a renderer-side footgun: caixa-mesh's
7095 // `cilium_network_policies` keys each emitted policy by
7096 // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
7097 // (de, para) and identical payload would land as two K8s
7098 // objects with colliding `metadata.name`, rejected at apply
7099 // time far from the source caixa.lisp.
7100 let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
7101 std::collections::HashSet::new();
7102 for c in self.contratos() {
7103 // Per-axis value-shape gate on every `:contratos` name
7104 // reference, before any graph-membership lookup. Empty +
7105 // DNS-1123-malformed `:de`/`:para` values silently fell
7106 // through to `ContratoMemberMissing` at the lookup arm
7107 // because every `:membros :caixa` is shape-validated
7108 // (3f9d7a0), so the `names` set structurally cannot contain
7109 // an empty / malformed string and the membership-lookup
7110 // diagnostic always misframed the root cause as
7111 // "this caixa is not in `:membros`". The shape gate runs
7112 // ahead of the lookup so structurally-impossible-to-match
7113 // inputs route through the narrower self-locating
7114 // diagnostic, preserving the legitimate "well-shaped
7115 // phantom reference" arm. `:de` runs before `:para` per
7116 // the canonical edge-direction order the existing
7117 // membership lookup, self-edge check, target dispatch,
7118 // and diagnostic strings already use.
7119 // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
7120 // + the paired [`AplicacaoError::ContratoMemberMissing`]
7121 // diagnostic's `caixa:` carrier through the lifted
7122 // [`WitContract::source`] / [`WitContract::destination`]
7123 // scalar accessors rather than the raw `&c.de` / `&c.para`
7124 // `&String`-borrow arg site + the raw `c.de.clone()` /
7125 // `c.para.clone()` field-access `String`-carry sites — the
7126 // last unlifted per-`:contratos` raw-field-access sites in
7127 // the M3 mesh-slot validator's per-edge per-arm shape-gate
7128 // arg + phantom-name diagnostic wrap-envelope emit surface.
7129 // `c.source()` is byte-identical to `&c.de` (pinned by the
7130 // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
7131 // + `wit_contract_source_borrows_from_de_storage` accessor
7132 // tests) and `c.destination()` is byte-identical to `&c.para`
7133 // (pinned by the sibling
7134 // `wit_contract_destination_returns_para_byte_equal_across_permutations`
7135 // + `wit_contract_destination_borrows_from_para_storage`
7136 // accessor tests) — so a future rebrand of either underlying
7137 // storage flows through the accessor's one body without a
7138 // coordinated per-consumer rewrite across the M3 mesh
7139 // validator's per-edge shape-gate + phantom-name refusal
7140 // arms. Peer of the sibling per-`:contratos` self-loop
7141 // arm's `.source().to_string()` / `.world_ref().to_string()`
7142 // `String`-carry sites the earlier convergence lifted onto
7143 // the same accessor pair.
7144 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
7145 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
7146 if !names.contains(c.source()) {
7147 return Err(AplicacaoError::ContratoMemberMissing {
7148 caixa: c.source().to_string(),
7149 });
7150 }
7151 if !names.contains(c.destination()) {
7152 return Err(AplicacaoError::ContratoMemberMissing {
7153 caixa: c.destination().to_string(),
7154 });
7155 }
7156 // A `:contratos` entry is an *inter*-Servico contract
7157 // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
7158 // typed edge between two distinct graph nodes. An edge whose
7159 // `:de` equals its `:para` is a Servico contracting with
7160 // itself — a degenerate edge under every WIT shape. The
7161 // synchronous shapes were caught only incidentally, and with
7162 // a misleading diagnostic: `detect_sync_cycles` reported
7163 // `cart → cart` as a `ContratoCycle` whose path is
7164 // `["cart", "cart"]` — framing a self-edge as a multi-node
7165 // deadlock. The pub-sub shape slipped through entirely
7166 // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
7167 // `nats:pub-sub` edge from a member to itself silently
7168 // validated, then rendered a `CiliumNetworkPolicy` whose
7169 // endpointSelector and fromEndpoints both name the same
7170 // program — a self-allow rule that is a no-op, since
7171 // intra-pod traffic never traverses the mesh). A self-edge's
7172 // runtime meaning is an in-process call, which doesn't go
7173 // through the mesh at all, so no `:contratos` edge can carry
7174 // it. Firing the gate before the `:wit`/`target()` shape
7175 // checks means the structural "this edge can't exist" error
7176 // precedes the narrower payload-shape diagnostics, and shape-
7177 // agnostically covers all four `WitTarget` arms (HTTP / Store
7178 // / Capability / PubSub) at one point — closing the pub-sub
7179 // hole and replacing the misleading cycle diagnostic in one
7180 // gate. Peer of the duplicate-`:contratos` / duplicate-
7181 // `:membros` set gates: both reject a structurally
7182 // ill-formed graph at the typed surface, before the renderer
7183 // emits a K8s object that fails or no-ops far from the source
7184 // caixa.lisp.
7185 // Route the per-`:contratos` structural self-edge probe
7186 // through the lifted [`WitContract::is_self_loop`] typed
7187 // predicate rather than the raw `c.de == c.para` field-
7188 // equality check — the one production consumer of the per-
7189 // `:contratos` caller-equals-callee endpoint-equality axis
7190 // now keys off exactly one typed dispatch on the substrate
7191 // primitive, so any future rebrand of the axis (an M4-typed-
7192 // caller enum whose identity comparison rule the predicate
7193 // could route through, a per-cluster caller/callee-alias
7194 // table the M4 CR materializer resolves per-CR before the
7195 // equality probe) migrates as a single caixa-core edit
7196 // rather than a coordinated rewrite of the gate + every
7197 // downstream self-edge consumer. Peer of the sibling
7198 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
7199 // [`WitContract::is_store`] shape-predicate routing on the
7200 // `:wit` world-ref axis, extended onto the per-edge
7201 // endpoint-equality axis.
7202 //
7203 // Route the paired [`AplicacaoError::ContratoSelfLoop`]
7204 // diagnostic's `caixa:` / `wit:` carriers through the
7205 // lifted [`WitContract::source`] / [`WitContract::world_ref`]
7206 // scalar accessors rather than the raw `c.de.clone()` /
7207 // `c.wit.clone()` field-access `String`-carry sites — the
7208 // last unlifted per-`:contratos` raw-field-access
7209 // `.clone()` sites in the M3 mesh-slot validator's self-
7210 // edge refusal arm. `.source().to_string()` is byte-
7211 // identical to `.de.clone()` (pinned by the sibling
7212 // `source_returns_de_byte_equal_across_permutations` accessor
7213 // test), and `.world_ref().to_string()` is byte-identical
7214 // to `.wit.clone()` (pinned by the sibling
7215 // `world_ref_returns_wit_byte_equal_across_permutations`
7216 // accessor test) — so a future rebrand of either underlying
7217 // storage flows through the accessor's one body without a
7218 // coordinated per-consumer rewrite across the M3 mesh
7219 // validator.
7220 if c.is_self_loop() {
7221 return Err(AplicacaoError::ContratoSelfLoop {
7222 caixa: c.source().to_string(),
7223 wit: c.world_ref().to_string(),
7224 });
7225 }
7226 if c.world_ref().is_empty() {
7227 let (de, para) = c.edge_pair();
7228 return Err(AplicacaoError::EmptyWit { de, para });
7229 }
7230 // Shape ↔ target consistency — surfaces "HTTP wit without
7231 // :endpoint", "NATS wit with :endpoint set", etc. as named
7232 // build errors instead of silent renderer drops. Threaded
7233 // through the duplicate-edge diagnostic below (via
7234 // [`WitTarget::label`]) so the "which typed target arm did
7235 // the duplicate carry" question is answered by the typed
7236 // enum's variant discriminator, not by re-probing the raw
7237 // `Option<String>` payload fields.
7238 let target_view = c.target()?;
7239 // Contract identity: (de, para, wit, endpoint, subject, slot).
7240 // Two contracts that match on all six are the same typed edge
7241 // declared twice — author error, not a legitimate variant of
7242 // "same caller-callee pair, different payload" (e.g.
7243 // cart→catalog at /products vs /search), which keeps distinct
7244 // identity keys via the differing endpoint payloads.
7245 //
7246 // Route the six-axis dedup key through the lifted
7247 // [`WitContract::identity`] composite-projection accessor
7248 // rather than the inline six-tuple builder — the two
7249 // substrate primitives on the per-`:contratos` identity axis
7250 // (the [`ContratoIdentity`] type alias's six axes, this
7251 // dedup-key's six tuple arms) now migrate as a unit on any
7252 // future axis addition. Peer of the sibling per-`:contratos`
7253 // composite-projection [`WitContract::edge_pair`] /
7254 // [`WitContract::edge_triple`] accessors on the
7255 // caller-callee / caller-callee-wit prefix axes; extends
7256 // the discipline onto the full-identity axis that carries
7257 // the three payload-shape arms too.
7258 let key = c.identity();
7259 crate::render::insert_first_seen(&mut seen_contracts, key, || {
7260 // Route the per-`:contratos` duplicate-gate diagnostic's
7261 // `(de, para, wit)` triple through the lifted
7262 // [`WitContract::edge_triple`] typed accessor rather
7263 // than pairing `edge_pair()` for the `(de, para)` prefix
7264 // with a raw `c.wit.clone()` for the `wit:` tail — the
7265 // paired-with-raw-field-access shape was the last
7266 // per-`:contratos` diagnostic constructor bypassing the
7267 // substrate-primitive composite projection, sibling to
7268 // the eight [`AplicacaoError::Contrato*`] triple-
7269 // carrying constructors [`WitContract::target`]'s edge
7270 // closure feeds through the same accessor.
7271 let (de, para, wit) = c.edge_triple();
7272 AplicacaoError::ContratoDuplicate {
7273 de,
7274 para,
7275 wit,
7276 target: target_view.label(),
7277 }
7278 })?;
7279 }
7280
7281 // Cycles in the synchronous-edge subgraph are build errors
7282 // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
7283 // are "acyclic by construction" because the publisher fires
7284 // and forgets, so no caller blocks on a downstream that loops
7285 // back to it.
7286 self.detect_sync_cycles()?;
7287
7288 if let Some(e) = self.entrada() {
7289 // Route the per-`:entrada` composite-reference read
7290 // through the lifted [`AplicacaoSpec::entrada`] accessor
7291 // rather than the raw `&self.entrada` field access — the
7292 // shape-and-membership gate's traversal head is now the
7293 // canonical read-side surface every per-Aplicacao entrada
7294 // consumer routes through, closing the fourth of four
7295 // open-coded outer-field accesses on the per-`:entrada`
7296 // outer-composite axis.
7297 //
7298 // Shape gate on `:entrada :para` runs ahead of the
7299 // membership lookup. Every `:membros :caixa` past
7300 // `validate_membro_caixa` is a valid DNS-1123 label
7301 // (3f9d7a0), so the `names` set structurally cannot
7302 // contain an empty / malformed string and the membership-
7303 // lookup diagnostic always misframed the root cause as
7304 // "this caixa is not in `:membros`". The shape gate
7305 // routes structurally-impossible-to-match inputs through
7306 // the narrower self-locating diagnostic, preserving the
7307 // legitimate "well-shaped phantom reference" arm — the
7308 // same trajectory the peer `:membros :caixa` (3f9d7a0),
7309 // `:placement :clusters` (6c8c00b), and `:contratos :de`
7310 // / `:para` (8d5af6b) axes already follow. This closes
7311 // the fourth and last Aplicacao-level Servico-name
7312 // reference axis on the canonical DNS-1123 floor.
7313 // Route the per-`:entrada :para` byte-string reads through
7314 // the lifted [`Entrada::destination`] accessor rather than
7315 // the raw `e.para` field access — the three
7316 // per-`AplicacaoSpec::validate` `:entrada :para` consumers
7317 // (shape-gate `validate_entrada_para` arg, membership
7318 // lookup, `EntradaMemberMissing` diagnostic carry) now key
7319 // off exactly one typed dispatch on the substrate
7320 // primitive, closing the last unlifted per-`:entrada :para`
7321 // raw-field-access axis on the M3 mesh-slot validator.
7322 // The `.destination().to_string()` at the diagnostic site
7323 // is byte-identical to `.para.clone()` — pinned by the
7324 // sibling `destination_returns_entrada_para_byte_equal` +
7325 // `destination_borrows_from_entrada_para_storage` accessor
7326 // tests — so a future rebrand of the underlying `:para`
7327 // storage (a lift from `String` to a typed
7328 // `ServicoName(String)` newtype, a per-Aplicacao interning
7329 // arena the M4 CR materializer authors, a
7330 // `smol_str::SmolStr` inline-buffer swap) flows through
7331 // the accessor's one body without a coordinated
7332 // per-consumer rewrite across the M3 mesh validator.
7333 validate_entrada_para(e.destination())?;
7334 if !names.contains(e.destination()) {
7335 return Err(AplicacaoError::EntradaMemberMissing {
7336 para: e.destination().to_string(),
7337 });
7338 }
7339 // Route the per-`:entrada :host` byte-string reads through
7340 // the lifted [`Entrada::hostname`] accessor rather than
7341 // the raw `e.host` field access — the emptiness gate and
7342 // the shape-gate `validate_entrada_host` arg now key off
7343 // exactly one typed dispatch on the substrate primitive,
7344 // closing the last unlifted per-`:entrada :host` raw-
7345 // field-access axis on the M3 mesh-slot validator. Peer
7346 // of the sibling per-`:entrada :para` convergence above
7347 // and pinned by the existing
7348 // `hostname_returns_entrada_host_byte_equal` +
7349 // `hostnames_returns_singleton_of_hostname_accessor`
7350 // accessor tests, so any future
7351 // Gateway-API-shaped host renormalization (a wildcard-
7352 // label lift, a trailing-`.` FQDN substitution, an IDNA
7353 // Punycode round-trip the SNI fan-out overlay authors)
7354 // flows through the accessor's one body without a
7355 // coordinated per-consumer rewrite across the M3 mesh
7356 // validator.
7357 if e.hostname().is_empty() {
7358 return Err(AplicacaoError::EmptyEntradaHost);
7359 }
7360 // The `:host` lands verbatim as a K8s Gateway API v1
7361 // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7362 // both apiserver-validated against the same restrictive
7363 // pattern: lowercase RFC 1123 DNS subdomain, optional
7364 // single leading wildcard label (`*.`), max length 253,
7365 // per-label max length 63, no IP literals, no scheme,
7366 // no port. Until this gate landed `validate()` only
7367 // refused the empty string (`EmptyEntradaHost`); a
7368 // structurally invalid hostname (`"https://example.com"`,
7369 // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
7370 // `"_underscored.example.com"`, `"FOO.example.com"`,
7371 // `"checkout.quero.cloud."`) silently passed validate
7372 // and the apiserver `field is invalid` error surfaced at
7373 // `kubectl apply` time, far from the source caixa.lisp.
7374 // Lifting the gate to caixa-build time mirrors the
7375 // `:entrada :paths` value-shape trajectory (eb3456d) and
7376 // closes the last unstructured `:entrada` axis.
7377 validate_entrada_host(e.hostname())?;
7378 // Structural-floor gate on `:entrada :port`: every
7379 // validated `Entrada::port` past this gate lies in
7380 // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
7381 // type-inferred ceiling closes the top edge, so no companion
7382 // upper-cap arm is needed here — unlike the peer capped-
7383 // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
7384 // `require_positive_bounded_u32` bracket covers both edges).
7385 // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
7386 // accept-set-floor const rather than the prior inline
7387 // `if e.port == 0` byte-check so a future rebrand of the
7388 // accept-set floor (a hypothetical unprivileged-only
7389 // migration lifting the floor to `1024`, a per-cluster
7390 // scoping the operator pins through a future
7391 // `:placement :port-floor` slot as the M4 typed-slot
7392 // trajectory adds it, the future
7393 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7394 // per-Aplicacao gateway resolver reaching for the same
7395 // floor) is a one-line edit on the canonical
7396 // [`SERVICO_PORT_MIN`] declaration, not a coordinated
7397 // rewrite across the emit site + the pin test + every
7398 // future per-target renderer the substrate adds.
7399 if e.port() < SERVICO_PORT_MIN {
7400 return Err(AplicacaoError::EntradaPortZero);
7401 }
7402 // Each `:entrada :paths` entry becomes a K8s Gateway API
7403 // HTTPRoute `matches[].path.value`. The Gateway API rejects
7404 // values that don't start with `/` for `type: PathPrefix`,
7405 // and an empty value is meaningless. Surface those as build
7406 // errors (MESH-COMPOSITION §III.3) rather than apply-time
7407 // failures. Empty `:paths` itself is fine — caixa-mesh
7408 // falls back to a single `/` catch-all.
7409 let mut seen = std::collections::HashSet::new();
7410 // Route the per-entry value-shape gate's traversal head
7411 // through the lifted [`Entrada::paths`] slice accessor
7412 // rather than the raw `&e.paths` field access — the
7413 // per-Aplicacao `:entrada :paths` validate loop now keys
7414 // off the canonical raw-slot surface every downstream
7415 // per-`:entrada` path-list consumer (the sibling
7416 // [`Entrada::resolved_paths`] fallback-applying resolver
7417 // internal reads, `feira app graph`'s per-Aplicacao entrada
7418 // summary line's `{:?}` Debug print) routes through, so any
7419 // future rebrand on the typed slot's raw-slot reader lands
7420 // at exactly one place. Same convergence discipline as the
7421 // sibling [`Placement::clusters`] (a6e18d7) reader-site
7422 // convergences on the peer M3 mesh-slot `Vec<String>`-carry
7423 // axis.
7424 for p in e.paths() {
7425 if p.is_empty() {
7426 return Err(AplicacaoError::EntradaPathEmpty);
7427 }
7428 if !p.starts_with('/') {
7429 return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
7430 }
7431 // Per-entry value-shape gate: the path lands verbatim
7432 // as a K8s Gateway API HTTPRoute `matches[].path.value`
7433 // (caixa-mesh/src/lib.rs:498), apiserver-validated
7434 // against `maxLength: 1024` + the Gateway API webhook's
7435 // path-grammar rules (no `//`, no `/./`, no `/../`, no
7436 // query/fragment separators, no whitespace, no control
7437 // characters, no non-ASCII bytes). Until this gate
7438 // landed `validate` only refused the empty string and
7439 // missing-leading-slash (eb3456d); a structurally
7440 // invalid path (`"/api?q=1"`, `"/api#frag"`,
7441 // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
7442 // 1025-byte URL-shaped slug) silently passed validate
7443 // and the failure surfaced at `kubectl apply` time as
7444 // a Gateway API webhook rejection, far from the source
7445 // caixa.lisp, with no field naming the offending
7446 // `:paths` entry. Lifting the gate to caixa-build time
7447 // mirrors the `:entrada :host` value-shape trajectory
7448 // (c7d05ec) on the sibling axis — every author surface
7449 // that emits a Gateway API field now matches the
7450 // apiserver's accepted set at validate time.
7451 validate_entrada_path(p)?;
7452 crate::render::insert_first_seen(&mut seen, p.as_str(), || {
7453 AplicacaoError::EntradaPathDuplicate { path: p.clone() }
7454 })?;
7455 }
7456 }
7457
7458 self.validate_placement()?;
7459
7460 self.validate_politicas()?;
7461
7462 Ok(())
7463 }
7464
7465 /// Reject `:membros` values that are operationally meaningless. The
7466 /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
7467 /// every entry names a Servico that participates in the Aplicacao,
7468 /// and the rendered programs.yaml fan-out emits one entry per
7469 /// `:membros`. Three authoring footguns are closed here:
7470 ///
7471 /// - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
7472 /// a `programs:` entry whose `name:` is the empty string, which
7473 /// downstream `lareira-fleet-programs` rejects at template time
7474 /// with a non-localized error;
7475 /// - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
7476 /// an empty semver constraint, so the failure surfaces far from
7477 /// the source caixa.lisp;
7478 /// - duplicate `:caixa` names — two entries with the same name
7479 /// produce duplicate programs.yaml entries (one silently
7480 /// overwrites the other in the cluster's HelmRelease values), and
7481 /// contract membership lookups against `:contratos` collapse the
7482 /// two onto one node, masking authoring mistakes.
7483 ///
7484 /// Same value-shape discipline as `:placement :clusters` (where empty
7485 /// + duplicate cluster names are rejected) and `:entrada :paths`
7486 /// (where empty + duplicate path entries are rejected). Lifting these
7487 /// invariants to the typed surface mirrors the MESH-COMPOSITION
7488 /// §III.3 promise that the `:membros` set — the load-bearing identity
7489 /// of the application graph — is well-formed by construction.
7490 fn validate_membros(&self) -> Result<(), AplicacaoError> {
7491 if self.membros().is_empty() {
7492 return Err(AplicacaoError::NoMembros);
7493 }
7494 let mut seen = std::collections::HashSet::new();
7495 for m in self.membros() {
7496 // Route the `MembroCaixaEmpty` refusal-arm's per-member
7497 // empty-`:caixa` shape-gate through the typed
7498 // [`Membro::nome`] accessor rather than the raw `.caixa`
7499 // field access — the last un-lifted `.caixa` production-
7500 // code read site on the per-`:membros` member-caixa `:nome`
7501 // axis, sibling to the six caixa-core validator read sites
7502 // (member-set collector, per-member value-shape gate,
7503 // duplicate dedup key, cycle-detector adjacency-map seed,
7504 // self-loop gate) the 4a32abf lift already routed through
7505 // the accessor and the peer 54bf2f3 caixa-mesh emit-side
7506 // per-`programs[]` entry-`name:` `String`-carry converge.
7507 // Prior to this converge the `MembroCaixaEmpty` refusal
7508 // arm was the solitary consumer bypassing the typed
7509 // dispatch — the same-loop iteration's very next call
7510 // `validate_membro_caixa(m.nome())` already routed through
7511 // the accessor, so an author landing an empty-`:caixa`
7512 // entry hit the accessor on the shape-gate line but
7513 // bypassed it on the emptiness line one line above. A
7514 // future extension of the `:membros :caixa` axis to a
7515 // richer author surface (a per-cluster alias table pinned
7516 // through a future `:placement`-scoped slot, a namespace-
7517 // qualified rewrite the M4 CR materializer applies per-CR,
7518 // a per-member overlay from the future `:membros
7519 // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
7520 // that lands on the accessor would silently disagree
7521 // between the emptiness gate and every peer consumer —
7522 // an author-declared `:caixa "checkout"` value the
7523 // accessor rewrote to `""` under a future alias arm would
7524 // pass the raw `.is_empty()` gate here while the peer
7525 // `validate_membro_caixa(m.nome())` call one line below
7526 // (and every downstream emit-side consumer routing through
7527 // the accessor) tripped on the empty-value shape far from
7528 // this diagnostic. Pinned by the drift-detection test
7529 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
7530 // below.
7531 if m.nome().is_empty() {
7532 return Err(AplicacaoError::MembroCaixaEmpty);
7533 }
7534 // Every emitted cluster artifact's `metadata.name` derives
7535 // from a `:membros :caixa` value verbatim — the rendered
7536 // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
7537 // the [`crate::LABEL_PROGRAM`] label value on every CNP
7538 // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
7539 // 272), the composed `CiliumNetworkPolicy` `metadata.name`
7540 // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
7541 // `metadata.name` when the member is the `:entrada :para`
7542 // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
7543 // schema enforces the DNS-1123 label rule on admission;
7544 // a structurally invalid member name (`"Cart"`, `"my_cart"`,
7545 // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
7546 // mistaken-identity slug) silently passes the prior empty-/
7547 // duplicate-only gate and the failure surfaces at `kubectl
7548 // apply` time as a `metadata.name: Invalid value` rejection,
7549 // far from the source caixa.lisp, with no field naming the
7550 // offending `:membros` entry. Lifting the gate to caixa-build
7551 // time mirrors the `:entrada :host` value-shape trajectory
7552 // (c7d05ec) on the peer axis — every author surface that
7553 // emits a K8s name now matches the apiserver's accepted set
7554 // at validate time.
7555 validate_membro_caixa(m.nome())?;
7556 // The author surface for `:versao` is the same Cargo-shaped
7557 // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
7558 // `"*"`) every `:deps` entry carries — and the lacre pipeline
7559 // resolves both axes through the same
7560 // [`crate::version::parse_requirement`] entry-point. The
7561 // shared [`crate::render::require_valid_versao_requirement`]
7562 // helper brackets the empty-first + parse cascade both peer
7563 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
7564 // [`crate::SupervisorSpec::validate`] on `:children :versao`)
7565 // route through, so drift between the three axes' accepted
7566 // requirement sets is structurally impossible and the parse-
7567 // side no-op the empty-first arm closes (semver's empty
7568 // parse yields an implicit `*`) lives in exactly one
7569 // predicate.
7570 crate::render::require_valid_versao_requirement(
7571 m.versao_requirement(),
7572 || AplicacaoError::MembroVersaoEmpty {
7573 caixa: m.nome().to_string(),
7574 },
7575 |reason| AplicacaoError::MembroVersaoInvalid {
7576 caixa: m.nome().to_string(),
7577 versao: m.versao_requirement().to_string(),
7578 reason,
7579 },
7580 )?;
7581 crate::render::insert_first_seen(&mut seen, m.nome(), || {
7582 AplicacaoError::MembroDuplicate {
7583 caixa: m.nome().to_string(),
7584 }
7585 })?;
7586 }
7587 Ok(())
7588 }
7589
7590 /// Reject `:placement` values that are operationally meaningless or
7591 /// internally contradictory. Each strategy variant has the same
7592 /// invariants on `:clusters` (non-empty list, non-empty unique
7593 /// entries) — the §III.1 author surface is uniform on this axis,
7594 /// even though the *meaning* of the list differs by strategy
7595 /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
7596 /// shard pool).
7597 ///
7598 /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
7599 /// are the same authoring footgun closed for `:politicas` zero
7600 /// values and `:entrada` empty paths: the field is *declared* but
7601 /// carries no meaning, so downstream renderers either skip it
7602 /// silently (cluster-fanout drops the empty entry, no diagnostic)
7603 /// or apply it literally and fail at admission time. Lifting both
7604 /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
7605 /// violation is a build error" promise.
7606 ///
7607 /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
7608 /// is required exactly when `:estrategia Sharded` (hash-keyed
7609 /// distribution, Akka cluster-sharding convention, §II.4) and
7610 /// refused on `:estrategia Replicated`/`SingleNode` (where no
7611 /// hash-keyed routing axis consumes it). The partition closes the
7612 /// "I think I configured sharding" footgun where an author writes
7613 /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
7614 /// the typed slot's value silently vanishes at the renderer layer
7615 /// — every validated `Placement` past this call satisfies
7616 /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
7617 fn validate_placement(&self) -> Result<(), AplicacaoError> {
7618 // Every strategy needs at least one named cluster: `Replicated`
7619 // and `SingleNode` use the list as hosting/takeover candidates
7620 // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
7621 // §II.1), while `Sharded` uses it as the shard pool
7622 // (Akka cluster-sharding convention — §II.4). An empty list is
7623 // meaningless under any of the three.
7624 //
7625 // Route the paired pre-flight `.is_empty()` refusal probe and
7626 // the per-cluster validate loop's traversal head through the
7627 // lifted [`Placement::clusters`] slice-return accessor rather
7628 // than the raw `self.placement.clusters` field access — the
7629 // two production consumers of the per-`:placement` cluster-
7630 // pool `Vec`-carry now key off exactly one typed dispatch on
7631 // the substrate primitive, so any future rebrand on the axis
7632 // (a per-tenant cluster-pool overlay the operator pins through
7633 // a future `:placement :clusters-overrides` slot, a per-
7634 // Aplicacao dynamic cluster-pool derivation the future M5
7635 // adaptive-placement engine computes from `:affinity` weights)
7636 // migrates as a single caixa-core edit rather than a
7637 // coordinated rewrite of the paired arms — sibling of the
7638 // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
7639 // arm migration on the per-`:supervisor` static-child-list
7640 // `Vec`-carry axis.
7641 //
7642 // Route the per-`:placement` outer-composite reference read
7643 // through the lifted [`AplicacaoSpec::placement`] outer accessor
7644 // rather than the raw `&self.placement` field access — the
7645 // per-axis bracket-dispatch fan-out below (`p.clusters()`,
7646 // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
7647 // axis-level lifted accessor family) now routes through the
7648 // substrate-primitive typed dispatch at the outer composition
7649 // altitude, the same shape the peer caixa-mesh
7650 // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
7651 // and the sibling `feira app graph` per-Aplicacao print line
7652 // now key off after this accessor lift.
7653 let p = self.placement();
7654 if p.clusters().is_empty() {
7655 return Err(AplicacaoError::PlacementWithoutClusters {
7656 estrategia: p.estrategia(),
7657 });
7658 }
7659 let mut seen = std::collections::HashSet::new();
7660 for c in p.clusters() {
7661 // Per-entry value-shape gate: the cluster name lands in
7662 // every K8s context / `lareira-fleet-programs` aggregator
7663 // filter / future M4 CR materializer's per-cluster axis
7664 // a validated `:clusters` entry passes through, each
7665 // enforcing the DNS-1123 label rule on admission. Same
7666 // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
7667 // on the peer name axis — both axes' validated values
7668 // are guaranteed-accepted by the apiserver without
7669 // re-validation at any downstream renderer or admission
7670 // layer.
7671 validate_placement_cluster(c)?;
7672 crate::render::insert_first_seen(&mut seen, c.as_str(), || {
7673 AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
7674 })?;
7675 }
7676 // Route the per-`:placement :affinity` per-hint value-shape
7677 // gate through the typed [`Placement::affinity`] accessor rather
7678 // than the raw `&self.placement.affinity` field access — the
7679 // sole open-coded field-access site on the per-`:placement`
7680 // M3-Adaptive-compression-hint axis the accessor lift now owns.
7681 // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
7682 // the accessor's `Option<&str>` return type;
7683 // [`validate_placement_affinity`]'s `&str` parameter accepts
7684 // the narrower borrow without a re-allocation, so the routing
7685 // change is byte-for-byte in the pass arm and remains
7686 // byte-for-byte in every failure diagnostic
7687 // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
7688 // String` field is populated inside
7689 // [`validate_placement_affinity`] via the peer `.to_string()`
7690 // path on the same borrowed slice). Peer of the sibling
7691 // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
7692 // routing through [`Placement::shard_key`] at the caixa-core
7693 // site above — extends the "read `:placement` optional-scalars
7694 // through the typed accessor" discipline to the second
7695 // `Option<String>`-shape slot on the M3 mesh-slot family.
7696 //
7697 // Per-hint value-shape gate: the `:affinity` value lands
7698 // verbatim in the M3 Adaptive compression overlay
7699 // (caixa-mesh's `placement.affinity` emission) and every
7700 // future M4 placement-engine routing axis keying off the
7701 // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7702 // selector — each enforces the DNS-1123 label rule on
7703 // admission. Same typed-shape trajectory as `:placement
7704 // :clusters` (6c8c00b) on the sibling slot and the four
7705 // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7706 // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7707 // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7708 // on the Aplicacao surface to land on the canonical
7709 // [`crate::render::is_dns_1123_label`] floor.
7710 if let Some(a) = p.affinity() {
7711 validate_placement_affinity(a)?;
7712 }
7713 match p.estrategia() {
7714 // Route the `Sharded`-arm shape-gate cascade through the
7715 // typed [`Placement::shard_key`] accessor rather than the
7716 // raw `&self.placement.shard_key` field access — one of the
7717 // two open-coded field-access sites on the per-`:placement`
7718 // Akka-cluster-sharding-key axis the accessor lift now
7719 // owns. The `Some(k)`-bound `k` narrows from `&String` to
7720 // `&str` under the accessor's `Option<&str>` return type;
7721 // `str::is_empty` and [`validate_placement_shard_key`]'s
7722 // `&str` parameter both accept the narrower borrow without
7723 // a re-allocation.
7724 PlacementStrategy::Sharded => match p.shard_key() {
7725 None => return Err(AplicacaoError::ShardedWithoutKey),
7726 Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7727 // Per-axis value-shape gate on the Akka-cluster-sharding
7728 // `:shard-key` extractor expression. The shape gate runs
7729 // after the more self-locating `ShardedKeyEmpty` arm so
7730 // a `:shard-key ""` surfaces the narrower empty
7731 // diagnostic first; every non-empty `:shard-key` past
7732 // this call is guaranteed to be a printable-ASCII
7733 // single-token reference the future M4 Akka-style
7734 // cluster-sharding reconciler can hash without
7735 // re-validating at the runtime layer. Mirrors the
7736 // payload-axis shape gates on the peer `:contratos`
7737 // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7738 // 63e18a0 / c4213a4) — each lifts the runtime parser's
7739 // intersection-floor to a caixa-build-time gate.
7740 Some(k) => validate_placement_shard_key(k)?,
7741 },
7742 // `:shard-key` is the Akka-cluster-sharding axis
7743 // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7744 // across the cluster pool. `Replicated` (active-active across
7745 // every named cluster) and `SingleNode` (Erlang/OTP
7746 // distributed-app takeover/failover, §II.1) have no hash-keyed
7747 // routing axis to consume the slot; downstream renderers
7748 // (caixa-mesh's `placement.shardKey` overlay at
7749 // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7750 // sharding reconciler) ignore `:shard-key` outside the
7751 // `Sharded` arm by construction. Until this gate landed an
7752 // author who wrote `:placement (:estrategia Replicated
7753 // :shard-key "tenantId")` (an off-by-one strategy typo, a
7754 // copy-paste from a Sharded sibling caixa, the "I think I
7755 // configured sharding" footgun) silently passed validate and
7756 // the typed slot's value vanished at the renderer layer with
7757 // no diagnostic — the canonical "declared-but-inert" footgun
7758 // the empty-:affinity / empty-shard-key / zero-:politicas /
7759 // empty-:contratos-target gates already close on every other
7760 // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7761 // Lifting the rejection to a build-time gate closes the
7762 // Sharded ↔ non-Sharded partition over the typed
7763 // `:placement` slot: every validated `Placement` past this
7764 // call has `shard_key.is_some()` iff `estrategia ==
7765 // Sharded`, structurally — the future Akka reconciler can
7766 // reach for `placement.shard_key` knowing it's `Some` exactly
7767 // when the strategy consumes it, without re-deriving the
7768 // partition from inline strategy probes.
7769 PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7770 // Route the non-`Sharded`-arm declared-but-inert refusal
7771 // through the typed [`Placement::shard_key`] accessor —
7772 // the second of the two open-coded field-access sites the
7773 // accessor lift now owns. The `Some(k)`-bound `k` narrows
7774 // from `&String` to `&str`; the `AplicacaoError::
7775 // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7776 // materializes the owned `String` via `k.to_string()`
7777 // (peer to the sibling per-Membro `String`-carry sites
7778 // 4127bb6 routed through `m.nome().to_string()` /
7779 // `m.versao_requirement().to_string()`), so the whole
7780 // `Sharded` ↔ non-`Sharded` partition on the
7781 // `:shard-key` axis now flows through the same typed
7782 // dispatch as the sibling `Sharded`-arm shape gate.
7783 if let Some(k) = p.shard_key() {
7784 return Err(AplicacaoError::ShardKeyOnNonSharded {
7785 estrategia: p.estrategia(),
7786 shard_key: k.to_string(),
7787 });
7788 }
7789 }
7790 }
7791 Ok(())
7792 }
7793
7794 /// Reject `:politicas` values that are operationally meaningless.
7795 /// Each axis is optional — omitting it expresses "no policy on this
7796 /// axis". Carrying a *zero* value for a declared axis is the bug
7797 /// this function rejects: zero is either
7798 ///
7799 /// - re-interpreted as "infinite" by downstream proxies (Envoy's
7800 /// `RouteAction.timeout = 0s` disables the timeout entirely),
7801 /// directly contradicting MESH-COMPOSITION §V CSE invariant
7802 /// "every Aplicacao declares :politicas :timeout (no infinite
7803 /// blocking)", or
7804 /// - a renderer footgun (a 0-failure circuit breaker trips on the
7805 /// first call; a 0-rate rate-limit denies every request).
7806 ///
7807 /// Lifting these "0 means the opposite of what you think" idioms to
7808 /// the typed Aplicacao surface as build errors mirrors the §III.3
7809 /// promise that contract drift, capability leaks, and cycles are all
7810 /// build errors — not runtime surprises.
7811 fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7812 // Route the per-`:politicas` composite-reference read through
7813 // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7814 // than the raw `&self.politicas` field access — the per-axis
7815 // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7816 // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7817 // the substrate-primitive typed dispatch at the outer
7818 // composition altitude AND at every per-axis altitude, matching
7819 // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7820 // timeout/retry-overlay emitters that already key off the same
7821 // per-axis accessor family. The four-axis fan-out is now
7822 // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7823 // `p.retries` field-access sites (co-resident with the peer
7824 // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7825 // b0e741a / 21a6c3b already lifted) now route through
7826 // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7827 // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7828 // access axis on the M3 mesh-slot family.
7829 let p = self.politicas();
7830 if let Some(t) = p.timeout() {
7831 // Zero-floor + integer-millisecond canonical-form +
7832 // upper-cap bracket on the typed `:timeout` axis. See
7833 // [`crate::render::require_positive_canonical_bounded_duration`]
7834 // for the full three-arm ordering discipline (zero-floor
7835 // strictly precedes the canonical-form arm so
7836 // `Duration::ZERO` surfaces the self-locating
7837 // `PolicyTimeoutZero` diagnostic naming the omit-axis
7838 // remediation; canonical-form strictly precedes the cap
7839 // arm so a sub-millisecond above-cap `Duration` surfaces
7840 // the more fundamental round-trip-shape diagnostic first)
7841 // and the four peer typed-`Duration` sites that now share
7842 // this canonical bracket. Every validated value lies in
7843 // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7844 // granularity — the same top-and-bottom-edge discipline
7845 // [`POLICY_RETRIES_MAX`] and
7846 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7847 // capped-`u32` `:politicas` axes.
7848 crate::render::require_positive_canonical_bounded_duration(
7849 t,
7850 POLICY_TIMEOUT_MAX,
7851 || AplicacaoError::PolicyTimeoutZero,
7852 |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7853 |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7854 )?;
7855 }
7856 if let Some(r) = p.retries() {
7857 // Zero-floor + upper-cap bracket on the typed `:retries`
7858 // axis. See [`crate::render::require_positive_bounded_u32`]
7859 // for the ordering discipline (zero-floor arm strictly
7860 // precedes cap arm so `Some(0)` surfaces the self-locating
7861 // `PolicyRetriesZero` diagnostic with its omit-axis
7862 // remediation directly named, not the misleading
7863 // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7864 // this bracket landed the top edge ran all the way to
7865 // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7866 // Some(100_000), .. }` (or the equivalent author-surface
7867 // `(:retries 100000)` / `(:retries 4294967295)` typo
7868 // landing in the slot) silently passed validate. The
7869 // runtime substrate consuming the value (Envoy's
7870 // `retry_policy.num_retries`, the future
7871 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7872 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7873 // policy into a thundering-herd amplification vector —
7874 // the caller's one request fans out to `retries`
7875 // server-side calls per edge per traversal, multiplying
7876 // load by `(retries+1)^depth` across the
7877 // synchronous-`:contratos` subgraph at the precise moment
7878 // the substrate is already failing (transient failure is
7879 // the trigger), exactly the failure mode AWS App Mesh's
7880 // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7881 // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7882 // the sibling capped-`u32` `:politicas` axes
7883 // (`max_failures`, `rate_limit.rate`) and the peer capped-
7884 // `u32` axes in `:supervisor :max-restarts` +
7885 // `:limits :cpu`; all five now route through the same
7886 // canonical bracket helper.
7887 crate::render::require_positive_bounded_u32(
7888 r,
7889 POLICY_RETRIES_MAX,
7890 || AplicacaoError::PolicyRetriesZero,
7891 |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7892 )?;
7893 }
7894 if let Some(cb) = p.circuit_breaker() {
7895 // Zero-floor + upper-cap bracket on the typed
7896 // `:max-failures` axis. See
7897 // [`crate::render::require_positive_bounded_u32`] for the
7898 // ordering discipline (zero-floor arm strictly precedes
7899 // cap arm so `max_failures == 0` surfaces the
7900 // self-locating `PolicyBreakerZeroFailures` diagnostic
7901 // with its omit-axis remediation directly named, not the
7902 // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7903 // false` cap-arm miss). Until this bracket landed the top
7904 // edge ran all the way to `u32::MAX` and a struct-literal
7905 // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7906 // equivalent author-surface `(:max-failures 100000)` /
7907 // `(:max-failures 4294967295)` typo landing in the slot)
7908 // silently passed validate. The runtime substrate
7909 // consuming the value (Envoy's
7910 // `outlier_detection.consecutive_5xx`, the future
7911 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7912 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7913 // breaker policy into a no-op — the trip threshold is
7914 // structurally so high that no realistic
7915 // failures-per-`:window` traffic shape can reach it, the
7916 // breaker never trips, and every typed-slot consumer
7917 // emits an Envoy / Cilium L7 overlay carrying a
7918 // protection that is structurally never enforced. The
7919 // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7920 // peer with `retries` and `rate_limit.rate` on the same
7921 // helper.
7922 crate::render::require_positive_bounded_u32(
7923 cb.max_failures(),
7924 POLICY_BREAKER_MAX_FAILURES_MAX,
7925 || AplicacaoError::PolicyBreakerZeroFailures,
7926 |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7927 )?;
7928 // Zero-floor + integer-millisecond canonical-form +
7929 // upper-cap bracket on the typed `:window` axis. See
7930 // [`crate::render::require_positive_canonical_bounded_duration`]
7931 // for the full three-arm ordering discipline (peer to the
7932 // `:timeout` site immediately above); every validated
7933 // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7934 // (1ms..=1h), integer-millisecond granularity — the same
7935 // top-and-bottom-edge discipline
7936 // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7937 // duration-typed `:politicas :timeout` axis.
7938 crate::render::require_positive_canonical_bounded_duration(
7939 cb.window(),
7940 POLICY_BREAKER_WINDOW_MAX,
7941 || AplicacaoError::PolicyBreakerZeroWindow,
7942 |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7943 |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7944 )?;
7945 }
7946 if let Some(rl) = p.rate_limit() {
7947 // Zero-floor + upper-cap bracket on the typed
7948 // `:rate-limit` rate axis. See
7949 // [`crate::render::require_positive_bounded_u32`] for the
7950 // ordering discipline (zero-floor arm strictly precedes
7951 // cap arm so `rl.rate == 0` surfaces the self-locating
7952 // `PolicyRateLimitZero` diagnostic with its omit-axis
7953 // remediation directly named, not the misleading
7954 // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7955 // Until this bracket landed the top edge ran all the way
7956 // to `u32::MAX` and a struct-literal
7957 // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7958 // author-surface `(:rate-limit "4294967295/s")` /
7959 // `(:rate-limit "100000000/m")` typo landing in the slot)
7960 // silently passed validate. The runtime substrate
7961 // consuming the value (Envoy's
7962 // `local_rate_limit.token_bucket.max_tokens`, the future
7963 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7964 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7965 // rate-limit policy into a no-op limiter: the bucket
7966 // capacity is structurally so high that no realistic
7967 // per-edge traffic shape can drain it, the limiter never
7968 // trips, and every typed-slot consumer emits a "rate
7969 // declared" L7 overlay carrying enforcement that is
7970 // structurally never reached — the canonical
7971 // declared-but-inert footgun the sibling
7972 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7973 // the peer no-op-breaker shape. The bracket set is
7974 // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7975 // `max_failures` on the same helper. The rate bracket
7976 // strictly precedes the window-canonical gate so a
7977 // structurally absurd rate magnitude surfaces the more
7978 // fundamental amplification-shape diagnostic before the
7979 // narrower codec-round-trip-shape diagnostic on `:window`.
7980 crate::render::require_positive_bounded_u32(
7981 rl.rate(),
7982 POLICY_RATE_LIMIT_MAX,
7983 || AplicacaoError::PolicyRateLimitZero,
7984 |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7985 )?;
7986 // The `:rate-limit` author surface is the canonical
7987 // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7988 // accepts exactly the three-unit set (1s/60s/3600s) the
7989 // [`rate_limit_codec::render`] formatter emits the canonical
7990 // unit suffix for. A `RateLimit` whose `:window` is anything
7991 // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7992 // programmatically (struct literals in Rust + the typed
7993 // `Duration` field) but renders to a `<n>/<k>s` fragment
7994 // (the codec's fall-through) the parser then rejects on
7995 // round-trip — silently breaking the THEORY.md §V.2.7
7996 // render-determinism contract for any consumer that
7997 // serializes-then-deserializes the typed slot. Lifting the
7998 // canonical-window invariant to a build-time gate at
7999 // `validate_politicas` makes the codec's round-trip property
8000 // a structural property of the validated typed value:
8001 // every `RateLimit` past `AplicacaoSpec::validate` has a
8002 // window the codec round-trips losslessly, so the next
8003 // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
8004 // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
8005 // §III.2 #3) reaches for `rate_limit.window` knowing the
8006 // value is in the codec's accepted set without re-validating
8007 // at the renderer layer. Same trajectory as c4213a4 (typed
8008 // WitContract endpoint/subject/slot value-shape gates) and
8009 // the b0c8389 :behavior + :upgrade-from script-path lifts:
8010 // the typed slot's valid set matches its codec's accepted
8011 // set, structurally.
8012 // Route the canonical-window shape-gate through the substrate
8013 // primitive [`RateLimit::canonical_unit`] rather than the free
8014 // module-private [`is_canonical_rate_limit_window`] predicate:
8015 // both projections resolve `Duration → Option<RateLimitUnit>`
8016 // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
8017 // arm on the closed-set typed enum), but the accessor is the
8018 // typed method every downstream consumer of the validated slot
8019 // ([`rate_limit_codec::render`]'s canonical arm above, the
8020 // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8021 // per-`:politicas :rate-limit` admission webhook, the future
8022 // per-`:contratos`-edge rate-limit-override overlay
8023 // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
8024 // production consumers of the canonical-unit axis (the codec
8025 // render and this validate gate) now key off exactly one typed
8026 // dispatch on the substrate primitive, so any future extension
8027 // to `canonical_unit` (a per-cluster canonical-window overlay
8028 // the operator pins through a future `:contratos :rate-limit
8029 // -unit-overrides` slot, a per-tenant unit-alias table the M4
8030 // CR materializer resolves per-CR) reaches both consumers by
8031 // construction rather than a coordinated rewrite of every
8032 // free-helper call site.
8033 if rl.canonical_unit().is_none() {
8034 return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
8035 window: rl.window(),
8036 });
8037 }
8038 }
8039 Ok(())
8040 }
8041
8042 /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
8043 /// A synchronous edge is any contract whose typed [`WitTarget`] is
8044 /// `Http`, `Store`, or `Capability` — the caller blocks on the
8045 /// callee, so a cycle would deadlock at runtime. Pub-sub edges
8046 /// (`WitTarget::PubSub`) are skipped: an event publisher does not
8047 /// block on its subscribers, so they can never close a sync loop.
8048 ///
8049 /// Iterative DFS with three-coloring; the reported cycle is the
8050 /// path of caixa names traversed from the back-edge target around
8051 /// to itself, in declaration order. Adjacency lists and DFS roots
8052 /// are visited in `BTreeMap` key order so the diagnostic is
8053 /// deterministic across runs.
8054 fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
8055 use std::collections::{BTreeMap, BTreeSet};
8056
8057 #[derive(Clone, Copy, PartialEq, Eq)]
8058 enum Mark {
8059 White,
8060 Gray,
8061 Black,
8062 }
8063
8064 let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
8065 for m in self.membros() {
8066 adj.entry(m.nome()).or_default();
8067 }
8068 for c in self.contratos() {
8069 // target() was already called by validate(); re-running here
8070 // keeps detect_sync_cycles self-contained for callers that
8071 // reuse it (M4 per-edge policy resolver) without revalidating.
8072 //
8073 // The pub-sub-arm check routes through the lifted
8074 // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
8075 // arm-discriminator predicate rather than a raw `matches!(…,
8076 // WitTarget::PubSub { .. })` on the variant so a future
8077 // rebrand on the axis (an M4 per-edge WIT registry split of
8078 // [`WitTarget::PubSub`] into shape-specific peers, a
8079 // per-consumer rename that the accept-set already carries)
8080 // reaches this call site through the derive rather than a
8081 // scattered per-arm `matches!` rewrite — same
8082 // `IsVariant`-derived-arm-discriminator discipline the
8083 // peer closed-set typed enums ([`crate::CaixaKind`] via
8084 // f5bba80, [`PlacementStrategy`] via 766ec63,
8085 // [`crate::supervisor::RestartStrategy`] +
8086 // [`crate::supervisor::RestartPolicy`],
8087 // [`crate::upgrade::UpgradeInstruction`] via 915a934)
8088 // already route through on the substrate's other typed-enum
8089 // arm-discriminator axes.
8090 if c.target()?.is_pubsub() {
8091 continue;
8092 }
8093 adj.entry(c.source()).or_default().insert(c.destination());
8094 }
8095
8096 let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
8097 let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
8098
8099 // Stable DFS root order — BTreeMap iteration is sorted by key.
8100 let roots: Vec<&str> = adj.keys().copied().collect();
8101
8102 // Frame: (node, sorted-neighbours snapshot, next-edge index).
8103 for root in roots {
8104 if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
8105 continue;
8106 }
8107 let root_neighbors: Vec<&str> = adj
8108 .get(root)
8109 .map(|s| s.iter().copied().collect())
8110 .unwrap_or_default();
8111 let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
8112 color.insert(root, Mark::Gray);
8113
8114 loop {
8115 // Read+advance the top frame in one borrow scope so we
8116 // can later mutate the stack (push/pop) without holding
8117 // a borrow across.
8118 let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
8119 let node = top.0;
8120 if top.2 >= top.1.len() {
8121 (node, None)
8122 } else {
8123 let nxt = top.1[top.2];
8124 top.2 += 1;
8125 (node, Some(nxt))
8126 }
8127 });
8128 let Some((node, nxt_opt)) = step else { break };
8129 let Some(nxt) = nxt_opt else {
8130 color.insert(node, Mark::Black);
8131 stack.pop();
8132 continue;
8133 };
8134 let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8135 match nxt_color {
8136 Mark::Gray => {
8137 // Reconstruct the cycle from `node` back through
8138 // the parent chain to `nxt`, then close.
8139 let mut cycle = Vec::new();
8140 let mut cur = node;
8141 cycle.push(cur.to_string());
8142 while cur != nxt {
8143 match parent.get(cur).copied() {
8144 Some(p) => {
8145 cur = p;
8146 cycle.push(cur.to_string());
8147 }
8148 None => break,
8149 }
8150 }
8151 cycle.reverse();
8152 cycle.push(nxt.to_string());
8153 return Err(AplicacaoError::ContratoCycle { cycle });
8154 }
8155 Mark::White => {
8156 parent.insert(nxt, node);
8157 color.insert(nxt, Mark::Gray);
8158 let nxt_neighbors: Vec<&str> = adj
8159 .get(nxt)
8160 .map(|s| s.iter().copied().collect())
8161 .unwrap_or_default();
8162 stack.push((nxt, nxt_neighbors, 0));
8163 }
8164 Mark::Black => {}
8165 }
8166 }
8167 }
8168 Ok(())
8169 }
8170
8171 /// Substrate-canonical destination-facing TCP port every emitted
8172 /// per-Aplicacao artifact must key `destination`-shaped port axes
8173 /// off. Returns the typed `:entrada :port` scalar when this
8174 /// Aplicacao's `:entrada` block names `destination` under its
8175 /// `:para` axis (the destination Servico *is* the ingress apex, so
8176 /// the substrate honors the author-declared listener port
8177 /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8178 /// fallback otherwise (every non-apex destination — the internal
8179 /// mesh Servicos `:contratos` reach across, the future per-edge
8180 /// policy resolver's per-destination probe targets, the
8181 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8182 /// L4 port resolver — reads the same substrate-canonical port floor
8183 /// by construction).
8184 ///
8185 /// Prior to this lift the "if :entrada matches this destination use
8186 /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8187 /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8188 /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8189 /// prior to this lift), with no typed method on the substrate primitive
8190 /// that named the rule. A future per-destination port axis addition
8191 /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8192 /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8193 /// per-Servico listener ports land, a per-cluster override the operator
8194 /// pins through a future `:placement :default-port` slot — would have
8195 /// to be threaded through every renderer's inline cascade in lockstep
8196 /// or one consumer would silently disagree on which port a given
8197 /// destination Servico's ingress lands at. Lifting the rule to a
8198 /// typed method on the substrate primitive means the M4 CR
8199 /// materializer, the future per-edge policy resolver, and every
8200 /// downstream test-fixture navigator reach for exactly one typed
8201 /// dispatch — the resolver's accept-set moves as a unit on any
8202 /// future axis addition.
8203 ///
8204 /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8205 /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8206 /// the typed primitive, thin projections at each consumer"
8207 /// discipline lifts on the sibling `:contratos` payload / `:politicas
8208 /// :rate-limit` unit-suffix axes; extends the discipline onto the
8209 /// destination-facing port-resolution axis every per-Aplicacao
8210 /// L4-fallback renderer consumes.
8211 #[must_use]
8212 pub fn port_for_destination(&self, destination: &str) -> u16 {
8213 // Route the per-`:entrada` composite-reference read through
8214 // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8215 // the raw `self.entrada.as_ref()` field access — the
8216 // per-destination L4-port fallback resolver's composite-
8217 // projection seed is now the canonical read-side surface
8218 // every per-Aplicacao entrada consumer routes through, peer
8219 // of the sibling `validate` per-`:entrada` shape-and-
8220 // membership gate migration on the same outer-composite
8221 // axis.
8222 // Route the per-`:entrada` apex-destination membership probe
8223 // through the lifted [`Entrada::destination`] accessor rather
8224 // than the raw `e.para == destination` field access — the last
8225 // un-lifted `.para` production-code read site on the per-
8226 // `:entrada` `:para` axis, sibling to the four caixa-core
8227 // consumer sites the peer 15ddd8c converge already routed
8228 // through the accessor (the three
8229 // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8230 // membership gate sites: the `validate_entrada_para` DNS-1123
8231 // shape gate, the per-`:membros` membership lookup, and the
8232 // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8233 // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8234 // `entrada.para`-projection converge at
8235 // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8236 // route-name projection site). Prior to this converge the
8237 // `port_for_destination` resolver was the solitary consumer
8238 // bypassing the typed dispatch on the `.para` axis — the two
8239 // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8240 // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8241 // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8242 // reach through the same accessor family compose with this
8243 // resolver at the emit boundary via the apex-identity
8244 // invariant `spec.port_for_destination(entrada.destination())
8245 // == entrada.port` the sibling
8246 // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8247 // pin pins across four permutations. A future extension of the
8248 // `:entrada :para` axis to a richer author surface (a per-
8249 // cluster alias overlay the operator pins through a future
8250 // `:placement`-scoped slot, a namespace-qualified rewrite the
8251 // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8252 // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8253 // §III.2 acknowledges) that lands on the accessor would silently
8254 // disagree between this resolver and the two `caixa-mesh` emit
8255 // sites — an author-declared `:para "cart"` value the accessor
8256 // rewrote to `"cart-v2"` under a future canary arm would leave
8257 // the resolver's membership arm falling through to
8258 // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8259 // `.para`) while the peer emit-site consumers landed on the
8260 // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8261 // silently disagreed on which destination port a given typed
8262 // `:entrada` resolves to at cluster-apply time. Pinned by the
8263 // drift-detection test
8264 // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8265 // below.
8266 self.entrada()
8267 .filter(|e| e.destination() == destination)
8268 .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8269 }
8270}
8271
8272/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8273/// entry may name the Aplicacao's own `:nome`.
8274///
8275/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8276/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8277/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8278/// Servicos that compose the app; an Aplicacao is never its own constituent),
8279/// and the lacre pipeline's closure-resolution would otherwise be handed a
8280/// node that is its own parent: a one-node cycle it either rejects far from
8281/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8282/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8283/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8284/// label + lacre closure root), a member whose `:caixa` equals the
8285/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8286/// peer.
8287///
8288/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8289/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8290/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8291/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8292/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8293/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8294/// (the Aplicacao :membros set; the supervision-tree :children list was the
8295/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8296/// every validated Supervisor's children are distinct from its `:nome`,
8297/// every validated Aplicacao's membros are distinct from its `:nome`. The
8298/// transitive consequence is that `:entrada :para` and `:contratos`
8299/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8300/// name the Aplicacao itself, without re-deriving the partition.
8301pub fn validate_no_self_membership(
8302 membros: &[Membro],
8303 parent_nome: &str,
8304) -> Result<(), AplicacaoError> {
8305 for m in membros {
8306 if m.nome() == parent_nome {
8307 return Err(AplicacaoError::MembroIsSelfAplicacao {
8308 caixa: parent_nome.to_string(),
8309 });
8310 }
8311 }
8312 Ok(())
8313}
8314
8315#[derive(Debug, Error, PartialEq, Eq)]
8316pub enum AplicacaoError {
8317 #[error("Aplicacao must declare at least one :membros entry")]
8318 NoMembros,
8319 #[error(
8320 ":membros entry has empty :caixa (every member must name a Servico; \
8321 omit the entry instead of carrying an empty name)"
8322 )]
8323 MembroCaixaEmpty,
8324 #[error(
8325 ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8326 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8327 name / label value the member name lands in; use a lowercase \
8328 alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8329 )]
8330 MembroCaixaInvalid { caixa: String, reason: String },
8331 #[error(
8332 ":membros entry {caixa:?} has empty :versao (every member must pin a \
8333 semver constraint that resolves through the lacre pipeline)"
8334 )]
8335 MembroVersaoEmpty { caixa: String },
8336 #[error(
8337 ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8338 requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8339 `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8340 carries; the lacre pipeline resolves both through the same parser)"
8341 )]
8342 MembroVersaoInvalid {
8343 caixa: String,
8344 versao: String,
8345 reason: String,
8346 },
8347 #[error(
8348 ":membros entry {caixa:?} appears more than once (the graph node set \
8349 is a set, not a multiset; duplicate members produce duplicate \
8350 programs.yaml entries and ambiguous :contratos membership lookups)"
8351 )]
8352 MembroDuplicate { caixa: String },
8353 #[error(
8354 "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8355 never its own constituent Servico (the application graph is a DAG rooted \
8356 at the Aplicacao; :membros names the *other* caixas that compose the \
8357 app, not the app itself). Since every :nome is a globally-unique \
8358 substrate identity, a member naming the Aplicacao's own :nome is a \
8359 one-node lacre-closure recursion, not a coincidentally-named peer; \
8360 drop the self-referential :membros entry or rename it to the actual \
8361 constituent caixa."
8362 )]
8363 MembroIsSelfAplicacao { caixa: String },
8364 #[error(
8365 "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8366 caixa declared in :membros; omit the contract or fill the {slot} field with a \
8367 member name)"
8368 )]
8369 ContratoCaixaEmpty { slot: &'static str },
8370 #[error(
8371 "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8372 :contratos {slot} value names a member of :membros, which is itself a \
8373 DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8374 object the member name lands in — Service, Pod, identity-based Cilium \
8375 selector; use a lowercase alphanumeric + hyphen identifier like \
8376 `\"checkout\"` or `\"cart-v2\"`)"
8377 )]
8378 ContratoCaixaInvalid {
8379 slot: &'static str,
8380 caixa: String,
8381 reason: String,
8382 },
8383 #[error("contrato references caixa {caixa:?} not declared in :membros")]
8384 ContratoMemberMissing { caixa: String },
8385 #[error(
8386 "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8387 entry is an inter-Servico contract whose :de and :para must name distinct \
8388 :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8389 the contract, or point :para at the member it actually calls)"
8390 )]
8391 ContratoSelfLoop { caixa: String, wit: String },
8392 #[error("contrato {de:?} → {para:?} has empty :wit")]
8393 EmptyWit { de: String, para: String },
8394 #[error(
8395 "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8396 {reason} (the substrate dispatches `:wit` values on the canonical \
8397 lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8398 `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8399 demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8400 kebab-case identifier per segment)"
8401 )]
8402 ContratoWitInvalid {
8403 de: String,
8404 para: String,
8405 wit: String,
8406 reason: String,
8407 },
8408 #[error(
8409 ":entrada :para is empty (every :entrada must route to a caixa declared in \
8410 :membros; fill the :para field with a member name)"
8411 )]
8412 EntradaParaEmpty,
8413 #[error(
8414 ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8415 :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8416 label per the K8s apiserver's `metadata.name` rule on every object the \
8417 member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8418 Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8419 `\"checkout\"` or `\"cart-v2\"`)"
8420 )]
8421 EntradaParaInvalid { para: String, reason: String },
8422 #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8423 EntradaMemberMissing { para: String },
8424 #[error(":entrada must declare a non-empty :host")]
8425 EmptyEntradaHost,
8426 #[error(
8427 ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8428 (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8429 `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8430 like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8431 )]
8432 EntradaHostInvalid { host: String, reason: String },
8433 #[error(":entrada :port must be in 1..=65535, got 0")]
8434 EntradaPortZero,
8435 #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8436 EntradaPathEmpty,
8437 #[error(
8438 ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8439 )]
8440 EntradaPathNotAbsolute { path: String },
8441 #[error(
8442 ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8443 value: {reason} (the K8s apiserver enforces the same shape on \
8444 `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8445 single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8446 requires percent-encoding `%XX` for non-ASCII and whitespace)"
8447 )]
8448 EntradaPathInvalid { path: String, reason: String },
8449 #[error(":entrada :paths entry {path:?} appears more than once")]
8450 EntradaPathDuplicate { path: String },
8451 #[error(
8452 ":placement {estrategia} requires at least one :clusters entry \
8453 (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8454 )]
8455 PlacementWithoutClusters { estrategia: PlacementStrategy },
8456 #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8457 PlacementClusterEmpty,
8458 #[error(
8459 ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8460 (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8461 in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8462 future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8463 — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8464 identifier like `\"rio\"` or `\"mar-east\"`)"
8465 )]
8466 PlacementClusterInvalid { cluster: String, reason: String },
8467 #[error(":placement :clusters entry {cluster:?} appears more than once")]
8468 PlacementClusterDuplicate { cluster: String },
8469 #[error(
8470 ":placement :affinity must be non-empty when set (omit :affinity to express \
8471 `no placement hint`)"
8472 )]
8473 PlacementAffinityEmpty,
8474 #[error(
8475 ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8476 (placement hints land verbatim in the M3 Adaptive compression overlay's \
8477 `placement.affinity` field and in every future M4 placement-engine routing \
8478 axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8479 selector — both enforce the DNS-1123 label rule on admission; use a \
8480 lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8481 `\"low-latency\"`, or `\"anti-affinity\"`)"
8482 )]
8483 PlacementAffinityInvalid { affinity: String, reason: String },
8484 #[error(":placement Sharded requires :shard-key")]
8485 ShardedWithoutKey,
8486 #[error(
8487 ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8488 hashes every entity onto the same shard, defeating sharding entirely)"
8489 )]
8490 ShardedKeyEmpty,
8491 #[error(
8492 ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8493 entity-id extractor expression: {reason} (the future M4 Akka-style \
8494 cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8495 as a single-token property reference and hashes the extracted entity ID \
8496 to compute shard placement; use a printable-ASCII extractor expression \
8497 like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8498 `\"${{tenant}}\"`)"
8499 )]
8500 ShardKeyInvalid { shard_key: String, reason: String },
8501 #[error(
8502 ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8503 Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8504 convention); :estrategia Replicated runs every cluster active-active and \
8505 :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8506 distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8507 to :estrategia Sharded if hash-keyed routing is the intent"
8508 )]
8509 ShardKeyOnNonSharded {
8510 estrategia: PlacementStrategy,
8511 shard_key: String,
8512 },
8513 #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8514 ContratoMissingTarget {
8515 de: String,
8516 para: String,
8517 wit: String,
8518 expected: &'static str,
8519 },
8520 #[error(
8521 "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8522 expected `:{expected}` only"
8523 )]
8524 ContratoWrongTarget {
8525 de: String,
8526 para: String,
8527 wit: String,
8528 expected: &'static str,
8529 },
8530 #[error(
8531 "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8532 like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8533 that matches no traffic and silently drops every request)"
8534 )]
8535 ContratoEndpointEmpty { de: String, para: String },
8536 #[error(
8537 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8538 (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8539 :entrada :paths)"
8540 )]
8541 ContratoEndpointNotAbsolute {
8542 de: String,
8543 para: String,
8544 endpoint: String,
8545 },
8546 #[error(
8547 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8548 Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8549 emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8550 caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8551 shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8552 like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8553 and whitespace)"
8554 )]
8555 ContratoEndpointInvalid {
8556 de: String,
8557 para: String,
8558 endpoint: String,
8559 reason: String,
8560 },
8561 #[error(
8562 "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8563 subject is a no-op subscribe; omit :subject only if the WIT world is not \
8564 pub-sub-shaped)"
8565 )]
8566 ContratoSubjectEmpty { de: String, para: String },
8567 #[error(
8568 "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8569 NATS subject: {reason} (the NATS server's subject parser enforces the \
8570 same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8571 single-token and `>` multi-token wildcards — at publish/subscribe time; \
8572 use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8573 `\"orders.*.completed\"` — a malformed subject silently drops every \
8574 message at runtime far from the source caixa.lisp)"
8575 )]
8576 ContratoSubjectInvalid {
8577 de: String,
8578 para: String,
8579 subject: String,
8580 reason: String,
8581 },
8582 #[error(
8583 "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8584 addresses the bucket root, defeating the per-key isolation the slot exists \
8585 for; omit :slot only if the WIT world is not store-shaped)"
8586 )]
8587 ContratoSlotEmpty { de: String, para: String },
8588 #[error(
8589 "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8590 WASI keyvalue store slot template: {reason} (the substrate enforces \
8591 the printable-ASCII intersection-floor every kv backend admits — \
8592 use a single-token path / template expression like `\"checkout/$orderId\"`, \
8593 `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8594 percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8595 slot either gets rejected on write by strict backends or silently \
8596 corrupts the next read on permissive ones, far from the source caixa.lisp)"
8597 )]
8598 ContratoSlotInvalid {
8599 de: String,
8600 para: String,
8601 slot: String,
8602 reason: String,
8603 },
8604 #[error(
8605 "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
8606 or an event-sourced indirection (MESH-COMPOSITION §III.3)",
8607 cycle.join(" → ")
8608 )]
8609 ContratoCycle { cycle: Vec<String> },
8610 #[error(
8611 ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
8612 than once (the typed graph edges are a set, not a multiset; duplicate \
8613 contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
8614 values that K8s admission rejects far from the source caixa.lisp)"
8615 )]
8616 ContratoDuplicate {
8617 de: String,
8618 para: String,
8619 wit: String,
8620 target: String,
8621 },
8622 #[error(
8623 ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
8624 contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
8625 express `no per-call deadline on this axis`"
8626 )]
8627 PolicyTimeoutZero,
8628 #[error(
8629 ":politicas :retries must be > 0 when set; omit :retries to express \
8630 `no retries on transient failure`"
8631 )]
8632 PolicyRetriesZero,
8633 #[error(
8634 ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
8635 (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
8636 retry policy into a thundering-herd amplification vector on transient \
8637 failure (one caller request fans out to `(retries+1)^depth` server-side \
8638 calls across the synchronous-:contratos subgraph), exactly the failure \
8639 mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
8640 Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
8641 or omit :retries to disable retries entirely"
8642 )]
8643 PolicyRetriesExceedsCap { retries: u32 },
8644 #[error(
8645 ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
8646 breaker trips on the first call); omit :circuit-breaker to disable it"
8647 )]
8648 PolicyBreakerZeroFailures,
8649 #[error(
8650 ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
8651 mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
8652 above this cap turns the typed breaker policy into a no-op: the trip \
8653 threshold is structurally so high that no realistic failures-per-:window \
8654 traffic shape can reach it, so the breaker never trips and every typed-slot \
8655 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
8656 Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
8657 structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
8658 Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
8659 omit :circuit-breaker to disable the breaker entirely"
8660 )]
8661 PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
8662 #[error(
8663 ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
8664 tracks no failures); omit :circuit-breaker to disable it"
8665 )]
8666 PolicyBreakerZeroWindow,
8667 #[error(
8668 ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
8669 request); omit :rate-limit to disable rate limiting"
8670 )]
8671 PolicyRateLimitZero,
8672 #[error(
8673 ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
8674 (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
8675 rate-limit policy into a no-op limiter: the token-bucket capacity is \
8676 structurally so high that no realistic per-edge traffic shape can drain it, \
8677 so the limiter never trips and every typed-slot consumer (the future \
8678 CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8679 local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
8680 that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
8681 Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
8682 Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
8683 Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
8684 to disable rate limiting entirely"
8685 )]
8686 PolicyRateLimitExceedsCap { rate: u32 },
8687 #[error(
8688 ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
8689 the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
8690 rate-limit codec round-trips losslessly; got {window:?} which renders to a \
8691 non-round-trippable form (omit :rate-limit to disable, or pick one of the \
8692 three canonical windows)"
8693 )]
8694 PolicyRateLimitWindowNotCanonical { window: Duration },
8695 #[error(
8696 ":politicas :timeout must be an integer number of milliseconds — the canonical \
8697 authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8698 duration codec round-trips losslessly; got {timeout:?} which carries a \
8699 sub-millisecond residue that either truncates to a different `Duration` on \
8700 re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8701 to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8702 zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8703 (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8704 )]
8705 PolicyTimeoutNotCanonical { timeout: Duration },
8706 #[error(
8707 ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8708 (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8709 per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8710 overlays carry a deadline so long no realistic synchronous-:contratos \
8711 traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8712 CSE invariant degenerates to enforcement only at the per-Servico \
8713 `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8714 `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8715 (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8716 ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8717 maxes out at the same `3600s` ceiling) or omit :timeout to express \
8718 `no per-call deadline on this axis` (the synchronous-call deadline then \
8719 relies entirely on the per-Servico `:limits :wall-clock` axis)"
8720 )]
8721 PolicyTimeoutExceedsCap { timeout: Duration },
8722 #[error(
8723 ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8724 the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8725 the shared duration codec round-trips losslessly; got {window:?} which carries a \
8726 sub-millisecond residue that either truncates to a different `Duration` on \
8727 re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8728 Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8729 )]
8730 PolicyBreakerWindowNotCanonical { window: Duration },
8731 #[error(
8732 ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8733 (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8734 rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8735 is structurally so long that transient failures are never forgotten, the breaker \
8736 trips once and stays tripped for the lifetime of the component, and every typed-slot \
8737 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8738 outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8739 Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8740 default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8741 the breaker entirely"
8742 )]
8743 PolicyBreakerWindowExceedsCap { window: Duration },
8744}
8745
8746#[cfg(test)]
8747mod tests {
8748 use super::*;
8749
8750 fn membro(name: &str, ver: &str) -> Membro {
8751 Membro {
8752 caixa: name.into(),
8753 versao: ver.into(),
8754 }
8755 }
8756
8757 fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8758 WitContract {
8759 de: de.into(),
8760 para: para.into(),
8761 wit: "wasi:http/proxy".into(),
8762 endpoint: Some(ep.into()),
8763 subject: None,
8764 slot: None,
8765 }
8766 }
8767
8768 fn three_member_spec() -> AplicacaoSpec {
8769 AplicacaoSpec {
8770 membros: vec![
8771 membro("catalog", "^0.1"),
8772 membro("cart", "^0.1"),
8773 membro("payment", "^0.2"),
8774 ],
8775 contratos: vec![
8776 contract_http("cart", "catalog", "/products/:id"),
8777 contract_http("cart", "payment", "/charge"),
8778 ],
8779 politicas: MeshPolicy {
8780 timeout: Some(Duration::from_secs(30)),
8781 retries: Some(3),
8782 mtls_required: Some(true),
8783 ..Default::default()
8784 },
8785 placement: Placement {
8786 estrategia: PlacementStrategy::Replicated,
8787 clusters: vec!["rio".into(), "mar".into()],
8788 affinity: Some("data-locality".into()),
8789 shard_key: None,
8790 },
8791 entrada: Some(Entrada {
8792 host: "checkout.quero.cloud".into(),
8793 para: "cart".into(),
8794 paths: vec!["/api/cart".into(), "/api/products".into()],
8795 port: 8080,
8796 }),
8797 }
8798 }
8799
8800 #[test]
8801 fn happy_path_validates() {
8802 three_member_spec().validate().unwrap();
8803 }
8804
8805 #[test]
8806 fn rejects_empty_membros() {
8807 let mut s = three_member_spec();
8808 s.membros = vec![];
8809 assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8810 }
8811
8812 #[test]
8813 fn rejects_empty_membro_caixa() {
8814 // A `:caixa ""` entry has no name to render into programs.yaml
8815 // and no caixa.lisp to resolve at lacre time.
8816 let mut s = three_member_spec();
8817 s.membros[1].caixa = String::new();
8818 assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8819 }
8820
8821 #[test]
8822 fn rejects_empty_membro_versao() {
8823 // A `:versao ""` entry can't pin a semver constraint, so the
8824 // lacre pipeline fails far from the source.
8825 let mut s = three_member_spec();
8826 s.membros[2].versao = String::new();
8827 let err = s.validate().unwrap_err();
8828 assert!(
8829 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8830 "got {err:?}"
8831 );
8832 }
8833
8834 #[test]
8835 fn rejects_duplicate_membro_caixa() {
8836 // Two `:membros` entries with the same `:caixa` collapse to one
8837 // node in the membership HashSet, which masks `:contratos`
8838 // membership errors and produces duplicate programs.yaml entries.
8839 let mut s = three_member_spec();
8840 s.membros.push(membro("cart", "^0.2"));
8841 let err = s.validate().unwrap_err();
8842 assert!(
8843 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8844 "got {err:?}"
8845 );
8846 }
8847
8848 #[test]
8849 fn rejects_invalid_membro_versao_requirement() {
8850 // The fail-before-pass-after pin: a non-empty but malformed
8851 // semver requirement (`"^bad-version"`) silently passed
8852 // `validate()` on every pre-gate codebase because the prior
8853 // shape only refused the empty string. The parse failure
8854 // surfaced far downstream at lacre-resolve time with a
8855 // `semver::Error` that didn't name which `:membros` entry
8856 // carried the typo. The new gate moves the check to caixa-build
8857 // time at the source caixa.lisp.
8858 let mut s = three_member_spec();
8859 s.membros[2].versao = "^bad-version".into();
8860 let err = s.validate().unwrap_err();
8861 assert!(
8862 matches!(
8863 err,
8864 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8865 if caixa == "payment" && versao == "^bad-version"
8866 ),
8867 "got {err:?}"
8868 );
8869 }
8870
8871 #[test]
8872 fn rejects_membro_versao_with_double_caret_typo() {
8873 // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8874 // Cargo-shaped requirement on first glance but fails the parser
8875 // because semver doesn't accept stacked operators. Pin this
8876 // adjacent-shape footgun explicitly so a future relaxation that
8877 // accepts "looks-canonical-but-isn't" forms surfaces here.
8878 let mut s = three_member_spec();
8879 s.membros[0].versao = "^^0.1".into();
8880 let err = s.validate().unwrap_err();
8881 assert!(
8882 matches!(
8883 err,
8884 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8885 if caixa == "catalog" && versao == "^^0.1"
8886 ),
8887 "got {err:?}"
8888 );
8889 }
8890
8891 #[test]
8892 fn rejects_membro_versao_with_v_prefixed_tag() {
8893 // `"v0.1"` is the canonical "git-tag-shape leaking into the
8894 // semver requirement slot" typo — an author copies the
8895 // publish-side git-tag string verbatim into `:versao`, but
8896 // Cargo's semver parser rejects the leading `v` (only digits +
8897 // canonical operators are valid in the major-version
8898 // position). The gate's diagnostic names which member entry
8899 // carried the v-prefix so the fix is one edit, not a grep
8900 // through every member's `:versao`. (Note: bare `x`-glob
8901 // shorthands like `^0.1.x` are *accepted* by the semver crate
8902 // as an `*` wildcard on the patch axis — they're a Cargo-side
8903 // valid shape, not a typo, so the gate intentionally lets them
8904 // through.)
8905 let mut s = three_member_spec();
8906 s.membros[1].versao = "v0.1".into();
8907 let err = s.validate().unwrap_err();
8908 assert!(
8909 matches!(
8910 err,
8911 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8912 if caixa == "cart" && versao == "v0.1"
8913 ),
8914 "got {err:?}"
8915 );
8916 }
8917
8918 #[test]
8919 fn accepts_canonical_membro_versao_forms() {
8920 // The four Cargo-shaped requirement forms `:deps :versao`
8921 // already accepts via `crate::parse_requirement` must pass the
8922 // membros gate without re-validating at the resolver layer.
8923 // Pin every leg so a future tightening of the canonical set
8924 // surfaces here as a test failure.
8925 for form in [
8926 "^0.1", // caret — minor-range pin (the most common shape)
8927 "~0.1.2", // tilde — patch-range pin
8928 "0.1.0", // exact — single-version pin
8929 "*", // wildcard — explicitly any-version (semver::VersionReq::STAR)
8930 ">=0.1, <2", // multi-range — comma-separated comparators
8931 ] {
8932 let mut s = three_member_spec();
8933 for m in &mut s.membros {
8934 m.versao = form.into();
8935 }
8936 s.validate()
8937 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8938 }
8939 }
8940
8941 #[test]
8942 fn membro_versao_empty_takes_precedence_over_invalid() {
8943 // Order pin: the existing `MembroVersaoEmpty` diagnostic
8944 // (which doesn't try to parse) fires before the new
8945 // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8946 // `:versao` keeps its narrower error message — `parse_requirement`
8947 // would also reject `""`, but the empty-string arm is the more
8948 // self-locating diagnostic for the author.
8949 let mut s = three_member_spec();
8950 s.membros[1].versao = String::new();
8951 let err = s.validate().unwrap_err();
8952 assert!(
8953 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8954 "got {err:?}"
8955 );
8956 }
8957
8958 #[test]
8959 fn membro_versao_invalid_fires_before_duplicate_check() {
8960 // Order pin: a malformed requirement on a non-duplicate entry
8961 // surfaces *its own* diagnostic (which names the offending
8962 // `:versao` string), even when a later entry would otherwise
8963 // collapse onto an earlier name. The per-entry shape gate runs
8964 // inline before the duplicate-key insert, parallel to
8965 // `membros_validation_runs_before_contratos_membership_check`
8966 // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8967 let mut s = three_member_spec();
8968 s.membros[0].versao = "^bad".into();
8969 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8970 let err = s.validate().unwrap_err();
8971 assert!(
8972 matches!(
8973 err,
8974 AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8975 ),
8976 "got {err:?}"
8977 );
8978 }
8979
8980 #[test]
8981 fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8982 // The diagnostic-shape pin: the error names the offending
8983 // `:versao` value verbatim so the author can grep their
8984 // caixa.lisp without re-running the build, and carries a
8985 // non-empty `reason` from `semver::VersionReq::parse` so the
8986 // parser's own wording flows through to the diagnostic.
8987 let mut s = three_member_spec();
8988 s.membros[2].versao = "not-a-req".into();
8989 let err = s.validate().unwrap_err();
8990 let AplicacaoError::MembroVersaoInvalid {
8991 caixa,
8992 versao,
8993 reason,
8994 } = err
8995 else {
8996 panic!("expected MembroVersaoInvalid, got other variant");
8997 };
8998 assert_eq!(caixa, "payment");
8999 assert_eq!(versao, "not-a-req");
9000 assert!(
9001 !reason.is_empty(),
9002 "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
9003 );
9004 }
9005
9006 #[test]
9007 fn membro_versao_invalid_runs_before_contratos_check() {
9008 // A malformed `:versao` on any member must surface its own
9009 // diagnostic (which names *which* member to fix) before any
9010 // `:contratos` membership lookup raises `ContratoMemberMissing`.
9011 // The `:contratos` gate runs after `validate_membros`, so this
9012 // is structurally guaranteed — pin it explicitly so a future
9013 // refactor that reorders the gates surfaces here.
9014 let mut s = three_member_spec();
9015 s.membros[1].versao = "^^0.1".into();
9016 // Add a contrato whose `:para` doesn't exist — would normally
9017 // raise ContratoMemberMissing at the membership lookup, but
9018 // the membros gate must fire first.
9019 s.contratos
9020 .push(contract_http("cart", "phantom", "/never-reached"));
9021 let err = s.validate().unwrap_err();
9022 assert!(
9023 matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
9024 "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
9025 );
9026 }
9027
9028 #[test]
9029 fn membros_validation_runs_before_contratos_membership_check() {
9030 // If `:membros` carries a duplicate, the membership-collapse
9031 // would silently accept a `:contratos :para "phantom"` so long
9032 // as some entry hashes to "phantom". Pinning order: the
9033 // duplicate-membros error fires first, regardless of whether
9034 // contratos reference real members.
9035 let mut s = three_member_spec();
9036 s.membros = vec![
9037 membro("cart", "^0.1"),
9038 membro("cart", "^0.2"),
9039 membro("catalog", "^0.1"),
9040 membro("payment", "^0.1"),
9041 ];
9042 let err = s.validate().unwrap_err();
9043 assert!(
9044 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
9045 "got {err:?}"
9046 );
9047 }
9048
9049 #[test]
9050 fn distinct_membros_validate() {
9051 // Pin the happy-path: every `:membros` entry has a non-empty
9052 // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
9053 // The fixture already satisfies this; this test makes the
9054 // invariant explicit so a future refactor of the fixture can't
9055 // silently break the guarantee.
9056 three_member_spec().validate().unwrap();
9057 }
9058
9059 // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
9060
9061 #[test]
9062 fn rejects_membro_caixa_with_uppercase() {
9063 // The canonical "I copied the Servico's display name verbatim"
9064 // typo — caixa names are lowercase per K8s DNS-1123 label rule,
9065 // but author tools often round-trip a TitleCase or CamelCase
9066 // identifier from an ADR or a sketch. Pin the diagnostic names
9067 // the offending name and suggests the lower-cased fix in one
9068 // edit, mirroring the `rejects_entrada_host_with_uppercase`
9069 // gate's shape (c7d05ec).
9070 let mut s = three_member_spec();
9071 s.membros[1].caixa = "Cart".into();
9072 let err = s.validate().unwrap_err();
9073 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9074 panic!("expected MembroCaixaInvalid, got other variant");
9075 };
9076 assert_eq!(caixa, "Cart");
9077 assert!(
9078 reason.contains("uppercase"),
9079 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9080 );
9081 assert!(
9082 reason.contains("\"cart\""),
9083 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
9084 );
9085 }
9086
9087 #[test]
9088 fn rejects_membro_caixa_with_underscore() {
9089 // The canonical "I'm thinking of a Python module / Postgres
9090 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
9091 // label schema. K8s rejects `metadata.name: my_cart` at admission
9092 // time with an opaque `field is invalid` (no source-citing
9093 // diagnostic). The gate moves it to caixa-build time.
9094 let mut s = three_member_spec();
9095 s.membros[0].caixa = "my_cart".into();
9096 let err = s.validate().unwrap_err();
9097 assert!(
9098 matches!(
9099 err,
9100 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9101 if caixa == "my_cart" && reason.contains('_')
9102 ),
9103 "got {err:?}"
9104 );
9105 }
9106
9107 #[test]
9108 fn rejects_membro_caixa_with_dot() {
9109 // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
9110 // subdomain — even though K8s `metadata.name` itself accepts
9111 // dots (DNS-1123 subdomain rule), this string also lands as a
9112 // K8s Service name (DNS-1035 label — no dots) and as a label
9113 // value on identity-based Cilium selectors. The strictest floor
9114 // among the use sites wins. The "I want to namespace my member
9115 // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
9116 let mut s = three_member_spec();
9117 s.membros[2].caixa = "team.cart".into();
9118 let err = s.validate().unwrap_err();
9119 assert!(
9120 matches!(
9121 err,
9122 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9123 if caixa == "team.cart" && reason.contains('.')
9124 ),
9125 "got {err:?}"
9126 );
9127 }
9128
9129 #[test]
9130 fn rejects_membro_caixa_with_leading_hyphen() {
9131 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
9132 // with an alphanumeric. The K8s apiserver rejects `-cart`
9133 // outright; the renderer would emit a `metadata.name: "-cart"`
9134 // that fails admission far from the source caixa.lisp.
9135 let mut s = three_member_spec();
9136 s.membros[0].caixa = "-cart".into();
9137 let err = s.validate().unwrap_err();
9138 assert!(
9139 matches!(
9140 err,
9141 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9142 if caixa == "-cart" && reason.contains("start and end")
9143 ),
9144 "got {err:?}"
9145 );
9146 }
9147
9148 #[test]
9149 fn rejects_membro_caixa_with_trailing_hyphen() {
9150 // The symmetric arm of the boundary rule. Pin separately so
9151 // both ends of the label are covered against a future relaxation
9152 // that only checks one boundary.
9153 let mut s = three_member_spec();
9154 s.membros[1].caixa = "cart-".into();
9155 let err = s.validate().unwrap_err();
9156 assert!(
9157 matches!(
9158 err,
9159 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9160 if caixa == "cart-"
9161 ),
9162 "got {err:?}"
9163 );
9164 }
9165
9166 #[test]
9167 fn rejects_membro_caixa_with_unicode() {
9168 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9169 // (`xn--…`) by the author before it reaches K8s. The byte-by-
9170 // byte ASCII validity check rejects multi-byte UTF-8 sequences
9171 // by the first byte that fails the `[a-z0-9-]` predicate.
9172 let mut s = three_member_spec();
9173 s.membros[2].caixa = "café".into();
9174 let err = s.validate().unwrap_err();
9175 assert!(
9176 matches!(
9177 err,
9178 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9179 if caixa == "café"
9180 ),
9181 "got {err:?}"
9182 );
9183 }
9184
9185 #[test]
9186 fn rejects_membro_caixa_with_whitespace() {
9187 // Whitespace is the canonical "I pasted from a sketch / doc"
9188 // footgun. The apiserver rejects every `metadata.name` value
9189 // carrying whitespace; pin the gate fires at the right boundary.
9190 let mut s = three_member_spec();
9191 s.membros[0].caixa = "my cart".into();
9192 let err = s.validate().unwrap_err();
9193 assert!(
9194 matches!(
9195 err,
9196 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9197 if caixa == "my cart"
9198 ),
9199 "got {err:?}"
9200 );
9201 }
9202
9203 #[test]
9204 fn rejects_membro_caixa_too_long() {
9205 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
9206 // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
9207 // exactly. The gate's reason names both the cap and the actual
9208 // length so the author can shorten in one edit.
9209 let mut s = three_member_spec();
9210 let too_long = "a".repeat(64);
9211 s.membros[1].caixa = too_long.clone();
9212 let err = s.validate().unwrap_err();
9213 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9214 panic!("expected MembroCaixaInvalid");
9215 };
9216 assert_eq!(caixa, too_long);
9217 assert!(
9218 reason.contains("63") && reason.contains("64"),
9219 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
9220 );
9221 }
9222
9223 #[test]
9224 fn membro_caixa_max_length_validates() {
9225 // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
9226 // so a future tightening (e.g. dropping to 62) surfaces here as
9227 // a regression, mirroring `entrada_host_max_length_validates`
9228 // (c7d05ec).
9229 let mut s = three_member_spec();
9230 s.membros[2].caixa = "a".repeat(63);
9231 s.entrada.as_mut().unwrap().para = "a".repeat(63);
9232 // remove contratos referencing the renamed member; they'd
9233 // raise ContratoMemberMissing otherwise
9234 s.contratos
9235 .retain(|c| c.de != "payment" && c.para != "payment");
9236 s.validate().unwrap();
9237 }
9238
9239 #[test]
9240 fn accepts_canonical_membro_caixa_forms() {
9241 // The DNS-1123 label shapes a caixa author is realistically
9242 // going to write: single-word lowercase, hyphen-joined, ending
9243 // in a digit-suffixed version (`cart-v2`), starting with a
9244 // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
9245 // DNS-1035 which requires a letter at position 0), single-
9246 // character (`a` — boundary). Pin every leg so a future
9247 // tightening that bans (e.g.) digit-start identifiers surfaces
9248 // here.
9249 for form in [
9250 "checkout",
9251 "cart",
9252 "cart-v2",
9253 "a",
9254 "c0",
9255 "3rd-party-shim",
9256 "x-1-2-3-4",
9257 ] {
9258 let mut s = three_member_spec();
9259 // Renaming a member also requires updating downstream refs;
9260 // drop everything else and rebuild a minimal spec around
9261 // just the one renamed member.
9262 s.membros = vec![membro(form, "^0.1")];
9263 s.contratos = vec![];
9264 s.entrada = None;
9265 s.validate()
9266 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
9267 }
9268 }
9269
9270 #[test]
9271 fn membro_caixa_empty_takes_precedence_over_invalid() {
9272 // Order pin: the existing `MembroCaixaEmpty` diagnostic
9273 // (which doesn't try to parse) fires before the new
9274 // `MembroCaixaInvalid` parse-side diagnostic, so an empty
9275 // `:caixa` keeps its narrower error message — the new gate
9276 // would also reject `""`, but the empty-string arm is the more
9277 // self-locating diagnostic for the author. Mirrors the
9278 // `entrada_host_empty_takes_precedence_over_invalid` pin
9279 // (c7d05ec).
9280 let mut s = three_member_spec();
9281 s.membros[1].caixa = String::new();
9282 let err = s.validate().unwrap_err();
9283 assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
9284 }
9285
9286 #[test]
9287 fn membro_caixa_invalid_fires_before_versao_check() {
9288 // Order pin: an invalid-shape `:caixa` surfaces *its own*
9289 // diagnostic (which names the offending caixa name), even when
9290 // the same entry's `:versao` is also empty/invalid. The shape
9291 // gate runs first because the diagnostic is more self-locating —
9292 // an empty/invalid `:versao` on an invalid-shape caixa name is
9293 // a downstream-fix-after-the-caixa-rename concern.
9294 let mut s = three_member_spec();
9295 s.membros[1].caixa = "Cart".into();
9296 s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
9297 let err = s.validate().unwrap_err();
9298 assert!(
9299 matches!(
9300 err,
9301 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
9302 ),
9303 "got {err:?}"
9304 );
9305 }
9306
9307 #[test]
9308 fn membro_caixa_invalid_fires_before_duplicate_check() {
9309 // Order pin: a malformed-shape `:caixa` on an earlier entry
9310 // surfaces *its own* diagnostic, even when a later entry would
9311 // otherwise collapse onto a duplicate name. The per-entry shape
9312 // gate runs inline before the duplicate-key insert, parallel
9313 // to `membro_versao_invalid_fires_before_duplicate_check`.
9314 let mut s = three_member_spec();
9315 s.membros[0].caixa = "Catalog".into();
9316 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
9317 let err = s.validate().unwrap_err();
9318 assert!(
9319 matches!(
9320 err,
9321 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
9322 ),
9323 "got {err:?}"
9324 );
9325 }
9326
9327 #[test]
9328 fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
9329 // The diagnostic-shape pin: the error names the offending
9330 // `:caixa` value verbatim so the author can grep their
9331 // caixa.lisp without re-running the build, and carries a
9332 // non-empty `reason` naming the specific violation. Same
9333 // shape every typed-shape gate enshrines (c7d05ec's
9334 // `entrada_host_diagnostic_carries_offending_host`,
9335 // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
9336 let mut s = three_member_spec();
9337 s.membros[2].caixa = "BAD_NAME".into();
9338 let err = s.validate().unwrap_err();
9339 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9340 panic!("expected MembroCaixaInvalid");
9341 };
9342 assert_eq!(caixa, "BAD_NAME");
9343 assert!(
9344 !reason.is_empty(),
9345 "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
9346 );
9347 }
9348
9349 #[test]
9350 fn rejects_contrato_with_unknown_de() {
9351 let mut s = three_member_spec();
9352 s.contratos.push(contract_http("phantom", "catalog", "/x"));
9353 let err = s.validate().unwrap_err();
9354 assert!(
9355 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9356 );
9357 }
9358
9359 #[test]
9360 fn rejects_contrato_with_unknown_para() {
9361 let mut s = three_member_spec();
9362 s.contratos.push(contract_http("cart", "phantom", "/x"));
9363 let err = s.validate().unwrap_err();
9364 assert!(
9365 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9366 );
9367 }
9368
9369 #[test]
9370 fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
9371 // The read-path pin: the phantom-`:de` refusal arm's
9372 // `ContratoMemberMissing.caixa` carrier must be observed through
9373 // the lifted [`WitContract::source`] accessor, not the raw
9374 // `.de.clone()` field-access `String`-carry. Peer of the sibling
9375 // per-`:contratos` self-loop arm's `.source().to_string()` /
9376 // `.world_ref().to_string()` `String`-carry sites the earlier
9377 // convergence lifted onto the same accessor pair. A future
9378 // silent detour that reintroduced the raw `.de.clone()` at the
9379 // wrap envelope while the shape-gate and membership lookup
9380 // routed through the accessor would surface here as a byte-equal
9381 // miss between the fired diagnostic's `caixa:` field and the
9382 // offending edge's `.source()` — pinning the accessor as the
9383 // sole read path across the phantom-name refusal arm's arg +
9384 // wrap-envelope emit surface.
9385 let mut s = three_member_spec();
9386 let phantom = contract_http("phantom", "catalog", "/x");
9387 s.contratos.push(phantom.clone());
9388 let err = s.validate().unwrap_err();
9389 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9390 panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
9391 };
9392 assert_eq!(
9393 caixa,
9394 phantom.source(),
9395 "ContratoMemberMissing.caixa on the phantom-:de arm must \
9396 byte-equal WitContract::source — the wrap envelope must \
9397 route through the lifted accessor rather than the raw \
9398 .de.clone() field-access String-carry"
9399 );
9400 }
9401
9402 #[test]
9403 fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9404 // The symmetric read-path pin on the `:para` phantom-name
9405 // refusal arm — same shape as the sibling `:de` pin above but
9406 // on the callee-Servico axis. Pins the wrap envelope's
9407 // `caixa:` field is observed through the lifted
9408 // [`WitContract::destination`] accessor, not the raw
9409 // `.para.clone()` field-access `String`-carry.
9410 let mut s = three_member_spec();
9411 let phantom = contract_http("cart", "phantom", "/x");
9412 s.contratos.push(phantom.clone());
9413 let err = s.validate().unwrap_err();
9414 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9415 panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
9416 };
9417 assert_eq!(
9418 caixa,
9419 phantom.destination(),
9420 "ContratoMemberMissing.caixa on the phantom-:para arm must \
9421 byte-equal WitContract::destination — the wrap envelope \
9422 must route through the lifted accessor rather than the raw \
9423 .para.clone() field-access String-carry"
9424 );
9425 }
9426
9427 #[test]
9428 fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
9429 // The read-path pin on the `:de` DNS-1123-malformed shape-gate
9430 // refusal arm — the `validate_contrato_caixa` arg must be
9431 // observed through the lifted [`WitContract::source`] accessor,
9432 // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
9433 // value routes through the shared
9434 // [`crate::render::require_valid_dns_1123_label`] floor with the
9435 // accessor-projected value; the fired
9436 // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
9437 // the offending edge's `.source()`, pinning that the arg + the
9438 // downstream `caixa: caixa.to_string()` wrap route through the
9439 // same accessor's read path.
9440 let mut s = three_member_spec();
9441 let malformed = contract_http("BAD_NAME", "catalog", "/x");
9442 s.contratos.push(malformed.clone());
9443 let err = s.validate().unwrap_err();
9444 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9445 panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
9446 };
9447 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9448 assert_eq!(
9449 caixa,
9450 malformed.source(),
9451 "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
9452 byte-equal WitContract::source — the shape-gate arg + wrap \
9453 envelope must route through the lifted accessor rather \
9454 than the raw &c.de &String-borrow"
9455 );
9456 }
9457
9458 #[test]
9459 fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9460 // Symmetric arm to the sibling `:de` malformed-shape pin above,
9461 // on the `:para` axis. Pins the shape-gate arg + wrap envelope
9462 // route through the lifted [`WitContract::destination`]
9463 // accessor. `:para` runs after the `:de` shape gate in the
9464 // canonical edge-direction order, so the `:de` value must be
9465 // well-shaped for the `:para` gate to fire — the `cart` :de is
9466 // canonical.
9467 let mut s = three_member_spec();
9468 let malformed = contract_http("cart", "BAD_NAME", "/x");
9469 s.contratos.push(malformed.clone());
9470 let err = s.validate().unwrap_err();
9471 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9472 panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
9473 };
9474 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9475 assert_eq!(
9476 caixa,
9477 malformed.destination(),
9478 "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
9479 byte-equal WitContract::destination — the shape-gate arg + \
9480 wrap envelope must route through the lifted accessor \
9481 rather than the raw &c.para &String-borrow"
9482 );
9483 }
9484
9485 // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
9486
9487 #[test]
9488 fn rejects_contrato_de_empty() {
9489 // `:de ""` previously fell through to `ContratoMemberMissing`
9490 // (with `caixa: ""`) because the validated `:membros :caixa`
9491 // set never contains the empty string. The narrower
9492 // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
9493 // the offending slot.
9494 let mut s = three_member_spec();
9495 s.contratos.push(contract_http("", "catalog", "/x"));
9496 let err = s.validate().unwrap_err();
9497 assert_eq!(
9498 err,
9499 AplicacaoError::ContratoCaixaEmpty {
9500 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9501 },
9502 "got {err:?}"
9503 );
9504 }
9505
9506 #[test]
9507 fn rejects_contrato_para_empty() {
9508 // Symmetric arm to `:de ""` — `:para ""` previously fell
9509 // through to `ContratoMemberMissing { caixa: "" }`.
9510 let mut s = three_member_spec();
9511 s.contratos.push(contract_http("cart", "", "/x"));
9512 let err = s.validate().unwrap_err();
9513 assert_eq!(
9514 err,
9515 AplicacaoError::ContratoCaixaEmpty {
9516 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9517 },
9518 "got {err:?}"
9519 );
9520 }
9521
9522 #[test]
9523 fn rejects_contrato_de_with_uppercase() {
9524 // The canonical "I copied the Servico's TitleCase display
9525 // name from an ADR" typo. Until this gate landed `:de "Cart"`
9526 // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
9527 // as "this caixa isn't in `:membros`" when the root cause is
9528 // "this `:de` value's shape can never legitimately match a
9529 // validated member (DNS-1123 labels are lowercase)". The
9530 // narrower diagnostic names the offending slot, the value
9531 // verbatim, and the parser-shaped reason.
9532 let mut s = three_member_spec();
9533 s.contratos.push(contract_http("Cart", "catalog", "/x"));
9534 let err = s.validate().unwrap_err();
9535 let AplicacaoError::ContratoCaixaInvalid {
9536 slot,
9537 caixa,
9538 reason,
9539 } = err
9540 else {
9541 panic!("expected ContratoCaixaInvalid, got other variant");
9542 };
9543 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9544 assert_eq!(caixa, "Cart");
9545 assert!(
9546 reason.contains("uppercase"),
9547 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9548 );
9549 }
9550
9551 #[test]
9552 fn rejects_contrato_para_with_underscore() {
9553 // The canonical "I'm thinking of a Python module" leak —
9554 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9555 // Pin the `:para` axis surfaces the same diagnostic shape as
9556 // the `:de` axis on the underscore violation.
9557 let mut s = three_member_spec();
9558 s.contratos.push(contract_http("cart", "my_catalog", "/x"));
9559 let err = s.validate().unwrap_err();
9560 assert!(
9561 matches!(
9562 err,
9563 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9564 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
9565 ),
9566 "got {err:?}"
9567 );
9568 }
9569
9570 #[test]
9571 fn rejects_contrato_de_with_dot() {
9572 // A `:contratos :de` value is a single DNS-1123 *label*, not
9573 // a subdomain — mirroring the `:membros :caixa` floor. The
9574 // strictest floor among the use sites wins.
9575 let mut s = three_member_spec();
9576 s.contratos
9577 .push(contract_http("team.cart", "catalog", "/x"));
9578 let err = s.validate().unwrap_err();
9579 assert!(
9580 matches!(
9581 err,
9582 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9583 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
9584 ),
9585 "got {err:?}"
9586 );
9587 }
9588
9589 #[test]
9590 fn rejects_contrato_para_with_unicode() {
9591 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9592 // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
9593 // validity check rejects multi-byte UTF-8 by the first
9594 // non-`[a-z0-9-]` byte.
9595 let mut s = three_member_spec();
9596 s.contratos.push(contract_http("cart", "café", "/x"));
9597 let err = s.validate().unwrap_err();
9598 assert!(
9599 matches!(
9600 err,
9601 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9602 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
9603 ),
9604 "got {err:?}"
9605 );
9606 }
9607
9608 #[test]
9609 fn rejects_contrato_de_with_leading_hyphen() {
9610 // DNS-1123 boundary rule: labels must start and end with an
9611 // alphanumeric. K8s rejects `-cart` outright; the narrower
9612 // shape diagnostic now names the violation at caixa-build
9613 // time rather than the misframed membership-lookup arm.
9614 let mut s = three_member_spec();
9615 s.contratos.push(contract_http("-cart", "catalog", "/x"));
9616 let err = s.validate().unwrap_err();
9617 assert!(
9618 matches!(
9619 err,
9620 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9621 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
9622 ),
9623 "got {err:?}"
9624 );
9625 }
9626
9627 #[test]
9628 fn contrato_de_empty_takes_precedence_over_invalid() {
9629 // Order pin: the `ContratoCaixaEmpty` arm fires before the
9630 // `ContratoCaixaInvalid` parse-side arm — same empty-first
9631 // cascade `validate_membro_caixa` / `validate_placement_cluster`
9632 // / `validate_entrada_host` already establish on their peer
9633 // name axes. The empty string is a structurally distinct
9634 // authoring footgun (the author left the field blank, vs.
9635 // typed a malformed value), so it gets its own diagnostic.
9636 let mut s = three_member_spec();
9637 s.contratos.push(contract_http("", "catalog", "/x"));
9638 let err = s.validate().unwrap_err();
9639 assert_eq!(
9640 err,
9641 AplicacaoError::ContratoCaixaEmpty {
9642 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9643 }
9644 );
9645 }
9646
9647 #[test]
9648 fn contrato_de_shape_fires_before_para_shape() {
9649 // Per-axis order pin: within one `:contratos` entry, the `:de`
9650 // shape gate fires before the `:para` shape gate — same
9651 // edge-direction order the existing `ContratoMemberMissing` /
9652 // `ContratoSelfLoop` / target-dispatch checks use, so the
9653 // diagnostic for a contract with both `:de` and `:para`
9654 // malformed is stable. Authors fixing the surfaced `:de`
9655 // first will see `:para`'s diagnostic on re-run.
9656 let mut s = three_member_spec();
9657 s.contratos.push(contract_http("Cart", "Catalog", "/x"));
9658 let err = s.validate().unwrap_err();
9659 assert!(
9660 matches!(
9661 err,
9662 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9663 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9664 ),
9665 "got {err:?}"
9666 );
9667 }
9668
9669 #[test]
9670 fn contrato_shape_fires_before_membership_lookup() {
9671 // The load-bearing pin: an invalid-shape `:de` surfaces its
9672 // *own* diagnostic, not the misframed `ContratoMemberMissing`.
9673 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9674 // an invalid-shape `:de` could never legitimately match any
9675 // member — the prior `ContratoMemberMissing` diagnostic was
9676 // a structural impossibility framed as a graph-membership
9677 // failure. The shape gate now routes every such input through
9678 // the narrower self-locating diagnostic.
9679 let mut s = three_member_spec();
9680 s.contratos.push(contract_http("Cart", "catalog", "/x"));
9681 let err = s.validate().unwrap_err();
9682 assert!(
9683 matches!(
9684 err,
9685 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
9686 ),
9687 "got {err:?}"
9688 );
9689 // And the symmetric case: an invalid-shape `:para` surfaces
9690 // its own diagnostic too, even when `:de` is well-shaped.
9691 let mut s = three_member_spec();
9692 s.contratos.push(contract_http("cart", "Catalog", "/x"));
9693 let err = s.validate().unwrap_err();
9694 assert!(
9695 matches!(
9696 err,
9697 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9698 ),
9699 "got {err:?}"
9700 );
9701 }
9702
9703 #[test]
9704 fn contrato_shape_fires_before_self_edge_check() {
9705 // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9706 // bugs: the shape violation (uppercase) and the self-edge
9707 // violation. The narrower per-axis shape diagnostic surfaces
9708 // first because fixing the shape may reveal that the author
9709 // also meant to point `:para` at a different member — the
9710 // self-edge framing is only useful once both endpoints have
9711 // valid shape.
9712 let mut s = three_member_spec();
9713 s.contratos.push(contract_http("Cart", "Cart", "/x"));
9714 let err = s.validate().unwrap_err();
9715 assert!(
9716 matches!(
9717 err,
9718 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9719 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9720 ),
9721 "got {err:?}"
9722 );
9723 }
9724
9725 #[test]
9726 fn contrato_well_shaped_phantom_still_raises_member_missing() {
9727 // Strict-improvement pin: a well-shaped `:de` that simply
9728 // isn't in `:membros` (a phantom reference — author meant
9729 // to add the member but didn't, or renamed and missed an
9730 // update) still surfaces `ContratoMemberMissing`, unchanged.
9731 // The shape gate only intercepts inputs that could never
9732 // legitimately match a validated member; legitimately-shaped
9733 // phantom references remain on the graph-membership axis.
9734 let mut s = three_member_spec();
9735 s.contratos
9736 .push(contract_http("phantom-shim", "catalog", "/x"));
9737 let err = s.validate().unwrap_err();
9738 assert!(
9739 matches!(
9740 err,
9741 AplicacaoError::ContratoMemberMissing { ref caixa }
9742 if caixa == "phantom-shim"
9743 ),
9744 "got {err:?}"
9745 );
9746 }
9747
9748 #[test]
9749 fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9750 // The diagnostic-shape pin: the error names the offending
9751 // slot (`:de` or `:para`) verbatim and the offending value
9752 // verbatim plus a non-empty parser-shaped reason, so the
9753 // author can grep their caixa.lisp for `:de "<name>"` /
9754 // `:para "<name>"` and fix it in one edit. Same diagnostic
9755 // shape as `MembroCaixaInvalid` (3f9d7a0) and
9756 // `PlacementClusterInvalid` (6c8c00b).
9757 let mut s = three_member_spec();
9758 s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9759 let err = s.validate().unwrap_err();
9760 let AplicacaoError::ContratoCaixaInvalid {
9761 slot,
9762 caixa,
9763 reason,
9764 } = err
9765 else {
9766 panic!("expected ContratoCaixaInvalid, got {err:?}");
9767 };
9768 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9769 assert_eq!(caixa, "BAD_NAME");
9770 assert!(
9771 !reason.is_empty(),
9772 "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9773 );
9774 }
9775
9776 #[test]
9777 fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9778 // Scalar-value pin: the two author-facing kebab-case labels the
9779 // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9780 // admits on the `:contratos` per-entry endpoint-shape axis,
9781 // one arm per typed sub-slot. Mirrors the peer scalar-value
9782 // pin the sibling top-level M2 / M3 / Supervisor
9783 // author-facing-label consts carry
9784 // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9785 // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9786 // slot itself), so every altitude of the typed-slot algebra
9787 // shares the same "one canonical byte-string per arm"
9788 // discipline. A future rebrand (`:de` → `:from` matching the
9789 // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9790 // sibling, `:para` → `:to` matching the same, or
9791 // `:de`/`:para` → `:source`/`:target` matching the WIT
9792 // world's `import`/`export` half-vocabulary) lands as an
9793 // edit to exactly one const, and every consumer that reaches
9794 // for the label picks it up at build time rather than at
9795 // runtime as a downstream `ContratoCaixaEmpty` /
9796 // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9797 // diagnostic mismatch far from the rename's commit.
9798 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9799 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9800 }
9801
9802 #[test]
9803 fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9804 // Production-through-const pin: the two per-axis labels the
9805 // per-`:contratos` entry endpoint-shape gate at
9806 // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9807 // argument to [`validate_contrato_caixa`] route through the
9808 // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9809 // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9810 // future rebrand that reaches the const but not the gate (or
9811 // vice versa) surfaces here at build time rather than at
9812 // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9813 // `slot: <stale-kebab-case>` diagnostic far from the rename's
9814 // commit. Mirror of the peer
9815 // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9816 // pin (882f498) on the sibling M3 top-level slot axis.
9817 let mut s = three_member_spec();
9818 s.contratos.push(contract_http("", "catalog", "/x"));
9819 assert_eq!(
9820 s.validate().unwrap_err(),
9821 AplicacaoError::ContratoCaixaEmpty {
9822 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9823 }
9824 );
9825 let mut s = three_member_spec();
9826 s.contratos.push(contract_http("cart", "", "/x"));
9827 assert_eq!(
9828 s.validate().unwrap_err(),
9829 AplicacaoError::ContratoCaixaEmpty {
9830 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9831 }
9832 );
9833 }
9834
9835 #[test]
9836 fn accepts_canonical_contrato_caixa_forms() {
9837 // The DNS-1123 label shapes a caixa author is realistically
9838 // going to write on a `:contratos :de` / `:para`. Pin every
9839 // leg so a future tightening that bans (e.g.) digit-start
9840 // identifiers surfaces here, mirroring
9841 // `accepts_canonical_membro_caixa_forms` on the peer name
9842 // axis.
9843 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9844 let mut s = three_member_spec();
9845 s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9846 s.contratos = vec![contract_http("checkout", form, "/x")];
9847 s.entrada = None;
9848 s.validate().unwrap_or_else(|e| {
9849 panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9850 });
9851
9852 let mut s = three_member_spec();
9853 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9854 s.contratos = vec![contract_http(form, "catalog", "/x")];
9855 s.entrada = None;
9856 s.validate().unwrap_or_else(|e| {
9857 panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9858 });
9859 }
9860 }
9861
9862 #[test]
9863 fn rejects_empty_wit() {
9864 let mut s = three_member_spec();
9865 s.contratos.push(WitContract {
9866 de: "cart".into(),
9867 para: "catalog".into(),
9868 wit: "".into(),
9869 endpoint: None,
9870 subject: None,
9871 slot: None,
9872 });
9873 let err = s.validate().unwrap_err();
9874 assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9875 }
9876
9877 #[test]
9878 fn rejects_entrada_to_unknown_member() {
9879 let mut s = three_member_spec();
9880 s.entrada.as_mut().unwrap().para = "phantom".into();
9881 assert!(matches!(
9882 s.validate().unwrap_err(),
9883 AplicacaoError::EntradaMemberMissing { .. }
9884 ));
9885 }
9886
9887 // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9888
9889 #[test]
9890 fn rejects_entrada_para_empty() {
9891 // `:para ""` previously fell through to
9892 // `EntradaMemberMissing { para: "" }` because the validated
9893 // `:membros :caixa` set never contains the empty string. The
9894 // narrower `EntradaParaEmpty` diagnostic now names the
9895 // offending slot directly — same empty-first cascade
9896 // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9897 // `ContratoCaixaEmpty` establish on the peer name axes.
9898 let mut s = three_member_spec();
9899 s.entrada.as_mut().unwrap().para = String::new();
9900 let err = s.validate().unwrap_err();
9901 assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9902 }
9903
9904 #[test]
9905 fn rejects_entrada_para_with_uppercase() {
9906 // The canonical "I copied the Servico's TitleCase display
9907 // name from an ADR" typo. Until this gate landed `:para "Cart"`
9908 // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9909 // as "this caixa isn't in `:membros`" when the root cause is
9910 // "this `:para` value's shape can never legitimately match a
9911 // validated member (DNS-1123 labels are lowercase)". The
9912 // narrower diagnostic names the value verbatim plus the
9913 // parser-shaped reason.
9914 let mut s = three_member_spec();
9915 s.entrada.as_mut().unwrap().para = "Cart".into();
9916 let err = s.validate().unwrap_err();
9917 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9918 panic!("expected EntradaParaInvalid, got other variant");
9919 };
9920 assert_eq!(para, "Cart");
9921 assert!(
9922 reason.contains("uppercase"),
9923 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9924 );
9925 }
9926
9927 #[test]
9928 fn rejects_entrada_para_with_underscore() {
9929 // The canonical "I'm thinking of a Python module" leak —
9930 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9931 let mut s = three_member_spec();
9932 s.entrada.as_mut().unwrap().para = "my_cart".into();
9933 let err = s.validate().unwrap_err();
9934 assert!(
9935 matches!(
9936 err,
9937 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9938 if para == "my_cart" && reason.contains('_')
9939 ),
9940 "got {err:?}"
9941 );
9942 }
9943
9944 #[test]
9945 fn rejects_entrada_para_with_dot() {
9946 // An `:entrada :para` value is a single DNS-1123 *label*, not
9947 // a subdomain — mirroring the `:membros :caixa` floor. The
9948 // strictest floor among the use sites wins.
9949 let mut s = three_member_spec();
9950 s.entrada.as_mut().unwrap().para = "team.cart".into();
9951 let err = s.validate().unwrap_err();
9952 assert!(
9953 matches!(
9954 err,
9955 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9956 if para == "team.cart" && reason.contains('.')
9957 ),
9958 "got {err:?}"
9959 );
9960 }
9961
9962 #[test]
9963 fn rejects_entrada_para_with_unicode() {
9964 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9965 // (`xn--…`) before it reaches K8s.
9966 let mut s = three_member_spec();
9967 s.entrada.as_mut().unwrap().para = "café".into();
9968 let err = s.validate().unwrap_err();
9969 assert!(
9970 matches!(
9971 err,
9972 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9973 ),
9974 "got {err:?}"
9975 );
9976 }
9977
9978 #[test]
9979 fn rejects_entrada_para_with_leading_hyphen() {
9980 // DNS-1123 boundary rule: labels must start and end with an
9981 // alphanumeric. K8s rejects `-cart` outright.
9982 let mut s = three_member_spec();
9983 s.entrada.as_mut().unwrap().para = "-cart".into();
9984 let err = s.validate().unwrap_err();
9985 assert!(
9986 matches!(
9987 err,
9988 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9989 if para == "-cart" && reason.contains("start and end")
9990 ),
9991 "got {err:?}"
9992 );
9993 }
9994
9995 #[test]
9996 fn rejects_entrada_para_with_trailing_hyphen() {
9997 // Symmetric boundary arm.
9998 let mut s = three_member_spec();
9999 s.entrada.as_mut().unwrap().para = "cart-".into();
10000 let err = s.validate().unwrap_err();
10001 assert!(
10002 matches!(
10003 err,
10004 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
10005 if para == "cart-" && reason.contains("start and end")
10006 ),
10007 "got {err:?}"
10008 );
10009 }
10010
10011 #[test]
10012 fn rejects_entrada_para_too_long() {
10013 // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
10014 // bytes per label. K8s rejects longer names at admission on
10015 // every `metadata.name` axis.
10016 let mut s = three_member_spec();
10017 s.entrada.as_mut().unwrap().para = "a".repeat(64);
10018 let err = s.validate().unwrap_err();
10019 assert!(
10020 matches!(
10021 err,
10022 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
10023 if para.len() == 64 && reason.contains("max length")
10024 ),
10025 "got {err:?}"
10026 );
10027 }
10028
10029 #[test]
10030 fn entrada_para_empty_takes_precedence_over_invalid() {
10031 // Order pin: the `EntradaParaEmpty` arm fires before the
10032 // `EntradaParaInvalid` parse-side arm — same empty-first
10033 // cascade `validate_membro_caixa` / `validate_placement_cluster`
10034 // / `validate_contrato_caixa` already establish.
10035 let mut s = three_member_spec();
10036 s.entrada.as_mut().unwrap().para = String::new();
10037 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
10038 }
10039
10040 #[test]
10041 fn entrada_para_shape_fires_before_membership_lookup() {
10042 // The load-bearing pin: an invalid-shape `:para` surfaces its
10043 // *own* diagnostic, not the misframed `EntradaMemberMissing`.
10044 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
10045 // an invalid-shape `:para` could never legitimately match any
10046 // member — the prior `EntradaMemberMissing` diagnostic framed
10047 // a structural impossibility as a graph-membership failure.
10048 let mut s = three_member_spec();
10049 s.entrada.as_mut().unwrap().para = "Cart".into();
10050 let err = s.validate().unwrap_err();
10051 assert!(
10052 matches!(
10053 err,
10054 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
10055 ),
10056 "got {err:?}"
10057 );
10058 }
10059
10060 #[test]
10061 fn entrada_para_shape_fires_before_host_gate() {
10062 // Per-`:entrada` order pin: the `:para` shape gate fires
10063 // before the `:host` gate, mirroring the existing
10064 // `entrada_host_member_missing_takes_precedence_over_host_invalid`
10065 // ordering where the member-lookup arm preceded the host gate.
10066 // The shape gate slots ahead of that, so a malformed `:para`
10067 // surfaces its own diagnostic even when `:host` is also wrong.
10068 let mut s = three_member_spec();
10069 let e = s.entrada.as_mut().unwrap();
10070 e.para = "Cart".into();
10071 e.host = "BAD HOST".into();
10072 let err = s.validate().unwrap_err();
10073 assert!(
10074 matches!(
10075 err,
10076 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
10077 ),
10078 "got {err:?}"
10079 );
10080 }
10081
10082 #[test]
10083 fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
10084 // Strict-improvement pin: a well-shaped `:para` that simply
10085 // isn't in `:membros` (a phantom reference — author meant to
10086 // add the member but didn't, or renamed and missed an
10087 // update) still surfaces `EntradaMemberMissing`, unchanged.
10088 // The shape gate only intercepts inputs that could never
10089 // legitimately match a validated member.
10090 let mut s = three_member_spec();
10091 s.entrada.as_mut().unwrap().para = "phantom-shim".into();
10092 let err = s.validate().unwrap_err();
10093 assert!(
10094 matches!(
10095 err,
10096 AplicacaoError::EntradaMemberMissing { ref para }
10097 if para == "phantom-shim"
10098 ),
10099 "got {err:?}"
10100 );
10101 }
10102
10103 #[test]
10104 fn entrada_para_invalid_diagnostic_carries_offending_para() {
10105 // The diagnostic-shape pin: the error names the offending
10106 // `:para` value verbatim plus a non-empty parser-shaped
10107 // reason, so the author can grep their caixa.lisp for
10108 // `:para "<name>"` and fix it in one edit. Same diagnostic
10109 // shape as `MembroCaixaInvalid` (3f9d7a0),
10110 // `PlacementClusterInvalid` (6c8c00b), and
10111 // `ContratoCaixaInvalid` (8d5af6b).
10112 let mut s = three_member_spec();
10113 s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
10114 let err = s.validate().unwrap_err();
10115 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
10116 panic!("expected EntradaParaInvalid, got {err:?}");
10117 };
10118 assert_eq!(para, "BAD_NAME");
10119 assert!(
10120 !reason.is_empty(),
10121 "EntradaParaInvalid `reason` must carry a parser-shaped wording"
10122 );
10123 }
10124
10125 #[test]
10126 fn accepts_canonical_entrada_para_forms() {
10127 // Positive-control sweep covering the DNS-1123 label shapes a
10128 // caixa author is realistically going to write on `:entrada
10129 // :para`. Pin every leg so a future tightening that bans
10130 // (e.g.) digit-start identifiers surfaces here, mirroring
10131 // `accepts_canonical_membro_caixa_forms` and
10132 // `accepts_canonical_contrato_caixa_forms` on the peer name
10133 // axes.
10134 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
10135 let mut s = three_member_spec();
10136 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
10137 s.contratos = vec![contract_http(form, "catalog", "/x")];
10138 s.entrada = Some(Entrada {
10139 host: "checkout.quero.cloud".into(),
10140 para: form.into(),
10141 paths: vec!["/api".into()],
10142 port: 8080,
10143 });
10144 s.validate().unwrap_or_else(|e| {
10145 panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
10146 });
10147 }
10148 }
10149
10150 #[test]
10151 fn rejects_replicated_without_clusters() {
10152 let mut s = three_member_spec();
10153 s.placement.clusters = vec![];
10154 assert!(matches!(
10155 s.validate().unwrap_err(),
10156 AplicacaoError::PlacementWithoutClusters { .. }
10157 ));
10158 }
10159
10160 #[test]
10161 fn rejects_sharded_without_key() {
10162 let mut s = three_member_spec();
10163 s.placement.estrategia = PlacementStrategy::Sharded;
10164 s.placement.shard_key = None;
10165 s.placement.clusters = vec!["rio".into()];
10166 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
10167 }
10168
10169 #[test]
10170 fn sharded_with_key_validates() {
10171 let mut s = three_member_spec();
10172 s.placement.estrategia = PlacementStrategy::Sharded;
10173 s.placement.shard_key = Some("$tenantId".into());
10174 s.validate().unwrap();
10175 }
10176
10177 #[test]
10178 fn round_trip_via_json_preserves_shape() {
10179 let s = three_member_spec();
10180 let json = serde_json::to_string(&s.membros).unwrap();
10181 let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
10182 assert_eq!(back, s.membros);
10183
10184 let json = serde_json::to_string(&s.contratos).unwrap();
10185 let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
10186 assert_eq!(back, s.contratos);
10187
10188 let json = serde_json::to_string(&s.placement).unwrap();
10189 let back: Placement = serde_json::from_str(&json).unwrap();
10190 assert_eq!(back, s.placement);
10191
10192 let json = serde_json::to_string(&s.entrada).unwrap();
10193 let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
10194 assert_eq!(back, s.entrada);
10195 }
10196
10197 #[test]
10198 fn rate_limit_round_trip_seconds() {
10199 let policy = MeshPolicy {
10200 rate_limit: Some(RateLimit {
10201 rate: 100,
10202 window: Duration::from_secs(1),
10203 }),
10204 ..Default::default()
10205 };
10206 let json = serde_json::to_string(&policy).unwrap();
10207 assert!(json.contains("\"100/s\""));
10208 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10209 assert_eq!(back.rate_limit.unwrap().rate, 100);
10210 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
10211 }
10212
10213 #[test]
10214 fn rate_limit_round_trip_minutes() {
10215 let policy = MeshPolicy {
10216 rate_limit: Some(RateLimit {
10217 rate: 5000,
10218 window: Duration::from_secs(60),
10219 }),
10220 ..Default::default()
10221 };
10222 let json = serde_json::to_string(&policy).unwrap();
10223 assert!(json.contains("\"5000/m\""));
10224 }
10225
10226 #[test]
10227 fn circuit_breaker_round_trip() {
10228 let policy = MeshPolicy {
10229 circuit_breaker: Some(CircuitBreaker {
10230 max_failures: 5,
10231 window: Duration::from_secs(60),
10232 }),
10233 ..Default::default()
10234 };
10235 let json = serde_json::to_string(&policy).unwrap();
10236 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10237 assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
10238 assert_eq!(
10239 back.circuit_breaker.unwrap().window,
10240 Duration::from_secs(60)
10241 );
10242 }
10243
10244 #[test]
10245 fn rejects_http_contrato_without_endpoint() {
10246 let mut s = three_member_spec();
10247 s.contratos.push(WitContract {
10248 de: "cart".into(),
10249 para: "catalog".into(),
10250 wit: "wasi:http/proxy".into(),
10251 endpoint: None,
10252 subject: None,
10253 slot: None,
10254 });
10255 let err = s.validate().unwrap_err();
10256 assert!(matches!(
10257 err,
10258 AplicacaoError::ContratoMissingTarget {
10259 expected: WitTarget::HTTP_FIELD_NAME,
10260 ..
10261 }
10262 ));
10263 }
10264
10265 #[test]
10266 fn rejects_http_contrato_with_subject() {
10267 let mut s = three_member_spec();
10268 s.contratos.push(WitContract {
10269 de: "cart".into(),
10270 para: "catalog".into(),
10271 wit: "wasi:http/proxy".into(),
10272 endpoint: Some("/x".into()),
10273 subject: Some("not.allowed.here".into()),
10274 slot: None,
10275 });
10276 let err = s.validate().unwrap_err();
10277 assert!(matches!(
10278 err,
10279 AplicacaoError::ContratoWrongTarget {
10280 expected: WitTarget::HTTP_FIELD_NAME,
10281 ..
10282 }
10283 ));
10284 }
10285
10286 #[test]
10287 fn rejects_pubsub_contrato_without_subject() {
10288 let mut s = three_member_spec();
10289 s.contratos.push(WitContract {
10290 de: "cart".into(),
10291 para: "catalog".into(),
10292 wit: "nats:pub-sub".into(),
10293 endpoint: None,
10294 subject: None,
10295 slot: None,
10296 });
10297 let err = s.validate().unwrap_err();
10298 assert!(matches!(
10299 err,
10300 AplicacaoError::ContratoMissingTarget {
10301 expected: WitTarget::PUBSUB_FIELD_NAME,
10302 ..
10303 }
10304 ));
10305 }
10306
10307 #[test]
10308 fn rejects_pubsub_contrato_with_endpoint() {
10309 let mut s = three_member_spec();
10310 s.contratos.push(WitContract {
10311 de: "cart".into(),
10312 para: "catalog".into(),
10313 wit: "kafka:topic".into(),
10314 endpoint: Some("/wrong".into()),
10315 subject: Some("topic.x".into()),
10316 slot: None,
10317 });
10318 let err = s.validate().unwrap_err();
10319 assert!(matches!(
10320 err,
10321 AplicacaoError::ContratoWrongTarget {
10322 expected: WitTarget::PUBSUB_FIELD_NAME,
10323 ..
10324 }
10325 ));
10326 }
10327
10328 #[test]
10329 fn rejects_store_contrato_without_slot() {
10330 let mut s = three_member_spec();
10331 s.contratos.push(WitContract {
10332 de: "cart".into(),
10333 para: "catalog".into(),
10334 wit: "wasi:keyvalue/store".into(),
10335 endpoint: None,
10336 subject: None,
10337 slot: None,
10338 });
10339 let err = s.validate().unwrap_err();
10340 assert!(matches!(
10341 err,
10342 AplicacaoError::ContratoMissingTarget {
10343 expected: WitTarget::STORE_FIELD_NAME,
10344 ..
10345 }
10346 ));
10347 }
10348
10349 // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
10350
10351 #[test]
10352 fn rejects_http_contrato_with_empty_endpoint() {
10353 // `Some("")` for an HTTP endpoint passes the presence check
10354 // (target() previously returned WitTarget::Http { endpoint: "" })
10355 // but renders as a `path: ""` Cilium L7 rule that matches no
10356 // traffic. Same value-shape footgun closed for :entrada :paths
10357 // entries (eb3456d).
10358 let mut s = three_member_spec();
10359 s.contratos.push(WitContract {
10360 de: "cart".into(),
10361 para: "catalog".into(),
10362 wit: "wasi:http/proxy".into(),
10363 endpoint: Some(String::new()),
10364 subject: None,
10365 slot: None,
10366 });
10367 let err = s.validate().unwrap_err();
10368 assert!(
10369 matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
10370 if de == "cart" && para == "catalog"),
10371 "got {err:?}"
10372 );
10373 }
10374
10375 #[test]
10376 fn rejects_http_contrato_with_relative_endpoint() {
10377 // Cilium L7 :path + Gateway API PathPrefix both require a
10378 // leading `/`. Same shape required of :entrada :paths
10379 // (eb3456d). Lifted into target() so every consumer of the
10380 // typed WitTarget view inherits the guarantee.
10381 let mut s = three_member_spec();
10382 s.contratos.push(WitContract {
10383 de: "cart".into(),
10384 para: "catalog".into(),
10385 wit: "wasi:http/proxy".into(),
10386 endpoint: Some("products/:id".into()),
10387 subject: None,
10388 slot: None,
10389 });
10390 let err = s.validate().unwrap_err();
10391 assert!(
10392 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10393 if endpoint == "products/:id"),
10394 "got {err:?}"
10395 );
10396 }
10397
10398 #[test]
10399 fn rejects_pubsub_contrato_with_empty_subject() {
10400 // NATS / Kafka publish without a subject is a no-op subscribe;
10401 // never the author's intent. Same empty-string rejection as
10402 // :membros :caixa, :placement :clusters entries, :entrada
10403 // :paths entries — every value carried by every typed slot is
10404 // value-shape-checked at validate().
10405 let mut s = three_member_spec();
10406 s.contratos.push(WitContract {
10407 de: "cart".into(),
10408 para: "catalog".into(),
10409 wit: "nats:pub-sub".into(),
10410 endpoint: None,
10411 subject: Some(String::new()),
10412 slot: None,
10413 });
10414 let err = s.validate().unwrap_err();
10415 assert!(
10416 matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
10417 if de == "cart" && para == "catalog"),
10418 "got {err:?}"
10419 );
10420 }
10421
10422 #[test]
10423 fn rejects_store_contrato_with_empty_slot() {
10424 // An empty slot template addresses the bucket root, defeating
10425 // the per-key isolation the slot exists for — a footgun on
10426 // `wasi:keyvalue/store` whose closest analog is the empty
10427 // shard-key rejected on :placement Sharded (c7c7799).
10428 let mut s = three_member_spec();
10429 s.contratos.push(WitContract {
10430 de: "cart".into(),
10431 para: "catalog".into(),
10432 wit: "wasi:keyvalue/store".into(),
10433 endpoint: None,
10434 subject: None,
10435 slot: Some(String::new()),
10436 });
10437 let err = s.validate().unwrap_err();
10438 assert!(
10439 matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
10440 if de == "cart" && para == "catalog"),
10441 "got {err:?}"
10442 );
10443 }
10444
10445 #[test]
10446 fn http_contrato_root_endpoint_validates() {
10447 // Pin the boundary case: a single-`/` endpoint is the catch-all
10448 // form the Gateway HTTPRoute renderer falls back to when
10449 // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
10450 // must remain a valid contrato endpoint too.
10451 let mut s = three_member_spec();
10452 s.contratos.push(contract_http("cart", "catalog", "/"));
10453 s.validate().unwrap();
10454 }
10455
10456 // ── :contratos :endpoint value-shape gate ────────────────────────────
10457 //
10458 // Mirrors the `:entrada :paths` value-shape suite on the peer
10459 // HTTP-path axis. Until this gate landed `WitContract::target()`
10460 // only refused the empty string + the missing-leading-`/` form
10461 // (c4213a4); a structurally invalid endpoint passed validate and
10462 // landed verbatim as a Cilium L7 `path:` rule
10463 // (caixa-mesh/src/lib.rs:311) that either silently dropped all
10464 // traffic or was rejected at apply time by Cilium policy admission.
10465 // Every authoring footgun the K8s Gateway API webhook / Cilium
10466 // policy validator would catch on admission now becomes a caixa-
10467 // build-time `ContratoEndpointInvalid` with the offending
10468 // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
10469 // shape as `EntradaPathInvalid` on the sibling axis; same shared
10470 // predicate (`crate::render::is_gateway_api_http_path`) ensures
10471 // drift between the two axes' rule enforcement is a build error
10472 // at the predicate.
10473
10474 fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
10475 // Fresh spec per call so the would-be-duplicate edge
10476 // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
10477 // `three_member_spec`'s pre-existing
10478 // `(cart, catalog, …, /products/:id)` entry — only the
10479 // endpoint payload differs.
10480 let mut s = three_member_spec();
10481 s.contratos.push(contract_http("cart", "catalog", ep));
10482 s.validate().unwrap_err()
10483 }
10484
10485 #[test]
10486 fn rejects_http_contrato_endpoint_with_query() {
10487 // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
10488 // silently rendered as a Cilium L7 `path: "/charge?token=X"`
10489 // rule the L7 matcher would never satisfy.
10490 let err = contrato_endpoint_err("/charge?token=X");
10491 assert!(
10492 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10493 if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
10494 "got {err:?}"
10495 );
10496 }
10497
10498 #[test]
10499 fn rejects_http_contrato_endpoint_with_fragment() {
10500 let err = contrato_endpoint_err("/charge#frag");
10501 assert!(
10502 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10503 if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
10504 "got {err:?}"
10505 );
10506 }
10507
10508 #[test]
10509 fn rejects_http_contrato_endpoint_with_whitespace() {
10510 let err = contrato_endpoint_err("/foo bar");
10511 assert!(
10512 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10513 if endpoint == "/foo bar" && reason.contains("whitespace")),
10514 "got {err:?}"
10515 );
10516 }
10517
10518 #[test]
10519 fn rejects_http_contrato_endpoint_with_control_char() {
10520 let err = contrato_endpoint_err("/api/\x01bar");
10521 assert!(
10522 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10523 if endpoint == "/api/\x01bar" && reason.contains("control character")),
10524 "got {err:?}"
10525 );
10526 }
10527
10528 #[test]
10529 fn rejects_http_contrato_endpoint_with_non_ascii() {
10530 let err = contrato_endpoint_err("/api/café");
10531 assert!(
10532 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10533 if endpoint == "/api/café" && reason.contains("non-ASCII")),
10534 "got {err:?}"
10535 );
10536 }
10537
10538 #[test]
10539 fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
10540 let err = contrato_endpoint_err("/api//cart");
10541 assert!(
10542 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10543 if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
10544 "got {err:?}"
10545 );
10546 }
10547
10548 #[test]
10549 fn rejects_http_contrato_endpoint_with_dot_segment() {
10550 let err = contrato_endpoint_err("/api/./cart");
10551 assert!(
10552 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10553 if endpoint == "/api/./cart" && reason.contains("`.` segment")),
10554 "got {err:?}"
10555 );
10556 }
10557
10558 #[test]
10559 fn rejects_http_contrato_endpoint_with_parent_segment() {
10560 // Path-traversal in a contrato endpoint is the canonical
10561 // "L7 rule that the workload's HTTP server's path-resolution
10562 // logic interprets differently than the policy enforcer"
10563 // footgun. Rejected outright at validate time.
10564 let err = contrato_endpoint_err("/api/../etc");
10565 assert!(
10566 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10567 if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
10568 "got {err:?}"
10569 );
10570 }
10571
10572 #[test]
10573 fn rejects_http_contrato_endpoint_too_long() {
10574 // 1025-byte endpoint — one over the Gateway API
10575 // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
10576 // path matcher has no inherent length limit but the policy
10577 // CR itself rides through the K8s apiserver, which enforces
10578 // ConfigMap-shaped limits; sharing the Gateway API cap is the
10579 // conservative floor.
10580 let big = format!("/api/{}", "a".repeat(1020));
10581 assert_eq!(big.len(), 1025);
10582 let err = contrato_endpoint_err(&big);
10583 assert!(
10584 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10585 if endpoint == &big && reason.contains("max length of 1024")),
10586 "got {err:?}"
10587 );
10588 }
10589
10590 #[test]
10591 fn http_contrato_endpoint_max_length_validates() {
10592 // 1024-byte endpoint — exactly the cap. Boundary pin: drift
10593 // in the cap surfaces here and at
10594 // `rejects_http_contrato_endpoint_too_long` simultaneously,
10595 // mirroring `entrada_path_max_length_validates` on the peer
10596 // axis.
10597 let big = format!("/api/{}", "a".repeat(1019));
10598 assert_eq!(big.len(), 1024);
10599 let mut s = three_member_spec();
10600 s.contratos.push(contract_http("cart", "catalog", &big));
10601 s.validate().unwrap();
10602 }
10603
10604 #[test]
10605 fn http_contrato_endpoint_accepts_canonical_forms() {
10606 // Positive-set sweep: every canonical HTTP-path shape the
10607 // sibling `:entrada :paths` axis accepts (the bare-root `/`,
10608 // plain paths, hidden-file-style `.config` segments distinct
10609 // from the `.` segment, digit-bearing segments, the canonical
10610 // route-template `:param` form, trailing-slash form,
10611 // percent-encoded segments, the `/foo..bar` interior-`..`-
10612 // substring forms that are NOT `..` segments) must remain a
10613 // valid contrato endpoint too. Drift between this list and
10614 // the entrada path positive sweep surfaces at the shared
10615 // `is_gateway_api_http_path` substrate-side suite — one
10616 // source of truth. Uses a fresh `(payment, catalog)` edge so
10617 // none of the swept endpoints collide with the pre-existing
10618 // `(cart, catalog, /products/:id)` / `(cart, payment,
10619 // /charge)` entries in `three_member_spec`.
10620 for ep in [
10621 "/",
10622 "/charge",
10623 "/v1/charge",
10624 "/api/.config",
10625 "/products/:id",
10626 "/api/cart/",
10627 "/api/caf%C3%A9",
10628 "/foo..bar",
10629 "/...",
10630 ] {
10631 let mut s = three_member_spec();
10632 s.contratos.push(contract_http("payment", "catalog", ep));
10633 s.validate()
10634 .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
10635 }
10636 }
10637
10638 #[test]
10639 fn contrato_endpoint_empty_takes_precedence_over_invalid() {
10640 // Ordering pin: `ContratoEndpointEmpty` is the more self-
10641 // locating diagnostic on `""` and must lead — the value-
10642 // shape gate is only reached after the empty-check fires.
10643 // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
10644 // on the peer axis.
10645 let mut s = three_member_spec();
10646 s.contratos.push(WitContract {
10647 de: "cart".into(),
10648 para: "catalog".into(),
10649 wit: "wasi:http/proxy".into(),
10650 endpoint: Some(String::new()),
10651 subject: None,
10652 slot: None,
10653 });
10654 let err = s.validate().unwrap_err();
10655 assert!(
10656 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10657 "got {err:?}"
10658 );
10659 }
10660
10661 #[test]
10662 fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
10663 // Ordering pin: an endpoint without a leading `/` surfaces the
10664 // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
10665 // value-shape gate is only consulted on endpoints that already
10666 // satisfy the absolute-prefix invariant. Mirrors
10667 // `entrada_path_not_absolute_takes_precedence_over_invalid`.
10668 let err = contrato_endpoint_err("bad path");
10669 assert!(
10670 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10671 if endpoint == "bad path"),
10672 "got {err:?}"
10673 );
10674 }
10675
10676 #[test]
10677 fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
10678 // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
10679 // `:para` + a non-empty reason flow through verbatim so the
10680 // author can grep their caixa.lisp for the offending contrato
10681 // block and fix it in one edit. Same shape as
10682 // `entrada_path_diagnostic_carries_offending_path`.
10683 let err = contrato_endpoint_err("/api?q=1");
10684 match err {
10685 AplicacaoError::ContratoEndpointInvalid {
10686 de,
10687 para,
10688 endpoint,
10689 reason,
10690 } => {
10691 assert_eq!(de, "cart");
10692 assert_eq!(para, "catalog");
10693 assert_eq!(endpoint, "/api?q=1");
10694 assert!(!reason.is_empty(), "reason field must be non-empty");
10695 }
10696 other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
10697 }
10698 }
10699
10700 #[test]
10701 fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10702 // The compounding theorem: every &str inside a WitTarget
10703 // returned by target() is non-empty (and absolute, for Http).
10704 // Renderers downstream of typed_view() can rely on this
10705 // without re-checking — the type system carries the proof.
10706 let http = contract_http("cart", "catalog", "/x");
10707 match http.target().unwrap() {
10708 WitTarget::Http { endpoint } => {
10709 assert!(!endpoint.is_empty());
10710 assert!(endpoint.starts_with('/'));
10711 }
10712 other => panic!("expected Http, got {other:?}"),
10713 }
10714 let nats = WitContract {
10715 de: "a".into(),
10716 para: "b".into(),
10717 wit: "nats:pub-sub".into(),
10718 endpoint: None,
10719 subject: Some("topic.x".into()),
10720 slot: None,
10721 };
10722 match nats.target().unwrap() {
10723 WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10724 other => panic!("expected PubSub, got {other:?}"),
10725 }
10726 let kv = WitContract {
10727 de: "a".into(),
10728 para: "b".into(),
10729 wit: "wasi:keyvalue/store".into(),
10730 endpoint: None,
10731 subject: None,
10732 slot: Some("checkout/$orderId".into()),
10733 };
10734 match kv.target().unwrap() {
10735 WitTarget::Store { slot } => assert!(!slot.is_empty()),
10736 other => panic!("expected Store, got {other:?}"),
10737 }
10738 }
10739
10740 #[test]
10741 fn target_diagnostic_names_offending_endpoint_value() {
10742 // When the malformed endpoint string is non-trivial, the
10743 // diagnostic carries the actual value back to the author —
10744 // not a generic "endpoint malformed" error.
10745 let bad = WitContract {
10746 de: "src".into(),
10747 para: "dst".into(),
10748 wit: "wasi:http/proxy".into(),
10749 endpoint: Some("api/v1/charge".into()),
10750 subject: None,
10751 slot: None,
10752 };
10753 match bad.target().unwrap_err() {
10754 AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10755 assert_eq!(de, "src");
10756 assert_eq!(para, "dst");
10757 assert_eq!(endpoint, "api/v1/charge");
10758 }
10759 other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10760 }
10761 }
10762
10763 #[test]
10764 fn rejects_unknown_wit_with_target_set() {
10765 let mut s = three_member_spec();
10766 s.contratos.push(WitContract {
10767 de: "cart".into(),
10768 para: "catalog".into(),
10769 wit: "custom:exchange".into(),
10770 endpoint: Some("/leaked".into()),
10771 subject: None,
10772 slot: None,
10773 });
10774 let err = s.validate().unwrap_err();
10775 assert!(matches!(
10776 err,
10777 AplicacaoError::ContratoWrongTarget {
10778 expected: WitTarget::CAPABILITY_EXPECTED,
10779 ..
10780 }
10781 ));
10782 }
10783
10784 #[test]
10785 fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10786 // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10787 // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10788 // fourth arm of the same "which payload field name goes in the
10789 // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10790 // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10791 // consts cover on the peer HTTP / PubSub / Store arms
10792 // (`wit_target_field_name_pins_per_variant`). Until this lift
10793 // landed the byte-string sat twice — once inline in the
10794 // [`WitContract::target`] Capability-arm rejection at the
10795 // production dispatch, once in `rejects_unknown_wit_with_target_set`
10796 // pinning against the same literal — with no compile-time link
10797 // between them. Same "one canonical declaration, next to the
10798 // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10799 // lift established for the payload-less arm's human-readable
10800 // label axis; this test is the shape peer of
10801 // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10802 // pair (routes-through-const + scalar-value pin) on the
10803 // wrong-target diagnostic-scalar axis.
10804 //
10805 // Fail-before-pass-after was verified locally by mutating the
10806 // const declaration to `"capability"` — the scalar-value pin
10807 // below fires (`"capability" != "none"`) and the routes-through
10808 // assertion below still holds (production and const walk in
10809 // lockstep), which is the correct behavior: a rename on the
10810 // const drifts here first, not at a downstream consumer.
10811 assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10812
10813 let mut s = three_member_spec();
10814 s.contratos.push(WitContract {
10815 de: "cart".into(),
10816 para: "catalog".into(),
10817 wit: "custom:exchange".into(),
10818 endpoint: Some("/leaked".into()),
10819 subject: None,
10820 slot: None,
10821 });
10822 match s.validate().unwrap_err() {
10823 AplicacaoError::ContratoWrongTarget { expected, .. } => {
10824 assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10825 }
10826 other => panic!("expected ContratoWrongTarget, got {other:?}"),
10827 }
10828 }
10829
10830 #[test]
10831 fn unknown_wit_capability_only_validates() {
10832 let mut s = three_member_spec();
10833 s.contratos.push(WitContract {
10834 de: "cart".into(),
10835 para: "catalog".into(),
10836 // A WIT world we haven't yet shaped — accept it as a typed
10837 // capability edge so authors aren't blocked while the WIT
10838 // registry catches up. No payload field may be carried.
10839 wit: "custom:exchange".into(),
10840 endpoint: None,
10841 subject: None,
10842 slot: None,
10843 });
10844 s.validate().unwrap();
10845 let added = s.contratos.last().unwrap();
10846 assert_eq!(added.target().unwrap(), WitTarget::Capability);
10847 }
10848
10849 #[test]
10850 fn target_typed_view_round_trips_each_shape() {
10851 let http = contract_http("cart", "catalog", "/products/:id");
10852 assert_eq!(
10853 http.target().unwrap(),
10854 WitTarget::Http {
10855 endpoint: "/products/:id"
10856 }
10857 );
10858 let nats = WitContract {
10859 de: "a".into(),
10860 para: "b".into(),
10861 wit: "nats:pub-sub".into(),
10862 endpoint: None,
10863 subject: Some("topic.x".into()),
10864 slot: None,
10865 };
10866 assert_eq!(
10867 nats.target().unwrap(),
10868 WitTarget::PubSub { subject: "topic.x" }
10869 );
10870 let kv = WitContract {
10871 de: "a".into(),
10872 para: "b".into(),
10873 wit: "wasi:keyvalue/store".into(),
10874 endpoint: None,
10875 subject: None,
10876 slot: Some("checkout/$orderId".into()),
10877 };
10878 assert_eq!(
10879 kv.target().unwrap(),
10880 WitTarget::Store {
10881 slot: "checkout/$orderId"
10882 }
10883 );
10884 }
10885
10886 #[test]
10887 fn wit_contract_kind_predicates() {
10888 let http = contract_http("a", "b", "/x");
10889 assert!(http.is_http());
10890 assert!(!http.is_pubsub());
10891 assert!(!http.is_store());
10892 assert!(!http.is_capability());
10893
10894 let nats = WitContract {
10895 de: "a".into(),
10896 para: "b".into(),
10897 wit: "nats:pub-sub".into(),
10898 endpoint: None,
10899 subject: Some("topic.x".into()),
10900 slot: None,
10901 };
10902 assert!(nats.is_pubsub());
10903 assert!(!nats.is_http());
10904 assert!(!nats.is_capability());
10905
10906 let kv = WitContract {
10907 de: "a".into(),
10908 para: "b".into(),
10909 wit: "wasi:keyvalue/store".into(),
10910 endpoint: None,
10911 subject: None,
10912 slot: Some("checkout/$orderId".into()),
10913 };
10914 assert!(kv.is_store());
10915 assert!(!kv.is_http());
10916 assert!(!kv.is_capability());
10917
10918 // Fourth arm on the paired closed-set predicate family: the
10919 // payload-less capability edge that projects to the payload-
10920 // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10921 // Extends the 3-arm predicate sweep this test opened to cover
10922 // the closed 4-way partition [`WitContract::is_capability`]
10923 // closes on the pre-projection WIT-shape axis, matched with the
10924 // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10925 // 4-arm predicate set.
10926 let cap = WitContract {
10927 de: "a".into(),
10928 para: "b".into(),
10929 wit: "custom:capability-only".into(),
10930 endpoint: None,
10931 subject: None,
10932 slot: None,
10933 };
10934 assert!(cap.is_capability());
10935 assert!(!cap.is_http());
10936 assert!(!cap.is_pubsub());
10937 assert!(!cap.is_store());
10938 }
10939
10940 // ── :contratos :wit value-shape gate ─────────────────────────────────
10941 //
10942 // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10943 // dispatch-discriminator axis. Until this gate landed
10944 // `WitContract::target()` accepted any non-empty string and
10945 // silently demoted unrecognized shapes to a capability-only L4
10946 // edge — the canonical "I thought I had L7 HTTP routing, got
10947 // L4-only" footgun. Every authoring footgun the WIT registry's
10948 // own grammar rejects (uppercase, hyphen-for-colon typo,
10949 // whitespace, empty package, doubled `@`, …) now becomes a
10950 // caixa-build-time `ContratoWitInvalid` with the offending
10951 // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10952 // as `ContratoEndpointInvalid` on the sibling axis; same shared
10953 // predicate (`crate::render::is_wit_world_ref`) ensures drift
10954 // between any two axes' rule enforcement is a build error at the
10955 // predicate, not piecemeal across renderers.
10956
10957 fn contrato_wit_err(wit: &str) -> AplicacaoError {
10958 // Fresh spec per call so the new contract doesn't collide on
10959 // identity with `three_member_spec`'s pre-existing entries.
10960 // The new edge uses `(payment, catalog)` — a pair the fixture
10961 // doesn't already declare — with no payload field set, so the
10962 // wit-shape gate fires before any payload-shape arm.
10963 let mut s = three_member_spec();
10964 s.contratos.push(WitContract {
10965 de: "payment".into(),
10966 para: "catalog".into(),
10967 wit: wit.into(),
10968 endpoint: None,
10969 subject: None,
10970 slot: None,
10971 });
10972 s.validate().unwrap_err()
10973 }
10974
10975 #[test]
10976 fn rejects_wit_with_uppercase_namespace() {
10977 // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10978 // didn't match the lowercase `wasi:http/` prefix is_http() keys
10979 // off, so the dispatch fell through to the capability arm and
10980 // the contract silently rendered as an L4-only Cilium edge.
10981 // The new gate surfaces the uppercase typo at validate time
10982 // with the offending `:wit` named.
10983 let err = contrato_wit_err("WASI:http/proxy");
10984 assert!(
10985 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10986 if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10987 "got {err:?}"
10988 );
10989 }
10990
10991 #[test]
10992 fn rejects_wit_with_hyphen_for_colon_typo() {
10993 // The canonical "I forgot the `:` separator" typo — pre-gate
10994 // this passed as Capability silently, so the renderer emitted
10995 // an L4-only policy where the author expected L7 HTTP rules.
10996 let err = contrato_wit_err("wasi-http/proxy");
10997 assert!(
10998 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10999 if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
11000 "got {err:?}"
11001 );
11002 }
11003
11004 #[test]
11005 fn rejects_wit_with_multiple_colons() {
11006 // Doubled `:` — the namespace/package split has nowhere to
11007 // anchor, so the dispatch silently demotes to Capability.
11008 let err = contrato_wit_err("wasi:http:proxy");
11009 assert!(
11010 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11011 if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
11012 "got {err:?}"
11013 );
11014 }
11015
11016 #[test]
11017 fn rejects_wit_with_empty_package() {
11018 // `wasi:` — namespace alone with no package. Pre-gate this
11019 // failed neither the is_http nor is_pubsub nor is_store
11020 // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
11021 // a bare `wasi:`), so it silently demoted to Capability.
11022 let err = contrato_wit_err("wasi:");
11023 assert!(
11024 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11025 if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
11026 "got {err:?}"
11027 );
11028 }
11029
11030 #[test]
11031 fn rejects_wit_with_underscore() {
11032 // Underscore — WIT identifiers are kebab-case, same rule
11033 // DNS-1123 enforces on its peer axes. The diagnostic carries
11034 // the explicit "use `-` instead" remediation.
11035 let err = contrato_wit_err("wasi:http_proxy");
11036 assert!(
11037 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11038 if wit == "wasi:http_proxy" && reason.contains('_')),
11039 "got {err:?}"
11040 );
11041 }
11042
11043 #[test]
11044 fn rejects_wit_with_whitespace() {
11045 // Whitespace mid-token — the prefix check matches but the
11046 // package-and-onward parse silently demoted to Capability.
11047 let err = contrato_wit_err("wasi:http proxy");
11048 assert!(
11049 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11050 if wit == "wasi:http proxy" && reason.contains("whitespace")),
11051 "got {err:?}"
11052 );
11053 }
11054
11055 #[test]
11056 fn rejects_wit_with_non_ascii() {
11057 // Un-percent-encoded non-ASCII byte — the canonical "I copied
11058 // the package name from a doc with smart quotes / accented
11059 // characters" footgun.
11060 let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
11061 assert!(
11062 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11063 if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
11064 "got {err:?}"
11065 );
11066 }
11067
11068 #[test]
11069 fn rejects_wit_with_consecutive_hyphens() {
11070 // `pub--sub` — WIT identifiers join words with single hyphens.
11071 let err = contrato_wit_err("nats:pub--sub");
11072 assert!(
11073 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11074 if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
11075 "got {err:?}"
11076 );
11077 }
11078
11079 #[test]
11080 fn rejects_wit_with_trailing_at_no_version() {
11081 // `wasi:http/proxy@` — the version-suffix author started to
11082 // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
11083 // parser would reject this; surface it at validate time.
11084 let err = contrato_wit_err("wasi:http/proxy@");
11085 assert!(
11086 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11087 if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
11088 "got {err:?}"
11089 );
11090 }
11091
11092 #[test]
11093 fn rejects_wit_too_long() {
11094 // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
11095 // The legitimate-shape arms all pass (lowercase, single `:`,
11096 // kebab-case identifiers); only the cap arm fires. Surfaces
11097 // the paste-from-binary / accidental-multi-line-blob landing
11098 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
11099 // on the peer axis.
11100 let big = format!("wasi:{}", "a".repeat(124));
11101 assert_eq!(big.len(), 129);
11102 let err = contrato_wit_err(&big);
11103 assert!(
11104 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11105 if wit == &big && reason.contains("max length of 128")),
11106 "got {err:?}"
11107 );
11108 }
11109
11110 #[test]
11111 fn wit_max_length_validates() {
11112 // 128-byte WIT reference — exactly the cap. Boundary pin:
11113 // drift in the cap surfaces here and at `rejects_wit_too_long`
11114 // simultaneously, mirroring
11115 // `http_contrato_endpoint_max_length_validates` on the peer
11116 // axis.
11117 let big = format!("wasi:{}", "a".repeat(123));
11118 assert_eq!(big.len(), 128);
11119 let mut s = three_member_spec();
11120 s.contratos.push(WitContract {
11121 de: "payment".into(),
11122 para: "catalog".into(),
11123 wit: big,
11124 endpoint: None,
11125 subject: None,
11126 slot: None,
11127 });
11128 s.validate().unwrap();
11129 }
11130
11131 #[test]
11132 fn wit_accepts_canonical_forms_at_aplicacao_layer() {
11133 // Positive-set sweep through the AplicacaoSpec::validate
11134 // surface (rather than the substrate-side predicate directly)
11135 // — pins every shape the existing test fixtures + the
11136 // checkout-aplicacao example carry, so the gate's accept-set
11137 // matches the substrate's emit-set. Drift between this list
11138 // and `render::tests::wit_world_ref_accepts_canonical_forms`
11139 // surfaces at the substrate layer's positive sweep — one
11140 // source of truth for the rule.
11141 for wit in [
11142 "wasi:http/proxy",
11143 "wasi:keyvalue/store",
11144 "nats:pub-sub",
11145 "kafka:topic",
11146 "custom:exchange",
11147 "pleme:cap/audit",
11148 "wasi:http/proxy@0.2.0",
11149 ] {
11150 // Payload field paired to the dispatched WIT shape so the
11151 // shape-↔-target arm doesn't fire instead of the wit-shape
11152 // arm we're exercising. Routes off the same
11153 // `wit_shape_is_http` / `wit_shape_is_pubsub` /
11154 // `wit_shape_is_store` free functions the production
11155 // `WitContract::is_http` / `is_pubsub` / `is_store`
11156 // methods delegate to (both consult the lifted
11157 // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
11158 // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
11159 // future prefix addition to the routing accept-set
11160 // reaches this test's payload-dispatch arm by
11161 // construction — no per-test-site drift can hide a
11162 // shape-→-target-slot mismatch that would silently
11163 // demote a canonical `:wit` value to the
11164 // `(None, None, None)` capability-only arm and let the
11165 // `AplicacaoSpec::validate` positive sweep pass on a
11166 // shape it should exercise as HTTP / pub-sub / store.
11167 let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
11168 (Some("/x".into()), None, None)
11169 } else if wit_shape_is_pubsub(wit) {
11170 (None, Some("topic.x".into()), None)
11171 } else if wit_shape_is_store(wit) {
11172 (None, None, Some("bucket/$key".into()))
11173 } else {
11174 (None, None, None)
11175 };
11176 let mut s = three_member_spec();
11177 s.contratos.push(WitContract {
11178 de: "payment".into(),
11179 para: "catalog".into(),
11180 wit: wit.into(),
11181 endpoint,
11182 subject,
11183 slot,
11184 });
11185 s.validate()
11186 .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
11187 }
11188 }
11189
11190 #[test]
11191 fn wit_shape_predicates_accept_canonical_prefix_set() {
11192 // Positive-set sweep pinning every prefix in
11193 // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
11194 // WIT_STORE_SHAPE_PREFIXES against the three free-function
11195 // dispatch predicates. The six prefixes are the load-bearing
11196 // routing keys the substrate's WIT-shape dispatch consults
11197 // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
11198 // key/value-store-slot admission); any drift between the
11199 // free-function accept-set and this list surfaces here
11200 // rather than at apply time as a silent
11201 // shape-→-capability-only demotion.
11202 assert!(wit_shape_is_http("wasi:http/proxy"));
11203 assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
11204 assert!(wit_shape_is_http("http:incoming"));
11205
11206 assert!(wit_shape_is_pubsub("nats:pub-sub"));
11207 assert!(wit_shape_is_pubsub("kafka:topic"));
11208
11209 assert!(wit_shape_is_store("wasi:keyvalue/store"));
11210 assert!(wit_shape_is_store("kv:cache/session"));
11211 }
11212
11213 #[test]
11214 fn wit_shape_predicates_reject_uncanonical_forms() {
11215 // Negative-set pin: the six canonical prefixes are
11216 // lowercase-only (mirrors the `is_wit_world_ref` substrate
11217 // predicate's lowercase invariant — see its docstring on the
11218 // "I thought I had L7 HTTP routing, got L4-only" footgun).
11219 // The empty string, an uppercase-prefixed form, a hyphen-
11220 // instead-of-colon typo, and a bare kebab identifier all miss
11221 // every shape arm — reachable-by-construction only via the
11222 // `is_wit_world_ref` gate that admission-checks the `:wit`
11223 // value first, but pinned here so any future
11224 // free-function change (e.g. a case-insensitive
11225 // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
11226 // this unit level.
11227 for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
11228 assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
11229 assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
11230 assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
11231 }
11232 }
11233
11234 #[test]
11235 fn wit_shape_predicates_partition_canonical_set() {
11236 // Every canonical prefix routes to exactly one shape arm —
11237 // the three prefix sets are pairwise disjoint. Pins the
11238 // routing property [`WitContract::target`] relies on: an
11239 // `is_http()` return of `true` guarantees `is_pubsub()` and
11240 // `is_store()` return `false`, so the shape-→-target-slot
11241 // dispatch (endpoint vs subject vs slot) is unambiguous.
11242 // Drift (e.g. a future `"kv:"` moved into the HTTP set
11243 // without removal from the store set) would silently route
11244 // one prefix to two arms and the first-matching-arm order
11245 // becomes load-bearing — this pin surfaces it as a build
11246 // error instead.
11247 for prefix in WIT_HTTP_SHAPE_PREFIXES {
11248 let sample = format!("{prefix}x");
11249 assert!(wit_shape_is_http(&sample));
11250 assert!(!wit_shape_is_pubsub(&sample));
11251 assert!(!wit_shape_is_store(&sample));
11252 }
11253 for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
11254 let sample = format!("{prefix}x");
11255 assert!(!wit_shape_is_http(&sample));
11256 assert!(wit_shape_is_pubsub(&sample));
11257 assert!(!wit_shape_is_store(&sample));
11258 }
11259 for prefix in WIT_STORE_SHAPE_PREFIXES {
11260 let sample = format!("{prefix}x");
11261 assert!(!wit_shape_is_http(&sample));
11262 assert!(!wit_shape_is_pubsub(&sample));
11263 assert!(wit_shape_is_store(&sample));
11264 }
11265 }
11266
11267 #[test]
11268 fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
11269 // Positive pin: [`wit_shape_matches`] is exactly the
11270 // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
11271 // parameterized on the accept-set. Two-prefix accept-set,
11272 // one-prefix accept-set, and empty accept-set (which must
11273 // reject everything, including the empty string — an empty
11274 // `any()` fold returns `false`) all pinned so a future
11275 // reimplementation that swaps `starts_with` for `contains`,
11276 // `==`, or a case-folded comparator surfaces at unit-test
11277 // time.
11278 let two = &["wasi:http/", "http:"];
11279 assert!(wit_shape_matches("wasi:http/proxy", two));
11280 assert!(wit_shape_matches("http:incoming", two));
11281 assert!(!wit_shape_matches("wasi:keyvalue/store", two));
11282
11283 let one = &["nats:"];
11284 assert!(wit_shape_matches("nats:pub-sub", one));
11285 assert!(!wit_shape_matches("kafka:topic", one));
11286
11287 // Empty accept-set matches nothing — the identity element
11288 // for the disjunctive `any()` fold across the prefix set.
11289 // Reachable via a future `wit_shape_is_<name>` const paired
11290 // to a still-empty prefix table on a nascent shape-arm draft.
11291 let empty: &[&str] = &[];
11292 assert!(!wit_shape_matches("wasi:http/proxy", empty));
11293 assert!(!wit_shape_matches("", empty));
11294
11295 // starts_with, not contains: a prefix embedded mid-string
11296 // never matches. Pins the routing invariant [`WitContract::target`]
11297 // relies on (an authored `:wit "custom:wasi:http/"` string
11298 // does not silently route through the HTTP arm just because
11299 // it happens to contain the canonical HTTP prefix).
11300 assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
11301 }
11302
11303 #[test]
11304 fn wit_shape_predicates_delegate_to_wit_shape_matches() {
11305 // Equivalence pin: each per-shape predicate is exactly
11306 // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
11307 // every canonical prefix + the empty string + one negative
11308 // sample against every peer so a future predicate that grew
11309 // its own inline `iter().any(starts_with)` (rather than
11310 // delegating through the lifted combinator) drifts loudly here
11311 // — the peer-const table's contents must agree with the
11312 // predicate's accept-set by construction.
11313 let samples = [
11314 String::new(),
11315 "wasi:http/proxy".to_string(),
11316 "http:incoming".to_string(),
11317 "nats:pub-sub".to_string(),
11318 "kafka:topic".to_string(),
11319 "wasi:keyvalue/store".to_string(),
11320 "kv:cache/session".to_string(),
11321 "custom-shape".to_string(),
11322 "WASI:HTTP/proxy".to_string(),
11323 ];
11324 for wit in &samples {
11325 assert_eq!(
11326 wit_shape_is_http(wit),
11327 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11328 "wit_shape_is_http drifted from combinator on {wit:?}",
11329 );
11330 assert_eq!(
11331 wit_shape_is_pubsub(wit),
11332 wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
11333 "wit_shape_is_pubsub drifted from combinator on {wit:?}",
11334 );
11335 assert_eq!(
11336 wit_shape_is_store(wit),
11337 wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
11338 "wit_shape_is_store drifted from combinator on {wit:?}",
11339 );
11340 }
11341 }
11342
11343 #[test]
11344 fn wit_contract_shape_methods_delegate_to_free_functions() {
11345 // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
11346 // `is_store` are `&self` conveniences on top of the free
11347 // functions — for every canonical prefix the method's return
11348 // matches its free-function peer. Sweeps the union of the
11349 // three prefix sets so a future method that grew its own
11350 // inline prefix logic (rather than delegating) drifts loudly
11351 // here on the first prefix the free function accepts and the
11352 // method doesn't.
11353 for shape_set in [
11354 WIT_HTTP_SHAPE_PREFIXES,
11355 WIT_PUBSUB_SHAPE_PREFIXES,
11356 WIT_STORE_SHAPE_PREFIXES,
11357 ] {
11358 for prefix in shape_set {
11359 let c = WitContract {
11360 de: "cart".into(),
11361 para: "catalog".into(),
11362 wit: format!("{prefix}x"),
11363 endpoint: None,
11364 subject: None,
11365 slot: None,
11366 };
11367 assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
11368 assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
11369 assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
11370 assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11371 }
11372 }
11373 // Capability-arm delegation sweep: two representative
11374 // Capability-shaped `:wit` values (a bare non-prefix-matching
11375 // WIT world, the deliberately-shaped empty string
11376 // [`WitContract::is_capability`]'s docstring calls out as
11377 // syntactically Capability). Extends the free-function
11378 // delegation pin onto the fourth arm so a future
11379 // [`WitContract::is_capability`] rewrite that grew an inline
11380 // prefix-set scan (rather than delegating through
11381 // [`wit_shape_is_capability`]) drifts loudly here on the first
11382 // Capability-shaped sample.
11383 for wit in ["custom:capability-only", ""] {
11384 let c = WitContract {
11385 de: "cart".into(),
11386 para: "catalog".into(),
11387 wit: wit.into(),
11388 endpoint: None,
11389 subject: None,
11390 slot: None,
11391 };
11392 assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11393 }
11394 }
11395
11396 #[test]
11397 fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
11398 // 4-way partition-witness pin on the raw `&str` axis: for every
11399 // canonical prefix in the three payload-arm accept-sets,
11400 // exactly one of the four [`wit_shape_is_http`] /
11401 // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11402 // [`wit_shape_is_capability`] free functions returns `true` and
11403 // the other three return `false` — the four-arm partition
11404 // witness that locks the free-function WIT-shape-classifier
11405 // family into a partition of the `:contratos :wit` axis
11406 // load-bearing. Peer of the sibling [`WitContract`]-surface
11407 // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
11408 // partition pin — extends the discipline onto the raw `&str`
11409 // axis so any future arm addition (a hypothetical
11410 // `wasi:sockets/*` transport-layer shape, an `oci:*`
11411 // capability-import carrier per the sibling
11412 // [`wit_shape_matches`] docstring's trajectory bullet) that
11413 // landed on one of the payload-arm free functions without
11414 // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
11415 // here as two arms returning `true` simultaneously at
11416 // caixa-core build time rather than a silent per-consumer
11417 // misclassification at renderer emit time.
11418 for shape_set in [
11419 WIT_HTTP_SHAPE_PREFIXES,
11420 WIT_PUBSUB_SHAPE_PREFIXES,
11421 WIT_STORE_SHAPE_PREFIXES,
11422 ] {
11423 for prefix in shape_set {
11424 let wit = format!("{prefix}x");
11425 let hits = [
11426 wit_shape_is_http(&wit),
11427 wit_shape_is_pubsub(&wit),
11428 wit_shape_is_store(&wit),
11429 wit_shape_is_capability(&wit),
11430 ]
11431 .iter()
11432 .filter(|&&b| b)
11433 .count();
11434 assert_eq!(
11435 hits,
11436 1,
11437 "raw-&str WIT-shape 4-way predicate partition must \
11438 admit exactly one arm per canonical prefix; got {hits} \
11439 hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
11440 is_capability={})",
11441 wit_shape_is_http(&wit),
11442 wit_shape_is_pubsub(&wit),
11443 wit_shape_is_store(&wit),
11444 wit_shape_is_capability(&wit),
11445 );
11446 }
11447 }
11448 // Capability-arm sweep on the raw `&str` axis: two
11449 // representative Capability-shaped `:wit` values (a bare non-
11450 // prefix-matching WIT world, the deliberately-shaped empty
11451 // string the pure classifier still admits per
11452 // [`wit_shape_is_capability`]'s docstring). Both must land on
11453 // the fourth arm exclusively so the partition witness holds
11454 // across the full 4-arm closure on the raw `&str` axis.
11455 for wit in ["custom:capability-only", ""] {
11456 let hits = [
11457 wit_shape_is_http(wit),
11458 wit_shape_is_pubsub(wit),
11459 wit_shape_is_store(wit),
11460 wit_shape_is_capability(wit),
11461 ]
11462 .iter()
11463 .filter(|&&b| b)
11464 .count();
11465 assert_eq!(
11466 hits, 1,
11467 "raw-&str WIT-shape 4-way predicate partition must \
11468 admit exactly one arm on Capability-shaped wit={wit:?}"
11469 );
11470 assert!(
11471 wit_shape_is_capability(wit),
11472 "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
11473 );
11474 }
11475 }
11476
11477 #[test]
11478 fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
11479 // Composition-witness pin: [`wit_shape_is_capability`] is the
11480 // exact-inverse disjunction of the sibling payload-arm free-
11481 // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
11482 // / [`wit_shape_is_store`]. A future reimplementation that
11483 // grew its own prefix-set scan (e.g. inlining a fourth
11484 // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
11485 // not own today) rather than delegating to the sibling trio
11486 // would drift loudly here — the composition contract binds the
11487 // fourth-arm free-function predicate to the exact-inverse of
11488 // the three payload-arm free-function predicates, so any
11489 // rebrand of any prefix-set const flows through
11490 // [`wit_shape_is_capability`] by construction without a
11491 // coordinated per-consumer rewrite. Peer of the sibling
11492 // [`WitContract`]-surface
11493 // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
11494 // composition pin — extends the discipline onto the raw
11495 // `&str` axis.
11496 let mut cases: Vec<String> = Vec::new();
11497 for shape_set in [
11498 WIT_HTTP_SHAPE_PREFIXES,
11499 WIT_PUBSUB_SHAPE_PREFIXES,
11500 WIT_STORE_SHAPE_PREFIXES,
11501 ] {
11502 for prefix in shape_set {
11503 cases.push(format!("{prefix}x"));
11504 }
11505 }
11506 cases.push("custom:capability-only".to_string());
11507 cases.push(String::new());
11508 for wit in cases {
11509 assert_eq!(
11510 wit_shape_is_capability(&wit),
11511 !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
11512 "wit_shape_is_capability must equal \
11513 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
11514 at wit={wit:?}"
11515 );
11516 }
11517 }
11518
11519 #[test]
11520 fn wit_shape_classifier_family_is_const_fn() {
11521 // Fail-before-pass-after pin on the 4-arm free-function WIT-
11522 // shape classifier family's `const`-eval posture. Each of the
11523 // four peer classifiers ([`wit_shape_is_http`] /
11524 // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11525 // [`wit_shape_is_capability`]) and the underlying combinator
11526 // [`wit_shape_matches`] must be `pub const fn` — any future
11527 // accidental downgrade to non-`const` fails the `const fn`
11528 // wrappers below at caixa-core build time with E0015
11529 // (`cannot call non-const function`), strictly stronger than
11530 // a runtime `assert!` and strictly stronger than the module-
11531 // scope `const _: () = assert!(…)` pins immediately after the
11532 // classifier declarations (those anchor specific accept-set
11533 // truth-table entries; this pin anchors the `const` posture
11534 // itself via `const fn` wrappers that are only well-formed
11535 // when the callee is itself `const fn`).
11536 //
11537 // Verified fail-before-pass-after by locally reverting
11538 // `pub const fn` → `pub fn` on each classifier and observing
11539 // E0015 at every corresponding wrapper call site (build
11540 // error, no test-time surface), then restoring `pub const fn`
11541 // and observing the pin pass at test time. Peer of the
11542 // sibling M3
11543 // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11544 // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11545 // M2
11546 // [`child_spec_restart_accessor_is_const_fn`] /
11547 // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11548 // and M3
11549 // [`placement_estrategia_accessor_is_const_fn`] /
11550 // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11551 // sibling `const`-eval-surface-pass axes.
11552 const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
11553 wit_shape_matches(wit, prefixes)
11554 }
11555 const fn http_via_const_fn(wit: &str) -> bool {
11556 wit_shape_is_http(wit)
11557 }
11558 const fn pubsub_via_const_fn(wit: &str) -> bool {
11559 wit_shape_is_pubsub(wit)
11560 }
11561 const fn store_via_const_fn(wit: &str) -> bool {
11562 wit_shape_is_store(wit)
11563 }
11564 const fn capability_via_const_fn(wit: &str) -> bool {
11565 wit_shape_is_capability(wit)
11566 }
11567 // Sweep one canonical accept-set sample per arm plus the
11568 // payload-less/empty capability samples, asserting the
11569 // wrapper and direct dispatches agree byte-for-byte across
11570 // the closed 4-arm partition.
11571 let cases: [(&str, bool, bool, bool, bool); 6] = [
11572 ("wasi:http/proxy", true, false, false, false),
11573 ("http:incoming", true, false, false, false),
11574 ("nats:events", false, true, false, false),
11575 ("kafka:topic", false, true, false, false),
11576 ("wasi:keyvalue/store", false, false, true, false),
11577 ("kv:cache", false, false, true, false),
11578 ];
11579 for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
11580 assert_eq!(
11581 matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
11582 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11583 "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
11584 );
11585 assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
11586 assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
11587 assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
11588 assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11589 assert_eq!(wit_shape_is_http(wit), is_http);
11590 assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
11591 assert_eq!(wit_shape_is_store(wit), is_store);
11592 }
11593 // Payload-less capability arm (the 4th partition arm).
11594 let capability_samples: [&str; 3] =
11595 ["wasi:filesystem/preopens", "custom:capability-only", ""];
11596 for wit in capability_samples {
11597 assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11598 assert!(wit_shape_is_capability(wit));
11599 assert!(!wit_shape_is_http(wit));
11600 assert!(!wit_shape_is_pubsub(wit));
11601 assert!(!wit_shape_is_store(wit));
11602 }
11603 }
11604
11605 #[test]
11606 fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
11607 // Composition-witness pin: [`wit_shape_matches`] agrees with
11608 // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
11609 // dispatch (the prior non-`const` implementation) across
11610 // boundary lengths — empty `wit`, empty prefix, one-byte
11611 // slack, prefix longer than `wit`, one-byte trailing slack.
11612 // The rewrite to a byte-level manual starts_with loop (the
11613 // enabler for the `pub const fn` posture) must not change any
11614 // truth-table entry on the canonical accept-set — this pin
11615 // sweeps a targeted boundary corpus and asserts byte-for-byte
11616 // agreement, locking the const-fn rewrite's semantics against
11617 // the prior iterator body by construction.
11618 let prefixes = &["wasi:http/", "http:"][..];
11619 let cases: [(&str, bool); 12] = [
11620 ("wasi:http/proxy", true),
11621 ("wasi:http/", true), // exact-length match on prefix
11622 ("wasi:http", false), // one byte short
11623 ("http:", true),
11624 ("http:incoming", true),
11625 ("http", false), // one byte short
11626 ("", false),
11627 ("wasi:https/proxy", false),
11628 ("nats:events", false),
11629 ("HTTPS:", false), // uppercase — no case-fold in classifier
11630 ("wasi:HTTP/proxy", false),
11631 ("wasi:http", false),
11632 ];
11633 for (wit, expected) in cases {
11634 assert_eq!(
11635 wit_shape_matches(wit, prefixes),
11636 expected,
11637 "wit_shape_matches disagrees with reference at wit={wit:?}",
11638 );
11639 // Byte-equal to the iterator body it replaced.
11640 let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
11641 assert_eq!(
11642 wit_shape_matches(wit, prefixes),
11643 via_iter,
11644 "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
11645 );
11646 }
11647 // Empty prefix set → always false regardless of `wit`.
11648 let empty: &[&str] = &[];
11649 assert!(!wit_shape_matches("", empty));
11650 assert!(!wit_shape_matches("wasi:http/proxy", empty));
11651 // Empty prefix inside a non-empty set → always true (every
11652 // string starts with the empty string, matching the
11653 // iterator body's semantics on `str::starts_with("")`).
11654 let contains_empty: &[&str] = &["nats:", ""];
11655 assert!(wit_shape_matches("", contains_empty));
11656 assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
11657 }
11658
11659 #[test]
11660 fn wit_contract_is_capability_partitions_the_wit_shape_space() {
11661 // 4-way partition-witness pin: for every canonical prefix in
11662 // the payload-arm accept-sets, exactly one of the four
11663 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11664 // [`WitContract::is_store`] / [`WitContract::is_capability`]
11665 // predicates returns `true` and the other three return `false`
11666 // — the four-arm partition witness that locks the substrate's
11667 // WIT-shape-space closure on the pre-projection axis load-
11668 // bearing. A future arm addition (a hypothetical fourth
11669 // payload-shape prefix set, a `wasi:sockets/*` transport-layer
11670 // shape) that landed on one of the payload-arm predicates
11671 // without shrinking [`WitContract::is_capability`]'s accept-set
11672 // would surface here as two arms returning `true` simultaneously
11673 // — a partition-witness break the pin catches at caixa-core
11674 // build time rather than a silent per-consumer misclassification
11675 // at renderer emit time. Peer of the sibling `WitTarget`-side
11676 // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
11677 // partition-witness pin on the post-projection payload-scalar
11678 // arm-set — extends the discipline onto the pre-projection
11679 // 4-arm shape-space.
11680 for shape_set in [
11681 WIT_HTTP_SHAPE_PREFIXES,
11682 WIT_PUBSUB_SHAPE_PREFIXES,
11683 WIT_STORE_SHAPE_PREFIXES,
11684 ] {
11685 for prefix in shape_set {
11686 let c = WitContract {
11687 de: "cart".into(),
11688 para: "catalog".into(),
11689 wit: format!("{prefix}x"),
11690 endpoint: None,
11691 subject: None,
11692 slot: None,
11693 };
11694 let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11695 .iter()
11696 .filter(|&&b| b)
11697 .count();
11698 assert_eq!(
11699 hits,
11700 1,
11701 "WitContract WIT-shape 4-way predicate partition must \
11702 admit exactly one arm per canonical prefix; got {hits} \
11703 hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
11704 is_capability={})",
11705 c.wit,
11706 c.is_http(),
11707 c.is_pubsub(),
11708 c.is_store(),
11709 c.is_capability(),
11710 );
11711 }
11712 }
11713 // Capability-arm sweep: two representative capability shapes
11714 // (a bare WIT world outside the three payload-arm prefix sets,
11715 // and the deliberately-shaped empty string that
11716 // [`crate::render::is_wit_world_ref`] rejects at
11717 // [`WitContract::target`] time but which the pure classifier
11718 // still admits — see the method docstring's "purely syntactic
11719 // classification" note). Both must land on the fourth arm
11720 // exclusively, so the partition witness holds across the full
11721 // 4-arm closure.
11722 for wit in ["custom:capability-only", ""] {
11723 let c = WitContract {
11724 de: "cart".into(),
11725 para: "catalog".into(),
11726 wit: wit.into(),
11727 endpoint: None,
11728 subject: None,
11729 slot: None,
11730 };
11731 let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11732 .iter()
11733 .filter(|&&b| b)
11734 .count();
11735 assert_eq!(
11736 hits, 1,
11737 "WitContract WIT-shape 4-way predicate partition must \
11738 admit exactly one arm on Capability-shaped wit={wit:?}"
11739 );
11740 assert!(
11741 c.is_capability(),
11742 "wit={wit:?} must project onto the Capability arm"
11743 );
11744 }
11745 }
11746
11747 #[test]
11748 fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
11749 // Composition-witness pin: [`WitContract::is_capability`] is the
11750 // exact-inverse disjunction of the sibling payload-arm predicate
11751 // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11752 // [`WitContract::is_store`]. A future reimplementation that
11753 // grew its own prefix-set scan (e.g. inlining a fourth
11754 // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
11755 // own today) rather than delegating to the sibling trio would
11756 // drift loudly here — the composition contract binds the
11757 // fourth-arm predicate to the exact-inverse of the three
11758 // payload-arm predicates, so any rebrand of any prefix-set const
11759 // flows through this method by construction without a
11760 // coordinated per-consumer rewrite. Sweeps the union of the
11761 // three payload-arm prefix sets plus two Capability-shaped
11762 // shapes (a bare non-prefix-matching WIT world, the deliberately-
11763 // empty string the pure classifier still admits per the method
11764 // docstring's "purely syntactic classification" note).
11765 let mut cases: Vec<String> = Vec::new();
11766 for shape_set in [
11767 WIT_HTTP_SHAPE_PREFIXES,
11768 WIT_PUBSUB_SHAPE_PREFIXES,
11769 WIT_STORE_SHAPE_PREFIXES,
11770 ] {
11771 for prefix in shape_set {
11772 cases.push(format!("{prefix}x"));
11773 }
11774 }
11775 cases.push("custom:capability-only".to_string());
11776 cases.push(String::new());
11777 for wit in cases {
11778 let c = WitContract {
11779 de: "cart".into(),
11780 para: "catalog".into(),
11781 wit: wit.clone(),
11782 endpoint: None,
11783 subject: None,
11784 slot: None,
11785 };
11786 assert_eq!(
11787 c.is_capability(),
11788 !c.is_http() && !c.is_pubsub() && !c.is_store(),
11789 "WitContract::is_capability must equal \
11790 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
11791 );
11792 }
11793 }
11794
11795 #[test]
11796 fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
11797 // Cross-projection-witness pin: whenever [`WitContract::target`]
11798 // succeeds, the pre-projection [`WitContract::is_capability`]
11799 // classification agrees with the post-projection
11800 // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
11801 // predicate — the 4-arm typed partition on the substrate's
11802 // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
11803 // partition on the pre-projection axis line up by construction.
11804 // A future divergence between the two axes (a peer
11805 // [`WitTarget`] variant addition that landed on the typed-view
11806 // surface without a peer prefix-set + [`WitContract`] predicate
11807 // extension, or vice versa) would surface here at caixa-core
11808 // build time rather than a silent per-consumer split at renderer
11809 // emit time. Peer of the sibling pre-/post-projection
11810 // agreement pins the payload-carrier trio
11811 // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11812 // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
11813 // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
11814 // post-projection — b11bb49 trio lift) already carry across the
11815 // three payload arms — this pin closes the pair on the fourth
11816 // payload-less arm.
11817 let http = WitContract {
11818 de: "cart".into(),
11819 para: "catalog".into(),
11820 wit: "wasi:http/proxy".into(),
11821 endpoint: Some("/x".into()),
11822 subject: None,
11823 slot: None,
11824 };
11825 assert!(!http.is_capability());
11826 assert!(!http.target().unwrap().is_capability());
11827
11828 let nats = WitContract {
11829 de: "cart".into(),
11830 para: "catalog".into(),
11831 wit: "nats:pub-sub".into(),
11832 endpoint: None,
11833 subject: Some("events.x".into()),
11834 slot: None,
11835 };
11836 assert!(!nats.is_capability());
11837 assert!(!nats.target().unwrap().is_capability());
11838
11839 let kv = WitContract {
11840 de: "cart".into(),
11841 para: "catalog".into(),
11842 wit: "wasi:keyvalue/store".into(),
11843 endpoint: None,
11844 subject: None,
11845 slot: Some("checkout/$orderId".into()),
11846 };
11847 assert!(!kv.is_capability());
11848 assert!(!kv.target().unwrap().is_capability());
11849
11850 let cap = WitContract {
11851 de: "cart".into(),
11852 para: "catalog".into(),
11853 wit: "custom:capability-only".into(),
11854 endpoint: None,
11855 subject: None,
11856 slot: None,
11857 };
11858 assert!(cap.is_capability());
11859 assert!(cap.target().unwrap().is_capability());
11860 }
11861
11862 #[test]
11863 fn wit_contract_pre_projection_accessor_family_is_const_fn() {
11864 // Fail-before-pass-after pin on the [`WitContract`] pre-
11865 // projection accessor family's `const`-eval-surface posture.
11866 // Each of the three per-`:contratos` byte-string scalar
11867 // accessors ([`WitContract::source`] / [`WitContract::destination`]
11868 // / [`WitContract::world_ref`], each projecting through
11869 // `String::as_str` — const-stable since Rust 1.87, well within
11870 // the workspace MSRV) and each of the four peer WIT-shape
11871 // predicates ([`WitContract::is_http`] /
11872 // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
11873 // [`WitContract::is_capability`], each composing
11874 // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
11875 // free-function classifier family the sibling
11876 // [`wit_shape_classifier_family_is_const_fn`] pin already
11877 // anchors on the raw `&str → bool` axis) must be `pub const fn`
11878 // — any future accidental downgrade to non-`const` fails the
11879 // `const fn` wrappers below at caixa-core build time with E0015
11880 // (`cannot call non-const function`), strictly stronger than a
11881 // runtime `assert!` and strictly stronger than a
11882 // module-scope `const _: () = assert!(…)` pin (which cannot be
11883 // formed on a `&WitContract` fixture because the type's
11884 // `String` / `Option<String>` carriers rule out `const`-context
11885 // construction; the `const fn` wrapper is the load-bearing
11886 // shape that side-steps the destructor-in-const restriction on
11887 // the value axis while still pinning the `const`-fn posture on
11888 // the callee).
11889 //
11890 // Peer of the sibling free-function classifier pin
11891 // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
11892 // raw `&str → bool` axis — this pin extends the same
11893 // `const`-eval-surface discipline onto the peer method surface
11894 // that composes through those free-function classifiers, and
11895 // simultaneously onto the underlying per-`:contratos`
11896 // byte-string scalar-accessor trio each predicate reads
11897 // through. Sibling of the peer M3
11898 // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11899 // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11900 // M2
11901 // [`child_spec_restart_accessor_is_const_fn`] /
11902 // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11903 // and M3
11904 // [`placement_estrategia_accessor_is_const_fn`] /
11905 // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11906 // sibling `const`-eval-surface-pass axes.
11907 const fn source_via_const_fn(c: &WitContract) -> &str {
11908 c.source()
11909 }
11910 const fn destination_via_const_fn(c: &WitContract) -> &str {
11911 c.destination()
11912 }
11913 const fn world_ref_via_const_fn(c: &WitContract) -> &str {
11914 c.world_ref()
11915 }
11916 const fn is_http_via_const_fn(c: &WitContract) -> bool {
11917 c.is_http()
11918 }
11919 const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
11920 c.is_pubsub()
11921 }
11922 const fn is_store_via_const_fn(c: &WitContract) -> bool {
11923 c.is_store()
11924 }
11925 const fn is_capability_via_const_fn(c: &WitContract) -> bool {
11926 c.is_capability()
11927 }
11928 // Sweep one canonical accept-set sample per WIT-shape arm plus
11929 // a payload-less capability sample, asserting the wrapper and
11930 // direct dispatches agree byte-for-byte across the closed
11931 // 4-arm partition on both the scalar-accessor trio and the
11932 // WIT-shape-predicate family.
11933 for (wit, is_http, is_pubsub, is_store, is_capability) in [
11934 ("wasi:http/proxy", true, false, false, false),
11935 ("http:incoming", true, false, false, false),
11936 ("nats:events", false, true, false, false),
11937 ("kafka:topic", false, true, false, false),
11938 ("wasi:keyvalue/store", false, false, true, false),
11939 ("kv:cache", false, false, true, false),
11940 ("custom:capability-only", false, false, false, true),
11941 ("", false, false, false, true),
11942 ] {
11943 let c = WitContract {
11944 de: "cart".into(),
11945 para: "catalog".into(),
11946 wit: wit.into(),
11947 endpoint: None,
11948 subject: None,
11949 slot: None,
11950 };
11951 assert_eq!(source_via_const_fn(&c), c.source());
11952 assert_eq!(destination_via_const_fn(&c), c.destination());
11953 assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
11954 assert_eq!(is_http_via_const_fn(&c), c.is_http());
11955 assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
11956 assert_eq!(is_store_via_const_fn(&c), c.is_store());
11957 assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
11958 assert_eq!(c.source(), "cart");
11959 assert_eq!(c.destination(), "catalog");
11960 assert_eq!(c.world_ref(), wit);
11961 assert_eq!(c.is_http(), is_http);
11962 assert_eq!(c.is_pubsub(), is_pubsub);
11963 assert_eq!(c.is_store(), is_store);
11964 assert_eq!(c.is_capability(), is_capability);
11965 }
11966 }
11967
11968 #[test]
11969 fn wit_contract_identity_projection_accessor_is_const_fn() {
11970 // Fail-before-pass-after pin on the [`WitContract::identity`]
11971 // six-arm composite-projection accessor's `const`-eval-surface
11972 // posture. The accessor projects the typed edge's six identity
11973 // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
11974 // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
11975 // every callee is itself `pub const fn` ([`WitContract::source`]
11976 // / [`WitContract::destination`] / [`WitContract::world_ref`]
11977 // through `String::as_str`, const-stable since Rust 1.87;
11978 // [`WitContract::endpoint`] / [`WitContract::subject`] /
11979 // [`WitContract::slot`] through the sibling `match &self
11980 // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
11981 // 0650f64 closed the const-eval surface on) and the tuple
11982 // constructor from borrowed-reference / `Option`-of-borrowed-
11983 // reference arms is trivially const. Any future accidental
11984 // downgrade fails the `identity_via_const_fn` wrapper at
11985 // caixa-core build time with E0015 (`cannot call non-const
11986 // method`), strictly stronger than a runtime `assert!` and
11987 // strictly stronger than a module-scope `const _: () =
11988 // assert!(…)` pin (which cannot be formed on a `&WitContract`
11989 // fixture because the type's `String` / `Option<String>`
11990 // carriers rule out `const`-context value construction; the
11991 // `const fn` wrapper is the load-bearing shape that side-steps
11992 // the destructor-in-const restriction on the value axis while
11993 // still pinning the `const`-fn posture on the callee — mirror
11994 // of the sibling
11995 // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11996 // pin's discipline verbatim on the peer scalar-accessor
11997 // surface).
11998 //
11999 // Peer of the sibling
12000 // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
12001 // (279823b) pin on the six per-`:contratos` scalar-accessor
12002 // callees this composite-projection reads through — where that
12003 // pin anchors the const-eval surface at the six individual
12004 // scalar-accessor arms, this pin extends the same posture onto
12005 // the composite six-tuple projection every consumer that dedups
12006 // typed edges on the [`ContratoIdentity`] axis keys off (the
12007 // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
12008 // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
12009 // materializer's per-edge identity-based admission webhook; a
12010 // future L7 policy-emitter that shards CNPs by identity-tuple
12011 // rather than by name). Same fail-before-pass-after wrapper
12012 // discipline as the peer M2 / M3 accessor-family pins on the
12013 // sibling `const`-eval-surface passes.
12014 const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
12015 c.identity()
12016 }
12017 // Sweep one canonical WIT-shape sample per payload-carrier arm
12018 // plus a payload-less capability sample so the pin exercises
12019 // both `Some(_)`-carrying and `None`-carrying arms on all three
12020 // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
12021 // / `:slot`) — every wrapper dispatch must agree byte-for-byte
12022 // with the direct method call on every arm of the closed WIT-
12023 // shape partition.
12024 for (wit, endpoint, subject, slot) in [
12025 ("wasi:http/proxy", Some("/checkout"), None, None),
12026 ("http:incoming", Some("/api"), None, None),
12027 ("nats:events", None, Some("orders.placed"), None),
12028 ("kafka:topic", None, Some("orders.stream"), None),
12029 ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
12030 ("kv:cache", None, None, Some("session/{token}")),
12031 ("custom:capability-only", None, None, None),
12032 ] {
12033 let c = WitContract {
12034 de: "cart".into(),
12035 para: "catalog".into(),
12036 wit: wit.into(),
12037 endpoint: endpoint.map(str::to_string),
12038 subject: subject.map(str::to_string),
12039 slot: slot.map(str::to_string),
12040 };
12041 assert_eq!(identity_via_const_fn(&c), c.identity());
12042 assert_eq!(
12043 c.identity(),
12044 ("cart", "catalog", wit, endpoint, subject, slot,),
12045 );
12046 }
12047 }
12048
12049 #[test]
12050 fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
12051 // Fail-before-pass-after pin on the four M3 mesh-slot
12052 // `String → &str` scalar accessors ([`Membro::nome`] /
12053 // [`Membro::versao_requirement`] on the per-`:membros` axis,
12054 // [`Entrada::hostname`] / [`Entrada::destination`] on the
12055 // per-`:entrada` axis) — each projects the typed slot's
12056 // [`String`] storage through the `pub const fn`
12057 // [`String::as_str`] (const-stable since Rust 1.87, well
12058 // within the workspace MSRV) and any future accidental
12059 // downgrade to non-`const` fails the corresponding
12060 // `<name>_via_const_fn` wrapper at caixa-core build time with
12061 // E0015 (`cannot call non-const method`), strictly stronger
12062 // than a runtime `assert!` and strictly stronger than a
12063 // module-scope `const _: () = assert!(…)` pin (which cannot
12064 // be formed on `&Membro` / `&Entrada` fixtures because the
12065 // types' `String` carriers rule out `const`-context value
12066 // construction; the `const fn` wrapper is the load-bearing
12067 // shape that side-steps the destructor-in-const restriction
12068 // on the value axis while still pinning the `const`-fn
12069 // posture on the callee — mirror of the sibling
12070 // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
12071 // (279823b) pin on the per-`:contratos` axis). Peer of the
12072 // sibling per-M2/M3/universal-axis `String → &str` accessor
12073 // family pins on the sibling `const`-eval-surface passes
12074 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
12075 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
12076 // typed-newtype wrapper,
12077 // [`crate::supervisor::ChildSpec::nome`] /
12078 // [`crate::supervisor::ChildSpec::versao_requirement`] at the
12079 // M2 supervisor-tree axis,
12080 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
12081 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
12082 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
12083 // axis, and the sibling per-`:contratos`
12084 // [`WitContract::source`] / [`WitContract::destination`] /
12085 // [`WitContract::world_ref`] trio at 279823b).
12086 const fn membro_nome_via_const_fn(m: &Membro) -> &str {
12087 m.nome()
12088 }
12089 const fn membro_versao_via_const_fn(m: &Membro) -> &str {
12090 m.versao_requirement()
12091 }
12092 const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
12093 e.hostname()
12094 }
12095 const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
12096 e.destination()
12097 }
12098 for (caixa, versao) in [
12099 ("cart", "^0.1"),
12100 ("catalog-v2", "~0.2.3"),
12101 ("checkout", "*"),
12102 ] {
12103 let m = Membro {
12104 caixa: caixa.into(),
12105 versao: versao.into(),
12106 };
12107 assert_eq!(membro_nome_via_const_fn(&m), m.nome());
12108 assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
12109 assert_eq!(m.nome(), caixa);
12110 assert_eq!(m.versao_requirement(), versao);
12111 }
12112 for (host, para) in [
12113 ("cart.example.com", "cart"),
12114 ("api.checkout.io", "checkout"),
12115 ] {
12116 let e = Entrada {
12117 host: host.into(),
12118 para: para.into(),
12119 paths: vec![],
12120 port: DEFAULT_SERVICO_PORT,
12121 };
12122 assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
12123 assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
12124 assert_eq!(e.hostname(), host);
12125 assert_eq!(e.destination(), para);
12126 }
12127 }
12128
12129 #[test]
12130 fn m3_option_string_scalar_accessor_family_is_const_fn() {
12131 // Fail-before-pass-after pin on the five M3 mesh-slot
12132 // `Option<String> → Option<&str>` scalar accessors
12133 // ([`WitContract::endpoint`] / [`WitContract::subject`] /
12134 // [`WitContract::slot`] on the per-`:contratos` HTTP /
12135 // pub-sub / key-value payload-carrier trio,
12136 // [`Placement::shard_key`] / [`Placement::affinity`] on the
12137 // per-`:placement` Akka-sharding-key + Adaptive-compression-
12138 // hint pair). Each accessor destructures the typed slot's
12139 // `Option<String>` storage through the `match &self.<field> {
12140 // Some(s) => Some(s.as_str()), None => None }` shape —
12141 // routing through [`String::as_str`] (const-stable since Rust
12142 // 1.87, well within the workspace MSRV) rather than the
12143 // non-const [`Option::as_deref`] the pre-lift bodies carried
12144 // — and any future accidental downgrade to non-`const` fails
12145 // the corresponding `<name>_via_const_fn` wrapper at
12146 // caixa-core build time with E0015 (`cannot call non-const
12147 // method`), strictly stronger than a runtime `assert!` and
12148 // strictly stronger than a module-scope `const _: () =
12149 // assert!(…)` pin (which cannot be formed on `&WitContract`
12150 // / `&Placement` fixtures because the types' `String` /
12151 // `Option<String>` carriers rule out `const`-context value
12152 // construction; the `const fn` wrapper is the load-bearing
12153 // shape that side-steps the destructor-in-const restriction
12154 // on the value axis while still pinning the `const`-fn
12155 // posture on the callee — mirror of the sibling
12156 // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
12157 // (279823b) and
12158 // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
12159 // (29c5d7e) pins on the peer `String → &str` axes at the same
12160 // structs).
12161 //
12162 // Peer of the sibling per-`Caixa` `Option<String> →
12163 // Option<&str>` accessor family pin
12164 // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
12165 // on the top-level manifest's optional universal-axis surface
12166 // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
12167 // `:restart-window`).
12168 const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
12169 w.endpoint()
12170 }
12171 const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
12172 w.subject()
12173 }
12174 const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
12175 w.slot()
12176 }
12177 const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
12178 p.shard_key()
12179 }
12180 const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
12181 p.affinity()
12182 }
12183 // Sweep every closed shape-arm partition on the
12184 // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
12185 // Some, sibling pair None), pub-sub (`:subject` Some, sibling
12186 // pair None), key-value (`:slot` Some, sibling pair None),
12187 // and Capability (all three None) so each accessor's
12188 // Some/None arm carries a pin through the const dispatch.
12189 for (wit, endpoint, subject, slot) in [
12190 ("wasi:http/proxy", Some("/api"), None, None),
12191 ("nats:pub-sub", None, Some("orders.paid"), None),
12192 ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
12193 ("custom:capability-only", None, None, None),
12194 ] {
12195 let c = WitContract {
12196 de: "cart".into(),
12197 para: "catalog".into(),
12198 wit: wit.into(),
12199 endpoint: endpoint.map(str::to_string),
12200 subject: subject.map(str::to_string),
12201 slot: slot.map(str::to_string),
12202 };
12203 assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
12204 assert_eq!(wit_subject_via_const_fn(&c), c.subject());
12205 assert_eq!(wit_slot_via_const_fn(&c), c.slot());
12206 assert_eq!(c.endpoint(), endpoint);
12207 assert_eq!(c.subject(), subject);
12208 assert_eq!(c.slot(), slot);
12209 }
12210 // Sweep both `Some`/`None` arms on each per-`:placement`
12211 // optional-scalar so the shard-key + affinity pair carries a
12212 // const-dispatch pin on both arms.
12213 for (shard_key, affinity) in [
12214 (Some("tenantId"), Some("data-locality")),
12215 (Some("$tenantId"), None),
12216 (None, Some("low-latency")),
12217 (None, None),
12218 ] {
12219 let p = Placement {
12220 estrategia: PlacementStrategy::default(),
12221 clusters: vec![],
12222 affinity: affinity.map(str::to_string),
12223 shard_key: shard_key.map(str::to_string),
12224 };
12225 assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
12226 assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
12227 assert_eq!(p.shard_key(), shard_key);
12228 assert_eq!(p.affinity(), affinity);
12229 }
12230 }
12231
12232 #[test]
12233 fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
12234 // Fail-before-pass-after pin on the two M3-mesh-slot inner-
12235 // composite `Vec → &[String]` slice-return accessors on
12236 // [`Placement::clusters`] and [`Entrada::paths`]. Each
12237 // destructures the typed slot's `Vec<String>` storage through
12238 // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
12239 // 1.66, well within the workspace MSRV) — any future accidental
12240 // downgrade to non-`const` fails the corresponding
12241 // `<name>_via_const_fn` wrapper at caixa-core build time with
12242 // E0015 (`cannot call non-const method`), strictly stronger
12243 // than a runtime `assert!`. Sibling of the peer
12244 // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
12245 // pin on the outer-`AplicacaoSpec` reference-return family
12246 // (`:membros` / `:contratos` slice-return + `:politicas` /
12247 // `:placement` / `:entrada` composite-reference), and of the
12248 // peer M2 slice-return axis pins
12249 // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
12250 // (on `SupervisorSpec::children`) and
12251 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
12252 // (on `UpgradeFromEntry::instructions`). Together the four
12253 // pins close the last unlifted reference-return accessor
12254 // family across the substrate primitive.
12255 const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
12256 p.clusters()
12257 }
12258 const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
12259 e.paths()
12260 }
12261 // Sweep both the empty-Vec (no author-declared entries) and
12262 // the populated-Vec arms on every slice-return accessor so
12263 // each carries a const-dispatch pin on both arms.
12264 let p_empty = Placement {
12265 estrategia: PlacementStrategy::default(),
12266 clusters: vec![],
12267 affinity: None,
12268 shard_key: None,
12269 };
12270 let p_full = Placement {
12271 estrategia: PlacementStrategy::default(),
12272 clusters: vec!["prod-a".into(), "prod-b".into()],
12273 affinity: None,
12274 shard_key: None,
12275 };
12276 assert_eq!(
12277 placement_clusters_via_const_fn(&p_empty),
12278 p_empty.clusters()
12279 );
12280 assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
12281 assert!(p_empty.clusters().is_empty());
12282 assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
12283 let e_empty = Entrada {
12284 host: "web.example.com".into(),
12285 para: "web".into(),
12286 paths: vec![],
12287 port: DEFAULT_SERVICO_PORT,
12288 };
12289 let e_full = Entrada {
12290 host: "web.example.com".into(),
12291 para: "web".into(),
12292 paths: vec!["/api".into(), "/health".into()],
12293 port: DEFAULT_SERVICO_PORT,
12294 };
12295 assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
12296 assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
12297 assert!(e_empty.paths().is_empty());
12298 assert_eq!(e_full.paths(), &["/api", "/health"]);
12299 }
12300
12301 #[test]
12302 fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
12303 // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
12304 // reference-return accessors — the two `Vec → &[T]` slice-
12305 // return accessors on [`AplicacaoSpec::membros`] and
12306 // [`AplicacaoSpec::contratos`] (each routes through the
12307 // `pub const fn` [`Vec::as_slice`], const-stable since Rust
12308 // 1.66), the two `&Composite` composite-reference accessors
12309 // on [`AplicacaoSpec::politicas`] and
12310 // [`AplicacaoSpec::placement`] (each routes through a raw
12311 // `&self.<field>` borrow, trivially const), and the one
12312 // `Option<&Composite>` optional-composite-reference accessor
12313 // on [`AplicacaoSpec::entrada`] (routes through the
12314 // `pub const fn` [`Option::as_ref`], const-stable since Rust
12315 // 1.83). Any future accidental downgrade to non-`const` fails
12316 // the corresponding `<name>_via_const_fn` wrapper at caixa-
12317 // core build time with E0015 (`cannot call non-const
12318 // method`), strictly stronger than a runtime `assert!`.
12319 // Sibling of the peer inner-composite pin
12320 // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
12321 // on the `Placement::clusters` + `Entrada::paths` slice-
12322 // return pair, and of the peer M2 axis pins on
12323 // [`crate::supervisor::SupervisorSpec::children`] and
12324 // [`crate::upgrade::UpgradeFromEntry::instructions`].
12325 const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
12326 s.membros()
12327 }
12328 const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
12329 s.contratos()
12330 }
12331 const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
12332 s.politicas()
12333 }
12334 const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
12335 s.placement()
12336 }
12337 const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
12338 s.entrada()
12339 }
12340 // Construct both a minimal "no :entrada" (internal-only
12341 // mesh) and a full "with :entrada" (external-gateway)
12342 // fixture so the family pins both the `None`-arm (author-
12343 // omitted `:entrada`) and the `Some`-arm (author-declared
12344 // `:entrada`) on the optional-composite axis.
12345 let membro = Membro {
12346 caixa: "web".into(),
12347 versao: "^0.1".into(),
12348 };
12349 let entrada_full = Entrada {
12350 host: "web.example.com".into(),
12351 para: "web".into(),
12352 paths: vec!["/api".into()],
12353 port: DEFAULT_SERVICO_PORT,
12354 };
12355 let internal_only = AplicacaoSpec {
12356 membros: vec![membro.clone()],
12357 contratos: vec![],
12358 politicas: MeshPolicy::default(),
12359 placement: Placement::default(),
12360 entrada: None,
12361 };
12362 let with_entrada = AplicacaoSpec {
12363 membros: vec![membro],
12364 contratos: vec![],
12365 politicas: MeshPolicy::default(),
12366 placement: Placement::default(),
12367 entrada: Some(entrada_full),
12368 };
12369 assert_eq!(
12370 aplicacao_membros_via_const_fn(&internal_only),
12371 internal_only.membros()
12372 );
12373 assert_eq!(
12374 aplicacao_membros_via_const_fn(&with_entrada),
12375 with_entrada.membros()
12376 );
12377 assert_eq!(
12378 aplicacao_contratos_via_const_fn(&internal_only),
12379 internal_only.contratos()
12380 );
12381 assert!(std::ptr::eq(
12382 aplicacao_politicas_via_const_fn(&internal_only),
12383 internal_only.politicas(),
12384 ));
12385 assert!(std::ptr::eq(
12386 aplicacao_placement_via_const_fn(&internal_only),
12387 internal_only.placement(),
12388 ));
12389 assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
12390 match (
12391 aplicacao_entrada_via_const_fn(&with_entrada),
12392 with_entrada.entrada(),
12393 ) {
12394 (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
12395 _ => panic!(
12396 "aplicacao_entrada_via_const_fn must agree with \
12397 AplicacaoSpec::entrada on the Some-arm reference"
12398 ),
12399 }
12400 }
12401
12402 #[test]
12403 fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
12404 // Load-bearing contract pin: on every canonical
12405 // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
12406 // [`WitContract::target_projected`] returns byte-equal to
12407 // [`WitContract::target`]`().unwrap()` — the post-validation
12408 // projection accessor is a thin panicking wrapper over the
12409 // pre-validation validator, no extra work in the projection
12410 // path. Any future divergence (a validator-side normalization
12411 // the projection doesn't route through, an accessor-side
12412 // caching layer the validator doesn't populate) would surface
12413 // here at caixa-core build time rather than a silent per-consumer
12414 // split at renderer emit time. Sweeps the closed 4-arm
12415 // [`WitTarget`] partition ([`WitTarget::Http`] /
12416 // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
12417 // [`WitTarget::Capability`]) so every arm carries a byte-equality
12418 // pin on the two-accessor pair.
12419 for (wit, endpoint, subject, slot) in [
12420 ("wasi:http/proxy", Some("/x"), None, None),
12421 ("nats:pub-sub", None, Some("events.x"), None),
12422 ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
12423 ("custom:capability-only", None, None, None),
12424 ] {
12425 let c = WitContract {
12426 de: "cart".into(),
12427 para: "catalog".into(),
12428 wit: wit.into(),
12429 endpoint: endpoint.map(str::to_string),
12430 subject: subject.map(str::to_string),
12431 slot: slot.map(str::to_string),
12432 };
12433 assert_eq!(
12434 c.target_projected(),
12435 c.target().unwrap(),
12436 "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
12437 );
12438 }
12439 }
12440
12441 #[test]
12442 #[should_panic(expected = "validated by typed_view")]
12443 fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
12444 // Panic-path pin: [`WitContract::target_projected`] threads the
12445 // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
12446 // through its expect-panic when called on a contract whose
12447 // (`:wit`, payload) shape has not been crossed by
12448 // [`AplicacaoSpec::validate`] — a contract with a structurally-
12449 // invalid `:wit` (hyphen-for-colon typo) that would surface
12450 // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
12451 // A future rebrand on the panic-message axis would land at one
12452 // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
12453 // and this pin's [`should_panic(expected = …)`] literal would
12454 // migrate alongside — the pin catches drift between the const
12455 // and the accessor's `expect(…)` call by construction.
12456 let c = WitContract {
12457 de: "cart".into(),
12458 para: "catalog".into(),
12459 // Hyphen-for-colon typo: `WitContract::target` returns
12460 // [`AplicacaoError::ContratoWitInvalid`] on this shape,
12461 // driving the [`WitContract::target_projected`] expect-panic.
12462 wit: "wasi-http/proxy".into(),
12463 endpoint: Some("/x".into()),
12464 subject: None,
12465 slot: None,
12466 };
12467 let _ = c.target_projected();
12468 }
12469
12470 #[test]
12471 fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
12472 // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
12473 // carries the exact byte-string the two prior open-coded
12474 // `.target().expect("validated by typed_view")` production
12475 // consumers threaded through inline before this lift converged
12476 // them onto [`WitContract::target_projected`] — the caixa-mesh
12477 // per-`(:de, :para)` CNP L7 introspection branch at
12478 // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
12479 // graph` per-`:contratos` payload-column printer at
12480 // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
12481 // byte-string load-bearing so a well-meaning const-side rebrand
12482 // that didn't carry a matched pin migration would surface here
12483 // at caixa-core build time rather than a silent per-consumer
12484 // panic-message drift at cluster-apply time. Peer of the
12485 // sibling [`WitTarget::CAPABILITY_LABEL`] /
12486 // [`WitTarget::CAPABILITY_EXPECTED`] /
12487 // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
12488 // the paired payload-less-arm scalar-const family.
12489 assert_eq!(
12490 WitContract::PROJECTED_INVARIANT_MSG,
12491 "validated by typed_view"
12492 );
12493 }
12494
12495 #[test]
12496 fn empty_wit_takes_precedence_over_invalid() {
12497 // Ordering pin: `EmptyWit` is the more self-locating
12498 // diagnostic on `""` and must lead — the value-shape gate is
12499 // only reached after the empty-check fires. Mirrors
12500 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12501 // the peer payload axis.
12502 let mut s = three_member_spec();
12503 s.contratos.push(WitContract {
12504 de: "payment".into(),
12505 para: "catalog".into(),
12506 wit: String::new(),
12507 endpoint: None,
12508 subject: None,
12509 slot: None,
12510 });
12511 let err = s.validate().unwrap_err();
12512 assert!(
12513 matches!(err, AplicacaoError::EmptyWit { .. }),
12514 "got {err:?}"
12515 );
12516 }
12517
12518 #[test]
12519 fn wit_invalid_fires_before_payload_shape_arm() {
12520 // Ordering pin: a malformed `:wit` surfaces *its own*
12521 // diagnostic (which names the offending wit verbatim) before
12522 // any payload-field check — a contrato whose wit is
12523 // structurally invalid AND carries a wrong target field
12524 // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
12525 // because the dispatch on the wit is what decides which
12526 // payload field is "right" in the first place. Without this
12527 // ordering, the author would see "wrong target field" for a
12528 // wit that hasn't even been parsed, which doesn't name the
12529 // root cause.
12530 let mut s = three_member_spec();
12531 s.contratos.push(WitContract {
12532 de: "payment".into(),
12533 para: "catalog".into(),
12534 // Hyphen-for-colon typo + endpoint set: pre-gate this
12535 // raised `ContratoWrongTarget { expected: "none" }` (the
12536 // Capability arm rejecting the endpoint), masking the
12537 // real authoring mistake (the wit isn't `wasi:http/proxy`).
12538 wit: "wasi-http/proxy".into(),
12539 endpoint: Some("/x".into()),
12540 subject: None,
12541 slot: None,
12542 });
12543 let err = s.validate().unwrap_err();
12544 assert!(
12545 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
12546 if wit == "wasi-http/proxy"),
12547 "got {err:?}"
12548 );
12549 }
12550
12551 #[test]
12552 fn wit_invalid_diagnostic_carries_offending_wit() {
12553 // Diagnostic-shape pin — the offending `:wit` + `:de` +
12554 // `:para` + a non-empty reason flow through verbatim so the
12555 // author can grep their caixa.lisp for the offending contrato
12556 // block and fix it in one edit. Same shape as
12557 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
12558 let err = contrato_wit_err("WASI:HTTP/proxy");
12559 match err {
12560 AplicacaoError::ContratoWitInvalid {
12561 de,
12562 para,
12563 wit,
12564 reason,
12565 } => {
12566 assert_eq!(de, "payment");
12567 assert_eq!(para, "catalog");
12568 assert_eq!(wit, "WASI:HTTP/proxy");
12569 assert!(!reason.is_empty(), "reason field must be non-empty");
12570 }
12571 other => panic!("expected ContratoWitInvalid, got {other:?}"),
12572 }
12573 }
12574
12575 // ── :contratos :subject value-shape gate ─────────────────────────────
12576 //
12577 // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
12578 // suites on the peer payload axes. Until this gate landed
12579 // `WitContract::target()` only refused the empty string; a
12580 // structurally invalid subject silently passed validate and the
12581 // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
12582 // Subject'` on publish / subscribe, or as a silent message drop,
12583 // far from the source caixa.lisp. Every authoring footgun the
12584 // NATS server's subject parser would catch on admission now
12585 // becomes a caixa-build-time `ContratoSubjectInvalid` with the
12586 // offending `:subject` + `:de` + `:para` named verbatim. Same
12587 // diagnostic shape as `ContratoEndpointInvalid` /
12588 // `ContratoWitInvalid` on the peer payload axes; same shared
12589 // predicate (`crate::render::is_nats_subject`) ensures drift
12590 // between any two axes' rule enforcement is a build error at the
12591 // predicate, not piecemeal across renderers.
12592
12593 fn contrato_subject_err(subject: &str) -> AplicacaoError {
12594 // Fresh spec per call so the new contract doesn't collide on
12595 // identity with `three_member_spec`'s pre-existing entries.
12596 // The new edge uses `(payment, catalog)` — a pair the fixture
12597 // doesn't already declare — with `:wit "nats:pub-sub"` and the
12598 // varying `:subject`, so the subject-shape gate fires cleanly
12599 // after the wit-shape gate (which `"nats:pub-sub"` passes).
12600 let mut s = three_member_spec();
12601 s.contratos.push(WitContract {
12602 de: "payment".into(),
12603 para: "catalog".into(),
12604 wit: "nats:pub-sub".into(),
12605 endpoint: None,
12606 subject: Some(subject.into()),
12607 slot: None,
12608 });
12609 s.validate().unwrap_err()
12610 }
12611
12612 #[test]
12613 fn rejects_pubsub_contrato_subject_with_whitespace() {
12614 // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
12615 // landed at the NATS server as a malformed subject the parser
12616 // rejects with `-ERR 'Invalid Subject'`. Now caught at the
12617 // source caixa.lisp.
12618 let err = contrato_subject_err("foo bar");
12619 assert!(
12620 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12621 if subject == "foo bar" && reason.contains("whitespace")),
12622 "got {err:?}"
12623 );
12624 }
12625
12626 #[test]
12627 fn rejects_pubsub_contrato_subject_with_control_char() {
12628 let err = contrato_subject_err("foo\x01bar");
12629 assert!(
12630 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12631 if subject == "foo\x01bar" && reason.contains("control character")),
12632 "got {err:?}"
12633 );
12634 }
12635
12636 #[test]
12637 fn rejects_pubsub_contrato_subject_with_non_ascii() {
12638 // Un-percent-encoded non-ASCII byte — the canonical "I copied
12639 // the subject from a doc with smart quotes / accented
12640 // characters" footgun.
12641 let err = contrato_subject_err("foo.caf\u{e9}");
12642 assert!(
12643 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12644 if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
12645 "got {err:?}"
12646 );
12647 }
12648
12649 #[test]
12650 fn rejects_pubsub_contrato_subject_with_leading_dot() {
12651 // Empty leading token — NATS rejects.
12652 let err = contrato_subject_err(".foo");
12653 assert!(
12654 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12655 if subject == ".foo" && reason.contains("must not start with `.`")),
12656 "got {err:?}"
12657 );
12658 }
12659
12660 #[test]
12661 fn rejects_pubsub_contrato_subject_with_trailing_dot() {
12662 // Empty trailing token — NATS rejects. The remediation
12663 // (use `>` instead) is in the reason string.
12664 let err = contrato_subject_err("foo.");
12665 assert!(
12666 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12667 if subject == "foo." && reason.contains("must not end with `.`")),
12668 "got {err:?}"
12669 );
12670 }
12671
12672 #[test]
12673 fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
12674 // The canonical "I forgot to fill in the middle segment"
12675 // typo — `"foo..bar"`. NATS rejects empty tokens.
12676 let err = contrato_subject_err("foo..bar");
12677 assert!(
12678 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12679 if subject == "foo..bar" && reason.contains("consecutive `.`")),
12680 "got {err:?}"
12681 );
12682 }
12683
12684 #[test]
12685 fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
12686 // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
12687 // as the final segment. Pre-gate this passed as a typed edge
12688 // and surfaced at runtime as a NATS subscribe rejection.
12689 let err = contrato_subject_err("foo.>.bar");
12690 assert!(
12691 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12692 if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
12693 "got {err:?}"
12694 );
12695 }
12696
12697 #[test]
12698 fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
12699 // `foo*.bar` — NATS wildcards are standalone tokens. The
12700 // remediation is in the reason string.
12701 let err = contrato_subject_err("foo*.bar");
12702 assert!(
12703 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12704 if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
12705 "got {err:?}"
12706 );
12707 }
12708
12709 #[test]
12710 fn rejects_pubsub_contrato_subject_with_invalid_char() {
12711 // `foo,bar` — comma is not a valid NATS subject character.
12712 // Pinned separately from the wildcard arms so the invalid-
12713 // character diagnostic is in force.
12714 let err = contrato_subject_err("foo,bar");
12715 assert!(
12716 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12717 if subject == "foo,bar" && reason.contains("invalid character")),
12718 "got {err:?}"
12719 );
12720 }
12721
12722 #[test]
12723 fn rejects_pubsub_contrato_subject_too_long() {
12724 // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
12725 // The legitimate-shape arms all pass (one all-`a` token, no
12726 // `.`, no wildcards); only the cap arm fires. Surfaces the
12727 // paste-from-binary / accidental-multi-line-blob landing
12728 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
12729 // on the peer axis.
12730 let big = "a".repeat(257);
12731 assert_eq!(big.len(), 257);
12732 let err = contrato_subject_err(&big);
12733 assert!(
12734 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12735 if subject == &big && reason.contains("max length of 256")),
12736 "got {err:?}"
12737 );
12738 }
12739
12740 #[test]
12741 fn pubsub_contrato_subject_max_length_validates() {
12742 // 256-byte subject — exactly the cap. Boundary pin: drift in
12743 // the cap surfaces here and at
12744 // `rejects_pubsub_contrato_subject_too_long` simultaneously,
12745 // mirroring `http_contrato_endpoint_max_length_validates` and
12746 // `wit_max_length_validates` on the peer axes.
12747 let big = "a".repeat(256);
12748 assert_eq!(big.len(), 256);
12749 let mut s = three_member_spec();
12750 s.contratos.push(WitContract {
12751 de: "payment".into(),
12752 para: "catalog".into(),
12753 wit: "nats:pub-sub".into(),
12754 endpoint: None,
12755 subject: Some(big),
12756 slot: None,
12757 });
12758 s.validate().unwrap();
12759 }
12760
12761 #[test]
12762 fn pubsub_contrato_subject_accepts_canonical_forms() {
12763 // Positive-set sweep: every canonical NATS subject shape the
12764 // substrate-side `is_nats_subject` predicate accepts (the
12765 // multi-dot `events.order.charged`, the snake_case / kebab-
12766 // case / mixed-case tokens, the digit-bearing tokens, the
12767 // single-token wildcard `*` at every segment position, and
12768 // the trailing `>` multi-token wildcard) must remain a valid
12769 // contrato subject too. Drift between this list and the
12770 // substrate-side `nats_subject_accepts_canonical_forms` sweep
12771 // surfaces at the shared predicate — one source of truth.
12772 // Uses a fresh `(payment, catalog)` edge so none of the swept
12773 // subjects collide with the pre-existing entries in
12774 // `three_member_spec`.
12775 for subject in [
12776 "checkout.events.charge.failed",
12777 "rio.events.order.charged",
12778 "orders",
12779 "orders.123",
12780 "snake_case.token",
12781 "kebab-case.token",
12782 "MixedCase.Token",
12783 "orders.*.charged",
12784 "*.events.*",
12785 "orders.>",
12786 ] {
12787 let mut s = three_member_spec();
12788 s.contratos.push(WitContract {
12789 de: "payment".into(),
12790 para: "catalog".into(),
12791 wit: "nats:pub-sub".into(),
12792 endpoint: None,
12793 subject: Some(subject.into()),
12794 slot: None,
12795 });
12796 s.validate()
12797 .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
12798 }
12799 }
12800
12801 #[test]
12802 fn contrato_subject_empty_takes_precedence_over_invalid() {
12803 // Ordering pin: `ContratoSubjectEmpty` is the more self-
12804 // locating diagnostic on `""` and must lead — the value-shape
12805 // gate is only reached after the empty-check fires. Mirrors
12806 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12807 // the peer payload axis.
12808 let mut s = three_member_spec();
12809 s.contratos.push(WitContract {
12810 de: "payment".into(),
12811 para: "catalog".into(),
12812 wit: "nats:pub-sub".into(),
12813 endpoint: None,
12814 subject: Some(String::new()),
12815 slot: None,
12816 });
12817 let err = s.validate().unwrap_err();
12818 assert!(
12819 matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
12820 "got {err:?}"
12821 );
12822 }
12823
12824 #[test]
12825 fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
12826 // Diagnostic-shape pin — the offending `:subject` + `:de` +
12827 // `:para` + a non-empty reason flow through verbatim so the
12828 // author can grep their caixa.lisp for the offending contrato
12829 // block and fix it in one edit. Same shape as
12830 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12831 // and `wit_invalid_diagnostic_carries_offending_wit`.
12832 let err = contrato_subject_err("foo..bar");
12833 match err {
12834 AplicacaoError::ContratoSubjectInvalid {
12835 de,
12836 para,
12837 subject,
12838 reason,
12839 } => {
12840 assert_eq!(de, "payment");
12841 assert_eq!(para, "catalog");
12842 assert_eq!(subject, "foo..bar");
12843 assert!(!reason.is_empty(), "reason field must be non-empty");
12844 }
12845 other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
12846 }
12847 }
12848
12849 #[test]
12850 fn target_view_pubsub_subject_passes_through_to_typed_view() {
12851 // The compounding theorem on the pub-sub axis: every
12852 // `WitTarget::PubSub { subject }` returned by `target()` carries
12853 // a NATS-server-accepted subject. Renderers downstream of
12854 // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
12855 // NATS Stream/Consumer CR emitter, the future `feira app graph`
12856 // view's subject labeller) can rely on this without re-checking
12857 // — the type system carries the proof. Mirrors
12858 // `target_view_payload_is_guaranteed_nonempty_after_target_call`
12859 // on the peer axes.
12860 let nats = WitContract {
12861 de: "a".into(),
12862 para: "b".into(),
12863 wit: "nats:pub-sub".into(),
12864 endpoint: None,
12865 subject: Some("orders.events.*.charged".into()),
12866 slot: None,
12867 };
12868 match nats.target().unwrap() {
12869 WitTarget::PubSub { subject } => {
12870 assert_eq!(subject, "orders.events.*.charged");
12871 }
12872 other => panic!("expected PubSub, got {other:?}"),
12873 }
12874 }
12875
12876 // ── :contratos :slot value-shape gate ────────────────────────────────
12877 //
12878 // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
12879 // (63e18a0) value-shape suites on the peer payload axes. Until this
12880 // gate landed `WitContract::target()` only refused the empty string
12881 // for the Store arm; a structurally invalid slot (raw whitespace,
12882 // control character, non-ASCII byte, paste-from-binary multi-line
12883 // blob) silently passed validate and surfaced at runtime as a
12884 // per-backend kv write rejection or a silent next-read corruption,
12885 // far from the source caixa.lisp with no field naming which
12886 // `:contratos` edge carried the typo. Every authoring footgun the
12887 // kv backend intersection-floor would catch on write now becomes a
12888 // caixa-build-time `ContratoSlotInvalid` with the offending
12889 // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
12890 // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
12891 // peer payload axes; same shared predicate
12892 // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
12893 // any two axes' rule enforcement is a build error at the
12894 // predicate, not piecemeal across renderers. Closes the typed
12895 // payload-axis value-shape trajectory across all three legs of the
12896 // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
12897
12898 fn contrato_slot_err(slot: &str) -> AplicacaoError {
12899 // Fresh spec per call so the new contract doesn't collide on
12900 // identity with `three_member_spec`'s pre-existing entries
12901 // and doesn't close a synchronous cycle the cycle detector
12902 // would reject before the slot-shape gate fires. The new edge
12903 // uses `(payment, catalog)` — a pair the fixture doesn't
12904 // already declare in either direction (the fixture carries
12905 // `cart -> catalog` and `cart -> payment`, so `payment ->
12906 // catalog` doesn't form a cycle on the sync subgraph) — with
12907 // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
12908 // slot-shape gate fires cleanly after the wit-shape gate
12909 // (which `"wasi:keyvalue/store"` passes). Same edge pair the
12910 // peer `contrato_subject_err` helper uses (63e18a0).
12911 let mut s = three_member_spec();
12912 s.contratos.push(WitContract {
12913 de: "payment".into(),
12914 para: "catalog".into(),
12915 wit: "wasi:keyvalue/store".into(),
12916 endpoint: None,
12917 subject: None,
12918 slot: Some(slot.into()),
12919 });
12920 s.validate().unwrap_err()
12921 }
12922
12923 #[test]
12924 fn rejects_store_contrato_slot_with_whitespace() {
12925 // Fail-before-pass-after pin — pre-gate `"check out/$order"`
12926 // silently landed at the kv backend with whitespace whose
12927 // runtime behavior varies unpredictably across backends (etcd
12928 // accepts, Redis accepts then breaks on next CLI op, DynamoDB
12929 // rejects on write). Now caught at the source caixa.lisp.
12930 let err = contrato_slot_err("check out/$order");
12931 assert!(
12932 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12933 if slot == "check out/$order" && reason.contains("whitespace")),
12934 "got {err:?}"
12935 );
12936 }
12937
12938 #[test]
12939 fn rejects_store_contrato_slot_with_tab() {
12940 // Tab byte arm-pinned separately from the space arm so a
12941 // future relaxation that admits one but not the other surfaces
12942 // here.
12943 let err = contrato_slot_err("check\tout");
12944 assert!(
12945 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12946 if slot == "check\tout" && reason.contains("whitespace")),
12947 "got {err:?}"
12948 );
12949 }
12950
12951 #[test]
12952 fn rejects_store_contrato_slot_with_control_char() {
12953 // SOH (0x01) — distinct from the whitespace arm. Redis admits
12954 // and corrupts on RESP protocol framing; DynamoDB rejects on
12955 // write.
12956 let err = contrato_slot_err("checkout/\x01order");
12957 assert!(
12958 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12959 if slot == "checkout/\x01order" && reason.contains("control character")),
12960 "got {err:?}"
12961 );
12962 }
12963
12964 #[test]
12965 fn rejects_store_contrato_slot_with_newline() {
12966 // Embedded newline — the canonical "the paste-from-binary slug
12967 // spans multiple lines" footgun. Distinct from the whitespace
12968 // arm because `\n` is a control character (0x0A).
12969 let err = contrato_slot_err("checkout\norder");
12970 assert!(
12971 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12972 if slot == "checkout\norder" && reason.contains("control character")),
12973 "got {err:?}"
12974 );
12975 }
12976
12977 #[test]
12978 fn rejects_store_contrato_slot_with_non_ascii() {
12979 // Un-percent-encoded non-ASCII byte — the canonical "I copied
12980 // the slot from a doc with accented characters" footgun. Each
12981 // kv backend re-encodes non-ASCII differently (etcd preserves
12982 // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
12983 // rejects), so the typed slot's value set is the intersection-
12984 // floor every backend admits identically (printable ASCII).
12985 let err = contrato_slot_err("ch\u{e9}ckout/$order");
12986 assert!(
12987 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12988 if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
12989 "got {err:?}"
12990 );
12991 }
12992
12993 #[test]
12994 fn rejects_store_contrato_slot_too_long() {
12995 // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
12996 // legitimate-shape arms all pass (a single all-`a` token, no
12997 // separators); only the cap arm fires. Surfaces the paste-
12998 // from-binary / accidental-multi-line-blob landing footgun.
12999 // Mirrors `rejects_pubsub_contrato_subject_too_long` and
13000 // `rejects_http_contrato_endpoint_too_long` on the peer
13001 // payload axes.
13002 let big = "a".repeat(513);
13003 assert_eq!(big.len(), 513);
13004 let err = contrato_slot_err(&big);
13005 assert!(
13006 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
13007 if slot == &big && reason.contains("max length of 512")),
13008 "got {err:?}"
13009 );
13010 }
13011
13012 #[test]
13013 fn store_contrato_slot_max_length_validates() {
13014 // 512-byte slot — exactly the cap. Boundary pin: drift in the
13015 // cap surfaces here and at `rejects_store_contrato_slot_too_long`
13016 // simultaneously, mirroring
13017 // `pubsub_contrato_subject_max_length_validates` and
13018 // `http_contrato_endpoint_max_length_validates` on the peer
13019 // payload axes.
13020 let big = "a".repeat(512);
13021 assert_eq!(big.len(), 512);
13022 let mut s = three_member_spec();
13023 s.contratos.push(WitContract {
13024 de: "payment".into(),
13025 para: "catalog".into(),
13026 wit: "wasi:keyvalue/store".into(),
13027 endpoint: None,
13028 subject: None,
13029 slot: Some(big),
13030 });
13031 s.validate().unwrap();
13032 }
13033
13034 #[test]
13035 fn store_contrato_slot_accepts_canonical_forms() {
13036 // Positive-set sweep: every canonical kv slot template the
13037 // substrate-side `is_wasi_keyvalue_slot` predicate accepts
13038 // (single-token identifiers, path-namespaced `$`-templates,
13039 // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
13040 // snake_case / kebab-case / MixedCase tokens, digit-bearing
13041 // tokens, percent-encoded fragments) must remain valid
13042 // contrato slots too. Drift between this list and the
13043 // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
13044 // surfaces at the shared predicate — one source of truth.
13045 // Uses a fresh `(payment, catalog)` edge so none of the swept
13046 // slots collide with the pre-existing entries in
13047 // `three_member_spec`.
13048 for slot in [
13049 "checkout",
13050 "checkout/$orderId",
13051 "users:{tenant}/{id}",
13052 "session.<sid>",
13053 "session.tokens.<sid>",
13054 "snake_case_key",
13055 "kebab-case-key",
13056 "MixedCase",
13057 "shard0",
13058 "v2/key",
13059 "users/caf%C3%A9",
13060 ] {
13061 let mut s = three_member_spec();
13062 s.contratos.push(WitContract {
13063 de: "payment".into(),
13064 para: "catalog".into(),
13065 wit: "wasi:keyvalue/store".into(),
13066 endpoint: None,
13067 subject: None,
13068 slot: Some(slot.into()),
13069 });
13070 s.validate()
13071 .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
13072 }
13073 }
13074
13075 #[test]
13076 fn contrato_slot_empty_takes_precedence_over_invalid() {
13077 // Ordering pin: `ContratoSlotEmpty` is the more self-locating
13078 // diagnostic on `""` and must lead — the value-shape gate is
13079 // only reached after the empty-check fires. Mirrors
13080 // `contrato_subject_empty_takes_precedence_over_invalid` and
13081 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
13082 // the peer payload axes.
13083 let mut s = three_member_spec();
13084 s.contratos.push(WitContract {
13085 de: "payment".into(),
13086 para: "catalog".into(),
13087 wit: "wasi:keyvalue/store".into(),
13088 endpoint: None,
13089 subject: None,
13090 slot: Some(String::new()),
13091 });
13092 let err = s.validate().unwrap_err();
13093 assert!(
13094 matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
13095 "got {err:?}"
13096 );
13097 }
13098
13099 #[test]
13100 fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
13101 // Diagnostic-shape pin — the offending `:slot` + `:de` +
13102 // `:para` + a non-empty reason flow through verbatim so the
13103 // author can grep their caixa.lisp for the offending contrato
13104 // block and fix it in one edit. Same shape as
13105 // `contrato_subject_invalid_diagnostic_carries_offending_subject`
13106 // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
13107 // on the peer payload axes.
13108 let err = contrato_slot_err("check out/$order");
13109 match err {
13110 AplicacaoError::ContratoSlotInvalid {
13111 de,
13112 para,
13113 slot,
13114 reason,
13115 } => {
13116 assert_eq!(de, "payment");
13117 assert_eq!(para, "catalog");
13118 assert_eq!(slot, "check out/$order");
13119 assert!(!reason.is_empty(), "reason field must be non-empty");
13120 }
13121 other => panic!("expected ContratoSlotInvalid, got {other:?}"),
13122 }
13123 }
13124
13125 #[test]
13126 fn target_view_store_slot_passes_through_to_typed_view() {
13127 // The compounding theorem on the store axis: every
13128 // `WitTarget::Store { slot }` returned by `target()` carries a
13129 // kv-backend-accepted slot template. Renderers downstream of
13130 // `typed_view()` (the future per-Servico `:capabilities
13131 // wasi:keyvalue/store` axis emitter, the future `feira app
13132 // graph` view's slot labeller, the future kv-provider CR
13133 // materializer) can rely on this without re-checking — the
13134 // type system carries the proof. Mirrors
13135 // `target_view_pubsub_subject_passes_through_to_typed_view` on
13136 // the peer payload axis.
13137 let store = WitContract {
13138 de: "a".into(),
13139 para: "b".into(),
13140 wit: "wasi:keyvalue/store".into(),
13141 endpoint: None,
13142 subject: None,
13143 slot: Some("checkout/$orderId".into()),
13144 };
13145 match store.target().unwrap() {
13146 WitTarget::Store { slot } => {
13147 assert_eq!(slot, "checkout/$orderId");
13148 }
13149 other => panic!("expected Store, got {other:?}"),
13150 }
13151 }
13152
13153 #[test]
13154 fn rejects_self_loop_in_synchronous_contratos() {
13155 // A synchronous self-edge (`cart → cart` over HTTP) is now
13156 // rejected by the dedicated `ContratoSelfLoop` gate — a precise
13157 // "this edge is degenerate" diagnostic — rather than incidentally
13158 // by the cycle detector framing it as a `["cart", "cart"]`
13159 // multi-node deadlock.
13160 let mut s = three_member_spec();
13161 s.contratos.push(contract_http("cart", "cart", "/loop"));
13162 let err = s.validate().unwrap_err();
13163 match err {
13164 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
13165 assert_eq!(caixa, "cart");
13166 assert_eq!(wit, "wasi:http/proxy");
13167 }
13168 other => panic!("expected ContratoSelfLoop, got {other:?}"),
13169 }
13170 }
13171
13172 #[test]
13173 fn rejects_self_loop_in_pubsub_contratos() {
13174 // The cycle detector excludes pub-sub edges (acyclic by
13175 // construction), so before the explicit gate a `nats:pub-sub`
13176 // self-edge silently validated and rendered a self-allow CNP.
13177 // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
13178 let mut s = three_member_spec();
13179 s.contratos.push(WitContract {
13180 de: "payment".into(),
13181 para: "payment".into(),
13182 wit: "nats:pub-sub".into(),
13183 endpoint: None,
13184 subject: Some("rio.events.payment".into()),
13185 slot: None,
13186 });
13187 let err = s.validate().unwrap_err();
13188 match err {
13189 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
13190 assert_eq!(caixa, "payment");
13191 assert_eq!(wit, "nats:pub-sub");
13192 }
13193 other => panic!("expected ContratoSelfLoop, got {other:?}"),
13194 }
13195 }
13196
13197 #[test]
13198 fn self_loop_fires_before_payload_shape_check() {
13199 // The structural "this edge can't exist" error precedes the
13200 // narrower payload-shape diagnostics: a self-edge carrying an
13201 // otherwise-malformed endpoint still reports ContratoSelfLoop,
13202 // not ContratoEndpointInvalid.
13203 let mut s = three_member_spec();
13204 s.contratos.push(WitContract {
13205 de: "cart".into(),
13206 para: "cart".into(),
13207 wit: "wasi:http/proxy".into(),
13208 endpoint: Some("not-absolute".into()),
13209 subject: None,
13210 slot: None,
13211 });
13212 match s.validate().unwrap_err() {
13213 AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
13214 other => panic!("expected ContratoSelfLoop, got {other:?}"),
13215 }
13216 }
13217
13218 #[test]
13219 fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
13220 // A self-edge naming a non-member reports the more fundamental
13221 // ContratoMemberMissing first (the member doesn't exist), so the
13222 // self-loop gate is reached only once both endpoints resolve.
13223 let mut s = three_member_spec();
13224 s.contratos.push(contract_http("ghost", "ghost", "/loop"));
13225 match s.validate().unwrap_err() {
13226 AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
13227 other => panic!("expected ContratoMemberMissing, got {other:?}"),
13228 }
13229 }
13230
13231 #[test]
13232 fn rejects_two_node_synchronous_cycle() {
13233 let mut s = three_member_spec();
13234 // existing edges: cart → catalog, cart → payment
13235 // adding catalog → cart closes a 2-cycle on the HTTP subgraph
13236 s.contratos
13237 .push(contract_http("catalog", "cart", "/refresh"));
13238 let err = s.validate().unwrap_err();
13239 match err {
13240 AplicacaoError::ContratoCycle { cycle } => {
13241 // Cycle traversal should mention both endpoints, with
13242 // the back-edge target appearing as both first and last
13243 // element to close the loop.
13244 assert!(cycle.len() >= 3);
13245 assert_eq!(cycle.first(), cycle.last());
13246 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
13247 assert!(body.contains("cart"));
13248 assert!(body.contains("catalog"));
13249 }
13250 other => panic!("expected ContratoCycle, got {other:?}"),
13251 }
13252 }
13253
13254 #[test]
13255 fn rejects_three_node_synchronous_cycle() {
13256 let mut s = three_member_spec();
13257 // Reset to a clean 3-cycle: catalog → cart → payment → catalog
13258 s.contratos = vec![
13259 contract_http("catalog", "cart", "/x"),
13260 contract_http("cart", "payment", "/y"),
13261 contract_http("payment", "catalog", "/z"),
13262 ];
13263 let err = s.validate().unwrap_err();
13264 match err {
13265 AplicacaoError::ContratoCycle { cycle } => {
13266 assert_eq!(cycle.first(), cycle.last());
13267 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
13268 assert_eq!(body.len(), 3);
13269 assert!(body.contains("cart"));
13270 assert!(body.contains("catalog"));
13271 assert!(body.contains("payment"));
13272 }
13273 other => panic!("expected ContratoCycle, got {other:?}"),
13274 }
13275 }
13276
13277 #[test]
13278 fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
13279 // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
13280 // "acyclic by construction" — so a cycle whose closing edge
13281 // is pub-sub should NOT raise ContratoCycle.
13282 let mut s = three_member_spec();
13283 s.contratos = vec![
13284 contract_http("catalog", "cart", "/x"),
13285 contract_http("cart", "payment", "/y"),
13286 // Closing edge is pub-sub — async; not a sync deadlock.
13287 WitContract {
13288 de: "payment".into(),
13289 para: "catalog".into(),
13290 wit: "nats:pub-sub".into(),
13291 endpoint: None,
13292 subject: Some("checkout.events.charge.completed".into()),
13293 slot: None,
13294 },
13295 ];
13296 s.validate().expect("pub-sub edge breaks the sync cycle");
13297 }
13298
13299 #[test]
13300 fn store_edge_counts_as_synchronous_for_cycle_detection() {
13301 // wasi:keyvalue/store is request/response; a cycle through one
13302 // *is* a sync deadlock, just like HTTP.
13303 let mut s = three_member_spec();
13304 s.contratos = vec![
13305 contract_http("catalog", "cart", "/x"),
13306 WitContract {
13307 de: "cart".into(),
13308 para: "catalog".into(),
13309 wit: "wasi:keyvalue/store".into(),
13310 endpoint: None,
13311 subject: None,
13312 slot: Some("session/$id".into()),
13313 },
13314 ];
13315 let err = s.validate().unwrap_err();
13316 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
13317 }
13318
13319 #[test]
13320 fn capability_edge_counts_as_synchronous_for_cycle_detection() {
13321 // Capability-only edges (unknown WIT shape, no payload) default
13322 // to synchronous — safer; authors with truly async capability
13323 // semantics can model them as pub-sub explicitly.
13324 let mut s = three_member_spec();
13325 s.contratos = vec![
13326 contract_http("catalog", "cart", "/x"),
13327 WitContract {
13328 de: "cart".into(),
13329 para: "catalog".into(),
13330 wit: "custom:exchange".into(),
13331 endpoint: None,
13332 subject: None,
13333 slot: None,
13334 },
13335 ];
13336 let err = s.validate().unwrap_err();
13337 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
13338 }
13339
13340 #[test]
13341 fn long_acyclic_chain_validates() {
13342 // A long sync chain (no back-edges) must validate even when
13343 // every node is reachable from the first.
13344 let mut s = three_member_spec();
13345 s.membros = vec![
13346 membro("a", "^0.1"),
13347 membro("b", "^0.1"),
13348 membro("c", "^0.1"),
13349 membro("d", "^0.1"),
13350 membro("e", "^0.1"),
13351 ];
13352 s.contratos = vec![
13353 contract_http("a", "b", "/1"),
13354 contract_http("b", "c", "/2"),
13355 contract_http("c", "d", "/3"),
13356 contract_http("d", "e", "/4"),
13357 ];
13358 s.entrada.as_mut().unwrap().para = "a".into();
13359 s.validate().unwrap();
13360 }
13361
13362 #[test]
13363 fn diamond_acyclic_validates() {
13364 // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
13365 let mut s = three_member_spec();
13366 s.membros = vec![
13367 membro("a", "^0.1"),
13368 membro("b", "^0.1"),
13369 membro("c", "^0.1"),
13370 membro("d", "^0.1"),
13371 ];
13372 s.contratos = vec![
13373 contract_http("a", "b", "/1"),
13374 contract_http("a", "c", "/2"),
13375 contract_http("b", "d", "/3"),
13376 contract_http("c", "d", "/4"),
13377 ];
13378 s.entrada.as_mut().unwrap().para = "a".into();
13379 s.validate().unwrap();
13380 }
13381
13382 // ── duplicate-`:contratos` build-error gate ──────────────────────────
13383
13384 #[test]
13385 fn rejects_duplicate_http_contrato() {
13386 // Fail-before-pass-after pin: the fixture's `cart → catalog`
13387 // HTTP edge appears once. Push an identical entry — same
13388 // (de, para, wit, endpoint) — and validate() must reject it.
13389 // Until this gate landed the typed surface accepted the
13390 // duplicate silently and caixa-mesh's `cilium_network_policies`
13391 // emitted two ``CiliumNetworkPolicy`` objects with identical
13392 // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
13393 // admission rejects on `kubectl apply` far from the source.
13394 let mut s = three_member_spec();
13395 s.contratos
13396 .push(contract_http("cart", "catalog", "/products/:id"));
13397 let err = s.validate().unwrap_err();
13398 assert!(
13399 matches!(
13400 err,
13401 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13402 if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
13403 ),
13404 "got {err:?}"
13405 );
13406 }
13407
13408 #[test]
13409 fn rejects_duplicate_pubsub_contrato() {
13410 // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
13411 // edges with identical (de, para, subject) are degenerate;
13412 // pin that the typed surface refuses both at validate time.
13413 let mut s = three_member_spec();
13414 let pubsub = WitContract {
13415 de: "payment".into(),
13416 para: "cart".into(),
13417 wit: "nats:pub-sub".into(),
13418 endpoint: None,
13419 subject: Some("checkout.events.charge.failed".into()),
13420 slot: None,
13421 };
13422 s.contratos.push(pubsub.clone());
13423 s.contratos.push(pubsub);
13424 let err = s.validate().unwrap_err();
13425 assert!(
13426 matches!(
13427 err,
13428 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13429 if de == "payment" && para == "cart" && wit == "nats:pub-sub"
13430 ),
13431 "got {err:?}"
13432 );
13433 }
13434
13435 #[test]
13436 fn rejects_duplicate_store_contrato() {
13437 // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
13438 // edges with identical (de, para, slot) collapse to one mesh-
13439 // policy edge; pin the build error.
13440 let mut s = three_member_spec();
13441 let store = WitContract {
13442 de: "cart".into(),
13443 para: "payment".into(),
13444 wit: "wasi:keyvalue/store".into(),
13445 endpoint: None,
13446 subject: None,
13447 slot: Some("checkout/$orderId".into()),
13448 };
13449 // Drop the conflicting HTTP `cart → payment` edge from the
13450 // fixture so the duplicate-store pair is the only one
13451 // distinguishable on this pair.
13452 s.contratos
13453 .retain(|c| !(c.de == "cart" && c.para == "payment"));
13454 s.contratos.push(store.clone());
13455 s.contratos.push(store);
13456 let err = s.validate().unwrap_err();
13457 assert!(
13458 matches!(
13459 err,
13460 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13461 if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
13462 ),
13463 "got {err:?}"
13464 );
13465 }
13466
13467 #[test]
13468 fn rejects_duplicate_capability_contrato() {
13469 // Same gate on the pure-capability axis (no payload selector).
13470 // Two contracts with identical (de, para, wit) and no
13471 // endpoint/subject/slot are duplicate edges; pin so a future
13472 // `target_label` change can't accidentally collapse the
13473 // capability arm into a None-shaped key that compares equal
13474 // to a populated one.
13475 let mut s = three_member_spec();
13476 let capability = WitContract {
13477 de: "cart".into(),
13478 para: "catalog".into(),
13479 wit: "pleme:cap/audit".into(),
13480 endpoint: None,
13481 subject: None,
13482 slot: None,
13483 };
13484 s.contratos.push(capability.clone());
13485 s.contratos.push(capability);
13486 let err = s.validate().unwrap_err();
13487 match err {
13488 AplicacaoError::ContratoDuplicate {
13489 de,
13490 para,
13491 wit,
13492 target,
13493 } => {
13494 assert_eq!(de, "cart");
13495 assert_eq!(para, "catalog");
13496 assert_eq!(wit, "pleme:cap/audit");
13497 assert!(
13498 target.contains("capability"),
13499 "capability-edge duplicate diagnostic must surface the \
13500 no-payload shape (got target = {target:?})"
13501 );
13502 }
13503 other => panic!("expected ContratoDuplicate, got {other:?}"),
13504 }
13505 }
13506
13507 #[test]
13508 fn accepts_distinct_http_paths_between_same_pair() {
13509 // Negative pin: two HTTP contracts cart → catalog at distinct
13510 // endpoints (`/products/:id` and `/search`) are *not*
13511 // duplicates — they're distinct typed edges differing on the
13512 // payload axis. The duplicate-gate must not over-match here,
13513 // since the cart-calls-catalog-on-multiple-paths shape is the
13514 // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
13515 // example: cart calls catalog at /products/:id, payment at
13516 // /charge — same shape extends to two paths on one para).
13517 let mut s = three_member_spec();
13518 s.contratos
13519 .push(contract_http("cart", "catalog", "/search"));
13520 s.validate()
13521 .expect("distinct endpoints between same (de, para) must validate");
13522 }
13523
13524 #[test]
13525 fn accepts_same_endpoint_on_different_pairs() {
13526 // Negative pin: the same `/charge` endpoint reused on two
13527 // different (de, para) pairs is two distinct edges, not a
13528 // duplicate. Pinning this shape so the gate's identity key
13529 // includes both `de` and `para` (not just `(wit, endpoint)`).
13530 let mut s = three_member_spec();
13531 s.contratos
13532 .push(contract_http("payment", "catalog", "/charge"));
13533 s.validate()
13534 .expect("same endpoint reused on distinct (de, para) must validate");
13535 }
13536
13537 #[test]
13538 fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
13539 // Pin the diagnostic shape: the duplicate-edge error names
13540 // *which* target field carried the conflict, so the author
13541 // doesn't have to re-grep the source caixa.lisp to find it.
13542 // Same self-locating diagnostic discipline as
13543 // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
13544 let mut s = three_member_spec();
13545 s.contratos
13546 .push(contract_http("cart", "catalog", "/products/:id"));
13547 let err = s.validate().unwrap_err();
13548 let msg = format!("{err}");
13549 assert!(
13550 msg.contains("\"/products/:id\""),
13551 "duplicate-contrato diagnostic must name the offending \
13552 :endpoint payload (got: {msg:?})"
13553 );
13554 assert!(
13555 msg.contains("cart") && msg.contains("catalog"),
13556 "diagnostic must name both endpoints of the duplicate edge \
13557 (got: {msg:?})"
13558 );
13559 }
13560
13561 #[test]
13562 fn duplicate_contrato_gate_runs_after_membership_check() {
13563 // Order pin: a duplicate contract whose `:de` is *also* not in
13564 // `:membros` surfaces the membership error first — the
13565 // missing-member diagnostic is more locating than the
13566 // duplicate-edge one (the author has to fix the membership
13567 // before the duplicate is meaningful). Same ordering
13568 // discipline as `membros_validation_runs_before_contratos_membership_check`.
13569 let mut s = three_member_spec();
13570 s.contratos.push(contract_http("phantom", "catalog", "/x"));
13571 s.contratos.push(contract_http("phantom", "catalog", "/x"));
13572 let err = s.validate().unwrap_err();
13573 assert!(
13574 matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
13575 "membership-missing must fire before duplicate-edge (got {err:?})"
13576 );
13577 }
13578
13579 #[test]
13580 fn duplicate_contrato_gate_runs_after_target_shape_check() {
13581 // Order pin: a contract with a malformed target (e.g. an HTTP
13582 // wit world with an empty :endpoint) surfaces the target-shape
13583 // error first, not the duplicate one. Even when two such
13584 // malformed entries are identical, the per-contract `target()`
13585 // check fires inside the loop *before* the duplicate-key
13586 // insert, so the diagnostic remains the most-locating one.
13587 let mut s = three_member_spec();
13588 let malformed = WitContract {
13589 de: "cart".into(),
13590 para: "catalog".into(),
13591 wit: "wasi:http/proxy".into(),
13592 endpoint: Some(String::new()),
13593 subject: None,
13594 slot: None,
13595 };
13596 s.contratos.push(malformed.clone());
13597 s.contratos.push(malformed);
13598 let err = s.validate().unwrap_err();
13599 assert!(
13600 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
13601 "endpoint-empty must fire before duplicate-edge (got {err:?})"
13602 );
13603 }
13604
13605 #[test]
13606 fn wit_target_label_pins_per_variant_format() {
13607 // Label format is the single source of truth every duplicate-
13608 // `:contratos` diagnostic + every future `feira app graph`
13609 // consumer routes through. Pin the shape per variant so a
13610 // future edit to `WitTarget::label` (e.g. a JSON emitter that
13611 // strips the leading `:`, or a rename from `endpoint` →
13612 // `path`) surfaces as a red-red test rather than as a silent
13613 // downstream diagnostic drift. Together with the exhaustive
13614 // `match` on `WitTarget` inside `label()`, adding a future
13615 // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
13616 // peer, per-edge WIT registry variants) is a compile error at
13617 // the label site — not a fall-through into the `Capability`
13618 // "no payload" default the prior raw-field-probe helper
13619 // silently landed on.
13620 assert_eq!(
13621 WitTarget::Http {
13622 endpoint: "/charge",
13623 }
13624 .label(),
13625 "\
13626:endpoint \"/charge\""
13627 );
13628 assert_eq!(
13629 WitTarget::PubSub {
13630 subject: "events.checkout.paid",
13631 }
13632 .label(),
13633 "\
13634:subject \"events.checkout.paid\""
13635 );
13636 assert_eq!(
13637 WitTarget::Store {
13638 slot: "checkout/$order",
13639 }
13640 .label(),
13641 "\
13642:slot \"checkout/$order\""
13643 );
13644 assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
13645 // Capability-arm label routes through the lifted
13646 // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
13647 // declaration per arm, next to the variant" discipline the
13648 // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
13649 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13650 // consts already carry extends to the payload-less arm; the
13651 // byte-string equality pin below plus this label-routes-
13652 // through-the-const pin make a future rebrand on either the
13653 // const declaration or the `label()` template a build error
13654 // here rather than a downstream consumer surprise.
13655 assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
13656 assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
13657 }
13658
13659 #[test]
13660 fn wit_target_display_routes_through_label_helper() {
13661 // Fail-before-pass-after pin on the fourth (and only remaining)
13662 // typed-shape-discriminator axis to converge onto the
13663 // three-path-convergence discipline the sibling M3
13664 // [`PlacementStrategy`] (0a2f653) and M2
13665 // [`crate::supervisor::RestartStrategy`] /
13666 // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
13667 // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
13668 // through [`WitTarget::label`], so every consumer reaching for
13669 // `format!("{v}")` on a typed payload target lands on the same
13670 // stable author-facing byte-string [`WitTarget::label`] returns
13671 // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
13672 // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
13673 // `:contratos` gate seeds via [`WitTarget::label`] at
13674 // aplicacao.rs:5491 already threads through.
13675 //
13676 // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
13677 // through to the `Debug` derive's structural output
13678 // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
13679 // rather than the [`WitTarget::label`] helper's stable byte-
13680 // string (`:endpoint "/charge"` — the author-facing `:contratos`
13681 // keyword form). Every future consumer that reaches for
13682 // `format!("{target}")` — the canonical shape every user-facing
13683 // pretty-print site on the sibling typed-enum axes
13684 // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
13685 // [`crate::supervisor::RestartPolicy`]) already uses — would
13686 // silently land under a different byte-string than the
13687 // [`WitTarget::label`] callers that the duplicate-`:contratos`
13688 // diagnostic already threads through, with the mismatch
13689 // surfacing as a downstream diagnostic / graph / audit line
13690 // reading one spelling while the substrate's own gate emitted
13691 // another.
13692 //
13693 // Pin the routing here so a future
13694 // `impl std::fmt::Display for WitTarget<'_>` reimplementation
13695 // that hand-rolls the per-arm formatting instead of delegating
13696 // to [`WitTarget::label`] fails at caixa-core build time.
13697 for variant in [
13698 WitTarget::Http {
13699 endpoint: "/charge",
13700 },
13701 WitTarget::PubSub {
13702 subject: "events.checkout.paid",
13703 },
13704 WitTarget::Store {
13705 slot: "checkout/$order",
13706 },
13707 WitTarget::Capability,
13708 ] {
13709 assert_eq!(
13710 variant.to_string(),
13711 variant.label(),
13712 "WitTarget::{variant:?} Display must route through \
13713 WitTarget::label (single source of truth: the lifted \
13714 payload_pair 4-arm dispatch the label helper already \
13715 threads through)"
13716 );
13717 }
13718 }
13719
13720 #[test]
13721 fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
13722 // Consumer-side pin on the three-path convergence:
13723 // [`std::fmt::Display`] agrees byte-for-byte with the
13724 // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
13725 // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
13726 // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
13727 // Pre-lift the two paths were structurally independent — the
13728 // substrate-side gate reached for `target_view.label()` while a
13729 // future downstream diagnostic / graph / audit line reaching
13730 // for `format!("{target}")` would silently land on the `Debug`
13731 // derive's structural output. Pin the two paths byte-for-byte
13732 // here so any future variant addition (M4 `Rest`/`Grpc` split
13733 // of [`WitTarget::Http`], `Queue`-shaped peer of
13734 // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
13735 // match error at [`WitTarget::payload_pair`] rather than a
13736 // silent per-consumer dispatch miss.
13737 for variant in [
13738 WitTarget::Http {
13739 endpoint: "/charge",
13740 },
13741 WitTarget::PubSub {
13742 subject: "events.checkout.paid",
13743 },
13744 WitTarget::Store {
13745 slot: "checkout/$order",
13746 },
13747 WitTarget::Capability,
13748 ] {
13749 assert_eq!(
13750 format!("{variant}"),
13751 variant.label(),
13752 "WitTarget::{variant:?} Display byte-string must match \
13753 the AplicacaoError::ContratoDuplicate `target:` carrier \
13754 the AplicacaoSpec::validate duplicate-`:contratos` gate \
13755 seeds via WitTarget::label — three-path convergence: \
13756 Display + label + payload_pair all resolve to the same \
13757 per-arm byte-string"
13758 );
13759 }
13760 }
13761
13762 #[test]
13763 fn wit_target_payload_pair_pins_per_variant() {
13764 // Pin the per-arm `(field-name, payload)` pair single-sourced
13765 // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
13766 // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
13767 // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
13768 // and [`WitTarget::field_name`] (returns the first component)
13769 // route through. Until this lift landed [`WitTarget::label`]
13770 // dispatched on the same three arms with a per-arm
13771 // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
13772 // paired [`WitTarget::HTTP_FIELD_NAME`] /
13773 // [`WitTarget::PUBSUB_FIELD_NAME`] /
13774 // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
13775 // canonical "same shape, written N times" duplication
13776 // THEORY.md §I.3.5 promotes to a build-time concern. A future
13777 // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
13778 // [`WitTarget::Http`], `Queue`-shaped peer of
13779 // [`WitTarget::Store`]) is one match-arm edit at
13780 // [`WitTarget::payload_pair`], visible here as a compile-time
13781 // exhaustiveness error on both this pin and the label-format
13782 // pin above.
13783 assert_eq!(
13784 WitTarget::Http {
13785 endpoint: "/charge"
13786 }
13787 .payload_pair(),
13788 Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
13789 );
13790 assert_eq!(
13791 WitTarget::PubSub {
13792 subject: "events.x",
13793 }
13794 .payload_pair(),
13795 Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
13796 );
13797 assert_eq!(
13798 WitTarget::Store {
13799 slot: "checkout/$order",
13800 }
13801 .payload_pair(),
13802 Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
13803 );
13804 assert_eq!(WitTarget::Capability.payload_pair(), None);
13805 }
13806
13807 #[test]
13808 fn wit_target_field_name_pins_per_variant() {
13809 // Pin the per-arm author-facing `:contratos` payload field
13810 // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
13811 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13812 // + returned by [`WitTarget::field_name`]. Every downstream
13813 // consumer (the [`WitContract::target`] gate's `expected:`
13814 // scalar, the [`WitTarget::label`] template's keyword prefix,
13815 // the `feira app graph` verb's `endpoint=…` prefix) routes
13816 // through the same three peer consts, so a rename on the
13817 // author-surface `(defcaixa … :contratos ((:de … :para …
13818 // :wit … :endpoint …)))` field lands in exactly one place.
13819 assert_eq!(
13820 WitTarget::Http {
13821 endpoint: "/charge"
13822 }
13823 .field_name(),
13824 Some(WitTarget::HTTP_FIELD_NAME),
13825 );
13826 assert_eq!(
13827 WitTarget::PubSub {
13828 subject: "events.x",
13829 }
13830 .field_name(),
13831 Some(WitTarget::PUBSUB_FIELD_NAME),
13832 );
13833 assert_eq!(
13834 WitTarget::Store {
13835 slot: "checkout/$order",
13836 }
13837 .field_name(),
13838 Some(WitTarget::STORE_FIELD_NAME),
13839 );
13840 // Capability arm carries no payload field — the diagnostic
13841 // never reports `expected: "capability"` because the gate's
13842 // Capability arm accepts no payload at all (it fires the
13843 // "expected: none" WrongTarget error instead), so the field-
13844 // name method returns None here rather than a placeholder.
13845 assert_eq!(WitTarget::Capability.field_name(), None);
13846
13847 // Peer const scalar values pinned so a rename on either side
13848 // (author-surface field name in the `(defcaixa …)` DSL, or
13849 // the diagnostic's `expected:` scalar) can't drift without
13850 // failing here first.
13851 assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
13852 assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
13853 assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
13854 }
13855
13856 #[test]
13857 fn wit_target_payload_pins_per_variant() {
13858 // Pin the per-arm payload scalar single-sourced onto the
13859 // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
13860 // [`WitTarget::payload`] — the peer per-half projection to
13861 // [`WitTarget::field_name`] on the paired sub-selector axis. The
13862 // three payload-carrying arms round-trip their author-declared
13863 // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
13864 // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
13865 // the payload-less [`WitTarget::Capability`] arm returns `None`.
13866 // Same shape as the sibling `wit_target_field_name_pins_per_variant`
13867 // (c6ec2af) pin on the Component-0 projection axis, extended
13868 // onto the Component-1 projection axis so both per-half readers
13869 // on the paired dispatch carry their own byte-shape pin.
13870 assert_eq!(
13871 WitTarget::Http {
13872 endpoint: "/charge",
13873 }
13874 .payload(),
13875 Some("/charge"),
13876 );
13877 assert_eq!(
13878 WitTarget::PubSub {
13879 subject: "events.x",
13880 }
13881 .payload(),
13882 Some("events.x"),
13883 );
13884 assert_eq!(
13885 WitTarget::Store {
13886 slot: "checkout/$order",
13887 }
13888 .payload(),
13889 Some("checkout/$order"),
13890 );
13891 assert_eq!(WitTarget::Capability.payload(), None);
13892 }
13893
13894 #[test]
13895 fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
13896 // Per-variant equivalence pin: for every arm of [`WitTarget`],
13897 // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
13898 // byte-for-byte. Guards the drift surface where a future refactor
13899 // that split one accessor off the shared match onto its own
13900 // dispatch — a well-meaning "inline the pair back into per-half
13901 // fields for one crate-internal caller who only wanted one half"
13902 // or a scratch `impl` shadowing the derived projection — would
13903 // silently desynchronize [`WitTarget::payload`] from the
13904 // authoritative [`WitTarget::payload_pair`] dispatch, and every
13905 // downstream consumer that thinks "the payload half of the pair"
13906 // would drift from the diagnostic / graph consumers reading the
13907 // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
13908 // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
13909 // per-half projection pin (`gitrefspec_ref_pair_projects_
13910 // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
13911 // FluxCD source-controller `spec.ref.<field>` axis — same "one
13912 // paired dispatch, both per-half projections agree byte-for-
13913 // byte" discipline extended onto the M3 `:contratos` payload-
13914 // arm surface.
13915 for variant in [
13916 WitTarget::Http {
13917 endpoint: "/charge",
13918 },
13919 WitTarget::PubSub {
13920 subject: "events.checkout.paid",
13921 },
13922 WitTarget::Store {
13923 slot: "checkout/$order",
13924 },
13925 WitTarget::Capability,
13926 ] {
13927 let via_projection = variant.payload();
13928 let via_pair = variant.payload_pair().map(|(_, p)| p);
13929 assert_eq!(
13930 via_projection, via_pair,
13931 "WitTarget::{variant:?} payload() must equal \
13932 payload_pair().map(|(_, p)| p) byte-for-byte — a \
13933 regression that splits the two per-half projections off \
13934 their shared match would silently desynchronize the \
13935 payload accessor from the paired dispatch every \
13936 diagnostic / graph consumer reads through",
13937 );
13938 }
13939 }
13940
13941 #[test]
13942 fn wit_target_http_endpoint_pins_per_variant() {
13943 // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
13944 // [`WitTarget::http_endpoint`] 2-arm dispatch — the
13945 // substrate-primitive per-arm post-projection accessor every
13946 // L7-HTTP-facing consumer routes through, sibling to the peer
13947 // WitContract pre-projection [`WitContract::endpoint`] (7020470)
13948 // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
13949 // arm round-trips its author-declared endpoint verbatim as
13950 // `Some("/charge")`; the three sibling arms
13951 // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
13952 // [`WitTarget::Capability`]) each return `None` because they
13953 // carry no HTTP endpoint by definition. Same fail-before-pass-
13954 // after per-variant discipline as the sibling
13955 // `wit_target_payload_pins_per_variant` (5d6dc92) /
13956 // `wit_target_field_name_pins_per_variant` (c6ec2af) /
13957 // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
13958 // the peer pan-arm / per-half projection axes — extended onto
13959 // the per-arm HTTP-shape post-projection axis so a future
13960 // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
13961 // [`WitTarget::Http`], a `Queue`-shaped peer of
13962 // [`WitTarget::Store`]) trips a compile-time exhaustiveness
13963 // error on the sibling [`WitTarget::http_endpoint`] match arms
13964 // whose payload the L7-HTTP-shape accept-set is meant to bound.
13965 assert_eq!(
13966 WitTarget::Http {
13967 endpoint: "/charge",
13968 }
13969 .http_endpoint(),
13970 Some("/charge"),
13971 );
13972 assert_eq!(
13973 WitTarget::PubSub {
13974 subject: "events.checkout.paid",
13975 }
13976 .http_endpoint(),
13977 None,
13978 );
13979 assert_eq!(
13980 WitTarget::Store {
13981 slot: "checkout/$order",
13982 }
13983 .http_endpoint(),
13984 None,
13985 );
13986 assert_eq!(WitTarget::Capability.http_endpoint(), None);
13987 }
13988
13989 #[test]
13990 fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
13991 // Per-variant coherence pin: for every arm of [`WitTarget`],
13992 // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
13993 // arm (both project the same author-declared request-path
13994 // scalar), and returns `None` on every sibling arm regardless of
13995 // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
13996 // Store carry their own payload the pan-arm accessor surfaces,
13997 // but that payload is not an HTTP endpoint — the per-arm
13998 // accessor must not leak it through the HTTP-shape channel).
13999 // Guards the drift surface where a future refactor that
14000 // conflated the per-arm HTTP projection with the pan-arm
14001 // [`WitTarget::payload`] projection — a well-meaning "one
14002 // accessor for the L7 branch, one for the graph" collapse that
14003 // routes both through the same 4-arm dispatch — would silently
14004 // widen the L7-HTTP-shape accept-set onto pub-sub / store
14005 // payloads at the caixa-mesh L7 emit branch, admitting a
14006 // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
14007 // rule with the operator-side apply-time symptom (Cilium's
14008 // eBPF data-plane rejects every ingress edge whose L7 filter
14009 // doesn't match the wire-format HTTP request line) far from
14010 // the source refactor. Sibling to the peer
14011 // `wit_target_payload_matches_payload_pair_second_component_
14012 // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
14013 // extended onto the per-arm HTTP specialization axis so both
14014 // the pan-arm and the per-arm projections carry their own
14015 // byte-shape coherence witness against the substrate's typed
14016 // arm-family accept-set.
14017 for variant in [
14018 WitTarget::Http {
14019 endpoint: "/charge",
14020 },
14021 WitTarget::PubSub {
14022 subject: "events.checkout.paid",
14023 },
14024 WitTarget::Store {
14025 slot: "checkout/$order",
14026 },
14027 WitTarget::Capability,
14028 ] {
14029 let per_arm = variant.http_endpoint();
14030 let pan_arm = variant.payload();
14031 if variant.is_http() {
14032 assert_eq!(
14033 per_arm, pan_arm,
14034 "WitTarget::{variant:?} http_endpoint() must equal \
14035 payload() on the Http arm — a per-arm-vs-pan-arm \
14036 split would silently drift the L7 emit branch's \
14037 path-scalar source from the graph verb's payload \
14038 scalar source",
14039 );
14040 } else {
14041 assert_eq!(
14042 per_arm, None,
14043 "WitTarget::{variant:?} http_endpoint() must return \
14044 None on non-Http arms — a leak that surfaced a \
14045 pub-sub :subject or a key/value :slot through the \
14046 HTTP-endpoint accessor would silently widen the \
14047 Cilium L7 HTTP `path:` rule accept-set onto \
14048 protocol shapes Cilium's eBPF data-plane can't \
14049 introspect",
14050 );
14051 }
14052 }
14053 }
14054
14055 #[test]
14056 fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
14057 // Per-variant coherence pin: for every arm of [`WitTarget`],
14058 // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
14059 // drift surface where a future extension of the
14060 // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
14061 // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
14062 // accessor to cover both peers) landed without a paired
14063 // extension of the [`gen_platform::IsVariant`]-derived
14064 // `is_http()` predicate's accept-set, or vice versa — a
14065 // regression that split the "which arms count as HTTP-shaped
14066 // for L7-path emission?" answer between two dispatch surfaces
14067 // the substrate ships. Sibling to the peer
14068 // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
14069 // on the paired dispatch axis — extended onto the per-arm
14070 // predicate-vs-accessor coherence axis so the gen-platform
14071 // IsVariant predicate and the substrate-lifted per-arm
14072 // accessor carry one shared answer to "is this the HTTP arm?".
14073 for variant in [
14074 WitTarget::Http {
14075 endpoint: "/charge",
14076 },
14077 WitTarget::PubSub {
14078 subject: "events.checkout.paid",
14079 },
14080 WitTarget::Store {
14081 slot: "checkout/$order",
14082 },
14083 WitTarget::Capability,
14084 ] {
14085 assert_eq!(
14086 variant.http_endpoint().is_some(),
14087 variant.is_http(),
14088 "WitTarget::{variant:?} http_endpoint().is_some() must \
14089 equal is_http() — a drift would split the L7 emit \
14090 branch's arm-set gate from the substrate-derived \
14091 shape-discrimination predicate on the same axis",
14092 );
14093 }
14094 }
14095
14096 #[test]
14097 fn wit_target_pubsub_subject_pins_per_variant() {
14098 // Fail-before-pass-after pin: the substrate-canonical per-arm
14099 // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
14100 // is the single dispatch every future pub-sub-facing consumer
14101 // routes through, sibling to the peer [`WitContract::subject`]
14102 // (63e18a0) pre-projection scalar accessor on the raw-field
14103 // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
14104 // post-projection per-arm accessor on the sibling HTTP-shape
14105 // axis. The [`WitTarget::PubSub`] arm round-trips its
14106 // author-declared subject verbatim as
14107 // `Some("events.checkout.paid")`; the three sibling arms each
14108 // return `None` because they carry no NATS-shaped subject by
14109 // definition. Same fail-before-pass-after per-variant discipline
14110 // as the sibling `wit_target_http_endpoint_pins_per_variant`
14111 // pin on the peer per-arm axis — extended onto the per-arm
14112 // pub-sub-shape post-projection axis so a future [`WitTarget`]
14113 // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
14114 // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
14115 // compile-time exhaustiveness error on the sibling
14116 // [`WitTarget::pubsub_subject`] match arms whose payload the
14117 // pub-sub-shape accept-set is meant to bound.
14118 assert_eq!(
14119 WitTarget::PubSub {
14120 subject: "events.checkout.paid",
14121 }
14122 .pubsub_subject(),
14123 Some("events.checkout.paid"),
14124 );
14125 assert_eq!(
14126 WitTarget::Http {
14127 endpoint: "/charge",
14128 }
14129 .pubsub_subject(),
14130 None,
14131 );
14132 assert_eq!(
14133 WitTarget::Store {
14134 slot: "checkout/$order",
14135 }
14136 .pubsub_subject(),
14137 None,
14138 );
14139 assert_eq!(WitTarget::Capability.pubsub_subject(), None);
14140 }
14141
14142 #[test]
14143 fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
14144 // Per-variant coherence pin: for every arm of [`WitTarget`],
14145 // `.pubsub_subject()` equals `.payload()` on the
14146 // [`WitTarget::PubSub`] arm (both project the same
14147 // author-declared subject scalar), and returns `None` on every
14148 // sibling arm regardless of whether [`WitTarget::payload`]
14149 // itself returns `Some` (Http / Store carry their own payload
14150 // the pan-arm accessor surfaces, but that payload is not a
14151 // pub-sub subject — the per-arm accessor must not leak it
14152 // through the pub-sub-shape channel). Sibling to the peer
14153 // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
14154 // coherence pin on the per-arm HTTP-shape axis — extended onto
14155 // the per-arm pub-sub specialization axis so both per-arm
14156 // projections carry their own byte-shape coherence witness
14157 // against the substrate's typed arm-family accept-set.
14158 for variant in [
14159 WitTarget::Http {
14160 endpoint: "/charge",
14161 },
14162 WitTarget::PubSub {
14163 subject: "events.checkout.paid",
14164 },
14165 WitTarget::Store {
14166 slot: "checkout/$order",
14167 },
14168 WitTarget::Capability,
14169 ] {
14170 let per_arm = variant.pubsub_subject();
14171 let pan_arm = variant.payload();
14172 if variant.is_pubsub() {
14173 assert_eq!(
14174 per_arm, pan_arm,
14175 "WitTarget::{variant:?} pubsub_subject() must equal \
14176 payload() on the PubSub arm — a per-arm-vs-pan-arm \
14177 split would silently drift the pub-sub-shape emit \
14178 branch's subject-scalar source from the graph verb's \
14179 payload scalar source",
14180 );
14181 } else {
14182 assert_eq!(
14183 per_arm, None,
14184 "WitTarget::{variant:?} pubsub_subject() must return \
14185 None on non-PubSub arms — a leak that surfaced an \
14186 HTTP :endpoint or a key/value :slot through the \
14187 pub-sub-subject accessor would silently widen the \
14188 downstream NATS-shape accept-set onto protocol \
14189 shapes NATS servers can't route",
14190 );
14191 }
14192 }
14193 }
14194
14195 #[test]
14196 fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
14197 // Per-variant coherence pin: for every arm of [`WitTarget`],
14198 // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
14199 // drift surface where a future extension of the
14200 // [`WitTarget::pubsub_subject`] accessor's accept-set landed
14201 // without a paired extension of the [`gen_platform::IsVariant`]-
14202 // derived `is_pubsub()` predicate's accept-set, or vice versa
14203 // — a regression that split the "which arms count as pub-sub-
14204 // shaped for subject emission?" answer between two dispatch
14205 // surfaces the substrate ships. Sibling to the peer
14206 // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
14207 // pin on the per-arm HTTP-shape axis — extended onto the
14208 // per-arm pub-sub predicate-vs-accessor coherence axis so the
14209 // gen-platform IsVariant predicate and the substrate-lifted
14210 // per-arm accessor carry one shared answer to "is this the
14211 // PubSub arm?".
14212 for variant in [
14213 WitTarget::Http {
14214 endpoint: "/charge",
14215 },
14216 WitTarget::PubSub {
14217 subject: "events.checkout.paid",
14218 },
14219 WitTarget::Store {
14220 slot: "checkout/$order",
14221 },
14222 WitTarget::Capability,
14223 ] {
14224 assert_eq!(
14225 variant.pubsub_subject().is_some(),
14226 variant.is_pubsub(),
14227 "WitTarget::{variant:?} pubsub_subject().is_some() must \
14228 equal is_pubsub() — a drift would split the pub-sub \
14229 emit branch's arm-set gate from the substrate-derived \
14230 shape-discrimination predicate on the same axis",
14231 );
14232 }
14233 }
14234
14235 #[test]
14236 fn wit_target_store_slot_pins_per_variant() {
14237 // Fail-before-pass-after pin: the substrate-canonical per-arm
14238 // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
14239 // is the single dispatch every future store-facing consumer
14240 // routes through, sibling to the peer [`WitContract::slot`]
14241 // pre-projection scalar accessor on the raw-field axis and to
14242 // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
14243 // [`WitTarget::pubsub_subject`] post-projection per-arm
14244 // accessors on the sibling per-payload-arm axes. The
14245 // [`WitTarget::Store`] arm round-trips its author-declared
14246 // slot verbatim as `Some("checkout/$order")`; the three
14247 // sibling arms each return `None` because they carry no
14248 // WASI-key/value slot by definition. Same fail-before-pass-
14249 // after per-variant discipline as the sibling
14250 // `wit_target_http_endpoint_pins_per_variant` +
14251 // `wit_target_pubsub_subject_pins_per_variant` pins on the
14252 // peer per-arm axes — extended onto the per-arm store-shape
14253 // post-projection axis so a future [`WitTarget`] variant
14254 // addition trips a compile-time exhaustiveness error on the
14255 // sibling [`WitTarget::store_slot`] match arms whose payload
14256 // the store-shape accept-set is meant to bound.
14257 assert_eq!(
14258 WitTarget::Store {
14259 slot: "checkout/$order",
14260 }
14261 .store_slot(),
14262 Some("checkout/$order"),
14263 );
14264 assert_eq!(
14265 WitTarget::Http {
14266 endpoint: "/charge",
14267 }
14268 .store_slot(),
14269 None,
14270 );
14271 assert_eq!(
14272 WitTarget::PubSub {
14273 subject: "events.checkout.paid",
14274 }
14275 .store_slot(),
14276 None,
14277 );
14278 assert_eq!(WitTarget::Capability.store_slot(), None);
14279 }
14280
14281 #[test]
14282 fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
14283 // Per-variant coherence pin: for every arm of [`WitTarget`],
14284 // `.store_slot()` equals `.payload()` on the
14285 // [`WitTarget::Store`] arm (both project the same
14286 // author-declared slot scalar), and returns `None` on every
14287 // sibling arm regardless of whether [`WitTarget::payload`]
14288 // itself returns `Some`. Sibling to the peer
14289 // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
14290 // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
14291 // pins on the per-arm HTTP and PubSub axes — closes the
14292 // per-arm-vs-pan-arm byte-shape coherence trio across all
14293 // three payload arms.
14294 for variant in [
14295 WitTarget::Http {
14296 endpoint: "/charge",
14297 },
14298 WitTarget::PubSub {
14299 subject: "events.checkout.paid",
14300 },
14301 WitTarget::Store {
14302 slot: "checkout/$order",
14303 },
14304 WitTarget::Capability,
14305 ] {
14306 let per_arm = variant.store_slot();
14307 let pan_arm = variant.payload();
14308 if variant.is_store() {
14309 assert_eq!(
14310 per_arm, pan_arm,
14311 "WitTarget::{variant:?} store_slot() must equal \
14312 payload() on the Store arm — a per-arm-vs-pan-arm \
14313 split would silently drift the store-shape emit \
14314 branch's slot-scalar source from the graph verb's \
14315 payload scalar source",
14316 );
14317 } else {
14318 assert_eq!(
14319 per_arm, None,
14320 "WitTarget::{variant:?} store_slot() must return \
14321 None on non-Store arms — a leak that surfaced an \
14322 HTTP :endpoint or a NATS :subject through the \
14323 key/value-slot accessor would silently widen the \
14324 downstream WASI-key/value slot accept-set onto \
14325 protocol shapes the kv backends can't route",
14326 );
14327 }
14328 }
14329 }
14330
14331 #[test]
14332 fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
14333 // Per-variant coherence pin: for every arm of [`WitTarget`],
14334 // `.store_slot().is_some()` iff `.is_store()`. Guards the
14335 // drift surface where a future extension of the
14336 // [`WitTarget::store_slot`] accessor's accept-set landed
14337 // without a paired extension of the [`gen_platform::IsVariant`]-
14338 // derived `is_store()` predicate's accept-set. Sibling to the
14339 // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
14340 // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
14341 // pins — closes the per-arm predicate-vs-accessor coherence
14342 // trio across all three payload arms so the gen-platform
14343 // IsVariant predicate and the substrate-lifted per-arm
14344 // accessor carry one shared answer to "is this the Store arm?".
14345 for variant in [
14346 WitTarget::Http {
14347 endpoint: "/charge",
14348 },
14349 WitTarget::PubSub {
14350 subject: "events.checkout.paid",
14351 },
14352 WitTarget::Store {
14353 slot: "checkout/$order",
14354 },
14355 WitTarget::Capability,
14356 ] {
14357 assert_eq!(
14358 variant.store_slot().is_some(),
14359 variant.is_store(),
14360 "WitTarget::{variant:?} store_slot().is_some() must \
14361 equal is_store() — a drift would split the store-shape \
14362 emit branch's arm-set gate from the substrate-derived \
14363 shape-discrimination predicate on the same axis",
14364 );
14365 }
14366 }
14367
14368 #[test]
14369 fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
14370 // Fail-before-pass-after cross-axis pin on the trio
14371 // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
14372 // payload-carrying arm of [`WitTarget`], exactly one per-arm
14373 // accessor returns `Some(payload)` and the two peers return
14374 // `None`; and on the payload-less [`WitTarget::Capability`]
14375 // arm, all three return `None`. Guards the drift surface where
14376 // a future extension of one per-arm accessor's accept-set (e.g.
14377 // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
14378 // that widened `http_endpoint` to cover both peers without
14379 // narrowing the peer `pubsub_subject` / `store_slot` accept-
14380 // sets to keep the partition mutually exclusive) landed without
14381 // threading through the peer per-arm accessors — the resulting
14382 // silent overlap would land the same edge's payload on two
14383 // downstream per-shape emit branches at once, or leak a
14384 // pub-sub subject through the store-slot channel, at renderer
14385 // emit time far from the substrate primitive's arm-widening
14386 // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
14387 // 3-way pin on the payload-field-name axis — extended onto the
14388 // per-arm-accessor payload-projection axis so the substrate-
14389 // owned partition invariant is load-bearing at every per-arm
14390 // consumer's read site.
14391 let payload_variants = [
14392 (
14393 WitTarget::Http {
14394 endpoint: "/charge",
14395 },
14396 "http",
14397 ),
14398 (
14399 WitTarget::PubSub {
14400 subject: "events.checkout.paid",
14401 },
14402 "pubsub",
14403 ),
14404 (
14405 WitTarget::Store {
14406 slot: "checkout/$order",
14407 },
14408 "store",
14409 ),
14410 ];
14411 for (variant, own_arm_label) in payload_variants {
14412 let own_arm_hit = match own_arm_label {
14413 "http" => variant.is_http(),
14414 "pubsub" => variant.is_pubsub(),
14415 "store" => variant.is_store(),
14416 other => panic!("unknown own-arm label {other:?}"),
14417 };
14418 let per_arm_results = [
14419 ("http_endpoint", variant.http_endpoint()),
14420 ("pubsub_subject", variant.pubsub_subject()),
14421 ("store_slot", variant.store_slot()),
14422 ];
14423 let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
14424 assert_eq!(
14425 some_count, 1,
14426 "WitTarget::{variant:?} must land exactly one per-arm \
14427 post-projection accessor's Some result — the trio \
14428 (http_endpoint, pubsub_subject, store_slot) must \
14429 partition the payload arm-set; got {per_arm_results:?}",
14430 );
14431 assert!(
14432 own_arm_hit,
14433 "WitTarget::{variant:?} own-arm gen-platform predicate \
14434 must return true on its own arm — a partition failure \
14435 upstream of this pin",
14436 );
14437 assert!(
14438 variant.payload().is_some(),
14439 "WitTarget::{variant:?} pan-arm payload() must return \
14440 Some on every payload-carrying arm the trio partitions",
14441 );
14442 }
14443 // The payload-less Capability arm must return None on every
14444 // per-arm accessor — the partition's terminal-fallback shape.
14445 let cap = WitTarget::Capability;
14446 assert_eq!(cap.http_endpoint(), None);
14447 assert_eq!(cap.pubsub_subject(), None);
14448 assert_eq!(cap.store_slot(), None);
14449 assert_eq!(
14450 cap.payload(),
14451 None,
14452 "WitTarget::Capability pan-arm payload() must return None — \
14453 the trio's payload-less-arm coherence witness",
14454 );
14455 }
14456
14457 #[test]
14458 fn wit_target_field_names_are_pairwise_distinct() {
14459 // Distinctness pin: if any two of the three payload-field-name
14460 // scalars ever collapse (e.g. an accidental `endpoint` copy-
14461 // paste over the `subject` const), the [`WitContract::target`]
14462 // gate's diagnostic would point authors at the wrong field —
14463 // an "expected `:endpoint`" error on a pub-sub edge would
14464 // silently misroute the fix. Same cross-axis-distinctness
14465 // discipline as the peer M3 `:placement :estrategia` variant-
14466 // discriminator scalar-value pins (cc8f749) applied to the
14467 // payload-field-name axis.
14468 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
14469 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
14470 assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
14471 }
14472
14473 #[test]
14474 fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
14475 // Fail-before-pass-after pin: the graph-verb payload column's
14476 // per-arm `{field}={payload}` byte-string is derived through the
14477 // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
14478 // payload-carrying arms, not through a hand-rolled per-arm match
14479 // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
14480 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14481 // inline. A future variant addition — the M4-and-later per-edge
14482 // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
14483 // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
14484 // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
14485 // and both [`WitTarget::label`] (duplicate-`:contratos`
14486 // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
14487 // payload column) pick up the new arm from the same dispatch.
14488 // Prior to this lift the graph verb open-coded the 4-arm match
14489 // in caixa-feira, so a variant addition would have to be threaded
14490 // through both projections in lockstep or the graph verb would
14491 // silently drop the new arm to `(capability-only)`.
14492 for variant in [
14493 WitTarget::Http {
14494 endpoint: "/charge",
14495 },
14496 WitTarget::PubSub {
14497 subject: "events.checkout.paid",
14498 },
14499 WitTarget::Store {
14500 slot: "checkout/$order",
14501 },
14502 ] {
14503 let (field, payload) = variant
14504 .payload_pair()
14505 .expect("payload arm must expose (field, payload)");
14506 assert_eq!(
14507 variant.graph_label(),
14508 format!("{field}={payload}"),
14509 "WitTarget::{variant:?} graph_label must route the \
14510 `{{field}}={{payload}}` template through payload_pair — \
14511 a regression to a hand-rolled per-arm match at the graph \
14512 verb would silently disagree with a future variant \
14513 addition landed only at payload_pair"
14514 );
14515 }
14516 }
14517
14518 #[test]
14519 fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
14520 // Fail-before-pass-after pin on the payload-less arm: the graph
14521 // verb's `(capability-only)` byte-string routes through the
14522 // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
14523 // [`WitTarget::Capability`] arm, not through an inline
14524 // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
14525 // per-`:contratos` payload column. Peer of the sibling
14526 // [`wit_target_label_pins_per_variant_format`] Capability-arm
14527 // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
14528 // extended here onto the third payload-less-arm consumer axis
14529 // (graph verb, sibling to the duplicate-`:contratos` diagnostic
14530 // axis and the wrong-target diagnostic axis).
14531 assert_eq!(
14532 WitTarget::Capability.graph_label(),
14533 WitTarget::CAPABILITY_GRAPH_LABEL,
14534 );
14535 assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
14536 }
14537
14538 #[test]
14539 fn wit_target_capability_graph_label_distinct_from_capability_label() {
14540 // Cross-consumer-axis distinctness pin: the graph-verb
14541 // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
14542 // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
14543 // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
14544 // payload)`) surface the payload-less arm on two distinct
14545 // consumer axes; a collapse (an accidental rebrand that lands
14546 // one spelling on both consts, a copy-paste that unifies them
14547 // "for consistency") would silently merge the two byte-strings
14548 // and lose the vocabulary distinction the graph verb's
14549 // compact-column form and the diagnostic's descriptive-clause
14550 // form each carry on purpose. Peer of the sibling 4-way
14551 // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
14552 // pin on the `ContratoWrongTarget::expected` scalar-value axis —
14553 // extended here onto the cross-consumer-axis distinctness of the
14554 // two payload-less-arm consts.
14555 assert_ne!(
14556 WitTarget::CAPABILITY_GRAPH_LABEL,
14557 WitTarget::CAPABILITY_LABEL,
14558 "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
14559 and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
14560 diagnostic) must remain distinct — a collapse would silently \
14561 merge two consumer axes onto one spelling"
14562 );
14563 }
14564
14565 #[test]
14566 fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
14567 // 4-way distinctness pin extending the sibling
14568 // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
14569 // (which covers only the HTTP / PubSub / Store payload arms)
14570 // onto the fourth scalar the shared
14571 // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
14572 // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
14573 // (`"none"`), the payload-less Capability-arm rejection scalar.
14574 //
14575 // All four [`WitTarget::HTTP_FIELD_NAME`] /
14576 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14577 // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
14578 // dispatch surface [`WitContract::target`] writes onto the
14579 // `ContratoWrongTarget::expected` field — the same `&'static
14580 // str` axis authors read as "this WIT world's shape admits
14581 // (only|not) `:<field>`". Pairwise-distinctness is the invariant
14582 // downstream consumers rely on: an `expected: "endpoint"`
14583 // diagnostic on a Capability-shaped edge tells the author to
14584 // add a `:endpoint "…"` slot to a WIT world that admits none,
14585 // silently misrouting the fix. Until this pin landed the three
14586 // payload-arm consts were distinctness-guarded by the sibling
14587 // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
14588 // scalar (d4f54f2) sat unguarded — a rebrand collision (the
14589 // author-facing vocabulary shift from `"none"` to `"endpoint"`
14590 // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
14591 // into per-shape peers) would have silently landed one
14592 // Capability-arm rejection on a payload-arm's `expected:` byte-
14593 // string and desynchronized the diagnostic from the author's
14594 // typed shape.
14595 //
14596 // Same 4-way pairwise-distinctness pin discipline as the peer
14597 // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
14598 // (cc8f749) applies on the sibling M3 closed-set typed-enum
14599 // scalar-value dispatch axis; extends the pin trajectory the
14600 // sibling `wit_target_field_names_are_pairwise_distinct`
14601 // 3-way pin opened to cover the last unguarded corner on the
14602 // `ContratoWrongTarget::expected` scalar-value axis.
14603 //
14604 // Fail-before-pass-after locally verified by mutating
14605 // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
14606 // — this pin fires as expected; restoring passes.
14607 let all = [
14608 WitTarget::HTTP_FIELD_NAME,
14609 WitTarget::PUBSUB_FIELD_NAME,
14610 WitTarget::STORE_FIELD_NAME,
14611 WitTarget::CAPABILITY_EXPECTED,
14612 ];
14613 for (i, a) in all.iter().enumerate() {
14614 for (j, b) in all.iter().enumerate() {
14615 if i != j {
14616 assert_ne!(
14617 a, b,
14618 "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
14619 STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
14620 pairwise distinct — got duplicate {a:?} at indices \
14621 {i} and {j}; all four scalars thread through the \
14622 shared `AplicacaoError::ContratoWrongTarget::expected` \
14623 &'static str axis, so a collapse silently misdirects \
14624 the diagnostic on which typed shape the WIT world admits",
14625 );
14626 }
14627 }
14628 }
14629 }
14630
14631 #[test]
14632 fn wit_target_is_variant_predicates_partition_the_arm_set() {
14633 // Fail-before-pass-after pin on the
14634 // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
14635 // each of the four variants exactly one of the generated
14636 // `is_http` / `is_pubsub` / `is_store` / `is_capability`
14637 // predicates returns `true` and the other three return
14638 // `false`. Prior to this derive the only production
14639 // arm-discriminator on [`WitTarget`] — the sync-cycle
14640 // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
14641 // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
14642 // the variant that expressed no compile-time link back to
14643 // the closed-set typed dispatch a future fifth
14644 // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
14645 // split of [`WitTarget::PubSub`] into shape-specific peers,
14646 // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
14647 // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
14648 // to thread through in lockstep or the DFS exclusion would
14649 // silently disagree with the peer diagnostic templates on
14650 // which arms carry sync-versus-async semantics. Peer of the
14651 // sibling [`crate::CaixaKind`] (f5bba80),
14652 // [`PlacementStrategy`] (766ec63),
14653 // [`crate::supervisor::RestartStrategy`],
14654 // [`crate::supervisor::RestartPolicy`], and
14655 // [`crate::upgrade::UpgradeInstruction`] (915a934)
14656 // `IsVariant` derives on the sibling closed-set typed-enum
14657 // discriminator axes — extends the same one-typed-dispatch-
14658 // per-variant discipline onto the last unlifted closed-set
14659 // typed-enum discriminator on the caixa surface (the M3
14660 // mesh-slot per-`:contratos` target-arm axis), closing the
14661 // arm-discriminator convergence trajectory across every
14662 // closed-set typed enum in caixa-core.
14663 let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
14664 (
14665 WitTarget::Http { endpoint: "/x" },
14666 [true, false, false, false],
14667 ),
14668 (
14669 WitTarget::PubSub {
14670 subject: "events.x",
14671 },
14672 [false, true, false, false],
14673 ),
14674 (
14675 WitTarget::Store { slot: "kv/x" },
14676 [false, false, true, false],
14677 ),
14678 (WitTarget::Capability, [false, false, false, true]),
14679 ];
14680 for (variant, expected) in rows {
14681 let observed = [
14682 variant.is_http(),
14683 variant.is_pubsub(),
14684 variant.is_store(),
14685 variant.is_capability(),
14686 ];
14687 assert_eq!(
14688 observed, expected,
14689 "WitTarget::{variant:?} is_* predicates must partition \
14690 the arm set (http, pubsub, store, capability); got {observed:?}"
14691 );
14692 }
14693 }
14694
14695 #[test]
14696 fn wit_target_is_variant_predicates_are_const_fn() {
14697 // The [`gen_platform::IsVariant`] derive emits `const fn`
14698 // predicates on the peer [`crate::CaixaKind`] +
14699 // [`crate::upgrade::UpgradeInstruction`] +
14700 // [`crate::supervisor::RestartStrategy`] +
14701 // [`crate::supervisor::RestartPolicy`] +
14702 // [`PlacementStrategy`] closed-set typed enums — pin the
14703 // same posture on [`WitTarget`] so a future accidental
14704 // downgrade to non-`const` (an added runtime helper reachable
14705 // only from a non-`const` context, a manual hand-rolled
14706 // `impl` that shadows the derive-generated method) trips at
14707 // caixa-core build time rather than surfacing as a downstream
14708 // `const`-context regression far from the derive declaration.
14709 //
14710 // Unlike the peer unit-variant enums (`CaixaKind` /
14711 // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
14712 // whose `const` constructors need no arguments, the three
14713 // payload-carrying [`WitTarget`] arms are const-constructed
14714 // through `&'static str` payloads — the same `'static`
14715 // lifetime the closed-set typed enum's four-arm partition
14716 // pin above already threads through.
14717 const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
14718 const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
14719 const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
14720 const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
14721 const IS_HTTP: bool = HTTP.is_http();
14722 const IS_PUBSUB: bool = PUBSUB.is_pubsub();
14723 const IS_STORE: bool = STORE.is_store();
14724 const IS_CAPABILITY: bool = CAPABILITY.is_capability();
14725 assert!(IS_HTTP);
14726 assert!(IS_PUBSUB);
14727 assert!(IS_STORE);
14728 assert!(IS_CAPABILITY);
14729 }
14730
14731 #[test]
14732 fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
14733 // Consumer-side pin on the sole production converge site:
14734 // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
14735 // edges from the synchronous-subgraph DFS via the lifted
14736 // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
14737 // predicate (rebound from the prior raw
14738 // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
14739 // variant). Byte-equivalent today (`is_pubsub` is the
14740 // derive-generated `matches!(self, Self::PubSub { .. })` by
14741 // construction, the `#[is_variant(name = "pubsub")]` override
14742 // aliasing the auto-derived `is_pub_sub` back to the sibling
14743 // [`WitContract::is_pubsub`] name); pin the behavior so a
14744 // future accidental drift (a rebind onto a peer arm
14745 // predicate, a manual hand-rolled `impl` that shadows the
14746 // derive-generated method with different semantics, a peer
14747 // arm rename that shifts which variant carries sync-versus-
14748 // async semantics) trips at caixa-core test time rather than
14749 // at some downstream operator's runtime dispatch far from the
14750 // rebind commit.
14751 //
14752 // The fixture constructs a two-Servico Aplicacao with one
14753 // pub-sub edge that would close a sync-cycle if the DFS did
14754 // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
14755 // pub-sub exclusion means the DFS sees only the `b → a` HTTP
14756 // edge, which is not a cycle. A regression in the converge
14757 // (a rebind that reads the pub-sub arm as sync) would report
14758 // `AplicacaoError::ContratoCycle`.
14759 let s = AplicacaoSpec {
14760 membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
14761 contratos: vec![
14762 // Pub-sub edge: DFS must skip via is_pubsub().
14763 WitContract {
14764 de: "a".into(),
14765 para: "b".into(),
14766 wit: "nats:pub-sub".into(),
14767 endpoint: None,
14768 subject: Some("events.x".into()),
14769 slot: None,
14770 },
14771 // HTTP edge: DFS must include.
14772 WitContract {
14773 de: "b".into(),
14774 para: "a".into(),
14775 wit: "wasi:http/proxy".into(),
14776 endpoint: Some("/x".into()),
14777 subject: None,
14778 slot: None,
14779 },
14780 ],
14781 politicas: MeshPolicy::default(),
14782 placement: Placement {
14783 estrategia: PlacementStrategy::Replicated,
14784 clusters: vec!["rio".into()],
14785 affinity: None,
14786 shard_key: None,
14787 },
14788 entrada: None,
14789 };
14790 s.validate()
14791 .expect("pub-sub edge must be excluded from sync-cycle DFS");
14792 }
14793
14794 #[test]
14795 fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
14796 // Consumer-side pin: the same three peer consts thread through
14797 // both the [`WitTarget::label`] template (leading-`:` keyword
14798 // prefix in the duplicate-`:contratos` diagnostic) and the
14799 // [`WitContract::target`] gate's [`AplicacaoError::
14800 // ContratoMissingTarget`] `expected:` scalar (the field the
14801 // author needs to add). Pin both routes at once so a future
14802 // refactor can't accidentally split them onto separate string
14803 // literals — the "one place, everywhere reaches for it"
14804 // invariant the peer const set carries.
14805 let http_label = WitTarget::Http { endpoint: "/x" }.label();
14806 assert!(
14807 http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
14808 "label must lead with :{} keyword (got {http_label:?})",
14809 WitTarget::HTTP_FIELD_NAME,
14810 );
14811
14812 let mut s = three_member_spec();
14813 s.contratos.push(WitContract {
14814 de: "cart".into(),
14815 para: "catalog".into(),
14816 wit: "kafka:topic".into(),
14817 endpoint: None,
14818 subject: None,
14819 slot: None,
14820 });
14821 match s.validate().unwrap_err() {
14822 AplicacaoError::ContratoMissingTarget { expected, .. } => {
14823 assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
14824 }
14825 other => panic!("expected ContratoMissingTarget, got {other:?}"),
14826 }
14827 }
14828
14829 #[test]
14830 fn duplicate_pubsub_diagnostic_names_offending_subject() {
14831 // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
14832 // on the pub-sub target axis: the duplicate-edge diagnostic
14833 // must name the `:subject` payload verbatim (not just the
14834 // `(de, para, wit)` triple). Prior to lifting the label onto
14835 // [`WitTarget::label`] the diagnostic derived the label from
14836 // raw [`WitContract`] `Option<String>` probes — a future
14837 // `WitTarget` variant addition (M4 per-edge WIT registry)
14838 // would silently fall through to the `Capability` "no
14839 // payload" default without a compiler warning. Pinning the
14840 // pub-sub arm's format closes the second of three
14841 // payload-carrying `WitTarget` arms this diagnostic threads
14842 // through.
14843 let mut s = three_member_spec();
14844 let pubsub = WitContract {
14845 de: "payment".into(),
14846 para: "cart".into(),
14847 wit: "nats:pub-sub".into(),
14848 endpoint: None,
14849 subject: Some("events.checkout.paid".into()),
14850 slot: None,
14851 };
14852 s.contratos.push(pubsub.clone());
14853 s.contratos.push(pubsub);
14854 let err = s.validate().unwrap_err();
14855 let msg = format!("{err}");
14856 assert!(
14857 msg.contains(":subject \"events.checkout.paid\""),
14858 "duplicate-pubsub diagnostic must name the offending \
14859 :subject payload (got: {msg:?})"
14860 );
14861 }
14862
14863 #[test]
14864 fn duplicate_store_diagnostic_names_offending_slot() {
14865 // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
14866 // key-value target axis: the diagnostic must name the `:slot`
14867 // payload verbatim. Third of three payload-carrying
14868 // `WitTarget` arms this diagnostic threads through, closing
14869 // the per-arm label pin trilogy (`Http` — 6841,
14870 // `PubSub` + `Store` — this test + peer above).
14871 let mut s = three_member_spec();
14872 let store = WitContract {
14873 de: "cart".into(),
14874 para: "payment".into(),
14875 wit: "wasi:keyvalue/store".into(),
14876 endpoint: None,
14877 subject: None,
14878 slot: Some("checkout/$orderId".into()),
14879 };
14880 s.contratos
14881 .retain(|c| !(c.de == "cart" && c.para == "payment"));
14882 s.contratos.push(store.clone());
14883 s.contratos.push(store);
14884 let err = s.validate().unwrap_err();
14885 let msg = format!("{err}");
14886 assert!(
14887 msg.contains(":slot \"checkout/$orderId\""),
14888 "duplicate-store diagnostic must name the offending :slot \
14889 payload (got: {msg:?})"
14890 );
14891 }
14892
14893 #[test]
14894 fn rejects_entrada_path_without_leading_slash() {
14895 let mut s = three_member_spec();
14896 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
14897 let err = s.validate().unwrap_err();
14898 assert!(
14899 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
14900 "got {err:?}"
14901 );
14902 }
14903
14904 #[test]
14905 fn rejects_empty_entrada_path() {
14906 let mut s = three_member_spec();
14907 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
14908 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14909 }
14910
14911 #[test]
14912 fn rejects_duplicate_entrada_paths() {
14913 let mut s = three_member_spec();
14914 s.entrada.as_mut().unwrap().paths = vec![
14915 "/api/cart".into(),
14916 "/api/products".into(),
14917 "/api/cart".into(),
14918 ];
14919 let err = s.validate().unwrap_err();
14920 assert!(
14921 matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
14922 "got {err:?}"
14923 );
14924 }
14925
14926 #[test]
14927 fn rejects_zero_entrada_port() {
14928 let mut s = three_member_spec();
14929 s.entrada.as_mut().unwrap().port = 0;
14930 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
14931 }
14932
14933 // ── :entrada :paths value-shape gate ─────────────────────────────
14934 //
14935 // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
14936 // sibling `:paths` axis. Every authoring footgun the K8s Gateway
14937 // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
14938 // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
14939 // time now becomes a caixa-build-time `EntradaPathInvalid` with
14940 // the offending `:paths` entry named verbatim.
14941
14942 #[test]
14943 fn rejects_entrada_path_with_query() {
14944 // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
14945 // silently passed validate and the Gateway API webhook
14946 // rejected it at apply time with no source citation.
14947 let mut s = three_member_spec();
14948 s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
14949 let err = s.validate().unwrap_err();
14950 assert!(
14951 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14952 if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
14953 "got {err:?}"
14954 );
14955 }
14956
14957 #[test]
14958 fn rejects_entrada_path_with_fragment() {
14959 let mut s = three_member_spec();
14960 s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
14961 let err = s.validate().unwrap_err();
14962 assert!(
14963 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14964 if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
14965 "got {err:?}"
14966 );
14967 }
14968
14969 #[test]
14970 fn rejects_entrada_path_with_space() {
14971 let mut s = three_member_spec();
14972 s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
14973 let err = s.validate().unwrap_err();
14974 assert!(
14975 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14976 if path == "/api/my cart" && reason.contains("whitespace")),
14977 "got {err:?}"
14978 );
14979 }
14980
14981 #[test]
14982 fn rejects_entrada_path_with_tab() {
14983 let mut s = three_member_spec();
14984 s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
14985 let err = s.validate().unwrap_err();
14986 assert!(
14987 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14988 if path == "/api/\tcart" && reason.contains("whitespace")),
14989 "got {err:?}"
14990 );
14991 }
14992
14993 #[test]
14994 fn rejects_entrada_path_with_control_char() {
14995 // 0x01 (SOH) — a non-whitespace control char surfaces the
14996 // distinct "control character" reason arm, separate from
14997 // the whitespace arm. Pinned so a future refactor that
14998 // collapses the two arms can't accidentally drop the more
14999 // self-locating diagnostic.
15000 let mut s = three_member_spec();
15001 s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
15002 let err = s.validate().unwrap_err();
15003 assert!(
15004 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15005 if path == "/api/\x01cart" && reason.contains("control character")),
15006 "got {err:?}"
15007 );
15008 }
15009
15010 #[test]
15011 fn rejects_entrada_path_with_non_ascii() {
15012 // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
15013 // unreserved-set rule rejects. The Gateway API webhook
15014 // rejects literal non-ASCII bytes; percent-encoding is the
15015 // only way to author non-ASCII in a path.
15016 let mut s = three_member_spec();
15017 s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
15018 let err = s.validate().unwrap_err();
15019 assert!(
15020 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15021 if path == "/api/café" && reason.contains("non-ASCII")),
15022 "got {err:?}"
15023 );
15024 }
15025
15026 #[test]
15027 fn rejects_entrada_path_with_consecutive_slashes() {
15028 let mut s = three_member_spec();
15029 s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
15030 let err = s.validate().unwrap_err();
15031 assert!(
15032 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15033 if path == "/api//cart" && reason.contains("consecutive `/`")),
15034 "got {err:?}"
15035 );
15036 }
15037
15038 #[test]
15039 fn rejects_entrada_path_with_dot_segment() {
15040 let mut s = three_member_spec();
15041 s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
15042 let err = s.validate().unwrap_err();
15043 assert!(
15044 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15045 if path == "/api/./cart" && reason.contains("`.` segment")),
15046 "got {err:?}"
15047 );
15048 }
15049
15050 #[test]
15051 fn rejects_entrada_path_with_trailing_dot_segment() {
15052 // The bare `/.` and the trailing `/foo/.` are both rejected
15053 // by the Gateway API webhook; pinned separately so a future
15054 // narrowing that catches only the inner form surfaces here.
15055 let mut s = three_member_spec();
15056 s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
15057 let err = s.validate().unwrap_err();
15058 assert!(
15059 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15060 if path == "/api/." && reason.contains("`.` segment")),
15061 "got {err:?}"
15062 );
15063 }
15064
15065 #[test]
15066 fn rejects_entrada_path_with_parent_segment() {
15067 let mut s = three_member_spec();
15068 s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
15069 let err = s.validate().unwrap_err();
15070 assert!(
15071 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15072 if path == "/api/../etc" && reason.contains("`..` parent-segment")),
15073 "got {err:?}"
15074 );
15075 }
15076
15077 #[test]
15078 fn rejects_entrada_path_with_trailing_parent_segment() {
15079 // Trailing `/..` — symmetric arm of the parent-segment rule,
15080 // pinned separately so a future relaxation that only checks
15081 // the inner form (`/../`) surfaces here.
15082 let mut s = three_member_spec();
15083 s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
15084 let err = s.validate().unwrap_err();
15085 assert!(
15086 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15087 if path == "/api/.." && reason.contains("`..` parent-segment")),
15088 "got {err:?}"
15089 );
15090 }
15091
15092 #[test]
15093 fn rejects_entrada_path_too_long() {
15094 // 1025-byte path — one over the Gateway API HTTPPathMatch.value
15095 // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
15096 // ASCII-alphanumeric body so only the length rule fires.
15097 let mut s = three_member_spec();
15098 let big = format!("/api/{}", "a".repeat(1020));
15099 assert_eq!(big.len(), 1025);
15100 s.entrada.as_mut().unwrap().paths = vec![big.clone()];
15101 let err = s.validate().unwrap_err();
15102 assert!(
15103 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15104 if path == &big && reason.contains("max length of 1024")),
15105 "got {err:?}"
15106 );
15107 }
15108
15109 #[test]
15110 fn entrada_path_max_length_validates() {
15111 // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
15112 // maxLength cap. Boundary pin: drift in the cap surfaces here
15113 // and at `rejects_entrada_path_too_long` simultaneously.
15114 let mut s = three_member_spec();
15115 let big = format!("/api/{}", "a".repeat(1019));
15116 assert_eq!(big.len(), 1024);
15117 s.entrada.as_mut().unwrap().paths = vec![big];
15118 s.validate().unwrap();
15119 }
15120
15121 #[test]
15122 fn entrada_accepts_canonical_paths() {
15123 // Positive-control sweep — every form the Gateway API
15124 // apiserver accepts must round-trip through validate. Covers
15125 // the root catch-all, plain paths, dot-prefixed segments
15126 // (hidden-file-style, distinct from `.` and `..` segments
15127 // which are rejected), digit-bearing segments, the canonical
15128 // route-template `:param` form (`:` is RFC 3986 reserved-set
15129 // valid in paths), trailing-slash form, percent-encoded
15130 // segments, and an interior `..` *substring* (`/foo..bar` is
15131 // not the `..` segment and is allowed).
15132 for path in [
15133 "/",
15134 "/api/cart",
15135 "/healthz",
15136 "/api/.config",
15137 "/v1/products",
15138 "/products/:id",
15139 "/api/cart/",
15140 "/api/caf%C3%A9",
15141 "/foo..bar",
15142 "/...",
15143 ] {
15144 let mut s = three_member_spec();
15145 s.entrada.as_mut().unwrap().paths = vec![path.into()];
15146 s.validate()
15147 .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
15148 }
15149 }
15150
15151 #[test]
15152 fn entrada_path_empty_takes_precedence_over_invalid() {
15153 // Ordering pin: `EntradaPathEmpty` is the more self-locating
15154 // diagnostic on `""` and must lead — `validate_entrada_path`
15155 // is only reached after the empty-check fires at the call
15156 // site. (The predicate itself defends against direct
15157 // invocation by returning the same error on `""`.)
15158 let mut s = three_member_spec();
15159 s.entrada.as_mut().unwrap().paths = vec!["".into()];
15160 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
15161 }
15162
15163 #[test]
15164 fn entrada_path_not_absolute_takes_precedence_over_invalid() {
15165 // Ordering pin: a path without a leading `/` surfaces the
15166 // narrower `EntradaPathNotAbsolute` diagnostic first; the
15167 // value-shape gate is only consulted on paths that already
15168 // satisfy the absolute-prefix invariant.
15169 let mut s = three_member_spec();
15170 // `bad path` would fire the whitespace rule under the
15171 // value-shape gate, but missing-leading-`/` is the more
15172 // self-locating diagnostic.
15173 s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
15174 let err = s.validate().unwrap_err();
15175 assert!(
15176 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
15177 "got {err:?}"
15178 );
15179 }
15180
15181 #[test]
15182 fn entrada_path_invalid_fires_before_duplicate_check() {
15183 // Ordering pin: a malformed path on the *first* entry of a
15184 // would-be duplicate pair fires the value-shape gate before
15185 // the duplicate gate, mirroring the
15186 // `placement_cluster_invalid_fires_before_duplicate_check`
15187 // (6cbb900) pattern on the peer axis.
15188 let mut s = three_member_spec();
15189 s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
15190 let err = s.validate().unwrap_err();
15191 assert!(
15192 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
15193 "got {err:?}"
15194 );
15195 }
15196
15197 #[test]
15198 fn entrada_path_diagnostic_carries_offending_path() {
15199 // Diagnostic-shape pin — the offending path + a non-empty
15200 // reason flow through verbatim so the author can grep their
15201 // caixa.lisp for `:paths` and fix it in one edit. Same shape
15202 // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
15203 let mut s = three_member_spec();
15204 s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
15205 let err = s.validate().unwrap_err();
15206 match err {
15207 AplicacaoError::EntradaPathInvalid { path, reason } => {
15208 assert_eq!(path, "/api?q=1");
15209 assert!(!reason.is_empty(), "reason field must be non-empty");
15210 }
15211 other => panic!("expected EntradaPathInvalid, got {other:?}"),
15212 }
15213 }
15214
15215 #[test]
15216 fn rejects_entrada_path_with_curly_brace_template_form() {
15217 // Per-axis pin on the shared `is_gateway_api_http_path`
15218 // reserved-byte arm: the canonical "I wrote an OpenAPI
15219 // path-template `{id}` instead of the Gateway API `:id` form"
15220 // footgun the K8s apiserver would otherwise catch at admission
15221 // time on every `HTTPRoute.spec.rules[].matches[].path.value`
15222 // landing site, far from the caixa.lisp. Surfaces as
15223 // `EntradaPathInvalid` carrying the offending path verbatim
15224 // plus the canonical `%7B`/`%7D` percent-encoding remediation
15225 // — the substrate-side `gateway_api_http_path_rejects_every_
15226 // reserved_printable_ascii_byte` predicate-level sweep pins the
15227 // full eleven-byte set; this per-axis pin confirms the
15228 // diagnostic flows through to the `EntradaPathInvalid` variant.
15229 let mut s = three_member_spec();
15230 s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
15231 let err = s.validate().unwrap_err();
15232 assert!(
15233 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15234 if path == "/api/cart/{id}"
15235 && reason.contains("reserved character")
15236 && reason.contains("'{'")
15237 && reason.contains("%7B")),
15238 "got {err:?}"
15239 );
15240 }
15241
15242 #[test]
15243 fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
15244 // Per-axis peer of `rejects_entrada_path_with_curly_brace_
15245 // template_form` on the sibling `:contratos :endpoint` axis.
15246 // Same shared `is_gateway_api_http_path` reserved-byte arm
15247 // fires through `ContratoEndpointInvalid`, with the offending
15248 // endpoint + `:de` + `:para` + reason flowing through verbatim.
15249 // Pins that the lifted predicate's tightening lands on both
15250 // caller axes simultaneously — one source of truth for the
15251 // Gateway API HTTPPathMatch.value accepted set.
15252 let err = contrato_endpoint_err("/api/cart/{id}");
15253 assert!(
15254 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15255 if endpoint == "/api/cart/{id}"
15256 && reason.contains("reserved character")
15257 && reason.contains("'{'")
15258 && reason.contains("%7B")),
15259 "got {err:?}"
15260 );
15261 }
15262
15263 // ── :entrada :host value-shape gate ──────────────────────────────
15264 //
15265 // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
15266 // the sibling `:host` axis. Every authoring footgun the K8s
15267 // Gateway API v1 apiserver would catch at admission time becomes
15268 // a caixa-build-time `EntradaHostInvalid` with the offending
15269 // `:host` named verbatim. Same diagnostic shape as
15270 // `MembroVersaoInvalid` (9888b13).
15271
15272 #[test]
15273 fn rejects_entrada_host_with_scheme() {
15274 // Fail-before-pass-after pin — pre-gate codebases silently
15275 // accepted `https://…` and the apiserver rejected it at apply
15276 // time with no source citation.
15277 let mut s = three_member_spec();
15278 s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
15279 let err = s.validate().unwrap_err();
15280 assert!(
15281 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15282 if host == "https://checkout.quero.cloud"),
15283 "got {err:?}"
15284 );
15285 }
15286
15287 #[test]
15288 fn rejects_entrada_host_with_port() {
15289 // The `:8080` port suffix is the canonical "I forgot the port
15290 // belongs in `:entrada :port`" footgun. The top-level `:` arm
15291 // (introduced after the per-label loop-only impl silently
15292 // surfaced a deep "label \"cloud:8080\" contains invalid
15293 // character ':'" leak) names the canonical fix verbatim — the
15294 // `:entrada :port` slot.
15295 let mut s = three_member_spec();
15296 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15297 let err = s.validate().unwrap_err();
15298 assert!(
15299 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15300 if host == "checkout.quero.cloud:8080"
15301 && reason.contains(":entrada :port")),
15302 "got {err:?}"
15303 );
15304 }
15305
15306 #[test]
15307 fn rejects_entrada_host_with_trailing_colon() {
15308 // Trailing `:` (e.g. an in-progress `:host "example.com:"`
15309 // edit) — the per-label loop would land it as a deep
15310 // "label \"com:\" must start and end with an alphanumeric"
15311 // / "contains invalid character ':'" leak. The top-level
15312 // `:` arm pre-empts with the canonical `:port` slot
15313 // diagnostic.
15314 let mut s = three_member_spec();
15315 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
15316 let err = s.validate().unwrap_err();
15317 assert!(
15318 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15319 if host == "checkout.quero.cloud:"
15320 && reason.contains(":entrada :port")),
15321 "got {err:?}"
15322 );
15323 }
15324
15325 #[test]
15326 fn rejects_entrada_host_unbracketed_ipv6_literal() {
15327 // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
15328 // literals across the board (peer with `rejects_entrada_host_
15329 // ipv4_literal` above for the four-label-all-digit IPv4 arm).
15330 // Before this top-level `:` arm landed the per-label loop
15331 // surfaced a single-label byte-class diagnostic that named the
15332 // `:` byte but not the IP-literal prohibition. The top-level
15333 // `:` arm names both the `:port` slot and the IP-literal
15334 // prohibition verbatim, so an author whose `:host "2001:..."`
15335 // value lands here gets a self-locating fix either way.
15336 let mut s = three_member_spec();
15337 s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
15338 let err = s.validate().unwrap_err();
15339 assert!(
15340 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15341 if host == "2001:db8::1"
15342 && reason.contains("IPv6")),
15343 "got {err:?}"
15344 );
15345 }
15346
15347 #[test]
15348 fn rejects_entrada_host_wildcard_with_port() {
15349 // Wildcard host with port suffix — the `*.` strip and the
15350 // per-label loop on `["foo", "quero", "cloud:8080"]` would
15351 // surface the deep byte-class leak. The top-level `:` arm sits
15352 // upstream of the `*.` strip, so it names the canonical `:port`
15353 // fix verbatim regardless of whether the host is wildcard-led.
15354 let mut s = three_member_spec();
15355 s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
15356 let err = s.validate().unwrap_err();
15357 assert!(
15358 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15359 if host == "*.quero.cloud:8080"
15360 && reason.contains(":entrada :port")),
15361 "got {err:?}"
15362 );
15363 }
15364
15365 #[test]
15366 fn rejects_entrada_host_with_path() {
15367 let mut s = three_member_spec();
15368 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
15369 let err = s.validate().unwrap_err();
15370 assert!(
15371 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15372 if host == "checkout.quero.cloud/api"),
15373 "got {err:?}"
15374 );
15375 }
15376
15377 #[test]
15378 fn rejects_entrada_host_with_uppercase() {
15379 // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
15380 // rejected, not silently lower-cased.
15381 let mut s = three_member_spec();
15382 s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
15383 let err = s.validate().unwrap_err();
15384 assert!(
15385 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15386 if reason.contains("uppercase")),
15387 "got {err:?}"
15388 );
15389 }
15390
15391 #[test]
15392 fn rejects_entrada_host_with_underscore() {
15393 // RFC 1123 allows `[a-z0-9-]` only; underscore is the
15394 // canonical "I'm thinking of HTTP cookies / SRV records" leak.
15395 let mut s = three_member_spec();
15396 s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
15397 let err = s.validate().unwrap_err();
15398 assert!(
15399 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15400 if reason.contains('_')),
15401 "got {err:?}"
15402 );
15403 }
15404
15405 #[test]
15406 fn rejects_entrada_host_ipv4_literal() {
15407 // Gateway API v1 explicitly forbids IP literals as Hostnames.
15408 let mut s = three_member_spec();
15409 s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
15410 let err = s.validate().unwrap_err();
15411 assert!(
15412 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15413 if reason.contains("IPv4")),
15414 "got {err:?}"
15415 );
15416 }
15417
15418 #[test]
15419 fn rejects_entrada_host_with_trailing_dot() {
15420 // The Gateway API regex anchors at end-of-string with no
15421 // trailing `.` allowance — the FQDN root-dot form is rejected.
15422 let mut s = three_member_spec();
15423 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
15424 let err = s.validate().unwrap_err();
15425 assert!(
15426 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15427 if host == "checkout.quero.cloud."),
15428 "got {err:?}"
15429 );
15430 }
15431
15432 #[test]
15433 fn rejects_entrada_host_with_leading_dot() {
15434 let mut s = three_member_spec();
15435 s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
15436 let err = s.validate().unwrap_err();
15437 assert!(
15438 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15439 if reason.contains("empty label")),
15440 "got {err:?}"
15441 );
15442 }
15443
15444 #[test]
15445 fn rejects_entrada_host_with_consecutive_dots() {
15446 let mut s = three_member_spec();
15447 s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
15448 let err = s.validate().unwrap_err();
15449 assert!(
15450 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15451 if reason.contains("empty label")),
15452 "got {err:?}"
15453 );
15454 }
15455
15456 #[test]
15457 fn rejects_entrada_host_with_leading_hyphen_label() {
15458 let mut s = three_member_spec();
15459 s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
15460 let err = s.validate().unwrap_err();
15461 assert!(
15462 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15463 if reason.contains("alphanumeric")),
15464 "got {err:?}"
15465 );
15466 }
15467
15468 #[test]
15469 fn rejects_entrada_host_with_trailing_hyphen_label() {
15470 let mut s = three_member_spec();
15471 s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
15472 let err = s.validate().unwrap_err();
15473 assert!(
15474 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15475 if reason.contains("alphanumeric")),
15476 "got {err:?}"
15477 );
15478 }
15479
15480 #[test]
15481 fn rejects_entrada_host_with_inner_wildcard() {
15482 // Gateway API allows `*` only as the first label (`*.foo`);
15483 // any inner or trailing `*` is rejected.
15484 let mut s = three_member_spec();
15485 s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
15486 let err = s.validate().unwrap_err();
15487 assert!(
15488 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15489 if reason.contains("wildcard")),
15490 "got {err:?}"
15491 );
15492 }
15493
15494 #[test]
15495 fn rejects_entrada_host_bare_wildcard() {
15496 // `*.` with no domain is meaningless; Gateway API rejects it.
15497 let mut s = three_member_spec();
15498 s.entrada.as_mut().unwrap().host = "*.".into();
15499 let err = s.validate().unwrap_err();
15500 assert!(
15501 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15502 if reason.contains("wildcard")),
15503 "got {err:?}"
15504 );
15505 }
15506
15507 #[test]
15508 fn rejects_entrada_host_with_whitespace() {
15509 let mut s = three_member_spec();
15510 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15511 let err = s.validate().unwrap_err();
15512 assert!(
15513 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15514 if reason.contains("whitespace")),
15515 "got {err:?}"
15516 );
15517 }
15518
15519 #[test]
15520 fn rejects_entrada_host_space_names_offending_byte() {
15521 // Embedded space in the `:entrada :host` axis surfaces the
15522 // byte-naming diagnostic through the lifted
15523 // `find_ascii_whitespace_byte` predicate. Peer with the
15524 // sibling `parse_rejects_leading_whitespace` pins on
15525 // `supervisor::duration_codec` (a7ae622) — same "the
15526 // diagnostic carries the offending byte's `0x{b:02x}` shape"
15527 // discipline extended from the shared duration codec to the
15528 // Gateway API v1 Hostname axis.
15529 let mut s = three_member_spec();
15530 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15531 let err = s.validate().unwrap_err();
15532 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15533 panic!("expected EntradaHostInvalid, got {err:?}");
15534 };
15535 assert!(
15536 reason.contains("ASCII whitespace byte"),
15537 "expected byte-naming diagnostic, got {reason:?}"
15538 );
15539 assert!(
15540 reason.contains("0x20"),
15541 "expected offending space byte 0x20, got {reason:?}"
15542 );
15543 }
15544
15545 #[test]
15546 fn rejects_entrada_host_tab_names_offending_byte() {
15547 // Embedded tab byte in the `:entrada :host` axis — the
15548 // canonical paste-from-YAML-block-scalar / paste-from-
15549 // indented-doc footgun. Pins that the lifted predicate covers
15550 // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
15551 // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
15552 // not just the leading-space case the pre-lift `.bytes().any`
15553 // arm's opaque "must not contain whitespace" reason already
15554 // covered. Peer with `parse_rejects_tab_byte` on
15555 // `supervisor::duration_codec` (a7ae622).
15556 let mut s = three_member_spec();
15557 s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
15558 let err = s.validate().unwrap_err();
15559 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15560 panic!("expected EntradaHostInvalid, got {err:?}");
15561 };
15562 assert!(
15563 reason.contains("ASCII whitespace byte"),
15564 "expected byte-naming diagnostic, got {reason:?}"
15565 );
15566 assert!(
15567 reason.contains("0x09"),
15568 "expected offending tab byte 0x09, got {reason:?}"
15569 );
15570 }
15571
15572 #[test]
15573 fn rejects_entrada_host_lf_names_offending_byte() {
15574 // Embedded LF byte in the `:entrada :host` axis — the
15575 // canonical paste-from-shell-heredoc / paste-from-multiline-
15576 // doc footgun the caixa-mesh YAML emitter would silently
15577 // reinterpret at the Gateway API v1 HTTPRoute admission
15578 // layer (an embedded LF byte in a YAML plain scalar either
15579 // truncates the value at the emitter or crashes the parser
15580 // on the k8s-apiserver side). Pins the third representative
15581 // of the full ASCII-whitespace set through the shared
15582 // predicate.
15583 let mut s = three_member_spec();
15584 s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
15585 let err = s.validate().unwrap_err();
15586 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15587 panic!("expected EntradaHostInvalid, got {err:?}");
15588 };
15589 assert!(
15590 reason.contains("ASCII whitespace byte"),
15591 "expected byte-naming diagnostic, got {reason:?}"
15592 );
15593 assert!(
15594 reason.contains("0x0a"),
15595 "expected offending LF byte 0x0a, got {reason:?}"
15596 );
15597 }
15598
15599 #[test]
15600 fn rejects_entrada_host_nbsp_names_offending_codepoint() {
15601 // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
15602 // axis — the canonical paste-from-typography /
15603 // paste-from-word-processor footgun. Before the non-ASCII
15604 // Unicode `White_Space` scan lifted through the shared
15605 // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
15606 // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
15607 // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
15608 // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
15609 // with the far-from-source `label "…" must start and end
15610 // with an alphanumeric` diagnostic — burying the
15611 // paste-from-typography origin under a label-shape leak.
15612 // Peer with the sibling non-ASCII-whitespace pins at
15613 // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
15614 // — 1b75b38), `limits::parse_duration`,
15615 // `limits::parse_millicores`, and the shared duration codec
15616 // — same "the diagnostic carries the offending Unicode
15617 // codepoint's `U+XXXX` shape" discipline extended from every
15618 // typed-magnitude codec to the Gateway API v1 Hostname axis.
15619 let mut s = three_member_spec();
15620 s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
15621 let err = s.validate().unwrap_err();
15622 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15623 panic!("expected EntradaHostInvalid, got {err:?}");
15624 };
15625 assert!(
15626 reason.contains("non-ASCII Unicode whitespace character"),
15627 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15628 );
15629 assert!(
15630 reason.contains("U+00A0"),
15631 "expected offending NBSP codepoint U+00A0, got {reason:?}"
15632 );
15633 }
15634
15635 #[test]
15636 fn rejects_entrada_host_line_separator_names_offending_codepoint() {
15637 // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
15638 // `:entrada :host` axis — the canonical paste-from-web-doc /
15639 // paste-from-published-HTML footgun. `char::is_whitespace`
15640 // returns true for `U+2028` per the Unicode `White_Space`
15641 // property, so `str::trim` at any downstream site would
15642 // silently strip it — same drift class as NBSP but on a
15643 // different codepoint region. Pins the second representative
15644 // (non-Latin-1 `char::is_whitespace` member) through the
15645 // shared predicate. Peer with
15646 // `parse_byte_size_rejects_internal_line_separator` on
15647 // `limits::parse_byte_size` (1b75b38).
15648 let mut s = three_member_spec();
15649 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
15650 let err = s.validate().unwrap_err();
15651 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15652 panic!("expected EntradaHostInvalid, got {err:?}");
15653 };
15654 assert!(
15655 reason.contains("non-ASCII Unicode whitespace character"),
15656 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15657 );
15658 assert!(
15659 reason.contains("U+2028"),
15660 "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
15661 );
15662 }
15663
15664 #[test]
15665 fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
15666 // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
15667 // labels in the `:entrada :host` axis — the canonical
15668 // paste-from-CJK-typography footgun (CJK IMEs default to
15669 // full-width whitespace when the space bar is pressed in
15670 // Japanese / Chinese input modes). Pins the third
15671 // representative of the non-ASCII Unicode `White_Space` set
15672 // through the shared predicate: the CJK block, distinct from
15673 // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
15674 // SEPARATOR `U+2028` — covering the same axis breadth the
15675 // sibling `parse_byte_size_rejects_trailing_ideographic_space`
15676 // (1b75b38) pins on `limits::parse_byte_size`.
15677 let mut s = three_member_spec();
15678 s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
15679 let err = s.validate().unwrap_err();
15680 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15681 panic!("expected EntradaHostInvalid, got {err:?}");
15682 };
15683 assert!(
15684 reason.contains("non-ASCII Unicode whitespace character"),
15685 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15686 );
15687 assert!(
15688 reason.contains("U+3000"),
15689 "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
15690 );
15691 }
15692
15693 #[test]
15694 fn rejects_entrada_host_too_long() {
15695 // Total length cap = 253; build a 254-byte host out of two
15696 // 63-byte labels + one 62-byte label + dots.
15697 let mut s = three_member_spec();
15698 let big = format!(
15699 "{}.{}.{}.{}",
15700 "a".repeat(63),
15701 "b".repeat(63),
15702 "c".repeat(63),
15703 "d".repeat(254 - 63 * 3 - 3)
15704 );
15705 assert_eq!(big.len(), 254);
15706 s.entrada.as_mut().unwrap().host = big;
15707 let err = s.validate().unwrap_err();
15708 assert!(
15709 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15710 if reason.contains("max length of 253")),
15711 "got {err:?}"
15712 );
15713 }
15714
15715 #[test]
15716 fn rejects_entrada_host_label_too_long() {
15717 let mut s = three_member_spec();
15718 // 64-byte label — one over the per-label cap.
15719 s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
15720 let err = s.validate().unwrap_err();
15721 assert!(
15722 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15723 if reason.contains("label max length of 63")),
15724 "got {err:?}"
15725 );
15726 }
15727
15728 #[test]
15729 fn entrada_host_diagnostic_carries_offending_host() {
15730 // Diagnostic-shape pin — the offending host + a non-empty
15731 // reason flow through verbatim so the author can grep their
15732 // caixa.lisp for `:host "<host>"` and fix it in one edit.
15733 let mut s = three_member_spec();
15734 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15735 let err = s.validate().unwrap_err();
15736 match err {
15737 AplicacaoError::EntradaHostInvalid { host, reason } => {
15738 assert_eq!(host, "checkout.quero.cloud:8080");
15739 assert!(!reason.is_empty(), "reason field must be non-empty");
15740 }
15741 other => panic!("expected EntradaHostInvalid, got {other:?}"),
15742 }
15743 }
15744
15745 #[test]
15746 fn entrada_host_empty_takes_precedence_over_invalid() {
15747 // Ordering pin: `EmptyEntradaHost` is the more self-locating
15748 // diagnostic on `""` and must lead — `validate_entrada_host`
15749 // is only reached after the empty-check fires at the call
15750 // site. (The predicate itself defends against direct
15751 // invocation by returning the same error on `""`.)
15752 let mut s = three_member_spec();
15753 s.entrada.as_mut().unwrap().host = String::new();
15754 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
15755 }
15756
15757 #[test]
15758 fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
15759 // Ordering pin: a missing :para member is the more
15760 // self-locating diagnostic and fires before the host gate.
15761 let mut s = three_member_spec();
15762 let e = s.entrada.as_mut().unwrap();
15763 e.para = "ghost".into();
15764 e.host = "BAD HOST".into();
15765 let err = s.validate().unwrap_err();
15766 assert!(
15767 matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
15768 "got {err:?}"
15769 );
15770 }
15771
15772 #[test]
15773 fn entrada_host_invalid_fires_before_port_zero() {
15774 // Ordering pin: the host gate fires before the port gate so
15775 // a malformed host is named even when the port is also wrong.
15776 let mut s = three_member_spec();
15777 let e = s.entrada.as_mut().unwrap();
15778 e.host = "Checkout.quero.cloud".into();
15779 e.port = 0;
15780 let err = s.validate().unwrap_err();
15781 assert!(
15782 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15783 if host == "Checkout.quero.cloud"),
15784 "got {err:?}"
15785 );
15786 }
15787
15788 #[test]
15789 fn entrada_accepts_canonical_hosts() {
15790 // Positive-control sweep — every form the Gateway API
15791 // apiserver accepts must round-trip through validate. Covers
15792 // a plain DNS subdomain, a leading wildcard, a single-label
15793 // host (cluster-internal), a max-length-edge label, a
15794 // hyphen-bearing label, and a Punycode IDN label.
15795 for host in [
15796 "checkout.quero.cloud",
15797 "*.quero.cloud",
15798 "checkout",
15799 // 63-byte label — exactly the per-label cap.
15800 "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
15801 "foo-bar.quero.cloud",
15802 // Punycode IDN — valid because the author pre-encoded.
15803 "xn--bcher-kva.example.com",
15804 ] {
15805 let mut s = three_member_spec();
15806 s.entrada.as_mut().unwrap().host = host.into();
15807 s.validate()
15808 .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
15809 }
15810 }
15811
15812 #[test]
15813 fn entrada_host_max_length_validates() {
15814 // 253-byte host is the cap exactly — must validate. Build a
15815 // 253-byte host out of three 63-byte labels + one 61-byte
15816 // label + 3 dots = 252 bytes, then pad one byte to 253.
15817 let mut s = three_member_spec();
15818 let host = format!(
15819 "{}.{}.{}.{}",
15820 "a".repeat(63),
15821 "b".repeat(63),
15822 "c".repeat(63),
15823 "d".repeat(253 - 63 * 3 - 3)
15824 );
15825 assert_eq!(host.len(), 253);
15826 s.entrada.as_mut().unwrap().host = host;
15827 s.validate().unwrap();
15828 }
15829
15830 #[test]
15831 fn entrada_host_total_length_cap_threads_lifted_render_const() {
15832 // Cross-crate-side pin: the aplicacao-side `:entrada :host`
15833 // total-length gate now reads the K8s Gateway API v1 Hostname
15834 // `maxLength: 253` cap from the lifted
15835 // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
15836 // of truth — the same constant every future Gateway-API-Hostname
15837 // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
15838 // materializer's per-host validator, the future per-`Certificate`
15839 // SAN emitter for cert-manager, the multi-`:entrada`
15840 // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
15841 // from. Before the lift, the aplicacao-side reader consumed a
15842 // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
15843 // 253-byte value as the peer render-side canonical bounds
15844 // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
15845 // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
15846 // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
15847 // module boundary — a future 253-byte drift on either side would
15848 // silently split into two axes' worth of admission-schema mismatch
15849 // without a build-time signal. Pin the cap through a fresh 254-
15850 // byte host that hits the total-length arm, then read the reason
15851 // for the exact byte count the shared constant carries: any future
15852 // regression on the lift (a private alias reintroduced, a hard-
15853 // coded literal at the arm, a mismatch between the aplicacao-side
15854 // and render-side canonicals) surfaces as this pin's diagnostic
15855 // failing to match, not as a per-cluster admission rejection far
15856 // from the caixa.lisp source line.
15857 let mut s = three_member_spec();
15858 let over_cap = format!(
15859 "{}.{}.{}.{}",
15860 "a".repeat(63),
15861 "b".repeat(63),
15862 "c".repeat(63),
15863 "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
15864 );
15865 assert_eq!(
15866 over_cap.len(),
15867 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
15868 );
15869 s.entrada.as_mut().unwrap().host = over_cap;
15870 let err = s.validate().unwrap_err();
15871 match err {
15872 AplicacaoError::EntradaHostInvalid { reason, .. } => {
15873 let needle = format!(
15874 "max length of {} bytes",
15875 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
15876 );
15877 assert!(
15878 reason.contains(&needle),
15879 "diagnostic must name the lifted \
15880 GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
15881 );
15882 }
15883 other => panic!("expected EntradaHostInvalid, got {other:?}"),
15884 }
15885 }
15886
15887 #[test]
15888 fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
15889 // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
15890 // on the per-label-cap axis. Before the lift, the aplicacao-side
15891 // per-label arm consumed a private const alias
15892 // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
15893 // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
15894 // split from it at the module boundary — every `.`-separated
15895 // label in a Gateway API v1 Hostname is a DNS-1123 label under
15896 // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
15897 // so the private alias's 63 and the canonical const's 63 were
15898 // pinning the same underlying rule twice. Pin the cap through a
15899 // 64-byte label that hits the per-label arm, then read the reason
15900 // for the exact byte count the shared constant carries: any
15901 // future drift on either side (a private alias reintroduced, a
15902 // hard-coded literal at the arm, a mismatch between the two
15903 // 63-byte pins) surfaces at this pin's diagnostic rather than at
15904 // a per-cluster admission rejection whose "field is invalid"
15905 // opacity misframes the root cause.
15906 let mut s = three_member_spec();
15907 let over_cap_label = format!(
15908 "{}.quero.cloud",
15909 "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
15910 );
15911 s.entrada.as_mut().unwrap().host = over_cap_label;
15912 let err = s.validate().unwrap_err();
15913 match err {
15914 AplicacaoError::EntradaHostInvalid { reason, .. } => {
15915 let needle = format!(
15916 "label max length of {} bytes",
15917 crate::render::DNS_1123_LABEL_MAX_LEN,
15918 );
15919 assert!(
15920 reason.contains(&needle),
15921 "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
15922 cap verbatim on the per-label arm, got: {reason:?}",
15923 );
15924 }
15925 other => panic!("expected EntradaHostInvalid, got {other:?}"),
15926 }
15927 }
15928
15929 #[test]
15930 fn entrada_with_empty_paths_validates() {
15931 // Empty `:paths` is the documented "match every path" form;
15932 // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
15933 let mut s = three_member_spec();
15934 s.entrada.as_mut().unwrap().paths = vec![];
15935 s.validate().unwrap();
15936 }
15937
15938 #[test]
15939 fn entrada_root_path_validates() {
15940 // The author-supplied bare-root `:entrada :paths` entry is the
15941 // same byte-shape the peer emit-side catch-all constant
15942 // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
15943 // the author's `:paths` list is empty — sweeping the test-side
15944 // probe literal onto the lifted const closes the two-axis pin
15945 // (author-side admit + emit-side canonical fallback) around
15946 // one `&'static str`, so a future rebrand of the catch-all
15947 // reaches both consumers by construction. Peer to
15948 // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
15949 // on the canonical-literal pin surface.
15950 let mut s = three_member_spec();
15951 s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
15952 s.validate().unwrap();
15953 }
15954
15955 #[test]
15956 fn placement_strategy_variants_round_trip() {
15957 for s in [
15958 PlacementStrategy::SingleNode,
15959 PlacementStrategy::Replicated,
15960 PlacementStrategy::Sharded,
15961 ] {
15962 let p = Placement {
15963 estrategia: s,
15964 clusters: vec!["rio".into()],
15965 affinity: None,
15966 // Route the paired `:shard-key` fixture-builder through the
15967 // typed cross-slot invariant predicate
15968 // [`PlacementStrategy::requires_shard_key`] rather than the
15969 // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
15970 // arm-identity predicate — the two answer the same
15971 // question under today's closed accept-set but a future
15972 // arm addition that consumed `:shard-key` under a
15973 // non-`Sharded` name would silently mis-attach the
15974 // fixture's `:shard-key` if the builder read through the
15975 // arm-identity predicate. The cross-slot-invariant
15976 // predicate migrates through one caixa-core edit on any
15977 // future arm addition; the fixture keeps producing a
15978 // `validate()`-passing round-trip by construction.
15979 shard_key: if s.requires_shard_key() {
15980 Some("$key".into())
15981 } else {
15982 None
15983 },
15984 };
15985 let json = serde_json::to_string(&p).unwrap();
15986 let back: Placement = serde_json::from_str(&json).unwrap();
15987 assert_eq!(back, p);
15988 }
15989 }
15990
15991 #[test]
15992 fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
15993 // The fail-before-pass-after pin: pre-lift there was no
15994 // single-source binding between the [`PlacementStrategy`]
15995 // variant name the `Serialize` derive emits and the byte-
15996 // string every downstream cluster-side dispatcher (the
15997 // `lareira-fleet-programs` aggregator's per-entry strategy
15998 // branch, the future `app-operator` reconciler, the M3
15999 // Adaptive compression pass's per-strategy weighting) probes
16000 // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
16001 // future `#[serde(rename_all = "kebab-case")]` attribute on
16002 // the enum — or a variant rename in the source — would
16003 // silently rebrand the emitted scalar under one spelling
16004 // while every downstream dispatcher still probed the other,
16005 // with the failure surfacing at the aggregator's dispatch
16006 // step or the operator's reconcile posture (workloads coming
16007 // up under the `default()` `Replicated` arm rather than the
16008 // typed slot's declared strategy) far from the source
16009 // rebrand commit and with no field naming the drift. Pinning
16010 // the two paths (the `Serialize` derive's serialized string
16011 // AND the [`PlacementStrategy::as_str`] helper) to the same
16012 // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
16013 // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
16014 // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
16015 // makes any future drift on either endpoint fail here at
16016 // caixa-core build time.
16017 for (variant, expected) in [
16018 (
16019 PlacementStrategy::SingleNode,
16020 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16021 ),
16022 (
16023 PlacementStrategy::Replicated,
16024 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16025 ),
16026 (
16027 PlacementStrategy::Sharded,
16028 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16029 ),
16030 ] {
16031 let json = serde_json::to_string(&variant).unwrap();
16032 assert_eq!(
16033 json,
16034 format!("\"{expected}\""),
16035 "PlacementStrategy::{variant:?} must serialize to {expected:?}"
16036 );
16037 assert_eq!(
16038 variant.as_str(),
16039 expected,
16040 "PlacementStrategy::{variant:?}.as_str() must return the lifted \
16041 M3_PLACEMENT_ESTRATEGIA_* constant"
16042 );
16043 }
16044 }
16045
16046 #[test]
16047 fn m3_placement_estrategia_consts_are_pairwise_distinct() {
16048 // Cross-arm drift-detection pin on the M3
16049 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
16050 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
16051 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
16052 // scalar-value pentad: a future collapse of two canonical
16053 // variant byte-strings onto the same value (an accidental
16054 // copy-paste flip of
16055 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
16056 // read `"SingleNode"`, a per-arm rebrand that lands one const
16057 // without touching its paired peer) would silently reroute
16058 // every downstream operator's per-strategy dispatch onto the
16059 // sibling arm's reconcile branch and pass every
16060 // propagation-probe test that expected only the stale arm's
16061 // value — a `Replicated`-declared Aplicacao would come up
16062 // under the `SingleNode` primary-and-standby reconcile
16063 // posture, so every-cluster active-active workload would
16064 // silently collapse onto one-cluster-runs-at-a-time takeover
16065 // semantics against its declared strategy, with no field
16066 // naming the strategy-value drift root cause. Peer of the
16067 // sibling
16068 // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
16069 // (09ffb2d) /
16070 // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
16071 // (ccdf955) /
16072 // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
16073 // (d739850) distinctness pins on the sibling OTP-shape /
16074 // caixa-kind closed-set typed-enum discriminator axes — the
16075 // fourth (and structurally the M3 mesh-primitive-defining)
16076 // closed-set typed-enum axis to converge on the same
16077 // "pairwise-distinct-by-construction" discipline.
16078 //
16079 // Fail-before-pass-after locally verified by mutating
16080 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
16081 // also read `"SingleNode"` — this pin fires as expected;
16082 // restoring passes.
16083 let all = [
16084 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16085 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16086 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16087 ];
16088 for (i, a) in all.iter().enumerate() {
16089 for (j, b) in all.iter().enumerate() {
16090 if i != j {
16091 assert_ne!(
16092 a, b,
16093 "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
16094 distinct — got duplicate {a:?} at indices {i} and {j}",
16095 );
16096 }
16097 }
16098 }
16099 }
16100
16101 #[test]
16102 fn placement_strategy_display_routes_through_as_str_helper() {
16103 // The fail-before-pass-after pin: pre-lift the sibling
16104 // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
16105 // / [`crate::supervisor::RestartPolicy`] both carried a stable
16106 // [`std::fmt::Display`] surface via their
16107 // `#[discriminant(also_display)]` gen-platform derive, but
16108 // [`PlacementStrategy`] did not — every consumer reaching for
16109 // a strategy byte-string past the wire format had to pick
16110 // between three paths ([`PlacementStrategy::as_str`], the
16111 // `Serialize` derive's serialized string, or `format!("{v:?}")`
16112 // on the `Debug` derive), any two of which a future variant
16113 // rename or `#[serde(rename_all = "kebab-case")]` attribute
16114 // would silently desynchronize. Wiring [`std::fmt::Display`]
16115 // through [`PlacementStrategy::as_str`] closes the third path:
16116 // every `format!("{v}")` call reaches the same lifted
16117 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
16118 // and the [`PlacementStrategy::as_str`] helper already route
16119 // through, so a future variant rename lands at exactly one
16120 // place. Pin the routing here so a future
16121 // `impl std::fmt::Display for PlacementStrategy` reimplementation
16122 // that hand-rolls the arms instead of delegating to
16123 // [`PlacementStrategy::as_str`] fails at caixa-core build time.
16124 for variant in [
16125 PlacementStrategy::SingleNode,
16126 PlacementStrategy::Replicated,
16127 PlacementStrategy::Sharded,
16128 ] {
16129 assert_eq!(
16130 variant.to_string(),
16131 variant.as_str(),
16132 "PlacementStrategy::{variant:?} Display must route through \
16133 PlacementStrategy::as_str (single source of truth: the lifted \
16134 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
16135 );
16136 }
16137 }
16138
16139 #[test]
16140 fn placement_strategy_display_matches_serialized_wire_byte_string() {
16141 // The fail-before-pass-after pin on the second half of the
16142 // three-path convergence: `Display` (user-facing text) agrees
16143 // byte-for-byte with the `Serialize` derive's wire format
16144 // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
16145 // scalar) on every variant. Pre-lift the two paths were
16146 // structurally independent — a future
16147 // `#[serde(rename_all = "kebab-case")]` attribute on the enum
16148 // would silently rebrand the emitted wire scalar
16149 // (`single-node`, `replicated`, `sharded`) while every consumer
16150 // that pretty-prints the strategy (the M3 diagnostic templates,
16151 // the future `feira app graph` per-Aplicacao strategy line,
16152 // the future M4 CR materializer's admission-webhook rejection
16153 // body) would still emit the TitleCase form the `as_str` /
16154 // `Display` route returns, with the mismatch surfacing at
16155 // consumer parse time / operator dispatch time far from the
16156 // source rebrand commit. Pin the two paths byte-for-byte here
16157 // so any future serde-attribute or variant-rename drift is a
16158 // caixa-core-build-time test failure at this call, not a
16159 // silent per-consumer dispatch miss.
16160 for variant in [
16161 PlacementStrategy::SingleNode,
16162 PlacementStrategy::Replicated,
16163 PlacementStrategy::Sharded,
16164 ] {
16165 let wire = serde_json::to_string(&variant).unwrap();
16166 // Strip the outer `"…"` the JSON string form carries — the
16167 // wire scalar the K8s / YAML apiserver consumes is the
16168 // enclosed byte-string, not the quote wrapper.
16169 let unquoted = wire
16170 .strip_prefix('"')
16171 .and_then(|s| s.strip_suffix('"'))
16172 .expect("serialized PlacementStrategy is a JSON string");
16173 assert_eq!(
16174 variant.to_string(),
16175 unquoted,
16176 "PlacementStrategy::{variant:?} Display byte-string must match the \
16177 Serialize derive's wire byte-string (three-path convergence: \
16178 Display + as_str + Serialize all resolve to the same \
16179 M3_PLACEMENT_ESTRATEGIA_* const)"
16180 );
16181 }
16182 }
16183
16184 #[test]
16185 fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
16186 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
16187 // derive on [`PlacementStrategy`]: for each of the three variants
16188 // exactly one of the generated `is_single_node` / `is_replicated`
16189 // / `is_sharded` predicates returns `true` and the other two
16190 // return `false`. Prior to this derive the three per-arm
16191 // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
16192 // (the `placement_strategy_variants_round_trip` fixture, the
16193 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
16194 // fixture, and the
16195 // `validate_placement_reads_through_lifted_estrategia_accessor`
16196 // fixture) each open-coded a per-arm PartialEq compare against
16197 // the enum variant — three sites that expressed no compile-time
16198 // link back to the closed-set typed dispatch a future fourth
16199 // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
16200 // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
16201 // would have to thread through in lockstep or one fixture would
16202 // silently disagree with the others on which arms consume the
16203 // `:shard-key` axis. Peer of the sibling
16204 // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
16205 // / [`crate::supervisor::RestartPolicy`] /
16206 // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
16207 // the sibling closed-set typed-enum discriminator axes — extends
16208 // the same one-typed-dispatch-per-variant discipline onto the
16209 // fifth (and only remaining) closed-set typed-enum discriminator
16210 // on the caixa surface, closing the axis on the M3 mesh-slot
16211 // family.
16212 let rows: [(PlacementStrategy, [bool; 3]); 3] = [
16213 (PlacementStrategy::SingleNode, [true, false, false]),
16214 (PlacementStrategy::Replicated, [false, true, false]),
16215 (PlacementStrategy::Sharded, [false, false, true]),
16216 ];
16217 for (variant, expected) in rows {
16218 let observed = [
16219 variant.is_single_node(),
16220 variant.is_replicated(),
16221 variant.is_sharded(),
16222 ];
16223 assert_eq!(
16224 observed, expected,
16225 "PlacementStrategy::{variant:?} is_* predicates must partition \
16226 the arm set (single_node, replicated, sharded); got {observed:?}"
16227 );
16228 }
16229 }
16230
16231 #[test]
16232 fn placement_strategy_is_variant_predicates_are_const_fn() {
16233 // The [`gen_platform::IsVariant`] derive emits `const fn`
16234 // predicates on the peer [`crate::CaixaKind`] +
16235 // [`crate::upgrade::UpgradeInstruction`] +
16236 // [`crate::supervisor::RestartStrategy`] +
16237 // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
16238 // pin the same posture on [`PlacementStrategy`] so a future
16239 // accidental downgrade to non-`const` (an added runtime helper
16240 // reachable only from a non-`const` context, a manual hand-rolled
16241 // `impl` that shadows the derive-generated method) trips at
16242 // caixa-core build time rather than surfacing as a downstream
16243 // `const`-context regression far from the derive declaration.
16244 const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
16245 const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
16246 const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
16247 assert!(IS_SINGLE_NODE);
16248 assert!(IS_REPLICATED);
16249 assert!(IS_SHARDED);
16250 }
16251
16252 #[test]
16253 fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
16254 // Fail-before-pass-after pin on the substrate-lifted
16255 // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
16256 // per-arm predicate: for each variant in the closed accept-set the
16257 // predicate returns `true` iff the variant consumes the paired
16258 // [`Placement::shard_key`] axis under
16259 // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
16260 // partition. Today the accept-set is the singleton `{Sharded}` —
16261 // `Sharded` is the Akka-style hash-keyed distribution arm
16262 // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
16263 // §II.1) and `Replicated` (active-active) refuse the axis through
16264 // [`AplicacaoError::ShardKeyOnNonSharded`].
16265 //
16266 // Pins the per-arm truth-table so a future arm addition (an
16267 // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
16268 // roadmap names, a `WeightedShard` promotion the future M5
16269 // adaptive-placement engine acknowledges) that landed a variant
16270 // without extending this predicate's arm-set would surface as a
16271 // caixa-core build-time exhaustiveness error at the
16272 // `match self { … }` arm-fan below rather than a silent per-consumer
16273 // mis-classification at renderer emit time. The paired
16274 // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
16275 // predicate stays a distinct question — arm-identity (which the
16276 // sibling
16277 // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
16278 // pin already locks) is not cross-slot-invariant consumption; today
16279 // they trip on the same singleton but the pair migrates through
16280 // one caixa-core edit on any future arm addition.
16281 //
16282 // Peer of the sibling per-arm classifier pins
16283 // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
16284 // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
16285 // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
16286 // derived paired predicate on the post-projection typed-view axis
16287 // — same "per-arm semantic-classification predicate paired with
16288 // the arm-identity predicate the derive already emits" discipline
16289 // extended onto the M3 mesh-slot `:placement :estrategia` ↔
16290 // `:placement :shard-key` cross-slot-invariant axis.
16291 let rows: [(PlacementStrategy, bool); 3] = [
16292 (PlacementStrategy::SingleNode, false),
16293 (PlacementStrategy::Replicated, false),
16294 (PlacementStrategy::Sharded, true),
16295 ];
16296 for (variant, expected) in rows {
16297 assert_eq!(
16298 variant.requires_shard_key(),
16299 expected,
16300 "PlacementStrategy::{variant:?}.requires_shard_key() must \
16301 be {expected} (the substrate-canonical cross-slot invariant \
16302 on the :placement :shard-key axis; today `Sharded` is the \
16303 singleton consuming arm — MESH-COMPOSITION §II.4)",
16304 );
16305 }
16306 }
16307
16308 #[test]
16309 fn placement_strategy_requires_shard_key_is_const_fn() {
16310 // The [`PlacementStrategy::requires_shard_key`] cross-slot-
16311 // invariant per-arm predicate is declared `#[must_use] pub const
16312 // fn` — pin the `const`-eval posture here so a future accidental
16313 // downgrade to non-`const` (an added runtime helper reachable
16314 // only from a non-`const` context, a manual hand-rolled `impl`
16315 // that shadows the current three-arm `match self { … }` dispatch)
16316 // trips at caixa-core build time rather than surfacing as a
16317 // downstream `const`-context regression far from the declaration.
16318 // Same shape as the sibling
16319 // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
16320 // the peer [`gen_platform::IsVariant`]-derived arm-identity
16321 // predicate axis, but here the load-bearing assertions live in
16322 // module-scope `const _: () = assert!(…)` items so a violation
16323 // fails at compile time (const-eval trip) rather than test time —
16324 // strictly stronger than the runtime `assert!(CONST)` pattern the
16325 // sibling pin uses, and side-steps the
16326 // `clippy::assertions_on_constants` lint the runtime pattern
16327 // otherwise accumulates on the module baseline.
16328 //
16329 // The test body simply witnesses that the module-scope items
16330 // compiled and the runtime dispatch agrees with the const-eval
16331 // dispatch on every arm — the runtime read gives the test a
16332 // failure surface (rather than an empty test body clippy would
16333 // flag as a no-op).
16334 const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
16335 const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
16336 const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
16337 assert_eq!(
16338 [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
16339 [
16340 PlacementStrategy::SingleNode.requires_shard_key(),
16341 PlacementStrategy::Replicated.requires_shard_key(),
16342 PlacementStrategy::Sharded.requires_shard_key(),
16343 ],
16344 "runtime and const-eval dispatch on \
16345 PlacementStrategy::requires_shard_key must agree on every arm",
16346 );
16347 }
16348
16349 #[test]
16350 fn placement_estrategia_accessor_is_const_fn() {
16351 // The [`Placement::estrategia`] per-`:placement` distribution-
16352 // strategy `Copy`-return scalar accessor is declared
16353 // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
16354 // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
16355 // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
16356 // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
16357 // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
16358 // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
16359 // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
16360 // [`RateLimit`], every one a `pub const fn`). Pin the
16361 // `const`-eval posture here so a future accidental downgrade to
16362 // non-`const` (an added runtime helper reachable only from a
16363 // non-`const` context, a slot promotion to a non-`Copy` return
16364 // that would silently drop the `const` qualifier, a manual
16365 // hand-rolled shadow) trips at caixa-core build time rather
16366 // than surfacing as a downstream `const`-context regression far
16367 // from the declaration.
16368 //
16369 // Same shape as the sibling
16370 // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
16371 // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
16372 // predicate axis — the load-bearing witness lives in the
16373 // module-scope `const fn` wrapper `estrategia_via_const_fn`
16374 // below: a body that calls [`Placement::estrategia`] under a
16375 // `const fn` signature is well-formed only when the callee is
16376 // itself `const fn`, so any future accidental downgrade of
16377 // [`Placement::estrategia`] to non-`const` fails at caixa-core
16378 // build time (const-eval E0015 / E0658 depending on the arm),
16379 // strictly stronger than a runtime `assert!(CONST)` and
16380 // side-stepping the destructor-in-const restriction that
16381 // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
16382 // items on `Placement`'s `Vec<String>` / `Option<String>`
16383 // carriers.
16384 //
16385 // The runtime body witnesses that the const-eval-shaped
16386 // wrapper agrees with a direct call on every closed-set arm.
16387 const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
16388 p.estrategia()
16389 }
16390 for estrategia in [
16391 PlacementStrategy::SingleNode,
16392 PlacementStrategy::Replicated,
16393 PlacementStrategy::Sharded,
16394 ] {
16395 let placement = Placement {
16396 estrategia,
16397 clusters: Vec::new(),
16398 affinity: None,
16399 shard_key: None,
16400 };
16401 assert_eq!(
16402 estrategia_via_const_fn(&placement),
16403 placement.estrategia(),
16404 "const-fn-wrapped and direct dispatch on \
16405 Placement::estrategia must agree for {estrategia:?}",
16406 );
16407 }
16408 }
16409
16410 #[test]
16411 fn entrada_port_accessor_is_const_fn() {
16412 // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
16413 // scalar accessor is declared `#[must_use] pub const fn` —
16414 // matching the peer M3 mesh-slot `Copy`-return accessor family
16415 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
16416 // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
16417 // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
16418 // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
16419 // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
16420 // [`RateLimit::window`] on the sibling [`RateLimit`], the
16421 // sibling per-`:placement` [`Placement::estrategia`] pinned by
16422 // [`placement_estrategia_accessor_is_const_fn`] above — every
16423 // one a `pub const fn`). Pin the `const`-eval posture here so
16424 // a future accidental downgrade to non-`const` (an added
16425 // runtime helper reachable only from a non-`const` context, an
16426 // `Option<u16>`-shape migration once the substrate grows
16427 // per-`:membros` heterogeneous listener ports that would
16428 // silently drop the `const` qualifier, a manual hand-rolled
16429 // shadow) trips at caixa-core build time rather than surfacing
16430 // as a downstream `const`-context regression far from the
16431 // declaration.
16432 //
16433 // Same shape as the sibling
16434 // [`placement_estrategia_accessor_is_const_fn`] pin above — the
16435 // load-bearing witness lives in the module-scope `const fn`
16436 // wrapper `port_via_const_fn`: a body that calls
16437 // [`Entrada::port`] under a `const fn` signature is well-formed
16438 // only when the callee is itself `const fn`, side-stepping the
16439 // destructor-in-const restriction that would otherwise block a
16440 // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
16441 // `String` / `Vec<String>` carriers.
16442 //
16443 // The runtime body sweeps a representative port set spanning
16444 // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
16445 // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
16446 // ceiling — the const-fn-wrapped call must agree with a direct
16447 // call on every fixture (a violation trips the test) and every
16448 // returned scalar must byte-equal the input `port` (a violation
16449 // means the accessor stopped being a raw field-return copy).
16450 const fn port_via_const_fn(e: &Entrada) -> u16 {
16451 e.port()
16452 }
16453 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
16454 let entrada = Entrada {
16455 host: String::new(),
16456 para: String::new(),
16457 port,
16458 paths: Vec::new(),
16459 };
16460 assert_eq!(
16461 port_via_const_fn(&entrada),
16462 entrada.port(),
16463 "const-fn-wrapped and direct dispatch on Entrada::port \
16464 must agree for port={port}",
16465 );
16466 assert_eq!(
16467 entrada.port(),
16468 port,
16469 "Entrada::port must return the storage-side u16 verbatim \
16470 for port={port}",
16471 );
16472 }
16473 }
16474
16475 #[test]
16476 fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
16477 // Load-bearing cross-slot-partition pin closing the loop between
16478 // the substrate-lifted
16479 // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
16480 // the closed-set typed enum and the actual
16481 // [`AplicacaoSpec::validate_placement`] runtime behavior across
16482 // the paired `:placement :shard-key` axis: every validated
16483 // [`Placement`] past [`AplicacaoSpec::validate_placement`]
16484 // satisfies `placement.shard_key().is_some() ==
16485 // placement.estrategia().requires_shard_key()`. The four-cell
16486 // shape witness sweeps every combination of (variant in the
16487 // closed accept-set, `:shard-key` Some/None) and pins:
16488 //
16489 // * variant.requires_shard_key() && shard_key.is_some() →
16490 // validate() passes; the paired shape is the sole
16491 // `requires_shard_key` arm-family accepted shape.
16492 // * variant.requires_shard_key() && shard_key.is_none() →
16493 // validate() fails with [`AplicacaoError::ShardedWithoutKey`];
16494 // the paired shape is the refused missing-key shape on
16495 // Sharded-family arms.
16496 // * !variant.requires_shard_key() && shard_key.is_some() →
16497 // validate() fails with
16498 // [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
16499 // is the refused declared-but-inert shape on non-Sharded-
16500 // family arms.
16501 // * !variant.requires_shard_key() && shard_key.is_none() →
16502 // validate() passes; the paired shape is the sole
16503 // non-`requires_shard_key` arm-family accepted shape.
16504 //
16505 // The compile-time-exhaustive `match p.estrategia()` dispatch at
16506 // [`AplicacaoSpec::validate_placement`] preserves its structural
16507 // arm-fan (a future arm addition still surfaces a build-time
16508 // exhaustiveness error there); this pin closes the semantic loop
16509 // between the arm-fan's shape-gate cascades and the substrate-
16510 // canonical predicate every downstream consumer of the paired
16511 // shape reads through. Fail-before-pass-after locally verified by
16512 // mutating the predicate's `Sharded => true` arm to `false` — the
16513 // truthy `expects_ok` cell for `Sharded` + `Some` trips the
16514 // `validate() must pass` assertion; restoring passes. Same "close
16515 // the loop between the typed predicate and the runtime behavior"
16516 // discipline as the sibling
16517 // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
16518 // (7b97d26) cross-projection pin on the peer [`WitTarget`]
16519 // per-arm classifier axis.
16520 for variant in [
16521 PlacementStrategy::SingleNode,
16522 PlacementStrategy::Replicated,
16523 PlacementStrategy::Sharded,
16524 ] {
16525 for present in [false, true] {
16526 let mut spec = three_member_spec();
16527 spec.placement.estrategia = variant;
16528 spec.placement.shard_key = present.then(|| "tenantId".into());
16529 let expects_ok = variant.requires_shard_key() == present;
16530 let result = spec.validate();
16531 match (expects_ok, &result) {
16532 (true, Ok(())) => {}
16533 (false, Err(err)) => {
16534 // Cross-check the refusal diagnostic names the
16535 // right cell of the four-cell shape witness — the
16536 // `requires_shard_key && !present` cell must trip
16537 // [`AplicacaoError::ShardedWithoutKey`]; the
16538 // `!requires_shard_key && present` cell must trip
16539 // [`AplicacaoError::ShardKeyOnNonSharded`].
16540 match (variant.requires_shard_key(), present, err) {
16541 (true, false, AplicacaoError::ShardedWithoutKey) => {}
16542 (
16543 false,
16544 true,
16545 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
16546 ) => {
16547 assert_eq!(
16548 *e, variant,
16549 "ShardKeyOnNonSharded.estrategia must byte-equal \
16550 the paired PlacementStrategy",
16551 );
16552 }
16553 _ => panic!(
16554 "unexpected refusal for estrategia={variant:?} \
16555 present={present}: {err:?}"
16556 ),
16557 }
16558 }
16559 (true, Err(err)) => panic!(
16560 "validate() must pass for estrategia={variant:?} \
16561 present={present} (requires_shard_key={} == present={present}), \
16562 got {err:?}",
16563 variant.requires_shard_key(),
16564 ),
16565 (false, Ok(())) => panic!(
16566 "validate() must fail for estrategia={variant:?} \
16567 present={present} (requires_shard_key={} != present={present})",
16568 variant.requires_shard_key(),
16569 ),
16570 }
16571 }
16572 }
16573 }
16574
16575 #[test]
16576 fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
16577 // Pin the M3 diagnostic template routes through the typed
16578 // [`PlacementStrategy`] Display byte-string (rebound from the
16579 // prior `{estrategia:?}` `Debug` route). Pre-lift the two
16580 // routes emitted identical bytes (the `Debug` derive on a
16581 // unit variant emits the variant name verbatim, exactly what
16582 // `as_str` returns), but the two paths were structurally
16583 // independent — a future `#[serde(rename_all = "…")]`
16584 // attribute or variant rename would coordinate the wire /
16585 // `Display` / `as_str` triple through the lifted const but
16586 // leave the `Debug` route on the compiler-derived variant name,
16587 // silently desynchronizing the diagnostic byte-string from the
16588 // wire byte-string. Rebinding the template onto `Display`
16589 // ties the diagnostic to the same lifted
16590 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
16591 // emits — drift becomes structurally impossible. Pin the
16592 // byte-string here so a future edit that reverts the template
16593 // to `{estrategia:?}` is caught at caixa-core test time, not
16594 // at consumer dispatch time.
16595 for (variant, expected_scalar) in [
16596 (
16597 PlacementStrategy::SingleNode,
16598 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16599 ),
16600 (
16601 PlacementStrategy::Replicated,
16602 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16603 ),
16604 (
16605 PlacementStrategy::Sharded,
16606 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16607 ),
16608 ] {
16609 let err = AplicacaoError::PlacementWithoutClusters {
16610 estrategia: variant,
16611 };
16612 let msg = err.to_string();
16613 assert!(
16614 msg.starts_with(&format!(":placement {expected_scalar} requires")),
16615 "PlacementWithoutClusters diagnostic for {variant:?} must open \
16616 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16617 );
16618 }
16619 }
16620
16621 #[test]
16622 fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
16623 // Peer of
16624 // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
16625 // on the second M3 diagnostic that carries the typed
16626 // [`PlacementStrategy`] in its `#[error(…)]` template. Both
16627 // diagnostics now route the strategy scalar through the same
16628 // [`std::fmt::Display`] surface, tying the diagnostic
16629 // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
16630 // const set the wire format also emits. The two non-Sharded
16631 // arms are exercised here (the diagnostic exists to flag a
16632 // `:shard-key` slot the current strategy will never consume);
16633 // the peer `Sharded` arm never reaches this diagnostic (the
16634 // `Sharded` strategy consumes `:shard-key` — the
16635 // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
16636 // slot instead).
16637 for (variant, expected_scalar) in [
16638 (
16639 PlacementStrategy::SingleNode,
16640 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16641 ),
16642 (
16643 PlacementStrategy::Replicated,
16644 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16645 ),
16646 ] {
16647 let err = AplicacaoError::ShardKeyOnNonSharded {
16648 estrategia: variant,
16649 shard_key: "$tenantId".into(),
16650 };
16651 let msg = err.to_string();
16652 assert!(
16653 msg.starts_with(&format!(":placement {expected_scalar} carries")),
16654 "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
16655 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16656 );
16657 }
16658 }
16659
16660 #[test]
16661 fn placement_strategy_all_enumerates_every_variant_once() {
16662 // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
16663 // exhaustive-iteration surface: every variant appears exactly
16664 // once, and the slice length matches the arm count of the
16665 // closed set. Every consumer that walks the accepted-strategy
16666 // set (a future `feira app placement --list` CLI-side surfacing,
16667 // a future M4 admission-webhook's rejection body naming the
16668 // accepted-strategy list, the [`PlacementStrategy::from_wire`]
16669 // reverse-projection consumers that iterate the accept-set for
16670 // a "did you mean" hint) reads through this slice, so a future
16671 // variant addition (an `Anycast` mesh-anycast arm the
16672 // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
16673 // grows the enum but forgets to grow [`Self::ALL`] silently
16674 // truncates every downstream consumer's accept-set at the same
16675 // pre-addition boundary — this pin fails at caixa-core build
16676 // time on the pairwise-distinct + arm-count invariants.
16677 //
16678 // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
16679 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
16680 // pins on the peer closed-set typed-enum axes.
16681 let all: &[PlacementStrategy] = PlacementStrategy::ALL;
16682 assert_eq!(
16683 all.len(),
16684 3,
16685 "PlacementStrategy::ALL must enumerate every variant of the \
16686 three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
16687 );
16688 for (i, a) in all.iter().enumerate() {
16689 for (j, b) in all.iter().enumerate() {
16690 if i != j {
16691 assert_ne!(
16692 a, b,
16693 "PlacementStrategy::ALL must carry every variant exactly \
16694 once — got duplicate {a:?} at indices {i} and {j}"
16695 );
16696 }
16697 }
16698 }
16699 for variant in [
16700 PlacementStrategy::SingleNode,
16701 PlacementStrategy::Replicated,
16702 PlacementStrategy::Sharded,
16703 ] {
16704 assert!(
16705 all.contains(&variant),
16706 "PlacementStrategy::ALL must contain {variant:?} — a future variant \
16707 addition that grows the enum but forgets to grow the ALL slice \
16708 silently truncates every downstream consumer's accept-set at the \
16709 pre-addition boundary"
16710 );
16711 }
16712 }
16713
16714 #[test]
16715 fn placement_strategy_from_wire_accepts_every_lifted_constant() {
16716 // Fail-before-pass-after pin on the forward accept-set of the
16717 // [`PlacementStrategy::from_wire`] reverse projection: every
16718 // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
16719 // constant the [`PlacementStrategy::as_str`] emitter walks
16720 // parses back to its paired variant. Any future arm addition
16721 // that grows the emitter's `as_str` match but forgets to grow
16722 // the parser's `from_str` match silently splits the two halves
16723 // of the round-trip — the wire byte-string one non-serde
16724 // consumer parses from the one the emitter wrote — with the
16725 // failure surfacing at parse time far from the rebrand commit.
16726 // Pinning the three-arm accept-set here catches the drift at
16727 // caixa-core build time.
16728 //
16729 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
16730 // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
16731 // closed-set typed-enum `str → Self` axes.
16732 for (wire, expected) in [
16733 (
16734 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16735 PlacementStrategy::SingleNode,
16736 ),
16737 (
16738 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16739 PlacementStrategy::Replicated,
16740 ),
16741 (
16742 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16743 PlacementStrategy::Sharded,
16744 ),
16745 ] {
16746 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16747 panic!(
16748 "PlacementStrategy::from_wire({wire:?}) must accept every \
16749 M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
16750 lifted canonical byte-string that PlacementStrategy::{expected:?} \
16751 serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
16752 )
16753 });
16754 assert_eq!(
16755 parsed, expected,
16756 "PlacementStrategy::from_wire({wire:?}) must return \
16757 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
16758 );
16759 }
16760 }
16761
16762 #[test]
16763 fn placement_strategy_from_wire_round_trips_through_as_str() {
16764 // Fail-before-pass-after pin on the closed round-trip between
16765 // the forward [`PlacementStrategy::as_str`] emitter and the
16766 // reverse [`PlacementStrategy::from_wire`] parser: for every
16767 // variant in [`PlacementStrategy::ALL`], parsing the emitter's
16768 // output must return exactly the same variant. Any per-arm
16769 // divergence — a future arm added to `as_str` but not
16770 // `from_str`, an accidental copy-paste flip in one but not the
16771 // other — silently splits the emit and parse halves and the
16772 // failure surfaces at consumer parse time far from the drift
16773 // site. The `ALL`-iterating shape means a future variant
16774 // addition picks up the coverage by construction.
16775 //
16776 // Peer of the sibling [`crate::kind::tests`] round-trip pin on
16777 // [`crate::CaixaKind::from_wire`] and the
16778 // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
16779 // sibling round-trip pin on [`RateLimitUnit`].
16780 for &variant in PlacementStrategy::ALL {
16781 let wire = variant.as_str();
16782 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16783 panic!(
16784 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16785 must be Some({variant:?}) — the two halves of the round-trip \
16786 dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
16787 got None on wire byte-string {wire:?}"
16788 )
16789 });
16790 assert_eq!(
16791 parsed, variant,
16792 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16793 must round-trip to the same variant; got {parsed:?}"
16794 );
16795 }
16796 }
16797
16798 #[test]
16799 fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
16800 // Fail-before-pass-after pin on the closed-set refusal
16801 // discipline of [`PlacementStrategy::from_wire`]: every
16802 // byte-string outside the three-arm accept-set returns `None`
16803 // rather than silently collapsing onto the [`Default`]
16804 // (`Replicated`) arm or an arbitrary neighbor. The refusal set
16805 // exercised here sweeps the load-bearing drift shapes: the
16806 // empty string (a stripped serde-attribute drift), an all-
16807 // whitespace string (the canonical text-editor accidental
16808 // padding shape), the lowercased kebab-case forms a future
16809 // `#[serde(rename_all = "kebab-case")]` attribute would emit
16810 // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
16811 // coincidentally match the accepted canonical scalars, so only
16812 // `"single-node"` fires as a refusal, but pinning the case-
16813 // sensitivity of the accepted arms via the peer [`SingleNode`]
16814 // assertion in the round-trip pin makes the discipline
16815 // structurally clear), the lowercased single-word forms
16816 // (`"singlenode"`), the padded canonical scalar
16817 // (`" Sharded "`), the trailing-comma / trailing-newline shapes
16818 // (`"Sharded\n"`), and a pointer-different `&'static str` that
16819 // happens to alias a canonical byte-string by content but not
16820 // by identity (validated implicitly by the emitter's routing
16821 // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
16822 // identity a paired [`crate::assert_str_reexport_identity`] pin
16823 // in caixa-core's per-const declaration surface would catch).
16824 //
16825 // Peer of the sibling
16826 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
16827 // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
16828 for bad in [
16829 "",
16830 " ",
16831 "\n",
16832 "\t",
16833 "single-node",
16834 "singlenode",
16835 "SingleNodes",
16836 "single_node",
16837 "single node",
16838 "SINGLENODE",
16839 "SingleNode ",
16840 " SingleNode",
16841 " Sharded ",
16842 "Sharded\n",
16843 "replicated ",
16844 "sharded",
16845 "REPLICATED",
16846 "Anycast",
16847 "Global",
16848 "?",
16849 ] {
16850 assert!(
16851 PlacementStrategy::from_wire(bad).is_none(),
16852 "PlacementStrategy::from_wire({bad:?}) must return None — the \
16853 parser's accept-set is exactly the three PlacementStrategy::as_str \
16854 outputs (SingleNode, Replicated, Sharded), and this byte-string \
16855 is outside that closed set"
16856 );
16857 }
16858 }
16859
16860 #[test]
16861 fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
16862 // Fail-before-pass-after pin on the third path of the four-path
16863 // convergence: `from_str` (the reverse projection) inverts the
16864 // `Serialize` derive's wire byte-string on every variant.
16865 // Together with the pre-existing three-path convergence
16866 // (`Display` + `as_str` + `Serialize` all resolve to the same
16867 // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
16868 // the peer
16869 // [`placement_strategy_display_matches_serialized_wire_byte_string`])
16870 // this closes the round-trip: the wire byte-string the
16871 // `Serialize` derive emits parses back to the same variant
16872 // through `from_str`, so any future serde-attribute or variant-
16873 // rename drift on the emit half now surfaces as a matched drift
16874 // on the parse half at caixa-core build time — the two halves
16875 // migrate as a unit through the lifted consts on any future
16876 // rename, and the round-trip cannot silently split.
16877 //
16878 // Peer of the sibling
16879 // [`placement_strategy_display_matches_serialized_wire_byte_string`]
16880 // wire-format pin — extends the three-path convergence
16881 // (`Display` + `as_str` + `Serialize`) onto the fourth path
16882 // (`from_str`), closing the `str ↔ Self` round-trip on the
16883 // M3 `:placement :estrategia` closed-set axis.
16884 for &variant in PlacementStrategy::ALL {
16885 let wire = serde_json::to_string(&variant).unwrap();
16886 let unquoted = wire
16887 .strip_prefix('"')
16888 .and_then(|s| s.strip_suffix('"'))
16889 .expect("serialized PlacementStrategy is a JSON string");
16890 let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
16891 panic!(
16892 "PlacementStrategy::from_wire({unquoted:?}) must accept the \
16893 Serialize derive's wire byte-string for \
16894 PlacementStrategy::{variant:?} — the four-path convergence \
16895 (Display + as_str + Serialize + from_str) resolves through \
16896 the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
16897 )
16898 });
16899 assert_eq!(
16900 parsed, variant,
16901 "PlacementStrategy::from_wire of the Serialize derive's wire \
16902 byte-string for PlacementStrategy::{variant:?} must round-trip \
16903 to the same variant; got {parsed:?}"
16904 );
16905 }
16906 }
16907
16908 #[test]
16909 fn rejects_zero_policy_timeout() {
16910 let mut s = three_member_spec();
16911 s.politicas.timeout = Some(Duration::ZERO);
16912 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
16913 }
16914
16915 #[test]
16916 fn rejects_zero_policy_retries() {
16917 let mut s = three_member_spec();
16918 s.politicas.retries = Some(0);
16919 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
16920 }
16921
16922 #[test]
16923 fn rejects_policy_retries_above_cap() {
16924 // The fail-before-pass-after pin: `Some(11)` is structurally
16925 // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
16926 // passed validate on every pre-gate codebase because the
16927 // typed slot's only check was the zero-floor arm. The
16928 // thundering-herd amplification vector only surfaced at the
16929 // runtime substrate (Envoy / Cilium L7 retry overlay)
16930 // far from the source caixa.lisp with no field naming the
16931 // offending policy.
16932 let mut s = three_member_spec();
16933 s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
16934 assert_eq!(
16935 s.validate().unwrap_err(),
16936 AplicacaoError::PolicyRetriesExceedsCap {
16937 retries: POLICY_RETRIES_MAX + 1
16938 }
16939 );
16940 }
16941
16942 #[test]
16943 fn rejects_policy_retries_far_above_cap() {
16944 // The `u32::MAX` worst case — the four-billion-retry policy
16945 // a typo (`(:retries 4294967295)`) or struct-literal
16946 // copy-paste lands in the slot. Pin the cap arm's coverage
16947 // explicitly across the full `u32` overflow so a future
16948 // relaxation that drops the upper bound surfaces here.
16949 let mut s = three_member_spec();
16950 s.politicas.retries = Some(u32::MAX);
16951 assert_eq!(
16952 s.validate().unwrap_err(),
16953 AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
16954 );
16955 }
16956
16957 #[test]
16958 fn accepts_policy_retries_at_cap() {
16959 // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
16960 // must validate. The cap is inclusive on the top edge,
16961 // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16962 // discipline on the sibling [`crate::LimitsSpec::memory`]
16963 // axis. Pin the boundary explicitly so a future off-by-one
16964 // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
16965 // surfaces here as a test failure rather than a silent
16966 // contract narrowing.
16967 let mut s = three_member_spec();
16968 s.politicas.retries = Some(POLICY_RETRIES_MAX);
16969 s.validate()
16970 .expect("retries == POLICY_RETRIES_MAX must validate");
16971 }
16972
16973 #[test]
16974 fn accepts_policy_retries_typical_values() {
16975 // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
16976 // every value in the validated set must pass. The
16977 // Envoy / Istio production-playbook recommendation band
16978 // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
16979 // (`maxRetries ≤ 10`) both lie within this set.
16980 for r in 1..=POLICY_RETRIES_MAX {
16981 let mut s = three_member_spec();
16982 s.politicas.retries = Some(r);
16983 s.validate()
16984 .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
16985 }
16986 }
16987
16988 #[test]
16989 fn policy_retries_zero_takes_precedence_over_cap() {
16990 // The cross-arm ordering pin: `Some(0)` is structurally
16991 // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
16992 // (cap), but the zero-floor diagnostic is the more
16993 // self-locating one (it directly names the omit-axis
16994 // remediation), so the validate gate must fire on zero
16995 // first. Pin the order so a future refactor that reorders
16996 // the arms surfaces here as a test failure rather than a
16997 // silent diagnostic regression. Same shape every other
16998 // zero-then-shape ordering on this surface uses
16999 // ([`AplicacaoError::PolicyTimeoutZero`] then
17000 // [`AplicacaoError::PolicyTimeoutNotCanonical`];
17001 // [`AplicacaoError::PolicyBreakerZeroWindow`] then
17002 // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
17003 let mut s = three_member_spec();
17004 s.politicas.retries = Some(0);
17005 assert_eq!(
17006 s.validate().unwrap_err(),
17007 AplicacaoError::PolicyRetriesZero,
17008 "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
17009 );
17010 }
17011
17012 #[test]
17013 fn policy_retries_cap_diagnostic_carries_offending_value() {
17014 // The diagnostic-shape pin: the offending `u32` is carried
17015 // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
17016 // variant so the surfaced error message names the value the
17017 // author wrote (`":politicas :retries (47) exceeds the
17018 // mesh-policy ceiling …"`), not just the cap. Same
17019 // self-locating diagnostic shape every other typed-cap arm
17020 // on this surface carries
17021 // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
17022 // offending byte count verbatim).
17023 let mut s = three_member_spec();
17024 s.politicas.retries = Some(47);
17025 let err = s.validate().unwrap_err();
17026 assert!(
17027 matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
17028 "got {err:?}"
17029 );
17030 let msg = err.to_string();
17031 assert!(
17032 msg.contains("47"),
17033 ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
17034 );
17035 }
17036
17037 #[test]
17038 fn policy_retries_cap_is_aws_app_mesh_aligned() {
17039 // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
17040 // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
17041 // schema cap — the only upstream mesh-policy schema that
17042 // documents an explicit hard cap. Pinning the literal value
17043 // here surfaces a future drift (a relaxation to 20, a
17044 // tightening to 5) as a deliberate test edit, not a silent
17045 // contract narrowing.
17046 assert_eq!(POLICY_RETRIES_MAX, 10);
17047 }
17048
17049 #[test]
17050 fn rejects_circuit_breaker_zero_max_failures() {
17051 let mut s = three_member_spec();
17052 s.politicas.circuit_breaker = Some(CircuitBreaker {
17053 max_failures: 0,
17054 window: Duration::from_secs(60),
17055 });
17056 assert_eq!(
17057 s.validate().unwrap_err(),
17058 AplicacaoError::PolicyBreakerZeroFailures
17059 );
17060 }
17061
17062 #[test]
17063 fn rejects_circuit_breaker_max_failures_above_cap() {
17064 // The fail-before-pass-after pin: `1001` is structurally one
17065 // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
17066 // silently passed validate on every pre-gate codebase
17067 // because the typed slot's only check was the zero-floor
17068 // arm. The breaker-no-op vector only surfaced at the runtime
17069 // substrate (Envoy / Cilium L7 outlier-detection overlay)
17070 // far from the source caixa.lisp with no field naming the
17071 // offending policy.
17072 let mut s = three_member_spec();
17073 s.politicas.circuit_breaker = Some(CircuitBreaker {
17074 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17075 window: Duration::from_secs(60),
17076 });
17077 assert_eq!(
17078 s.validate().unwrap_err(),
17079 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17080 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17081 }
17082 );
17083 }
17084
17085 #[test]
17086 fn rejects_circuit_breaker_max_failures_far_above_cap() {
17087 // The `u32::MAX` worst case — the four-billion-failure
17088 // threshold a typo (`(:max-failures 4294967295)`) or a
17089 // struct-literal copy-paste lands in the slot. Pin the cap
17090 // arm's coverage explicitly across the full `u32` overflow
17091 // so a future relaxation that drops the upper bound surfaces
17092 // here.
17093 let mut s = three_member_spec();
17094 s.politicas.circuit_breaker = Some(CircuitBreaker {
17095 max_failures: u32::MAX,
17096 window: Duration::from_secs(60),
17097 });
17098 assert_eq!(
17099 s.validate().unwrap_err(),
17100 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17101 max_failures: u32::MAX,
17102 }
17103 );
17104 }
17105
17106 #[test]
17107 fn accepts_circuit_breaker_max_failures_at_cap() {
17108 // The boundary value — exactly
17109 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
17110 // cap is inclusive on the top edge, matching the
17111 // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
17112 // discipline on the sibling capped axes. Pin the boundary
17113 // explicitly so a future off-by-one tightening
17114 // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
17115 // surfaces here as a test failure rather than a silent
17116 // contract narrowing.
17117 let mut s = three_member_spec();
17118 s.politicas.circuit_breaker = Some(CircuitBreaker {
17119 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
17120 window: Duration::from_secs(60),
17121 });
17122 s.validate()
17123 .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
17124 }
17125
17126 #[test]
17127 fn accepts_circuit_breaker_max_failures_typical_values() {
17128 // The documented production-playbook band positive-control
17129 // sweep — every value Hystrix / Istio / Envoy / Polly /
17130 // Resilience4j recommend (5..=50) must pass, plus a sweep
17131 // through the hyperscale band (100, 500, 1000) the cap
17132 // accepts. Pin the inclusive validated set explicitly so a
17133 // future tightening of the ceiling surfaces here.
17134 for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
17135 let mut s = three_member_spec();
17136 s.politicas.circuit_breaker = Some(CircuitBreaker {
17137 max_failures: n,
17138 window: Duration::from_secs(60),
17139 });
17140 s.validate()
17141 .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
17142 }
17143 }
17144
17145 #[test]
17146 fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
17147 // The cross-arm ordering pin: `0` is structurally outside
17148 // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
17149 // (cap), but the zero-floor diagnostic is the more
17150 // self-locating one (it directly names the omit-axis
17151 // remediation), so the validate gate must fire on zero
17152 // first. Same shape every other zero-then-shape ordering on
17153 // this surface uses
17154 // ([`AplicacaoError::PolicyRetriesZero`] then
17155 // [`AplicacaoError::PolicyRetriesExceedsCap`];
17156 // [`AplicacaoError::PolicyTimeoutZero`] then
17157 // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
17158 let mut s = three_member_spec();
17159 s.politicas.circuit_breaker = Some(CircuitBreaker {
17160 max_failures: 0,
17161 window: Duration::from_secs(60),
17162 });
17163 assert_eq!(
17164 s.validate().unwrap_err(),
17165 AplicacaoError::PolicyBreakerZeroFailures,
17166 "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
17167 );
17168 }
17169
17170 #[test]
17171 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
17172 // The cross-arm ordering pin between the cap and the
17173 // sibling `:window` gates (zero-window, canonical-window).
17174 // A breaker carrying both an over-cap `max_failures` AND a
17175 // structurally invalid window (zero, sub-ms) must surface
17176 // the cap diagnostic first — the cap arm is wired
17177 // immediately after the zero-failure arm and strictly
17178 // before the window arms, so the offending value the
17179 // diagnostic names matches the order the author would
17180 // discover the gates by reading top-to-bottom through
17181 // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
17182 // future refactor that reorders the arms surfaces here as a
17183 // test failure rather than a silent diagnostic regression.
17184 let mut s = three_member_spec();
17185 s.politicas.circuit_breaker = Some(CircuitBreaker {
17186 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17187 window: Duration::ZERO,
17188 });
17189 assert_eq!(
17190 s.validate().unwrap_err(),
17191 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17192 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17193 },
17194 "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
17195 );
17196 }
17197
17198 #[test]
17199 fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
17200 // The diagnostic-shape pin: the offending `u32` is carried
17201 // verbatim into the
17202 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
17203 // variant so the surfaced error message names the value the
17204 // author wrote (`":politicas :circuit-breaker :max-failures
17205 // (50000) exceeds the mesh-policy ceiling …"`), not just
17206 // the cap. Same self-locating diagnostic shape every other
17207 // typed-cap arm on this surface carries
17208 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
17209 // offending retry count verbatim,
17210 // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
17211 // offending byte count verbatim).
17212 let mut s = three_member_spec();
17213 s.politicas.circuit_breaker = Some(CircuitBreaker {
17214 max_failures: 50_000,
17215 window: Duration::from_secs(60),
17216 });
17217 let err = s.validate().unwrap_err();
17218 assert!(
17219 matches!(
17220 err,
17221 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17222 max_failures: 50_000
17223 }
17224 ),
17225 "got {err:?}"
17226 );
17227 let msg = err.to_string();
17228 assert!(
17229 msg.contains("50000"),
17230 ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
17231 );
17232 }
17233
17234 #[test]
17235 fn policy_breaker_max_failures_cap_pins_canonical_value() {
17236 // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
17237 // value at 1000 — an order of magnitude above every
17238 // documented production-playbook recommendation band
17239 // (Hystrix `requestVolumeThreshold` default 20, Istio
17240 // `outlierDetection.consecutive5xxErrors` default 5, Envoy
17241 // `outlier_detection.consecutive_5xx` default 5, Polly /
17242 // Resilience4j typical 5..=50) and below the
17243 // clearly-pathological "effectively no protection" floor
17244 // (10_000, 100_000, u32::MAX). Pinning the literal value
17245 // here surfaces a future drift (a relaxation to 10_000, a
17246 // tightening to 100) as a deliberate test edit, not a
17247 // silent contract narrowing.
17248 assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
17249 }
17250
17251 #[test]
17252 fn rejects_circuit_breaker_zero_window() {
17253 let mut s = three_member_spec();
17254 s.politicas.circuit_breaker = Some(CircuitBreaker {
17255 max_failures: 5,
17256 window: Duration::ZERO,
17257 });
17258 assert_eq!(
17259 s.validate().unwrap_err(),
17260 AplicacaoError::PolicyBreakerZeroWindow
17261 );
17262 }
17263
17264 #[test]
17265 fn rejects_zero_rate_limit() {
17266 let mut s = three_member_spec();
17267 s.politicas.rate_limit = Some(RateLimit {
17268 rate: 0,
17269 window: Duration::from_secs(1),
17270 });
17271 assert_eq!(
17272 s.validate().unwrap_err(),
17273 AplicacaoError::PolicyRateLimitZero
17274 );
17275 }
17276
17277 #[test]
17278 fn rejects_rate_limit_zero_window() {
17279 // `RateLimit { rate: 100, window: Duration::ZERO }` is
17280 // constructible programmatically (the typed `Duration` field
17281 // imposes no nonzero invariant) but renders through
17282 // `rate_limit_codec::render` as `"100/0s"` — a fragment the
17283 // codec's `parse` rejects as `unknown rate-limit window unit
17284 // "0s"`. Until this validate-time gate landed the typed slot
17285 // accepted the value silently and the round-trip break only
17286 // surfaced at deserialize time (potentially in a downstream
17287 // consumer that never re-validates). Pin the rejection at
17288 // `AplicacaoSpec::validate` so the typed slot's valid set
17289 // matches the codec's round-trippable set structurally.
17290 let mut s = three_member_spec();
17291 s.politicas.rate_limit = Some(RateLimit {
17292 rate: 100,
17293 window: Duration::ZERO,
17294 });
17295 assert_eq!(
17296 s.validate().unwrap_err(),
17297 AplicacaoError::PolicyRateLimitWindowNotCanonical {
17298 window: Duration::ZERO
17299 }
17300 );
17301 }
17302
17303 #[test]
17304 fn rejects_rate_limit_arbitrary_seconds_window() {
17305 // 45 seconds is a valid `Duration` but not one of the three
17306 // canonical rate-limit windows the codec round-trips
17307 // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
17308 // refuses on round-trip — same round-trip-break shape the
17309 // zero-window arm above pins, with a non-zero magnitude to
17310 // guard against a future "reject only zero" half-measure.
17311 let mut s = three_member_spec();
17312 let window = Duration::from_secs(45);
17313 s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
17314 assert_eq!(
17315 s.validate().unwrap_err(),
17316 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17317 );
17318 }
17319
17320 #[test]
17321 fn rejects_rate_limit_two_minute_window() {
17322 // 120 seconds = 2 minutes is a "looks-canonical" but
17323 // not-canonical window: it's a clean integer multiple of the
17324 // minute unit, but the codec only round-trips the
17325 // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
17326 // A `Duration::from_secs(120)` window renders as `"100/120s"`
17327 // which the parser rejects. Pinning this case rules out a
17328 // future "accept any clean multiple of s/m/h" relaxation
17329 // that would silently break the codec contract.
17330 let mut s = three_member_spec();
17331 let window = Duration::from_secs(120);
17332 s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
17333 assert_eq!(
17334 s.validate().unwrap_err(),
17335 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17336 );
17337 }
17338
17339 #[test]
17340 fn rejects_rate_limit_subsecond_window() {
17341 // A sub-second window (e.g. 500ms) is a valid `Duration` but
17342 // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
17343 // Pin the rejection so a future relaxation can't silently
17344 // admit fractional-second windows that the codec can't
17345 // round-trip.
17346 let mut s = three_member_spec();
17347 let window = Duration::from_millis(500);
17348 s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
17349 assert_eq!(
17350 s.validate().unwrap_err(),
17351 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17352 );
17353 }
17354
17355 #[test]
17356 fn rejects_policy_rate_limit_above_cap() {
17357 // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
17358 // is structurally one past the cap and silently passed
17359 // validate on every pre-gate codebase because the typed slot's
17360 // only `rate` check was the zero-floor arm. The no-op-limiter
17361 // shape only surfaced at the runtime substrate (Envoy's
17362 // `local_rate_limit.token_bucket.max_tokens`, the future
17363 // Cilium L7 rate-limit overlay) far from the source caixa.lisp
17364 // with no field naming the offending policy.
17365 let mut s = three_member_spec();
17366 s.politicas.rate_limit = Some(RateLimit {
17367 rate: POLICY_RATE_LIMIT_MAX + 1,
17368 window: Duration::from_secs(1),
17369 });
17370 assert_eq!(
17371 s.validate().unwrap_err(),
17372 AplicacaoError::PolicyRateLimitExceedsCap {
17373 rate: POLICY_RATE_LIMIT_MAX + 1
17374 }
17375 );
17376 }
17377
17378 #[test]
17379 fn rejects_policy_rate_limit_far_above_cap() {
17380 // The `u32::MAX` worst case — the four-billion-token rate-limit
17381 // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
17382 // copy-paste lands in the slot. Pin the cap arm's coverage
17383 // explicitly across the full `u32` overflow so a future
17384 // relaxation that drops the upper bound surfaces here. Peer to
17385 // `rejects_policy_retries_far_above_cap` on the sibling
17386 // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
17387 // on the sibling `:max-failures` axis.
17388 let mut s = three_member_spec();
17389 s.politicas.rate_limit = Some(RateLimit {
17390 rate: u32::MAX,
17391 window: Duration::from_secs(1),
17392 });
17393 assert_eq!(
17394 s.validate().unwrap_err(),
17395 AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
17396 );
17397 }
17398
17399 #[test]
17400 fn accepts_policy_rate_limit_at_cap() {
17401 // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
17402 // must validate. The cap is inclusive on the top edge, matching
17403 // every other typed upper bound in this crate
17404 // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
17405 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
17406 // across all three canonical windows so a future off-by-one
17407 // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
17408 // window-conditional cap surfaces here as a test failure rather
17409 // than a silent contract narrowing.
17410 for secs in [1u64, 60, 3600] {
17411 let mut s = three_member_spec();
17412 s.politicas.rate_limit = Some(RateLimit {
17413 rate: POLICY_RATE_LIMIT_MAX,
17414 window: Duration::from_secs(secs),
17415 });
17416 s.validate().unwrap_or_else(|e| {
17417 panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
17418 });
17419 }
17420 }
17421
17422 #[test]
17423 fn accepts_policy_rate_limit_typical_values() {
17424 // The documented production-playbook recommendation band —
17425 // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
17426 // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
17427 // Enterprise ~1M per-hour. Every value in the validated set
17428 // must pass; pin the band explicitly so a future tightening
17429 // surfaces here.
17430 for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
17431 for secs in [1u64, 60, 3600] {
17432 let mut s = three_member_spec();
17433 s.politicas.rate_limit = Some(RateLimit {
17434 rate,
17435 window: Duration::from_secs(secs),
17436 });
17437 s.validate().unwrap_or_else(|e| {
17438 panic!("rate={rate} window={secs}s must validate; got {e:?}")
17439 });
17440 }
17441 }
17442 }
17443
17444 #[test]
17445 fn policy_rate_limit_zero_takes_precedence_over_cap() {
17446 // The cross-arm ordering pin: `rate == 0` is structurally
17447 // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
17448 // (cap), but the zero-floor diagnostic is the more
17449 // self-locating one (it directly names the omit-axis
17450 // remediation). Pin the order so a future refactor that
17451 // reorders the arms surfaces here as a test failure rather
17452 // than a silent diagnostic regression. Same shape every other
17453 // zero-then-cap ordering on this surface uses
17454 // ([`AplicacaoError::PolicyRetriesZero`] then
17455 // [`AplicacaoError::PolicyRetriesExceedsCap`];
17456 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17457 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17458 let mut s = three_member_spec();
17459 s.politicas.rate_limit = Some(RateLimit {
17460 rate: 0,
17461 window: Duration::from_secs(1),
17462 });
17463 assert_eq!(
17464 s.validate().unwrap_err(),
17465 AplicacaoError::PolicyRateLimitZero,
17466 "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
17467 );
17468 }
17469
17470 #[test]
17471 fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
17472 // Two-axis-bad pin: rate above cap *and* window non-canonical.
17473 // The validate gate must fire on the rate cap first — the
17474 // amplification-shape (no-op limiter) diagnostic is the more
17475 // fundamental one; the window-canonical diagnostic is the
17476 // narrower codec-round-trip shape. Pin the ordering so a future
17477 // refactor that reorders the rate-then-window check arms
17478 // surfaces here as a test failure rather than a silent
17479 // diagnostic regression.
17480 let mut s = three_member_spec();
17481 s.politicas.rate_limit = Some(RateLimit {
17482 rate: POLICY_RATE_LIMIT_MAX + 1,
17483 window: Duration::from_secs(45),
17484 });
17485 assert_eq!(
17486 s.validate().unwrap_err(),
17487 AplicacaoError::PolicyRateLimitExceedsCap {
17488 rate: POLICY_RATE_LIMIT_MAX + 1
17489 },
17490 "above-cap rate must surface the cap diagnostic, not the window diagnostic"
17491 );
17492 }
17493
17494 #[test]
17495 fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
17496 // The diagnostic-shape pin: the offending `u32` is carried
17497 // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
17498 // variant so the surfaced error message names the value the
17499 // author wrote (`":politicas :rate-limit rate (5000000) exceeds
17500 // the mesh-policy ceiling …"`), not just the cap. Same
17501 // self-locating diagnostic shape every other typed-cap arm on
17502 // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
17503 // carries the offending retries count verbatim,
17504 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
17505 // the offending failure count verbatim).
17506 let mut s = three_member_spec();
17507 s.politicas.rate_limit = Some(RateLimit {
17508 rate: 5_000_000,
17509 window: Duration::from_secs(1),
17510 });
17511 let err = s.validate().unwrap_err();
17512 assert!(
17513 matches!(
17514 err,
17515 AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
17516 ),
17517 "got {err:?}"
17518 );
17519 let msg = err.to_string();
17520 assert!(
17521 msg.contains("5000000"),
17522 ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
17523 );
17524 }
17525
17526 #[test]
17527 fn policy_rate_limit_cap_pins_canonical_value() {
17528 // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
17529 // 1_000_000 — two-to-three orders of magnitude above every
17530 // documented production-playbook recommendation band (Envoy /
17531 // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
17532 // Gateway 10_000..=100_000 per-minute) and below the
17533 // clearly-pathological "paste-from-binary blob" floor
17534 // (100_000_000, u32::MAX). Pinning the literal value here
17535 // surfaces a future drift (a relaxation to 10_000_000, a
17536 // tightening to 100_000) as a deliberate test edit, not a
17537 // silent contract narrowing.
17538 assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
17539 }
17540
17541 #[test]
17542 fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
17543 // Both axes are invalid here: rate == 0 *and* window is
17544 // non-canonical. The validate gate must fire on rate first
17545 // (matching the existing `rejects_zero_rate_limit` ordering),
17546 // so the existing diagnostic continues to lead with the
17547 // simpler "zero rate" framing. Pinning the order of checks
17548 // so a future refactor that reorders the arms surfaces here
17549 // as a test failure rather than a silent diagnostic
17550 // regression.
17551 let mut s = three_member_spec();
17552 s.politicas.rate_limit = Some(RateLimit {
17553 rate: 0,
17554 window: Duration::from_secs(45),
17555 });
17556 assert_eq!(
17557 s.validate().unwrap_err(),
17558 AplicacaoError::PolicyRateLimitZero
17559 );
17560 }
17561
17562 #[test]
17563 fn rate_limit_canonical_windows_validate() {
17564 // The three canonical windows the codec round-trips
17565 // losslessly — 1s / 60s / 3600s — must all pass `validate()`
17566 // unchanged. Pin the full canonical set as a positive case
17567 // (the existing `rate_limit_round_trip_seconds` /
17568 // `rate_limit_round_trip_minutes` tests pin the
17569 // serialize-then-deserialize property at the codec layer; this
17570 // test pins the validate-side complement so a future tightening
17571 // of the canonical set — e.g. dropping `:hour` — surfaces here
17572 // as a test failure rather than a silent contract narrowing).
17573 for secs in [1u64, 60, 3600] {
17574 let mut s = three_member_spec();
17575 s.politicas.rate_limit = Some(RateLimit {
17576 rate: 100,
17577 window: Duration::from_secs(secs),
17578 });
17579 s.validate().expect("canonical window must validate");
17580 }
17581 }
17582
17583 #[test]
17584 fn rate_limit_validated_value_round_trips_through_codec() {
17585 // The structural property the validate gate enforces:
17586 // every `RateLimit` past `AplicacaoSpec::validate` round-trips
17587 // losslessly through the `rate_limit_codec` (serialize → string
17588 // → deserialize → equal value). Pin this end-to-end so a future
17589 // change to either side (the validate gate's accepted window
17590 // set, the codec's parse/render unit set) that breaks the
17591 // alignment surfaces here. The previous-state shape (typed
17592 // slot accepts arbitrary `Duration`, codec only round-trips
17593 // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
17594 // window — the validate gate now forecloses that.
17595 for secs in [1u64, 60, 3600] {
17596 let mut s = three_member_spec();
17597 s.politicas.rate_limit = Some(RateLimit {
17598 rate: 250,
17599 window: Duration::from_secs(secs),
17600 });
17601 s.validate().unwrap();
17602 let json = serde_json::to_string(&s.politicas).unwrap();
17603 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17604 assert_eq!(
17605 back.rate_limit, s.politicas.rate_limit,
17606 "every validated :rate-limit must round-trip losslessly through the codec"
17607 );
17608 }
17609 }
17610
17611 #[test]
17612 fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
17613 // The hour-window canonical form (`"<n>/h"`) was missing from
17614 // the prior `rate_limit_round_trip_seconds` / `_minutes` test
17615 // pair. Now that the validate gate pins 3600s as part of the
17616 // canonical set, pin its serialize-side render shape too so
17617 // the third leg of the s/m/h tripod is explicitly tested.
17618 let policy = MeshPolicy {
17619 rate_limit: Some(RateLimit {
17620 rate: 10000,
17621 window: Duration::from_secs(3600),
17622 }),
17623 ..Default::default()
17624 };
17625 let json = serde_json::to_string(&policy).unwrap();
17626 assert!(
17627 json.contains("\"10000/h\""),
17628 "hour-window canonical form must render with `h` suffix (got: {json})"
17629 );
17630 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17631 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
17632 }
17633
17634 #[test]
17635 fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
17636 // Pin the substrate-primitive [`RateLimit::canonical_unit`]
17637 // typed accessor's accepted-window set against the codec's
17638 // accepted set explicitly. A future addition to the codec
17639 // (e.g. accepting `:day`/`:week` as authoring units) must be
17640 // accompanied by a parallel addition here, and a regression
17641 // that drops one of the three canonical units from either
17642 // side surfaces as a test failure. The accessor is the
17643 // single source of truth for the canonical-window set —
17644 // [`AplicacaoSpec::validate_politicas`]'s canonical-window
17645 // gate and [`rate_limit_codec::render`]'s canonical arm both
17646 // read through it — this test enshrines that its
17647 // `Duration → Option<RateLimitUnit>` projection matches the
17648 // codec's parse / render arms' accepted-window set exactly.
17649 //
17650 // Predecessor: this pin previously read the module-private
17651 // free helper `is_canonical_rate_limit_window` — a delegate
17652 // that composed [`RateLimitUnit::from_window`] with `.is_some()`
17653 // — but the helper had no production consumers left after the
17654 // validate-gate migration onto [`RateLimit::canonical_unit`]
17655 // and was deleted; the closed-set arm-window bijection now
17656 // lives on exactly one typed dispatch on the substrate
17657 // primitive.
17658 let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
17659 RateLimit { rate: 1, window }.canonical_unit()
17660 };
17661 assert!(canonical_unit(Duration::from_secs(1)).is_some());
17662 assert!(canonical_unit(Duration::from_secs(60)).is_some());
17663 assert!(canonical_unit(Duration::from_secs(3600)).is_some());
17664 // Non-canonical windows the accessor rejects.
17665 assert!(canonical_unit(Duration::ZERO).is_none());
17666 assert!(canonical_unit(Duration::from_secs(2)).is_none());
17667 assert!(canonical_unit(Duration::from_secs(30)).is_none());
17668 assert!(canonical_unit(Duration::from_secs(120)).is_none());
17669 assert!(canonical_unit(Duration::from_secs(86400)).is_none());
17670 // Sub-second windows: even `Duration::from_millis(1000)` is
17671 // exactly 1s and accepted; `Duration::from_millis(500)` is
17672 // sub-second and rejected.
17673 assert!(canonical_unit(Duration::from_millis(1000)).is_some());
17674 assert!(canonical_unit(Duration::from_millis(500)).is_none());
17675 assert!(canonical_unit(Duration::from_millis(1500)).is_none());
17676 }
17677
17678 #[test]
17679 fn rate_limit_unit_table_projections_are_mutual_inverses() {
17680 // Bidirection pin against the closed-set typed enum
17681 // [`RateLimitUnit`] arm-table (the canonical
17682 // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
17683 // of the rate-limit unit surface reads from). The two
17684 // projection directions [`RateLimitUnit::from_suffix`] /
17685 // [`RateLimitUnit::window`] (str → Duration, exposed as one
17686 // typed dispatch through [`RateLimitUnit::window_from_suffix`])
17687 // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
17688 // (Duration → str, exposed as one typed dispatch through
17689 // [`RateLimit::canonical_unit`] composed with
17690 // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
17691 // codec's parse arm ([`rate_limit_codec::parse`] via
17692 // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
17693 // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
17694 // and the validate gate ([`AplicacaoSpec::validate_politicas`]
17695 // via [`RateLimit::canonical_unit`]) all key off. A future
17696 // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
17697 // sub-second window) is one variant + one arm per method on the
17698 // closed-set enum; the compiler-enforced exhaustiveness on
17699 // every consumer's `match self` arms picks it up by
17700 // construction. This pin enshrines that both projection
17701 // directions agree on every canonical arm row and neither
17702 // leaks a spurious entry the other doesn't recognize.
17703 //
17704 // Predecessor: this test previously read the two vestigial
17705 // module-private free helpers `rate_limit_window_unit` and
17706 // `rate_limit_window_from_unit` on the `Duration → &str` and
17707 // `&str → Duration` axes; the former was deleted after its
17708 // sole production consumer ([`rate_limit_codec::render`])
17709 // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
17710 // the latter is folded here into the substrate primitive
17711 // [`RateLimitUnit::window_from_suffix`] so both projection
17712 // directions live on the closed-set enum's arm-table.
17713 for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
17714 let window = super::RateLimitUnit::window_from_suffix(unit)
17715 .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
17716 assert_eq!(
17717 window,
17718 Duration::from_secs(secs),
17719 "unit {unit:?} must resolve to {secs}s"
17720 );
17721 let projected_suffix = RateLimit { rate: 1, window }
17722 .canonical_unit()
17723 .map(super::RateLimitUnit::as_suffix);
17724 assert_eq!(
17725 projected_suffix,
17726 Some(unit),
17727 "Duration({secs}s) must render as {unit:?} \
17728 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
17729 );
17730 }
17731 // Non-table units yield None on the `unit → Duration`
17732 // projection — a future `"d"` addition to the table would
17733 // flip this arm; today it pins the current three-row table's
17734 // rejection semantics.
17735 assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
17736 assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
17737 assert!(super::RateLimitUnit::window_from_suffix("").is_none());
17738 // Non-table Durations yield None on the `Duration → unit`
17739 // projection — pins that the two projections agree on the
17740 // "not in the table" semantic too, so a drift where the
17741 // parse-side accepts a value the render-side can't emit is
17742 // a build error at the two-arm pair, not a silent codec
17743 // round-trip break.
17744 let projected_suffix = |window: Duration| -> Option<&'static str> {
17745 RateLimit { rate: 1, window }
17746 .canonical_unit()
17747 .map(super::RateLimitUnit::as_suffix)
17748 };
17749 assert!(projected_suffix(Duration::from_secs(2)).is_none());
17750 assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
17751 assert!(projected_suffix(Duration::from_millis(1500)).is_none());
17752 }
17753
17754 #[test]
17755 fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
17756 // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
17757 // substrate-primitive `&str → Duration` associated method the
17758 // codec's parse arm ([`rate_limit_codec::parse`]) now routes
17759 // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
17760 // to the same [`Duration`] the two-step composition
17761 // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
17762 // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
17763 // `"MIN"`) must project to [`None`] on both paths. A future
17764 // implementation of `window_from_suffix` that took a shortcut
17765 // through a per-suffix `match` table (bypassing the arm-table's
17766 // `Self::from_suffix` scan and the arm-table's `Self::window`
17767 // dispatch) would silently split the accept-set — the parse
17768 // arm would accept a suffix the enum's arm-table doesn't know,
17769 // or reject a suffix the enum's arm-table does; this pin
17770 // surfaces that drift at caixa-core build time rather than at a
17771 // downstream serde round-trip audit on a live `MeshPolicy`.
17772 //
17773 // Same byte-parity discipline the sibling
17774 // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
17775 // pin carries on the peer `Duration → RateLimitUnit` axis via
17776 // [`RateLimit::canonical_unit`], and the peer
17777 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17778 // carries on the bidirectional arm-table axis — extended here
17779 // onto the fifth (and last unlifted) projection axis on the
17780 // closed-set enum's arm-table.
17781 let composition = |suffix: &str| -> Option<Duration> {
17782 super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
17783 };
17784 for suffix in ["s", "m", "h"] {
17785 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17786 let via_composition = composition(suffix);
17787 assert_eq!(
17788 via_method, via_composition,
17789 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17790 from_suffix({suffix:?}).map(window) — the substrate-primitive \
17791 method must delegate to the arm-table's two typed dispatches, \
17792 not shortcut through a per-suffix match table"
17793 );
17794 assert!(
17795 via_method.is_some(),
17796 "canonical suffix {suffix:?} must resolve to Some(Duration) via \
17797 RateLimitUnit::window_from_suffix"
17798 );
17799 }
17800 for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
17801 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17802 let via_composition = composition(suffix);
17803 assert_eq!(
17804 via_method, via_composition,
17805 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17806 from_suffix({suffix:?}).map(window) on the non-arm rejection \
17807 axis too"
17808 );
17809 assert!(
17810 via_method.is_none(),
17811 "non-arm suffix {suffix:?} must project to None via \
17812 RateLimitUnit::window_from_suffix — a future extension that \
17813 accepted this suffix without a corresponding arm on the enum \
17814 would split the codec's parse-accepted set from the enum's \
17815 arm-table"
17816 );
17817 }
17818 // And the codec's parse arm now reads through this method: a
17819 // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
17820 // the same `Duration` the method returns for its unit, closing
17821 // the two-consumer drift surface (the codec's parse arm and the
17822 // enum's arm-table) with one typed dispatch on the substrate
17823 // primitive.
17824 for suffix in ["s", "m", "h"] {
17825 let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
17826 let mp: MeshPolicy = serde_json::from_str(&wire)
17827 .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
17828 let parsed = mp.rate_limit().expect("rate_limit payload present");
17829 let via_method = super::RateLimitUnit::window_from_suffix(suffix)
17830 .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
17831 assert_eq!(
17832 parsed.window(),
17833 via_method,
17834 "codec parse arm on {wire:?} must resolve the window through \
17835 RateLimitUnit::window_from_suffix, not a divergent path"
17836 );
17837 }
17838 }
17839
17840 #[test]
17841 fn rate_limit_unit_all_enumerates_every_arm_once() {
17842 // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
17843 // enumerate every arm of the closed-set enum exactly once, in
17844 // the canonical shortest-to-longest window order (Second before
17845 // Minute before Hour) — the same order the sibling
17846 // [`crate::supervisor::RestartStrategy`] /
17847 // [`crate::supervisor::RestartPolicy`] /
17848 // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
17849 // typed enums carry (the arm declared first is the arm listed
17850 // first). A future variant addition that extends the enum
17851 // without appending to [`RateLimitUnit::ALL`] leaves the
17852 // exhaustive iteration surface silently short one arm — the
17853 // codec's parse arm would then reject the new suffix even
17854 // though the enum knows it. This pin closes the drift.
17855 assert_eq!(
17856 super::RateLimitUnit::ALL,
17857 &[
17858 super::RateLimitUnit::Second,
17859 super::RateLimitUnit::Minute,
17860 super::RateLimitUnit::Hour,
17861 ],
17862 "RateLimitUnit::ALL must enumerate every arm exactly once, \
17863 in canonical shortest-to-longest window order"
17864 );
17865 }
17866
17867 #[test]
17868 fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
17869 // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
17870 // every arm's [`RateLimitUnit::as_suffix`] output must parse
17871 // back through [`RateLimitUnit::from_suffix`] to the same
17872 // variant. A future arm addition that lands `as_suffix` but
17873 // forgets `from_suffix` (`from_suffix` iterates
17874 // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
17875 // is the load-bearing carrier of the round-trip; the sibling
17876 // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
17877 // the `ALL` half) trips here at caixa-core build time rather
17878 // than surfacing as a codec round-trip miss (a `render` emit
17879 // that lands a suffix the paired `parse` cannot decode).
17880 for unit in super::RateLimitUnit::ALL {
17881 let suffix = unit.as_suffix();
17882 let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
17883 panic!(
17884 "RateLimitUnit::from_suffix({suffix:?}) must accept every \
17885 RateLimitUnit::as_suffix output — got None for {unit:?}"
17886 )
17887 });
17888 assert_eq!(
17889 parsed, *unit,
17890 "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
17891 must return RateLimitUnit::{unit:?}"
17892 );
17893 }
17894 }
17895
17896 #[test]
17897 fn rate_limit_unit_from_window_and_window_round_trip() {
17898 // Total round-trip pin on the `(from_window, window)` pair:
17899 // every arm's [`RateLimitUnit::window`] output must parse back
17900 // through [`RateLimitUnit::from_window`] to the same variant.
17901 // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
17902 // on the peer `Duration` axis — the two round-trip pins
17903 // together enshrine that both projections of the typed
17904 // canonical-unit bijection are total on the arm-set.
17905 for unit in super::RateLimitUnit::ALL {
17906 let window = unit.window();
17907 let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
17908 panic!(
17909 "RateLimitUnit::from_window({window:?}) must accept every \
17910 RateLimitUnit::window output — got None for {unit:?}"
17911 )
17912 });
17913 assert_eq!(
17914 parsed, *unit,
17915 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17916 must return RateLimitUnit::{unit:?}"
17917 );
17918 }
17919 }
17920
17921 #[test]
17922 fn rate_limit_unit_from_window_accessor_is_const_fn() {
17923 // Fail-before-pass-after pin: witnesses the
17924 // [`RateLimitUnit::from_window`] `const`-eval posture via a
17925 // `const fn` wrapper `from_window_via_const_fn(window: Duration)
17926 // -> Option<RateLimitUnit>` whose body calls
17927 // `RateLimitUnit::from_window(window)`, well-formed only when
17928 // the callee is itself `const fn` (any future downgrade to
17929 // non-`const` fails at caixa-core build time with E0015 `cannot
17930 // call non-const function`, strictly stronger than a runtime
17931 // `assert!`, side-stepping the destructor-in-const restriction
17932 // that blocks direct `const _: Option<RateLimitUnit> =
17933 // RateLimitUnit::from_window(...)` items on `Duration`'s
17934 // carrier). The runtime body sweeps every closed-set
17935 // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
17936 // rejection sample (`Duration::from_millis(500)` sub-second
17937 // residue) and asserts the wrapped and direct dispatches agree
17938 // — a violation means the wrapper stopped compiling under a
17939 // future `const`-posture downgrade, or the reverse resolver's
17940 // arm-set silently split from the peer `Self::window` emitter's
17941 // arm-set. Peer of the sibling
17942 // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
17943 // (152c868) /
17944 // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
17945 // (152c868) /
17946 // [`entrada_port_accessor_is_const_fn`] (bafa004) /
17947 // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
17948 // `const`-eval-surface pins on the peer M2 / M3 substrate-
17949 // primitive `Copy`-return accessor axes, extended onto the
17950 // reverse `Duration → RateLimitUnit` projection axis on the
17951 // M3 mesh-slot rate-limit closed-set typed enum.
17952 const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
17953 super::RateLimitUnit::from_window(window)
17954 }
17955 for unit in super::RateLimitUnit::ALL {
17956 let window = unit.window();
17957 let via_wrapper = from_window_via_const_fn(window);
17958 let direct = super::RateLimitUnit::from_window(window);
17959 assert_eq!(
17960 via_wrapper, direct,
17961 "RateLimitUnit::from_window({window:?}) via const fn \
17962 wrapper must agree with direct dispatch for {unit:?}"
17963 );
17964 assert_eq!(
17965 via_wrapper,
17966 Some(*unit),
17967 "RateLimitUnit::from_window({window:?}) via const fn \
17968 wrapper must return Some({unit:?}) for the peer \
17969 window() output"
17970 );
17971 }
17972 assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
17973 assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
17974 }
17975
17976 #[test]
17977 fn rate_limit_unit_from_window_composes_through_window_accessor() {
17978 // Composition-witness pin on the routing-through-peer discipline:
17979 // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
17980 // through the peer `pub const fn` [`RateLimitUnit::window`]
17981 // canonical-`Duration` projection rather than a hand-authored
17982 // per-arm second-magnitude literal — a future arm-magnitude edit
17983 // on the sibling `window()` accessor (a `Second → 2s` typo, a
17984 // `Hour → 3599s` off-by-one) must therefore reach this reverse
17985 // resolver by construction. A pin that hard-coded the three
17986 // second-magnitudes here would silently split from the peer
17987 // emitter on any such edit; instead, this pin asserts the
17988 // composition invariant `from_window(u.window()) == Some(u)`
17989 // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
17990 // arm — a violation means either the peer `Self::window`
17991 // accessor drifted (breaking every downstream consumer that
17992 // reads through it), or the reverse resolver stopped routing
17993 // through the peer (introducing a hand-authored literal that
17994 // silently disagrees with the emitter). Either failure is a
17995 // caixa-core-build-time surface, not a downstream renderer
17996 // round-trip regression.
17997 //
17998 // Peer of the sibling
17999 // [`crate::render::assert_str_reexport_identity`] discipline on
18000 // the substrate-primitive `&'static str` re-export axis and the
18001 // [`rate_limit_unit_from_window_and_window_round_trip`]
18002 // round-trip pin on the peer projection direction; extends the
18003 // one-canonical-dispatch-per-projection discipline onto the
18004 // reverse-resolver's per-arm probe axis.
18005 for unit in super::RateLimitUnit::ALL {
18006 let window_via_peer = unit.window();
18007 let resolved = super::RateLimitUnit::from_window(window_via_peer);
18008 assert_eq!(
18009 resolved,
18010 Some(*unit),
18011 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
18012 must return Some({unit:?}) — the reverse resolver's per-arm \
18013 probes must route through the peer `Self::window` accessor \
18014 so any future arm-magnitude edit reaches both projection \
18015 directions by construction"
18016 );
18017 }
18018 }
18019
18020 #[test]
18021 fn rate_limit_canonical_unit_accessor_is_const_fn() {
18022 // Fail-before-pass-after pin: witnesses the
18023 // [`RateLimit::canonical_unit`] `const`-eval posture via a
18024 // `const fn` wrapper
18025 // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
18026 // whose body calls `rl.canonical_unit()`, well-formed only when
18027 // the callee is itself `const fn` (any future downgrade to
18028 // non-`const` fails at caixa-core build time with E0015 `cannot
18029 // call non-const method`). The runtime body sweeps every
18030 // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
18031 // constructs a typed [`RateLimit`] with the peer `Self::window`
18032 // canonical `Duration`, then asserts both the wrapper and the
18033 // direct dispatch agree and both return `Some(unit)`. Composes
18034 // with the sibling
18035 // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
18036 // typed [`RateLimit`] projection layer's `const`-posture is
18037 // load-bearing on the reverse resolver's `const`-posture, and
18038 // both must migrate together (a downgrade of either surface
18039 // splits the paired `const`-eval-surface pass on the M3
18040 // mesh-slot rate-limit `Duration ↔ Self` bijection).
18041 const fn canonical_unit_via_const_fn(
18042 rl: &super::RateLimit,
18043 ) -> Option<super::RateLimitUnit> {
18044 rl.canonical_unit()
18045 }
18046 for unit in super::RateLimitUnit::ALL {
18047 let rl = super::RateLimit {
18048 rate: 1,
18049 window: unit.window(),
18050 };
18051 let via_wrapper = canonical_unit_via_const_fn(&rl);
18052 let direct = rl.canonical_unit();
18053 assert_eq!(
18054 via_wrapper, direct,
18055 "RateLimit::canonical_unit() via const fn wrapper must \
18056 agree with direct dispatch for {unit:?}"
18057 );
18058 assert_eq!(
18059 via_wrapper,
18060 Some(*unit),
18061 "RateLimit::canonical_unit() via const fn wrapper must \
18062 return Some({unit:?}) for a RateLimit whose window is \
18063 the peer RateLimitUnit::{unit:?}.window() output"
18064 );
18065 }
18066 }
18067
18068 #[test]
18069 fn rate_limit_unit_projections_are_pairwise_distinct() {
18070 // Distinctness pin: [`RateLimitUnit::as_suffix`] and
18071 // [`RateLimitUnit::window`] outputs must be pairwise distinct
18072 // across every arm — an accidental copy-paste flip that
18073 // reroutes one arm's suffix or window to also match another
18074 // silently collapses two arms onto one, so
18075 // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
18076 // (both using `find` on `Self::ALL`) would return whichever
18077 // arm the linear scan lands on first — a match-arm-ordering-
18078 // dependent outcome the closed-set typed-enum shape is meant
18079 // to rule out structurally. Peer of the sibling
18080 // `caixa_kind_wire_consts_are_pairwise_distinct` /
18081 // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
18082 // other closed-set typed-enum discriminator axes.
18083 let all = super::RateLimitUnit::ALL;
18084 for (i, a) in all.iter().enumerate() {
18085 for (j, b) in all.iter().enumerate() {
18086 if i != j {
18087 assert_ne!(
18088 a.as_suffix(),
18089 b.as_suffix(),
18090 "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
18091 must be distinct — a collision silently collapses two \
18092 arms onto one under from_suffix's linear scan"
18093 );
18094 assert_ne!(
18095 a.window(),
18096 b.window(),
18097 "RateLimitUnit::{a:?}.window() and {b:?}.window() \
18098 must be distinct — a collision silently collapses two \
18099 arms onto one under from_window's linear scan"
18100 );
18101 }
18102 }
18103 }
18104 }
18105
18106 #[test]
18107 fn rate_limit_unit_display_routes_through_as_suffix() {
18108 // Route pin: [`std::fmt::Display`] must byte-equal
18109 // [`RateLimitUnit::as_suffix`] on every arm — the single
18110 // source of truth for the canonical suffix. A future
18111 // reimplementation that hand-rolls the arms instead of
18112 // delegating to [`RateLimitUnit::as_suffix`] would silently
18113 // desynchronize `format!("{u}")` from the codec's parse arm
18114 // (which uses `as_suffix` to compare suffixes). Peer of the
18115 // sibling `caixa_kind_display_routes_through_as_str_helper` /
18116 // `placement_strategy_display_routes_through_as_str_helper`
18117 // pins on the peer closed-set typed-enum Display axes.
18118 for unit in super::RateLimitUnit::ALL {
18119 assert_eq!(
18120 unit.to_string(),
18121 unit.as_suffix(),
18122 "RateLimitUnit::{unit:?} Display must route through \
18123 as_suffix (single source of truth: the canonical suffix \
18124 the codec parses and renders)"
18125 );
18126 }
18127 }
18128
18129 #[test]
18130 fn rate_limit_unit_from_window_rejects_non_canonical() {
18131 // Rejection pin on the parser's accept-set: any Duration
18132 // outside the three-arm [`RateLimitUnit::window`] output set
18133 // (sub-second residue, or a second-magnitude outside `{1, 60,
18134 // 3600}`) must return `None`. A future accidental widening of
18135 // the accept-set (rounding down sub-second residue to the
18136 // nearest arm, admitting `Duration::from_secs(30)` as a
18137 // half-minute unit) would silently drift the parser's accept-
18138 // set from the emitter's — a validated slot with a
18139 // non-canonical window would then round-trip through the
18140 // codec to a canonical form the author never wrote.
18141 assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
18142 assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
18143 assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
18144 assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
18145 assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
18146 assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
18147 assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
18148 }
18149
18150 #[test]
18151 fn rate_limit_unit_from_suffix_rejects_unknown() {
18152 // Rejection pin on the suffix parser's accept-set: any string
18153 // outside the three-arm [`RateLimitUnit::as_suffix`] output
18154 // set must return `None`. Peer of the sibling
18155 // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
18156 // the [`crate::CaixaKind`] `from_wire` accept-set.
18157 for bad in [
18158 "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
18159 " s",
18160 ] {
18161 assert!(
18162 super::RateLimitUnit::from_suffix(bad).is_none(),
18163 "RateLimitUnit::from_suffix({bad:?}) must return None — the \
18164 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
18165 outputs"
18166 );
18167 }
18168 }
18169
18170 #[test]
18171 fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
18172 // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
18173 // every canonical `:window` magnitude the validate gate
18174 // accepts must map to the paired [`RateLimitUnit`] arm through
18175 // this accessor. A future validate-gate rebrand that widened
18176 // the accepted-window set without extending [`RateLimitUnit`]
18177 // would silently split the accessor's `Some`-return set from
18178 // the validate gate's accept-set — a slot that satisfies
18179 // validate would land at the accessor with `None`, so a
18180 // consumer past validate that pattern-matches on the returned
18181 // `Some` would silently miss the newly-accepted magnitude.
18182 for (window_secs, expected) in [
18183 (1u64, super::RateLimitUnit::Second),
18184 (60, super::RateLimitUnit::Minute),
18185 (3600, super::RateLimitUnit::Hour),
18186 ] {
18187 let rl = RateLimit {
18188 rate: 100,
18189 window: Duration::from_secs(window_secs),
18190 };
18191 assert_eq!(
18192 rl.canonical_unit(),
18193 Some(expected),
18194 "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
18195 must return Some({expected:?})"
18196 );
18197 }
18198 // Non-canonical windows the validate gate rejects also return
18199 // None here — the accessor is the typed-enum projection of
18200 // the sibling `is_canonical_rate_limit_window` predicate.
18201 let bad = RateLimit {
18202 rate: 100,
18203 window: Duration::from_secs(30),
18204 };
18205 assert!(
18206 bad.canonical_unit().is_none(),
18207 "RateLimit with a non-canonical window must return None from \
18208 canonical_unit — the validate gate rejects the same set"
18209 );
18210 }
18211
18212 #[test]
18213 fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
18214 // Fail-before-pass-after byte-parity pin: for every canonical
18215 // window the [`rate_limit_codec::render`] arm's emitted string
18216 // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
18217 // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
18218 // the vestigial free helper [`rate_limit_window_unit`] (a
18219 // `find_map`-walked `Duration → &'static str` delegate) onto the
18220 // substrate primitive [`RateLimit::canonical_unit`] typed method
18221 // (a closed-set `match self.window` arm on
18222 // [`RateLimitUnit::from_window`], projected through
18223 // [`RateLimitUnit::as_suffix`] via the enum's
18224 // [`std::fmt::Display`] impl). A future re-routing of the render
18225 // arm through a differently-computed unit projection would break
18226 // this pin at build time rather than as a silent per-consumer
18227 // codec round-trip drift far from the substrate primitive edit.
18228 //
18229 // Sibling to the peer
18230 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
18231 // on the free-helper axis: that pin locks the two projections
18232 // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
18233 // on the closed-set arm table; this pin locks the codec's render
18234 // arm reads through the typed accessor rather than the free
18235 // helper. Two production consumers of the canonical-unit axis
18236 // now key off one typed dispatch on the substrate primitive.
18237 for (window_secs, unit) in [
18238 (1u64, super::RateLimitUnit::Second),
18239 (60, super::RateLimitUnit::Minute),
18240 (3600, super::RateLimitUnit::Hour),
18241 ] {
18242 let rl = RateLimit {
18243 rate: 42,
18244 window: Duration::from_secs(window_secs),
18245 };
18246 let policy = MeshPolicy {
18247 rate_limit: Some(rl),
18248 ..Default::default()
18249 };
18250 let json = serde_json::to_string(&policy).unwrap();
18251 let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
18252 assert!(
18253 json.contains(&expected),
18254 "rate_limit_codec::render must emit {expected} (via \
18255 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
18256 for a {window_secs}s window; serialized MeshPolicy was: {json}"
18257 );
18258 // And the accessor route resolves to the same typed unit
18259 // the render arm's Display formatting is asked to produce —
18260 // so a future edit that split the two paths (one through
18261 // the accessor, one through a re-introduced free helper)
18262 // trips this pin.
18263 assert_eq!(
18264 rl.canonical_unit(),
18265 Some(unit),
18266 "RateLimit::canonical_unit must return Some({unit:?}) for a \
18267 {window_secs}s window; the codec render arm reads the same \
18268 typed unit through this accessor"
18269 );
18270 }
18271 }
18272
18273 #[test]
18274 fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
18275 // Fail-before-pass-after byte-parity pin on the validate gate's
18276 // canonical-window shape probe: every non-canonical `:window`
18277 // the free-helper predicate [`is_canonical_rate_limit_window`]
18278 // rejects is also rejected by the substrate primitive
18279 // [`RateLimit::canonical_unit`] `.is_none()` route the validate
18280 // gate now reads through, and vice versa on the accepted set
18281 // (the three canonical windows). Locks the migration from the
18282 // free helper onto the substrate primitive: a future re-routing
18283 // of one of the two paths through a differently-computed unit
18284 // projection would silently split the codec's accepted set from
18285 // the validate gate's accepted set — a two-consumer drift the
18286 // codec-round-trip pin
18287 // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
18288 // above closes on the render arm and this pin closes on the
18289 // validate arm.
18290 for canonical_window_secs in [1u64, 60, 3600] {
18291 let mut s = three_member_spec();
18292 let rl = RateLimit {
18293 rate: 100,
18294 window: Duration::from_secs(canonical_window_secs),
18295 };
18296 s.politicas.rate_limit = Some(rl);
18297 assert!(
18298 s.validate().is_ok(),
18299 "canonical {canonical_window_secs}s window must pass \
18300 validate_politicas — the validate gate now reads \
18301 RateLimit::canonical_unit().is_none() and the accessor \
18302 returns Some on every canonical arm"
18303 );
18304 assert!(
18305 rl.canonical_unit().is_some(),
18306 "canonical {canonical_window_secs}s window must resolve to \
18307 Some on RateLimit::canonical_unit — the validate gate reads \
18308 this accessor directly"
18309 );
18310 }
18311 for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
18312 let mut s = three_member_spec();
18313 let rl = RateLimit {
18314 rate: 100,
18315 window: Duration::from_secs(non_canonical_window_secs),
18316 };
18317 s.politicas.rate_limit = Some(rl);
18318 assert_eq!(
18319 s.validate().unwrap_err(),
18320 AplicacaoError::PolicyRateLimitWindowNotCanonical {
18321 window: rl.window(),
18322 },
18323 "non-canonical {non_canonical_window_secs}s window must be \
18324 rejected by validate_politicas — the validate gate now \
18325 keys off RateLimit::canonical_unit().is_none()"
18326 );
18327 assert!(
18328 rl.canonical_unit().is_none(),
18329 "non-canonical {non_canonical_window_secs}s window must \
18330 resolve to None on RateLimit::canonical_unit — the two \
18331 paths (the free helper the validate gate previously read \
18332 and the substrate primitive the validate gate now reads) \
18333 must agree on the same rejected set"
18334 );
18335 }
18336 // And the substrate-primitive [`RateLimit::canonical_unit`]
18337 // accessor's accepted-window set matches the codec's parse arm's
18338 // accepted-suffix set on every canonical / non-canonical shape,
18339 // so a future silent drift between the codec's accepted set and
18340 // the validate gate's accepted set is a build error at test time
18341 // (both consumers key off the same closed-set enum's `match self`
18342 // arms). The predecessor free helper `is_canonical_rate_limit_window`
18343 // — a delegate that composed [`RateLimitUnit::from_window`] with
18344 // `.is_some()` — was deleted after this migration; the
18345 // canonical-window set now lives on exactly one typed dispatch
18346 // on the substrate primitive.
18347 for (secs, expected) in [
18348 (1u64, true),
18349 (60, true),
18350 (3600, true),
18351 (2, false),
18352 (30, false),
18353 (86_400, false),
18354 ] {
18355 let window = Duration::from_secs(secs);
18356 let rl = RateLimit { rate: 1, window };
18357 assert_eq!(
18358 rl.canonical_unit().is_some(),
18359 expected,
18360 "RateLimit::canonical_unit().is_some() must agree with the \
18361 codec-accepted canonical-window set on {secs}s"
18362 );
18363 let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
18364 1 => "s",
18365 60 => "m",
18366 3600 => "h",
18367 _ => return,
18368 })
18369 .is_some_and(|d| d == window);
18370 if expected {
18371 assert!(
18372 suffix_from_axis,
18373 "the codec's `&str → Duration` axis \
18374 ({secs}s) must round-trip to the same Duration the \
18375 substrate primitive's accessor returns Some on"
18376 );
18377 }
18378 }
18379 }
18380
18381 #[test]
18382 fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
18383 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
18384 // derive: for each of the three variants, exactly one of the
18385 // generated `is_second` / `is_minute` / `is_hour` predicates
18386 // returns `true` and the other two return `false`. Peer of
18387 // the sibling
18388 // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
18389 // sibling `IsVariant`-derived closed-set typed-enum pins.
18390 let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
18391 (super::RateLimitUnit::Second, [true, false, false]),
18392 (super::RateLimitUnit::Minute, [false, true, false]),
18393 (super::RateLimitUnit::Hour, [false, false, true]),
18394 ];
18395 for (variant, expected) in rows {
18396 let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
18397 assert_eq!(
18398 observed, expected,
18399 "RateLimitUnit::{variant:?} is_* predicates must partition \
18400 the arm set (second, minute, hour); got {observed:?}"
18401 );
18402 }
18403 }
18404
18405 #[test]
18406 fn rejects_policy_timeout_sub_millisecond() {
18407 // A purely sub-millisecond `Duration` (`from_micros(500)` =
18408 // 500_000 ns) is not the zero `Duration` — the `is_zero()`
18409 // arm passes — but `as_millis() == 0`, so the shared codec's
18410 // `render` arm returns the literal `"0s"`, which the
18411 // codec's `parse` arm then deserializes as `Duration::ZERO`
18412 // and the `PolicyTimeoutZero` zero-floor gate would reject
18413 // on re-validate. Pin the rejection at the typed slot's
18414 // canonical-floor gate so the round-trip break surfaces at
18415 // validate time, naming the offending `Duration`, rather
18416 // than at the next serialize → deserialize round-trip far
18417 // from the source `caixa.lisp`.
18418 let mut s = three_member_spec();
18419 let timeout = Duration::from_micros(500);
18420 s.politicas.timeout = Some(timeout);
18421 assert_eq!(
18422 s.validate().unwrap_err(),
18423 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
18424 );
18425 }
18426
18427 #[test]
18428 fn rejects_policy_timeout_non_integer_millisecond() {
18429 // A `Duration` with non-integer-millisecond residue
18430 // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
18431 // through the shared codec's `render` arm as `"1ms"` (the
18432 // `as_millis()` floor truncates), which the codec's `parse`
18433 // arm then deserializes as `Duration::from_millis(1)` =
18434 // 1_000_000 ns — silently *different* from the original.
18435 // Pin the rejection so this round-trip break surfaces at
18436 // validate time, where the offending `Duration` is named,
18437 // rather than as a silent value-laundered round-trip on the
18438 // next codec round-trip.
18439 let mut s = three_member_spec();
18440 let timeout = Duration::from_micros(1500);
18441 s.politicas.timeout = Some(timeout);
18442 assert_eq!(
18443 s.validate().unwrap_err(),
18444 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
18445 );
18446 }
18447
18448 #[test]
18449 fn accepts_policy_timeout_integer_millisecond_forms() {
18450 // The codec's accepted set — integer multiples of 1ms — is
18451 // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
18452 // `1h` all pass the canonical gate. Pin the canonical-forms
18453 // sweep so a future tightening of the codec's grammar (e.g.
18454 // dropping `:ms`) surfaces here as a test failure rather
18455 // than a silent contract narrowing on the typed slot.
18456 for timeout in [
18457 Duration::from_millis(1),
18458 Duration::from_millis(500),
18459 Duration::from_millis(1500),
18460 Duration::from_secs(30),
18461 Duration::from_secs(120),
18462 Duration::from_secs(3600),
18463 ] {
18464 let mut s = three_member_spec();
18465 s.politicas.timeout = Some(timeout);
18466 s.validate()
18467 .expect("integer-millisecond :timeout must validate");
18468 }
18469 }
18470
18471 #[test]
18472 fn policy_timeout_zero_takes_precedence_over_canonical() {
18473 // `Duration::ZERO` carries `subsec_nanos() == 0` and would
18474 // pass the canonical-millisecond gate; the more self-locating
18475 // `PolicyTimeoutZero` arm (which names the omit-axis
18476 // remediation directly) must fire first. Pin the ordering so
18477 // a future refactor that reorders the arms surfaces here as a
18478 // test failure rather than a silent diagnostic regression.
18479 let mut s = three_member_spec();
18480 s.politicas.timeout = Some(Duration::ZERO);
18481 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
18482 }
18483
18484 #[test]
18485 fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
18486 // The diagnostic envelope carries the offending `Duration`
18487 // verbatim so the author can grep their `caixa.lisp` for
18488 // `:timeout "<value>"` and fix it in one edit. Same
18489 // diagnostic shape every other typed-slot canonical-form
18490 // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
18491 // peer `:rate-limit :window` axis.
18492 let mut s = three_member_spec();
18493 let timeout = Duration::from_nanos(1_000_001);
18494 s.politicas.timeout = Some(timeout);
18495 match s.validate().unwrap_err() {
18496 AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
18497 assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
18498 }
18499 other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
18500 }
18501 }
18502
18503 #[test]
18504 fn rejects_policy_timeout_above_cap() {
18505 // The fail-before-pass-after pin: 3601s = 1h + 1s is
18506 // structurally one canonical-tick past the
18507 // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
18508 // integer-millisecond magnitude the canonical-form arm above
18509 // accepts cleanly, that the codec round-trips losslessly as
18510 // `"3601s"`, and that silently passed validate on every
18511 // pre-gate codebase because the typed slot's only checks were
18512 // the zero-floor and canonical-form arms. The mesh-level
18513 // deadline degenerates only at the runtime substrate (Envoy
18514 // / Cilium L7 timeout overlay) far from the source
18515 // `caixa.lisp` with no field naming the offending policy.
18516 let mut s = three_member_spec();
18517 let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
18518 s.politicas.timeout = Some(timeout);
18519 assert_eq!(
18520 s.validate().unwrap_err(),
18521 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18522 );
18523 }
18524
18525 #[test]
18526 fn rejects_policy_timeout_one_millisecond_above_cap() {
18527 // Boundary case: exactly 1ms past the cap (the granularity
18528 // the canonical-form gate enforces). Catches a future
18529 // "strictly less than" half-measure and pins the diagnostic
18530 // to name the offending `Duration` verbatim. Peer of
18531 // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
18532 // boundary pin on the sibling `:limits :memory` top edge.
18533 let mut s = three_member_spec();
18534 let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
18535 s.politicas.timeout = Some(timeout);
18536 assert_eq!(
18537 s.validate().unwrap_err(),
18538 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18539 );
18540 }
18541
18542 #[test]
18543 fn rejects_policy_timeout_far_above_cap() {
18544 // The "obvious authoring footgun" case: a `(:timeout "24h")`
18545 // or `(:timeout "86400s")` — values the canonical-form arm
18546 // accepts as integer-millisecond magnitudes, the codec
18547 // round-trips losslessly through serde, but the mesh-level
18548 // policy cannot honor (a 24-hour synchronous-`:contratos`
18549 // deadline is operationally indistinguishable from
18550 // omit-the-axis). Until this gate landed validate accepted
18551 // it. Pin both common above-cap values (24h, 7d) so a future
18552 // relaxation that drops the upper bound surfaces here.
18553 for timeout in [
18554 Duration::from_secs(86_400), // 24h
18555 Duration::from_secs(604_800), // 7d
18556 Duration::from_secs(1_000_000), // ~11.5 days
18557 ] {
18558 let mut s = three_member_spec();
18559 s.politicas.timeout = Some(timeout);
18560 assert_eq!(
18561 s.validate().unwrap_err(),
18562 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18563 );
18564 }
18565 }
18566
18567 #[test]
18568 fn accepts_policy_timeout_at_cap() {
18569 // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
18570 // must validate. The cap is inclusive on the top edge,
18571 // matching the [`POLICY_RETRIES_MAX`] /
18572 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
18573 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18574 // sibling capped axes. Pin the boundary explicitly so a
18575 // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
18576 // instead of `>`) surfaces here as a test failure rather
18577 // than a silent contract narrowing.
18578 let mut s = three_member_spec();
18579 s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
18580 s.validate()
18581 .expect("timeout == POLICY_TIMEOUT_MAX must validate");
18582 }
18583
18584 #[test]
18585 fn accepts_policy_timeout_typical_values() {
18586 // The documented production-playbook band positive-control
18587 // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
18588 // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
18589 // plus a sweep through the long-running-workflow band
18590 // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
18591 // validated set explicitly so a future tightening of the
18592 // ceiling surfaces here as a deliberate test edit, not a
18593 // silent contract narrowing.
18594 for timeout in [
18595 Duration::from_millis(1),
18596 Duration::from_millis(500),
18597 Duration::from_secs(1),
18598 Duration::from_secs(10),
18599 Duration::from_secs(15), // Envoy default
18600 Duration::from_secs(30),
18601 Duration::from_secs(60), // AWS App Mesh typical
18602 Duration::from_secs(300),
18603 Duration::from_secs(900),
18604 Duration::from_secs(1800),
18605 Duration::from_secs(3600), // exactly 1h, the cap
18606 ] {
18607 let mut s = three_member_spec();
18608 s.politicas.timeout = Some(timeout);
18609 s.validate()
18610 .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
18611 }
18612 }
18613
18614 #[test]
18615 fn policy_timeout_zero_takes_precedence_over_cap() {
18616 // The cross-arm ordering pin: `Duration::ZERO` is
18617 // structurally outside both `>= 1ms` (zero-floor) and
18618 // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
18619 // diagnostic is the more self-locating one (it directly
18620 // names the omit-axis remediation), so the validate gate
18621 // must fire on zero first. Same shape every other
18622 // zero-then-shape ordering on this surface uses
18623 // ([`AplicacaoError::PolicyRetriesZero`] then
18624 // [`AplicacaoError::PolicyRetriesExceedsCap`];
18625 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18626 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18627 let mut s = three_member_spec();
18628 s.politicas.timeout = Some(Duration::ZERO);
18629 assert_eq!(
18630 s.validate().unwrap_err(),
18631 AplicacaoError::PolicyTimeoutZero,
18632 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18633 );
18634 }
18635
18636 #[test]
18637 fn policy_timeout_canonical_takes_precedence_over_cap() {
18638 // The cross-arm ordering pin: a `Duration` that is *both*
18639 // sub-millisecond (non-canonical-form) and structurally
18640 // above the cap surfaces the canonical-form diagnostic
18641 // first, because the round-trip-shape break is the more
18642 // fundamental issue (the value can't even round-trip
18643 // through the codec, so the cap diagnostic naming
18644 // `1ms..=1h` would be misleading — there's no integer-ms
18645 // form of the offending value). Pin the order so a future
18646 // refactor that reorders the arms surfaces here as a test
18647 // failure rather than a silent diagnostic regression.
18648 let mut s = three_member_spec();
18649 // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
18650 // *and* total magnitude above the 1h cap.
18651 let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
18652 s.politicas.timeout = Some(timeout);
18653 assert_eq!(
18654 s.validate().unwrap_err(),
18655 AplicacaoError::PolicyTimeoutNotCanonical { timeout },
18656 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18657 );
18658 }
18659
18660 #[test]
18661 fn policy_timeout_cap_diagnostic_carries_offending_value() {
18662 // The diagnostic-shape pin: the offending `Duration` is
18663 // carried verbatim into the
18664 // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
18665 // surfaced error message names the value the author wrote
18666 // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
18667 // exceeds the mesh-policy ceiling …"`), not just the cap.
18668 // Same self-locating diagnostic shape every other typed-cap
18669 // arm on this surface carries
18670 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
18671 // offending retry count verbatim).
18672 let mut s = three_member_spec();
18673 let timeout = Duration::from_secs(7200); // 2h
18674 s.politicas.timeout = Some(timeout);
18675 let err = s.validate().unwrap_err();
18676 assert!(
18677 matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
18678 "got {err:?}"
18679 );
18680 let msg = err.to_string();
18681 assert!(
18682 msg.contains("7200"),
18683 ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
18684 );
18685 }
18686
18687 #[test]
18688 fn policy_timeout_cap_pins_canonical_value() {
18689 // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
18690 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
18691 // the shared duration codec emits as a clean canonical
18692 // string (`"<n>h"`). Pinning the literal value here surfaces
18693 // a future drift (a relaxation to 24h, a tightening to 5m)
18694 // as a deliberate test edit, not a silent contract
18695 // narrowing. Same shape every other typed-cap value pin on
18696 // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
18697 assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
18698 assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
18699 }
18700
18701 #[test]
18702 fn policy_timeout_cap_value_round_trips_through_codec() {
18703 // The codec round-trip property the cap arm preserves: the
18704 // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
18705 // the shared duration codec — every value at the cap renders
18706 // to a clean canonical string (`"1h"`) and parses back to
18707 // the same `Duration`. Pin this so a future drift between
18708 // the cap constant and the codec's largest emitted unit
18709 // surfaces here. Same shape every other typed boundary pin
18710 // on this surface uses
18711 // (`wasm32_memory_cap_matches_parsed_4_gib`).
18712 let policy = MeshPolicy {
18713 timeout: Some(POLICY_TIMEOUT_MAX),
18714 ..Default::default()
18715 };
18716 let json = serde_json::to_string(&policy).unwrap();
18717 // The codec emits `"1h"` for the canonical 1-hour magnitude.
18718 assert!(
18719 json.contains("\"1h\""),
18720 "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
18721 );
18722 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18723 assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
18724 }
18725
18726 #[test]
18727 fn rejects_circuit_breaker_window_sub_millisecond() {
18728 // Peer of the `:timeout` sub-millisecond arm on the second
18729 // typed-`Duration` `:politicas` axis: a purely sub-ms
18730 // `Duration` (`from_micros(500)`) renders through the shared
18731 // codec as `"0s"`, which the codec parses back to
18732 // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
18733 // zero-floor gate then rejects on re-validate.
18734 let mut s = three_member_spec();
18735 let window = Duration::from_micros(500);
18736 s.politicas.circuit_breaker = Some(CircuitBreaker {
18737 max_failures: 5,
18738 window,
18739 });
18740 assert_eq!(
18741 s.validate().unwrap_err(),
18742 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18743 );
18744 }
18745
18746 #[test]
18747 fn rejects_circuit_breaker_window_non_integer_millisecond() {
18748 // Peer of the `:timeout` non-integer-ms arm: a `Duration`
18749 // with non-integer-millisecond residue renders through the
18750 // shared codec as the truncated `"<n>ms"` form, parsing back
18751 // to a *different* `Duration` on the next round-trip.
18752 let mut s = three_member_spec();
18753 let window = Duration::from_micros(1500);
18754 s.politicas.circuit_breaker = Some(CircuitBreaker {
18755 max_failures: 5,
18756 window,
18757 });
18758 assert_eq!(
18759 s.validate().unwrap_err(),
18760 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18761 );
18762 }
18763
18764 #[test]
18765 fn accepts_circuit_breaker_window_integer_millisecond_forms() {
18766 // The canonical-forms sweep on the breaker axis: every
18767 // integer-ms multiple the codec round-trips losslessly
18768 // passes the canonical gate.
18769 for window in [
18770 Duration::from_millis(1),
18771 Duration::from_millis(500),
18772 Duration::from_millis(1500),
18773 Duration::from_secs(30),
18774 Duration::from_secs(60),
18775 Duration::from_secs(3600),
18776 ] {
18777 let mut s = three_member_spec();
18778 s.politicas.circuit_breaker = Some(CircuitBreaker {
18779 max_failures: 5,
18780 window,
18781 });
18782 s.validate()
18783 .expect("integer-millisecond :circuit-breaker :window must validate");
18784 }
18785 }
18786
18787 #[test]
18788 fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
18789 // `Duration::ZERO` would pass the canonical-ms gate (the
18790 // sub-ns residue is zero) but must surface the narrower
18791 // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
18792 // remediation.
18793 let mut s = three_member_spec();
18794 s.politicas.circuit_breaker = Some(CircuitBreaker {
18795 max_failures: 5,
18796 window: Duration::ZERO,
18797 });
18798 assert_eq!(
18799 s.validate().unwrap_err(),
18800 AplicacaoError::PolicyBreakerZeroWindow
18801 );
18802 }
18803
18804 #[test]
18805 fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
18806 // Both axes invalid: max_failures == 0 *and* window is
18807 // sub-ms. The validate gate must fire on max_failures first
18808 // (matching the existing ordering pin
18809 // `rejects_circuit_breaker_zero_max_failures` enshrines), so
18810 // the existing diagnostic continues to lead with the simpler
18811 // "zero threshold" framing.
18812 let mut s = three_member_spec();
18813 s.politicas.circuit_breaker = Some(CircuitBreaker {
18814 max_failures: 0,
18815 window: Duration::from_micros(500),
18816 });
18817 assert_eq!(
18818 s.validate().unwrap_err(),
18819 AplicacaoError::PolicyBreakerZeroFailures
18820 );
18821 }
18822
18823 #[test]
18824 fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
18825 let mut s = three_member_spec();
18826 let window = Duration::from_nanos(60_000_000_001);
18827 s.politicas.circuit_breaker = Some(CircuitBreaker {
18828 max_failures: 5,
18829 window,
18830 });
18831 match s.validate().unwrap_err() {
18832 AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
18833 assert_eq!(w, window, "diagnostic must carry the offending Duration");
18834 }
18835 other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
18836 }
18837 }
18838
18839 #[test]
18840 fn rejects_circuit_breaker_window_above_cap() {
18841 // The fail-before-pass-after pin: 3601s = 1h + 1s is
18842 // structurally one canonical-tick past the
18843 // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
18844 // integer-millisecond magnitude the canonical-form arm above
18845 // accepts cleanly, that the codec round-trips losslessly as
18846 // `"3601s"`, and that silently passed validate on every
18847 // pre-gate codebase because the typed slot's only checks were
18848 // the zero-floor and canonical-form arms. The
18849 // rolling-window-to-lifetime-counter degeneration surfaces
18850 // only at the runtime substrate (Envoy's outlier_detection
18851 // interval, the future CiliumClusterwideEnvoyConfig overlay)
18852 // far from the source `caixa.lisp` with no field naming the
18853 // offending policy.
18854 let mut s = three_member_spec();
18855 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18856 s.politicas.circuit_breaker = Some(CircuitBreaker {
18857 max_failures: 5,
18858 window,
18859 });
18860 assert_eq!(
18861 s.validate().unwrap_err(),
18862 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18863 );
18864 }
18865
18866 #[test]
18867 fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
18868 // Boundary case: exactly 1ms past the cap (the granularity the
18869 // canonical-form gate enforces). Catches a future "strictly
18870 // less than" half-measure and pins the diagnostic to name the
18871 // offending `Duration` verbatim. Peer of
18872 // `rejects_policy_timeout_one_millisecond_above_cap` on the
18873 // sibling duration-typed `:politicas :timeout` top edge.
18874 let mut s = three_member_spec();
18875 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
18876 s.politicas.circuit_breaker = Some(CircuitBreaker {
18877 max_failures: 5,
18878 window,
18879 });
18880 assert_eq!(
18881 s.validate().unwrap_err(),
18882 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18883 );
18884 }
18885
18886 #[test]
18887 fn rejects_circuit_breaker_window_far_above_cap() {
18888 // The "obvious authoring footgun" case: a `(:window "24h")` or
18889 // `(:window "86400s")` — values the canonical-form arm
18890 // accepts as integer-millisecond magnitudes, the codec
18891 // round-trips losslessly through serde, but the
18892 // rolling-window breaker contract cannot honor (a 24-hour
18893 // rolling failure window is operationally a lifetime counter).
18894 // Until this gate landed validate accepted it. Pin both common
18895 // above-cap values (24h, 7d) so a future relaxation that
18896 // drops the upper bound surfaces here.
18897 for window in [
18898 Duration::from_secs(86_400), // 24h
18899 Duration::from_secs(604_800), // 7d
18900 Duration::from_secs(1_000_000), // ~11.5 days
18901 ] {
18902 let mut s = three_member_spec();
18903 s.politicas.circuit_breaker = Some(CircuitBreaker {
18904 max_failures: 5,
18905 window,
18906 });
18907 assert_eq!(
18908 s.validate().unwrap_err(),
18909 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18910 );
18911 }
18912 }
18913
18914 #[test]
18915 fn accepts_circuit_breaker_window_at_cap() {
18916 // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
18917 // (1h) — must validate. The cap is inclusive on the top edge,
18918 // matching the [`POLICY_TIMEOUT_MAX`] /
18919 // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
18920 // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18921 // sibling capped axes. Pin the boundary explicitly so a
18922 // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
18923 // instead of `>`) surfaces here as a test failure rather than
18924 // a silent contract narrowing.
18925 let mut s = three_member_spec();
18926 s.politicas.circuit_breaker = Some(CircuitBreaker {
18927 max_failures: 5,
18928 window: POLICY_BREAKER_WINDOW_MAX,
18929 });
18930 s.validate()
18931 .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
18932 }
18933
18934 #[test]
18935 fn accepts_circuit_breaker_window_typical_values() {
18936 // The documented production-playbook band positive-control
18937 // sweep — every value Hystrix / resilience4j / Istio / Envoy
18938 // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
18939 // through the long-tail failure-detection band (15m, 30m, 1h)
18940 // the cap accepts. Pin the inclusive validated set explicitly
18941 // so a future tightening of the ceiling surfaces here as a
18942 // deliberate test edit, not a silent contract narrowing.
18943 for window in [
18944 Duration::from_millis(1),
18945 Duration::from_millis(500),
18946 Duration::from_secs(1),
18947 Duration::from_secs(10), // Hystrix / Istio / Envoy default
18948 Duration::from_secs(30),
18949 Duration::from_secs(60), // resilience4j typical
18950 Duration::from_secs(300), // AWS App Mesh typical
18951 Duration::from_secs(900),
18952 Duration::from_secs(1800),
18953 Duration::from_secs(3600), // exactly 1h, the cap
18954 ] {
18955 let mut s = three_member_spec();
18956 s.politicas.circuit_breaker = Some(CircuitBreaker {
18957 max_failures: 5,
18958 window,
18959 });
18960 s.validate()
18961 .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
18962 }
18963 }
18964
18965 #[test]
18966 fn circuit_breaker_zero_window_takes_precedence_over_cap() {
18967 // The cross-arm ordering pin: `Duration::ZERO` is structurally
18968 // outside both `>= 1ms` (zero-floor) and
18969 // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
18970 // diagnostic is the more self-locating one (it directly names
18971 // the omit-axis remediation), so the validate gate must fire
18972 // on zero first. Same shape every other zero-then-cap
18973 // ordering on this surface uses
18974 // ([`AplicacaoError::PolicyTimeoutZero`] then
18975 // [`AplicacaoError::PolicyTimeoutExceedsCap`];
18976 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18977 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18978 let mut s = three_member_spec();
18979 s.politicas.circuit_breaker = Some(CircuitBreaker {
18980 max_failures: 5,
18981 window: Duration::ZERO,
18982 });
18983 assert_eq!(
18984 s.validate().unwrap_err(),
18985 AplicacaoError::PolicyBreakerZeroWindow,
18986 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18987 );
18988 }
18989
18990 #[test]
18991 fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
18992 // The cross-arm ordering pin: a `Duration` that is *both*
18993 // sub-millisecond (non-canonical-form) and structurally above
18994 // the cap surfaces the canonical-form diagnostic first,
18995 // because the round-trip-shape break is the more fundamental
18996 // issue (the value can't even round-trip through the codec, so
18997 // the cap diagnostic naming `1ms..=1h` would be misleading —
18998 // there's no integer-ms form of the offending value). Pin the
18999 // order so a future refactor that reorders the arms surfaces
19000 // here as a test failure rather than a silent diagnostic
19001 // regression. Peer of
19002 // `policy_timeout_canonical_takes_precedence_over_cap` on the
19003 // sibling duration-typed `:politicas :timeout` axis.
19004 let mut s = three_member_spec();
19005 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
19006 s.politicas.circuit_breaker = Some(CircuitBreaker {
19007 max_failures: 5,
19008 window,
19009 });
19010 assert_eq!(
19011 s.validate().unwrap_err(),
19012 AplicacaoError::PolicyBreakerWindowNotCanonical { window },
19013 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
19014 );
19015 }
19016
19017 #[test]
19018 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
19019 // The cross-arm ordering pin between the two breaker axes: a
19020 // `CircuitBreaker` whose *both* `max_failures` is above its
19021 // cap *and* `window` is above its cap surfaces the
19022 // max-failures cap diagnostic first, because the validate
19023 // gate visits the failures arm before the window arm. Pin the
19024 // order so a future refactor that reorders the breaker arms
19025 // surfaces here.
19026 let mut s = three_member_spec();
19027 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
19028 s.politicas.circuit_breaker = Some(CircuitBreaker {
19029 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19030 window,
19031 });
19032 assert_eq!(
19033 s.validate().unwrap_err(),
19034 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19035 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
19036 },
19037 "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
19038 );
19039 }
19040
19041 #[test]
19042 fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
19043 // The diagnostic-shape pin: the offending `Duration` is
19044 // carried verbatim into the
19045 // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
19046 // the surfaced error message names the value the author wrote
19047 // (`":politicas :circuit-breaker :window (Duration { secs:
19048 // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
19049 // just the cap. Same self-locating diagnostic shape every
19050 // other typed-cap arm on this surface carries
19051 // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
19052 // offending `Duration` verbatim).
19053 let mut s = three_member_spec();
19054 let window = Duration::from_secs(7200); // 2h
19055 s.politicas.circuit_breaker = Some(CircuitBreaker {
19056 max_failures: 5,
19057 window,
19058 });
19059 let err = s.validate().unwrap_err();
19060 assert!(
19061 matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
19062 "got {err:?}"
19063 );
19064 let msg = err.to_string();
19065 assert!(
19066 msg.contains("7200"),
19067 ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
19068 );
19069 }
19070
19071 #[test]
19072 fn circuit_breaker_window_cap_pins_canonical_value() {
19073 // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
19074 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
19075 // shared duration codec emits as a clean canonical string
19076 // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
19077 // the sibling duration-typed `:politicas :timeout` axis (the
19078 // two duration-typed `:politicas` axes share a uniform top
19079 // edge). Pinning the literal value here surfaces a future
19080 // drift (a relaxation to 24h, a tightening to 5m) as a
19081 // deliberate test edit, not a silent contract narrowing. Same
19082 // shape every other typed-cap value pin on this surface uses
19083 // (`policy_timeout_cap_pins_canonical_value`).
19084 assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
19085 assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
19086 assert_eq!(
19087 POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
19088 "the two duration-typed `:politicas` caps share the same top edge"
19089 );
19090 }
19091
19092 #[test]
19093 fn circuit_breaker_window_cap_value_round_trips_through_codec() {
19094 // The codec round-trip property the cap arm preserves: the
19095 // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
19096 // through the shared duration codec — every value at the cap
19097 // renders to a clean canonical string (`"1h"`) and parses back
19098 // to the same `Duration`. Pin this so a future drift between
19099 // the cap constant and the codec's largest emitted unit
19100 // surfaces here. Same shape every other typed boundary pin on
19101 // this surface uses
19102 // (`policy_timeout_cap_value_round_trips_through_codec`).
19103 let policy = MeshPolicy {
19104 circuit_breaker: Some(CircuitBreaker {
19105 max_failures: 5,
19106 window: POLICY_BREAKER_WINDOW_MAX,
19107 }),
19108 ..Default::default()
19109 };
19110 let json = serde_json::to_string(&policy).unwrap();
19111 // The codec emits `"1h"` for the canonical 1-hour magnitude.
19112 assert!(
19113 json.contains("\"1h\""),
19114 "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
19115 );
19116 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19117 assert_eq!(
19118 back.circuit_breaker.unwrap().window,
19119 POLICY_BREAKER_WINDOW_MAX
19120 );
19121 }
19122
19123 #[test]
19124 fn is_integer_millisecond_duration_predicate_tracks_codec() {
19125 // Pin the predicate's accepted set against the codec's
19126 // accepted set explicitly. The codec parses
19127 // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
19128 // accepted value is an integer-millisecond multiple — so the
19129 // predicate must accept exactly that set. Same shape every
19130 // other predicate-on-the-typed-slot helper carries
19131 // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
19132 // Read directly from the codec-owned predicate — the crate's
19133 // single source of truth every typed-`Duration` axis now routes
19134 // through via
19135 // [`crate::render::require_positive_canonical_bounded_duration`].
19136 use super::supervisor::duration_codec::is_integer_millisecond_duration;
19137 assert!(is_integer_millisecond_duration(Duration::ZERO));
19138 assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
19139 assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
19140 assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
19141 assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
19142 assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
19143 // Non-integer-millisecond residue: rejected.
19144 assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
19145 assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
19146 assert!(!is_integer_millisecond_duration(Duration::from_micros(
19147 1500
19148 )));
19149 assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
19150 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
19151 999_999
19152 )));
19153 // The 1-ns-past-1ms boundary: rejected (no longer a clean
19154 // integer-millisecond multiple).
19155 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
19156 1_000_001
19157 )));
19158 }
19159
19160 #[test]
19161 fn policy_timeout_validated_value_round_trips_through_codec() {
19162 // The structural property the canonical-ms gate enforces:
19163 // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
19164 // round-trips losslessly through the shared `duration_codec`
19165 // (serialize → string → deserialize → equal value). Pin this
19166 // end-to-end so a future change to either side (the validate
19167 // gate's accepted granularity, the codec's parse/render unit
19168 // set) that breaks the alignment surfaces here. The
19169 // previous-state shape (typed slot accepts arbitrary
19170 // `Duration`, codec only round-trips integer-ms) would fail
19171 // this test for any `Duration::from_micros(1500)` timeout —
19172 // the validate gate now forecloses that.
19173 for timeout in [
19174 Duration::from_millis(1),
19175 Duration::from_millis(1500),
19176 Duration::from_secs(30),
19177 Duration::from_secs(3600),
19178 ] {
19179 let mut s = three_member_spec();
19180 s.politicas.timeout = Some(timeout);
19181 s.validate().unwrap();
19182 let json = serde_json::to_string(&s.politicas).unwrap();
19183 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19184 assert_eq!(
19185 back.timeout, s.politicas.timeout,
19186 "every validated :timeout must round-trip losslessly through the codec"
19187 );
19188 }
19189 }
19190
19191 #[test]
19192 fn circuit_breaker_window_validated_value_round_trips_through_codec() {
19193 // Peer of the `:timeout` round-trip property on the breaker
19194 // axis.
19195 for window in [
19196 Duration::from_millis(1),
19197 Duration::from_millis(1500),
19198 Duration::from_secs(30),
19199 Duration::from_secs(3600),
19200 ] {
19201 let mut s = three_member_spec();
19202 s.politicas.circuit_breaker = Some(CircuitBreaker {
19203 max_failures: 5,
19204 window,
19205 });
19206 s.validate().unwrap();
19207 let json = serde_json::to_string(&s.politicas).unwrap();
19208 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19209 assert_eq!(
19210 back.circuit_breaker.unwrap().window,
19211 window,
19212 "every validated :circuit-breaker :window must round-trip losslessly"
19213 );
19214 }
19215 }
19216
19217 #[test]
19218 fn empty_politicas_validates() {
19219 // Omitting every policy axis is fine — defaults express "no
19220 // policy on this axis", not "policy = 0". The fixture's typical
19221 // values continue to validate; this test pins that
19222 // MeshPolicy::default() is a clean pass through validate().
19223 let mut s = three_member_spec();
19224 s.politicas = MeshPolicy::default();
19225 s.validate().unwrap();
19226 }
19227
19228 #[test]
19229 fn typical_politicas_validates_with_every_axis_set() {
19230 // The full §III.1 example block (timeout + retries + breaker +
19231 // mtls + rate-limit) — every axis nonzero — must remain a
19232 // clean pass.
19233 let mut s = three_member_spec();
19234 s.politicas = MeshPolicy {
19235 timeout: Some(Duration::from_secs(30)),
19236 retries: Some(3),
19237 circuit_breaker: Some(CircuitBreaker {
19238 max_failures: 5,
19239 window: Duration::from_secs(60),
19240 }),
19241 mtls_required: Some(true),
19242 rate_limit: Some(RateLimit {
19243 rate: 100,
19244 window: Duration::from_secs(1),
19245 }),
19246 };
19247 s.validate().unwrap();
19248 }
19249
19250 #[test]
19251 fn rejects_empty_cluster_name() {
19252 let mut s = three_member_spec();
19253 s.placement.clusters = vec!["rio".into(), "".into()];
19254 assert_eq!(
19255 s.validate().unwrap_err(),
19256 AplicacaoError::PlacementClusterEmpty
19257 );
19258 }
19259
19260 #[test]
19261 fn rejects_duplicate_cluster_names() {
19262 let mut s = three_member_spec();
19263 s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
19264 let err = s.validate().unwrap_err();
19265 assert!(
19266 matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
19267 "got {err:?}"
19268 );
19269 }
19270
19271 #[test]
19272 fn rejects_placement_cluster_with_uppercase() {
19273 // The canonical "I copied the cluster's display name verbatim"
19274 // typo — K8s context names are lowercase per DNS-1123 label
19275 // rule, but org docs often round-trip a TitleCase identifier
19276 // (`Rio`, `Mar-East`) from an ADR. Mirrors the
19277 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
19278 // on the peer name axis.
19279 let mut s = three_member_spec();
19280 s.placement.clusters = vec!["Rio".into(), "mar".into()];
19281 let err = s.validate().unwrap_err();
19282 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19283 panic!("expected PlacementClusterInvalid, got other variant");
19284 };
19285 assert_eq!(cluster, "Rio");
19286 assert!(
19287 reason.contains("uppercase"),
19288 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19289 );
19290 assert!(
19291 reason.contains("\"rio\""),
19292 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19293 );
19294 }
19295
19296 #[test]
19297 fn rejects_placement_cluster_with_underscore() {
19298 // The canonical "I'm thinking of an env var / hostname slug"
19299 // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
19300 // schema. K8s context filtering on `my_cluster` silently misses
19301 // the cluster the author intended; the gate moves it to caixa-
19302 // build time. Same shape as `rejects_membro_caixa_with_underscore`
19303 // (3f9d7a0).
19304 let mut s = three_member_spec();
19305 s.placement.clusters = vec!["my_cluster".into()];
19306 let err = s.validate().unwrap_err();
19307 assert!(
19308 matches!(
19309 err,
19310 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19311 if cluster == "my_cluster" && reason.contains('_')
19312 ),
19313 "got {err:?}"
19314 );
19315 }
19316
19317 #[test]
19318 fn rejects_placement_cluster_with_dot() {
19319 // A `:placement :clusters` entry is a single DNS-1123 *label*,
19320 // not a subdomain — even though K8s context names sometimes
19321 // carry a dotted form via kubeconfig conventions, the strictest
19322 // floor among the use sites (DNS-1035 cluster.x-k8s.io
19323 // `metadata.name`, Cilium identity label values) wins. The "I
19324 // want to namespace my cluster names with `.`" intent is
19325 // expressed via `-` (`mar-east`).
19326 let mut s = three_member_spec();
19327 s.placement.clusters = vec!["team.rio".into()];
19328 let err = s.validate().unwrap_err();
19329 assert!(
19330 matches!(
19331 err,
19332 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19333 if cluster == "team.rio" && reason.contains('.')
19334 ),
19335 "got {err:?}"
19336 );
19337 }
19338
19339 #[test]
19340 fn rejects_placement_cluster_with_leading_hyphen() {
19341 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
19342 // with an alphanumeric. The K8s apiserver rejects `-rio`
19343 // outright; the rendered fan-out would emit a `metadata.name:
19344 // "-rio"` that fails admission far from the source caixa.lisp.
19345 let mut s = three_member_spec();
19346 s.placement.clusters = vec!["-rio".into()];
19347 let err = s.validate().unwrap_err();
19348 assert!(
19349 matches!(
19350 err,
19351 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19352 if cluster == "-rio" && reason.contains("start and end")
19353 ),
19354 "got {err:?}"
19355 );
19356 }
19357
19358 #[test]
19359 fn rejects_placement_cluster_with_trailing_hyphen() {
19360 // The symmetric arm of the boundary rule. Pin separately so
19361 // both ends are covered against a future relaxation that only
19362 // checks one boundary (parallel to
19363 // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
19364 let mut s = three_member_spec();
19365 s.placement.clusters = vec!["rio-".into()];
19366 let err = s.validate().unwrap_err();
19367 assert!(
19368 matches!(
19369 err,
19370 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19371 if cluster == "rio-"
19372 ),
19373 "got {err:?}"
19374 );
19375 }
19376
19377 #[test]
19378 fn rejects_placement_cluster_with_unicode() {
19379 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19380 // before it reaches K8s. The byte-by-byte ASCII validity check
19381 // rejects multi-byte UTF-8 sequences by the first byte that
19382 // fails `[a-z0-9-]`.
19383 let mut s = three_member_spec();
19384 s.placement.clusters = vec!["rió".into()];
19385 let err = s.validate().unwrap_err();
19386 assert!(
19387 matches!(
19388 err,
19389 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19390 if cluster == "rió"
19391 ),
19392 "got {err:?}"
19393 );
19394 }
19395
19396 #[test]
19397 fn rejects_placement_cluster_with_whitespace() {
19398 // Whitespace is the canonical "I pasted from a sketch / doc"
19399 // footgun. The apiserver rejects every cluster `metadata.name`
19400 // value carrying whitespace.
19401 let mut s = three_member_spec();
19402 s.placement.clusters = vec!["rio cluster".into()];
19403 let err = s.validate().unwrap_err();
19404 assert!(
19405 matches!(
19406 err,
19407 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19408 if cluster == "rio cluster"
19409 ),
19410 "got {err:?}"
19411 );
19412 }
19413
19414 #[test]
19415 fn rejects_placement_cluster_too_long() {
19416 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19417 // pin. The diagnostic names both the cap (63) and the actual
19418 // length so the author can shorten in one edit. Mirrors
19419 // `rejects_membro_caixa_too_long` (3f9d7a0).
19420 let mut s = three_member_spec();
19421 let too_long = "a".repeat(64);
19422 s.placement.clusters = vec![too_long.clone()];
19423 let err = s.validate().unwrap_err();
19424 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19425 panic!("expected PlacementClusterInvalid");
19426 };
19427 assert_eq!(cluster, too_long);
19428 assert!(
19429 reason.contains("63") && reason.contains("64"),
19430 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19431 );
19432 }
19433
19434 #[test]
19435 fn placement_cluster_max_length_validates() {
19436 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19437 // future tightening (e.g. dropping to 62) surfaces here as a
19438 // regression, mirroring `membro_caixa_max_length_validates`
19439 // (3f9d7a0).
19440 let mut s = three_member_spec();
19441 s.placement.clusters = vec!["a".repeat(63)];
19442 s.validate().unwrap();
19443 }
19444
19445 #[test]
19446 fn accepts_canonical_placement_cluster_forms() {
19447 // The DNS-1123 label shapes a caixa author is realistically
19448 // going to write for cluster names: single-word lowercase
19449 // (`rio`), regional hyphen-joined (`mar-east`), single
19450 // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
19451 // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
19452 // Pin every leg so a future tightening that bans (e.g.) digit-
19453 // start identifiers surfaces here.
19454 for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
19455 let mut s = three_member_spec();
19456 s.placement.clusters = vec![form.into()];
19457 s.validate().unwrap_or_else(|e| {
19458 panic!("canonical cluster form {form:?} must validate, got {e:?}")
19459 });
19460 }
19461 }
19462
19463 #[test]
19464 fn placement_cluster_empty_takes_precedence_over_invalid() {
19465 // Order pin: the existing `PlacementClusterEmpty` diagnostic
19466 // (which doesn't try to parse) fires before the new
19467 // `PlacementClusterInvalid` parse-side diagnostic, so an empty
19468 // `:clusters` entry keeps its narrower error message — the new
19469 // gate would also reject `""`, but the empty-string arm is the
19470 // more self-locating diagnostic. Mirrors the
19471 // `membro_caixa_empty_takes_precedence_over_invalid` pin
19472 // (3f9d7a0).
19473 let mut s = three_member_spec();
19474 s.placement.clusters = vec!["rio".into(), "".into()];
19475 let err = s.validate().unwrap_err();
19476 assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
19477 }
19478
19479 #[test]
19480 fn placement_cluster_invalid_fires_before_duplicate_check() {
19481 // Order pin: a malformed-shape `:clusters` entry surfaces *its
19482 // own* diagnostic, even when a later entry would otherwise
19483 // collapse onto a duplicate name. The per-entry shape gate runs
19484 // inline before the duplicate-key insert, parallel to
19485 // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
19486 let mut s = three_member_spec();
19487 s.placement.clusters = vec!["Rio".into(), "rio".into()];
19488 let err = s.validate().unwrap_err();
19489 assert!(
19490 matches!(
19491 err,
19492 AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
19493 ),
19494 "got {err:?}"
19495 );
19496 }
19497
19498 #[test]
19499 fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
19500 // The diagnostic-shape pin: the error names the offending
19501 // `:clusters` value verbatim so the author can grep their
19502 // caixa.lisp without re-running the build, and carries a
19503 // non-empty `reason` naming the specific violation. Same shape
19504 // every typed-shape gate enshrines
19505 // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
19506 // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
19507 let mut s = three_member_spec();
19508 s.placement.clusters = vec!["BAD_CLUSTER".into()];
19509 let err = s.validate().unwrap_err();
19510 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19511 panic!("expected PlacementClusterInvalid");
19512 };
19513 assert_eq!(cluster, "BAD_CLUSTER");
19514 assert!(
19515 !reason.is_empty(),
19516 "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
19517 );
19518 }
19519
19520 #[test]
19521 fn rejects_sharded_with_empty_clusters() {
19522 // §III.1: Sharded uses :clusters as the shard pool. An empty
19523 // pool means "shard across no clusters" — meaningless, same as
19524 // Replicated with no hosts.
19525 let mut s = three_member_spec();
19526 s.placement.estrategia = PlacementStrategy::Sharded;
19527 s.placement.shard_key = Some("$tenantId".into());
19528 s.placement.clusters = vec![];
19529 assert!(matches!(
19530 s.validate().unwrap_err(),
19531 AplicacaoError::PlacementWithoutClusters {
19532 estrategia: PlacementStrategy::Sharded
19533 }
19534 ));
19535 }
19536
19537 #[test]
19538 fn rejects_sharded_with_empty_shard_key() {
19539 let mut s = three_member_spec();
19540 s.placement.estrategia = PlacementStrategy::Sharded;
19541 s.placement.shard_key = Some("".into());
19542 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
19543 }
19544
19545 #[test]
19546 fn rejects_shard_key_under_replicated_strategy() {
19547 // The fail-before-pass-after pin: a `:placement (:estrategia
19548 // Replicated :shard-key "tenantId")` manifest carries the
19549 // hash-keyed-distribution slot on a strategy that never consumes
19550 // it. Before the gate the typed slot's value silently vanished
19551 // at the renderer layer (caixa-mesh emits `placement.shardKey`
19552 // verbatim regardless of strategy; the Akka-style cluster-
19553 // sharding reconciler keys off `estrategia == Sharded` and
19554 // ignores the slot otherwise), with no diagnostic. Lifting the
19555 // rejection to a build-time gate makes the
19556 // `shard_key.is_some() == matches!(estrategia, Sharded)`
19557 // partition a structural property of every validated
19558 // [`Placement`].
19559 let mut s = three_member_spec();
19560 // The fixture already uses Replicated; just add a shard-key.
19561 s.placement.shard_key = Some("$tenantId".into());
19562 let err = s.validate().unwrap_err();
19563 let AplicacaoError::ShardKeyOnNonSharded {
19564 estrategia,
19565 shard_key,
19566 } = err
19567 else {
19568 panic!("expected ShardKeyOnNonSharded, got {err:?}");
19569 };
19570 assert_eq!(estrategia, PlacementStrategy::Replicated);
19571 assert_eq!(shard_key, "$tenantId");
19572 }
19573
19574 #[test]
19575 fn rejects_shard_key_under_singlenode_strategy() {
19576 // Peer of the Replicated case above on the SingleNode arm: OTP
19577 // distributed-app takeover (one cluster runs at a time) has no
19578 // hash-keyed routing axis to consume `:shard-key` either, so
19579 // the rejection fires on both non-Sharded arms uniformly.
19580 let mut s = three_member_spec();
19581 s.placement.estrategia = PlacementStrategy::SingleNode;
19582 s.placement.shard_key = Some("$tenantId".into());
19583 let err = s.validate().unwrap_err();
19584 let AplicacaoError::ShardKeyOnNonSharded {
19585 estrategia,
19586 shard_key,
19587 } = err
19588 else {
19589 panic!("expected ShardKeyOnNonSharded, got {err:?}");
19590 };
19591 assert_eq!(estrategia, PlacementStrategy::SingleNode);
19592 assert_eq!(shard_key, "$tenantId");
19593 }
19594
19595 #[test]
19596 fn rejects_empty_shard_key_under_replicated_strategy() {
19597 // The `Some("")` case under non-Sharded is rejected by
19598 // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
19599 // fires before the empty-value gate), not
19600 // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
19601 // the `Sharded` arm). Pin the partition so a future reorder of
19602 // the validate_placement match arms doesn't silently swap which
19603 // diagnostic the author sees — both are author errors, but
19604 // ShardKeyOnNonSharded names which strategy is the actual fix
19605 // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
19606 // only says "pick a non-empty key".
19607 let mut s = three_member_spec();
19608 s.placement.shard_key = Some(String::new());
19609 let err = s.validate().unwrap_err();
19610 assert!(
19611 matches!(
19612 err,
19613 AplicacaoError::ShardKeyOnNonSharded {
19614 estrategia: PlacementStrategy::Replicated,
19615 ref shard_key,
19616 } if shard_key.is_empty()
19617 ),
19618 "got {err:?}"
19619 );
19620 }
19621
19622 #[test]
19623 fn replicated_without_shard_key_validates() {
19624 // The complement of the rejection: `:placement :estrategia
19625 // Replicated` with `:shard-key None` is the canonical happy
19626 // path on every existing fixture. Pin the no-shard-key case so
19627 // the new gate doesn't accidentally fire on `None`.
19628 let mut s = three_member_spec();
19629 assert!(matches!(
19630 s.placement.estrategia,
19631 PlacementStrategy::Replicated
19632 ));
19633 s.placement.shard_key = None;
19634 s.validate().unwrap();
19635 }
19636
19637 #[test]
19638 fn singlenode_without_shard_key_validates() {
19639 // Peer of the Replicated no-shard-key case on the SingleNode
19640 // arm — both non-Sharded strategies must validate cleanly when
19641 // the slot is omitted.
19642 let mut s = three_member_spec();
19643 s.placement.estrategia = PlacementStrategy::SingleNode;
19644 s.placement.shard_key = None;
19645 s.validate().unwrap();
19646 }
19647
19648 fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
19649 // Fixture builder for the `:placement :shard-key` shape gate
19650 // tests: a three-member Aplicacao on the `Sharded` strategy
19651 // with the supplied `:shard-key` slot. Co-locates the
19652 // arm-construction so every test below carries one line of
19653 // setup (the offending `:shard-key` value) and the assertion.
19654 let mut s = three_member_spec();
19655 s.placement.estrategia = PlacementStrategy::Sharded;
19656 s.placement.shard_key = Some(key.into());
19657 s
19658 }
19659
19660 #[test]
19661 fn rejects_shard_key_with_embedded_space() {
19662 // The canonical paste-from-aligned-doc footgun:
19663 // `:shard-key "$tenant Id"` — the Akka-style entity-id
19664 // extractor reads the slot as a single-token reference, and an
19665 // embedded space breaks the token boundary at the runtime
19666 // hash-extractor pass with no diagnostic naming the offending
19667 // entry.
19668 let s = sharded_spec_with_key("$tenant Id");
19669 let err = s.validate().unwrap_err();
19670 assert!(
19671 matches!(
19672 err,
19673 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19674 if shard_key == "$tenant Id" && reason.contains("space")
19675 ),
19676 "got {err:?}"
19677 );
19678 }
19679
19680 #[test]
19681 fn rejects_shard_key_with_leading_space() {
19682 // Leading-space arm of the embedded-whitespace footgun — the
19683 // paste-from-aligned-doc / paste-from-CSV-cell variant where
19684 // the leading column-padding leaked into the slot.
19685 let s = sharded_spec_with_key(" $tenantId");
19686 let err = s.validate().unwrap_err();
19687 assert!(
19688 matches!(
19689 err,
19690 AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
19691 if shard_key == " $tenantId"
19692 ),
19693 "got {err:?}"
19694 );
19695 }
19696
19697 #[test]
19698 fn rejects_shard_key_with_trailing_newline() {
19699 // The canonical paste-from-shell-heredoc footgun — every
19700 // `<<EOF` heredoc terminator paste leaves a trailing newline
19701 // the YAML emitter then folds away inconsistently across
19702 // emitter implementations.
19703 let s = sharded_spec_with_key("$tenantId\n");
19704 let err = s.validate().unwrap_err();
19705 assert!(
19706 matches!(
19707 err,
19708 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19709 if shard_key == "$tenantId\n" && reason.contains("0x0a")
19710 ),
19711 "got {err:?}"
19712 );
19713 }
19714
19715 #[test]
19716 fn rejects_shard_key_with_embedded_tab() {
19717 // The paste-from-aligned-doc tab-stop variant — tabs land
19718 // alongside spaces in copy-paste from formatted columns.
19719 let s = sharded_spec_with_key("$tenant\tId");
19720 let err = s.validate().unwrap_err();
19721 assert!(
19722 matches!(
19723 err,
19724 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19725 if shard_key == "$tenant\tId" && reason.contains("tab")
19726 ),
19727 "got {err:?}"
19728 );
19729 }
19730
19731 #[test]
19732 fn rejects_shard_key_with_control_character() {
19733 // The paste-from-binary / paste-from-screen-cleared-terminal
19734 // footgun — an embedded `\x01` (SOH) byte that some YAML
19735 // emitters silently strip and others escape as ``,
19736 // breaking round-trip across emitter implementations.
19737 let s = sharded_spec_with_key("$tenant\u{0001}Id");
19738 let err = s.validate().unwrap_err();
19739 assert!(
19740 matches!(
19741 err,
19742 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19743 if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
19744 ),
19745 "got {err:?}"
19746 );
19747 }
19748
19749 #[test]
19750 fn rejects_shard_key_with_non_ascii() {
19751 // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
19752 // footgun — non-ASCII bytes normalize differently between the
19753 // caixa-mesh-side YAML emitter and the in-cluster reconciler's
19754 // YAML parser, the same entity ID can silently map to two
19755 // distinct shards on a re-render.
19756 let s = sharded_spec_with_key("$tenàntId");
19757 let err = s.validate().unwrap_err();
19758 assert!(
19759 matches!(
19760 err,
19761 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19762 if shard_key == "$tenàntId" && reason.contains("non-ASCII")
19763 ),
19764 "got {err:?}"
19765 );
19766 }
19767
19768 #[test]
19769 fn rejects_shard_key_too_long() {
19770 // Length cap pin: 64 bytes — one byte over the
19771 // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
19772 // here is a paste-from-doc multi-line blob landing in
19773 // `:shard-key` instead of a single-token extractor expression.
19774 let too_long = "a".repeat(64);
19775 let s = sharded_spec_with_key(&too_long);
19776 let err = s.validate().unwrap_err();
19777 let AplicacaoError::ShardKeyInvalid {
19778 ref shard_key,
19779 ref reason,
19780 } = err
19781 else {
19782 panic!("expected ShardKeyInvalid, got {err:?}");
19783 };
19784 assert_eq!(shard_key, &too_long);
19785 assert!(
19786 reason.contains("63") && reason.contains("64"),
19787 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19788 );
19789 }
19790
19791 #[test]
19792 fn shard_key_max_length_validates() {
19793 // Boundary pin: 63 bytes exactly — the
19794 // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
19795 // dropping to 62) surfaces here as a regression, mirroring
19796 // `placement_cluster_max_length_validates` /
19797 // `placement_affinity_max_length_validates` on the peer
19798 // identifier-shaped slots.
19799 let s = sharded_spec_with_key(&"a".repeat(63));
19800 s.validate().unwrap();
19801 }
19802
19803 #[test]
19804 fn accepts_canonical_shard_key_forms() {
19805 // The Akka-style entity-id extractor shapes a caixa author is
19806 // realistically going to write — pin every leg so a future
19807 // tightening that bans (e.g.) the `${...}` interpolation
19808 // variant or the `metadata.<field>` JSONPath form surfaces
19809 // here as a regression. The canonical forms span:
19810 //
19811 // - bare property name (`tenantId`, `customerId`)
19812 // - Akka `ExtractEntityId` placeholder (`$tenantId`)
19813 // - JSONPath-style nested reference (`metadata.tenantId`,
19814 // `$.user.id`)
19815 // - interpolation-style template (`${tenant}`)
19816 // - snake_case property name (`customer_id`)
19817 // - kebab-case property name (`customer-id` — accepted
19818 // because the slot is a printable-ASCII single-token
19819 // reference, not a DNS-1123 label like
19820 // `:placement :affinity` / `:clusters`)
19821 // - single character (`a`, `$` — boundary)
19822 for form in [
19823 "tenantId",
19824 "customerId",
19825 "$tenantId",
19826 "metadata.tenantId",
19827 "$.user.id",
19828 "${tenant}",
19829 "customer_id",
19830 "customer-id",
19831 "a",
19832 "$",
19833 ] {
19834 let s = sharded_spec_with_key(form);
19835 s.validate().unwrap_or_else(|e| {
19836 panic!("canonical shard-key form {form:?} must validate, got {e:?}")
19837 });
19838 }
19839 }
19840
19841 #[test]
19842 fn shard_key_empty_takes_precedence_over_invalid() {
19843 // Order pin: the existing `ShardedKeyEmpty` diagnostic
19844 // (reserved for the `Sharded` `Some("")` arm) fires before the
19845 // new `ShardKeyInvalid` parse-side diagnostic, so an empty
19846 // `:shard-key` keeps its narrower error message — the new gate
19847 // would also reject `""` defensively, but the empty-string arm
19848 // is the more self-locating diagnostic. Mirrors the
19849 // `placement_cluster_empty_takes_precedence_over_invalid` pin
19850 // on the peer identifier-shaped slot.
19851 let s = sharded_spec_with_key("");
19852 let err = s.validate().unwrap_err();
19853 assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
19854 }
19855
19856 #[test]
19857 fn shard_key_invalid_diagnostic_carries_offending_value() {
19858 // The diagnostic-shape pin: the error names the offending
19859 // `:shard-key` value verbatim so the author can grep their
19860 // caixa.lisp without re-running the build, and carries a
19861 // parser-shaped `reason:` naming the specific violation —
19862 // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19863 // on the peer identifier-shaped slot.
19864 let s = sharded_spec_with_key("$tenant Id");
19865 let err = s.validate().unwrap_err();
19866 let AplicacaoError::ShardKeyInvalid {
19867 ref shard_key,
19868 ref reason,
19869 } = err
19870 else {
19871 panic!("expected ShardKeyInvalid, got {err:?}");
19872 };
19873 assert_eq!(shard_key, "$tenant Id");
19874 assert!(
19875 !reason.is_empty(),
19876 "reason must name the specific violation, got empty string"
19877 );
19878 }
19879
19880 #[test]
19881 fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
19882 // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
19883 // `:shard-key` carried on non-Sharded strategies) fires before
19884 // the shape gate, so a malformed `:shard-key` carried on (e.g.)
19885 // a `Replicated` strategy surfaces the more self-locating
19886 // strategy-mismatch diagnostic (naming the actual fix — drop
19887 // the slot, or switch to Sharded) rather than the shape
19888 // diagnostic. The strategy-mismatch arm is the more actionable
19889 // diagnostic: a malformed shard-key on Replicated is "you
19890 // shouldn't have a :shard-key here at all", not "your
19891 // :shard-key value is malformed".
19892 let mut s = three_member_spec();
19893 // Replicated is the default fixture strategy.
19894 s.placement.shard_key = Some("$tenant Id".into());
19895 let err = s.validate().unwrap_err();
19896 assert!(
19897 matches!(
19898 err,
19899 AplicacaoError::ShardKeyOnNonSharded {
19900 estrategia: PlacementStrategy::Replicated,
19901 ..
19902 }
19903 ),
19904 "got {err:?}"
19905 );
19906 }
19907
19908 #[test]
19909 fn rejects_empty_affinity_hint() {
19910 let mut s = three_member_spec();
19911 s.placement.affinity = Some("".into());
19912 assert_eq!(
19913 s.validate().unwrap_err(),
19914 AplicacaoError::PlacementAffinityEmpty
19915 );
19916 }
19917
19918 #[test]
19919 fn placement_without_affinity_validates() {
19920 // Omitting :affinity is fine — the placement engine falls back
19921 // to the default heuristic. Pin the no-hint case so the
19922 // affinity-empty rejection doesn't accidentally fire on `None`.
19923 let mut s = three_member_spec();
19924 s.placement.affinity = None;
19925 s.validate().unwrap();
19926 }
19927
19928 #[test]
19929 fn rejects_placement_affinity_with_uppercase() {
19930 // The canonical "I copied the ADR's display name verbatim" typo
19931 // — placement hints land verbatim in K8s label-selector
19932 // territory, where the apiserver enforces the DNS-1123 label
19933 // rule (lowercase-only) on every identity-keyed admission axis.
19934 // Mirrors `rejects_placement_cluster_with_uppercase` on the
19935 // sibling slot.
19936 let mut s = three_member_spec();
19937 s.placement.affinity = Some("DataLocality".into());
19938 let err = s.validate().unwrap_err();
19939 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19940 panic!("expected PlacementAffinityInvalid, got other variant");
19941 };
19942 assert_eq!(affinity, "DataLocality");
19943 assert!(
19944 reason.contains("uppercase"),
19945 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19946 );
19947 assert!(
19948 reason.contains("\"datalocality\""),
19949 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19950 );
19951 }
19952
19953 #[test]
19954 fn rejects_placement_affinity_with_underscore() {
19955 // The canonical "I'm thinking of an env var / Python identifier"
19956 // leak — `_` is forbidden by every DNS-1123 label schema. Same
19957 // shape as `rejects_placement_cluster_with_underscore` on the
19958 // sibling slot.
19959 let mut s = three_member_spec();
19960 s.placement.affinity = Some("data_locality".into());
19961 let err = s.validate().unwrap_err();
19962 assert!(
19963 matches!(
19964 err,
19965 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19966 if affinity == "data_locality" && reason.contains('_')
19967 ),
19968 "got {err:?}"
19969 );
19970 }
19971
19972 #[test]
19973 fn rejects_placement_affinity_with_dot() {
19974 // A `:placement :affinity` value is a single DNS-1123 *label*
19975 // (it lands as a K8s label value selector key), not a subdomain.
19976 // The "I want to namespace my hint with `.`" intent is expressed
19977 // via `-` (`data-locality-east`).
19978 let mut s = three_member_spec();
19979 s.placement.affinity = Some("data.locality".into());
19980 let err = s.validate().unwrap_err();
19981 assert!(
19982 matches!(
19983 err,
19984 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19985 if affinity == "data.locality" && reason.contains('.')
19986 ),
19987 "got {err:?}"
19988 );
19989 }
19990
19991 #[test]
19992 fn rejects_placement_affinity_with_unicode() {
19993 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19994 // before it reaches K8s. The byte-by-byte ASCII validity check
19995 // rejects multi-byte UTF-8 sequences by the first byte that
19996 // fails `[a-z0-9-]`.
19997 let mut s = three_member_spec();
19998 s.placement.affinity = Some("data-localité".into());
19999 let err = s.validate().unwrap_err();
20000 assert!(
20001 matches!(
20002 err,
20003 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
20004 if affinity == "data-localité"
20005 ),
20006 "got {err:?}"
20007 );
20008 }
20009
20010 #[test]
20011 fn rejects_placement_affinity_with_leading_hyphen() {
20012 // DNS-1123 boundary rule: labels must start with an
20013 // alphanumeric. Pin separately from the trailing-hyphen arm so
20014 // a future relaxation that only checks one boundary surfaces
20015 // here as a regression (parallel to
20016 // `rejects_placement_cluster_with_leading_hyphen`).
20017 let mut s = three_member_spec();
20018 s.placement.affinity = Some("-data-locality".into());
20019 let err = s.validate().unwrap_err();
20020 assert!(
20021 matches!(
20022 err,
20023 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
20024 if affinity == "-data-locality" && reason.contains("start and end")
20025 ),
20026 "got {err:?}"
20027 );
20028 }
20029
20030 #[test]
20031 fn rejects_placement_affinity_with_trailing_hyphen() {
20032 // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
20033 // ends are covered against a future relaxation.
20034 let mut s = three_member_spec();
20035 s.placement.affinity = Some("data-locality-".into());
20036 let err = s.validate().unwrap_err();
20037 assert!(
20038 matches!(
20039 err,
20040 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
20041 if affinity == "data-locality-"
20042 ),
20043 "got {err:?}"
20044 );
20045 }
20046
20047 #[test]
20048 fn rejects_placement_affinity_with_whitespace() {
20049 // Whitespace is the canonical "I pasted from a sketch / doc"
20050 // footgun. The apiserver rejects every label-selector value
20051 // carrying whitespace.
20052 let mut s = three_member_spec();
20053 s.placement.affinity = Some("data locality".into());
20054 let err = s.validate().unwrap_err();
20055 assert!(
20056 matches!(
20057 err,
20058 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
20059 if affinity == "data locality"
20060 ),
20061 "got {err:?}"
20062 );
20063 }
20064
20065 #[test]
20066 fn rejects_placement_affinity_too_long() {
20067 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
20068 // pin. The diagnostic names both the cap (63) and the actual
20069 // length so the author can shorten in one edit. Mirrors
20070 // `rejects_placement_cluster_too_long`.
20071 let mut s = three_member_spec();
20072 let too_long = "a".repeat(64);
20073 s.placement.affinity = Some(too_long.clone());
20074 let err = s.validate().unwrap_err();
20075 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
20076 panic!("expected PlacementAffinityInvalid");
20077 };
20078 assert_eq!(affinity, too_long);
20079 assert!(
20080 reason.contains("63") && reason.contains("64"),
20081 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
20082 );
20083 }
20084
20085 #[test]
20086 fn placement_affinity_max_length_validates() {
20087 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
20088 // future tightening (e.g. dropping to 62) surfaces here as a
20089 // regression, mirroring `placement_cluster_max_length_validates`.
20090 let mut s = three_member_spec();
20091 s.placement.affinity = Some("a".repeat(63));
20092 s.validate().unwrap();
20093 }
20094
20095 #[test]
20096 fn accepts_canonical_placement_affinity_forms() {
20097 // The DNS-1123 label shapes a caixa author is realistically
20098 // going to write for placement hints: the M3 canonical examples
20099 // (`data-locality`, `low-latency`, `anti-affinity`), the
20100 // single-token form (`affinity`), the single-character boundary
20101 // (`a`), the digit-start (DNS-1123 allows this, unlike
20102 // DNS-1035), and a regional-suffixed form. Pin every leg so a
20103 // future tightening that bans (e.g.) digit-start identifiers
20104 // surfaces here.
20105 for form in [
20106 "data-locality",
20107 "low-latency",
20108 "anti-affinity",
20109 "affinity",
20110 "a",
20111 "3-tier",
20112 "locality-east",
20113 ] {
20114 let mut s = three_member_spec();
20115 s.placement.affinity = Some(form.into());
20116 s.validate().unwrap_or_else(|e| {
20117 panic!("canonical affinity form {form:?} must validate, got {e:?}")
20118 });
20119 }
20120 }
20121
20122 #[test]
20123 fn placement_affinity_empty_takes_precedence_over_invalid() {
20124 // Order pin: the existing `PlacementAffinityEmpty` diagnostic
20125 // (which doesn't try to parse) fires before the new
20126 // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
20127 // `:affinity` keeps its narrower error message — the new gate
20128 // would also reject `""`, but the empty-string arm is the more
20129 // self-locating diagnostic. Mirrors the
20130 // `placement_cluster_empty_takes_precedence_over_invalid` pin.
20131 let mut s = three_member_spec();
20132 s.placement.affinity = Some(String::new());
20133 let err = s.validate().unwrap_err();
20134 assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
20135 }
20136
20137 #[test]
20138 fn placement_affinity_invalid_diagnostic_carries_offending_value() {
20139 // The diagnostic shape pin: every rejection carries the offending
20140 // `affinity:` verbatim plus a parser-shaped `reason:` so the
20141 // author can grep their caixa.lisp for `:affinity "<hint>"` and
20142 // fix it in one edit. Mirrors the
20143 // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
20144 // pin on the sibling slot.
20145 let mut s = three_member_spec();
20146 s.placement.affinity = Some("Data_Locality".into());
20147 let err = s.validate().unwrap_err();
20148 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
20149 panic!("expected PlacementAffinityInvalid");
20150 };
20151 assert_eq!(affinity, "Data_Locality");
20152 assert!(
20153 !reason.is_empty(),
20154 "diagnostic reason must not be empty (got: {reason:?})"
20155 );
20156 }
20157
20158 #[test]
20159 fn singlenode_with_takeover_candidates_validates() {
20160 // OTP distributed-application convention (MESH-COMPOSITION
20161 // §II.1): SingleNode runs on one cluster at a time but the
20162 // :clusters list enumerates the takeover candidates. Multiple
20163 // entries are not a contradiction — they are the failover pool.
20164 let mut s = three_member_spec();
20165 s.placement.estrategia = PlacementStrategy::SingleNode;
20166 s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
20167 s.validate().unwrap();
20168 }
20169
20170 // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
20171
20172 #[test]
20173 fn mesh_policy_default_is_empty() {
20174 // The Default impl carries None on every axis — the typed
20175 // analog of an unset `:politicas (())` slot. Renderers that
20176 // overlay the policy onto a cluster artifact key off this
20177 // predicate to skip the slot entirely; pinning so a future
20178 // axis added to MeshPolicy can't silently break the contract
20179 // (a new field whose Default is non-None would flip is_empty
20180 // to false on every existing caixa, surfacing here).
20181 assert!(MeshPolicy::default().is_empty());
20182 }
20183
20184 #[test]
20185 fn mesh_policy_with_only_timeout_is_not_empty() {
20186 let p = MeshPolicy {
20187 timeout: Some(Duration::from_secs(30)),
20188 ..Default::default()
20189 };
20190 assert!(!p.is_empty());
20191 }
20192
20193 #[test]
20194 fn mesh_policy_with_only_retries_is_not_empty() {
20195 let p = MeshPolicy {
20196 retries: Some(3),
20197 ..Default::default()
20198 };
20199 assert!(!p.is_empty());
20200 }
20201
20202 #[test]
20203 fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
20204 let p = MeshPolicy {
20205 circuit_breaker: Some(CircuitBreaker {
20206 max_failures: 5,
20207 window: Duration::from_secs(60),
20208 }),
20209 ..Default::default()
20210 };
20211 assert!(!p.is_empty());
20212 }
20213
20214 #[test]
20215 fn mesh_policy_with_only_mtls_required_is_not_empty() {
20216 // Even `mtls_required: Some(false)` (an explicit opt-out) is
20217 // not empty — the author *named* the axis, the renderer needs
20218 // to honor that vs. fall back to the cluster default.
20219 let p = MeshPolicy {
20220 mtls_required: Some(false),
20221 ..Default::default()
20222 };
20223 assert!(!p.is_empty());
20224 }
20225
20226 #[test]
20227 fn mesh_policy_with_only_rate_limit_is_not_empty() {
20228 let p = MeshPolicy {
20229 rate_limit: Some(RateLimit {
20230 rate: 100,
20231 window: Duration::from_secs(1),
20232 }),
20233 ..Default::default()
20234 };
20235 assert!(!p.is_empty());
20236 }
20237
20238 #[test]
20239 fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
20240 // The three-member happy-path fixture sets timeout + retries +
20241 // mtls_required — every populated axis must read non-empty.
20242 // Pin the round-trip so the M3.x per-:politicas emitter (the
20243 // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
20244 // on is_empty() to decide whether to emit at all without
20245 // re-deriving the contract from inline field probes.
20246 assert!(!three_member_spec().politicas.is_empty());
20247 }
20248
20249 // ── shared duration codec: cross-slot integer-magnitude gate ──
20250 //
20251 // The integer-magnitude discipline applied to
20252 // `supervisor::duration_codec::parse` lifts onto every typed slot
20253 // that routes through the shared codec — `MeshPolicy::timeout`
20254 // (`:politicas :timeout`) and `CircuitBreaker::window`
20255 // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
20256 // These cross-slot tests pin that the gate fires at the serde
20257 // layer for both typed slots, not just for the supervisor side.
20258
20259 #[test]
20260 fn policy_timeout_serde_rejects_fractional_seconds() {
20261 // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
20262 // so the shared codec's integer-magnitude gate applies on
20263 // deserialize. `"1.5s"` previously parsed to 1500ms and round-
20264 // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
20265 // deserialize with the canonical-form diagnostic naming the
20266 // offending `"1.5"` and the remediation `"1500ms"`.
20267 let payload = r#"{"timeout":"1.5s"}"#;
20268 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20269 let msg = err.to_string();
20270 assert!(
20271 msg.contains("not a non-negative integer"),
20272 "expected integer-magnitude diagnostic in {msg:?}"
20273 );
20274 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
20275 assert!(
20276 msg.contains("\"1500ms\""),
20277 "missing canonical-form remediation in {msg:?}"
20278 );
20279 }
20280
20281 #[test]
20282 fn policy_timeout_serde_rejects_leading_plus_sign() {
20283 // Pin the leading-`+` arm cross-slot — the prior f64 parser
20284 // accepted `"+30s"` silently and round-tripped to `"30s"`.
20285 let payload = r#"{"timeout":"+30s"}"#;
20286 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20287 let msg = err.to_string();
20288 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
20289 }
20290
20291 #[test]
20292 fn circuit_breaker_window_serde_rejects_fractional_minutes() {
20293 // `CircuitBreaker::window` uses `with =
20294 // "supervisor::duration_codec_required"` (the required-Duration
20295 // variant that delegates to the same shared parser). `"0.5m"`
20296 // parsed to 30s and round-tripped to `"30s"` on next emit —
20297 // DRIFT closed.
20298 let payload = format!(
20299 r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
20300 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
20301 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
20302 );
20303 let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
20304 let msg = err.to_string();
20305 assert!(
20306 msg.contains("not a non-negative integer"),
20307 "expected integer-magnitude diagnostic in {msg:?}"
20308 );
20309 assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
20310 assert!(
20311 msg.contains("\"30s\""),
20312 "missing canonical-form remediation in {msg:?}"
20313 );
20314 }
20315
20316 #[test]
20317 fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
20318 // Pin the happy-path on the cross-slot side: every canonical
20319 // author shape `render` ever emits parses cleanly through the
20320 // shared codec on the `CircuitBreaker` slot. The
20321 // codec's accepted set (post-gate) is exactly its emitted set
20322 // for the integer-magnitude class.
20323 for window_lit in ["30s", "500ms", "2m", "1h"] {
20324 let payload = format!(
20325 r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
20326 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
20327 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
20328 );
20329 let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
20330 panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
20331 });
20332 assert_eq!(cb.max_failures, 5);
20333 }
20334 }
20335
20336 // ── rate_limit_codec: integer-magnitude gate ──
20337 //
20338 // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
20339 // / 737a676 / d53c922 trajectory landed on every typed-duration /
20340 // typed-byte-size codec in caixa-core lifts onto the fifth typed
20341 // codec — `rate_limit_codec` — through the digit-only magnitude
20342 // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
20343 // These tests pin the gate at the serde layer for `:politicas
20344 // :rate-limit` (the only typed slot the codec backs), and at the
20345 // codec-internal `parse` layer for the canonical positive cases.
20346
20347 #[test]
20348 fn rate_limit_serde_rejects_fractional_rate() {
20349 // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
20350 // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
20351 // wording, which didn't name the canonical-form remediation or
20352 // the round-trip drift the next emit would produce. Now refused
20353 // at deserialize with the canonical-form diagnostic naming the
20354 // offending `"1.5"` magnitude and the round-trip drift wording.
20355 let payload = r#"{"rateLimit":"1.5/s"}"#;
20356 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20357 let msg = err.to_string();
20358 assert!(
20359 msg.contains("not a non-negative integer"),
20360 "expected integer-magnitude diagnostic in {msg:?}"
20361 );
20362 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
20363 assert!(
20364 msg.contains("THEORY.md"),
20365 "missing render-determinism contract citation in {msg:?}"
20366 );
20367 }
20368
20369 #[test]
20370 fn rate_limit_serde_rejects_leading_plus_sign() {
20371 // `u32::from_str("+100")` returns `Ok(100)` (Rust's
20372 // permissive-`+` parse), so `"+100/s"` silently parsed to
20373 // `RateLimit { 100, 1s }` and round-tripped through `render` to
20374 // `"100/s"` — a *different* canonical string on the next emit,
20375 // breaking the THEORY.md Part V render-determinism contract
20376 // exactly the way the peer duration codecs' `"+30s"` case did.
20377 // This is the load-bearing class the digit-only gate closes
20378 // beyond what `u32::from_str`'s strictness covers on its own.
20379 let payload = r#"{"rateLimit":"+100/s"}"#;
20380 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20381 let msg = err.to_string();
20382 assert!(
20383 msg.contains("not a non-negative integer"),
20384 "expected integer-magnitude diagnostic in {msg:?}"
20385 );
20386 assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
20387 }
20388
20389 #[test]
20390 fn rate_limit_serde_rejects_leading_minus_sign() {
20391 // The signed-negative arm: `"-1/s"` lands on the
20392 // non-canonical-but-numeric branch via the `i64` fallback (the
20393 // `f64` parse also succeeds), surfacing the canonical-form
20394 // diagnostic. Replaces the prior value-laundered "not a u32"
20395 // wording with the unified diagnostic across signs.
20396 let payload = r#"{"rateLimit":"-1/s"}"#;
20397 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20398 let msg = err.to_string();
20399 assert!(
20400 msg.contains("not a non-negative integer"),
20401 "expected integer-magnitude diagnostic in {msg:?}"
20402 );
20403 assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
20404 }
20405
20406 #[test]
20407 fn rate_limit_serde_rejects_decimal_shaped_integer() {
20408 // `"100.0/s"` is integer-valued numerically but not in the
20409 // codec's accepted set — `render` emits `"100/s"`, so the
20410 // round-trip would drift. Lifted to the canonical-form
20411 // diagnostic peer with the duration codec's `"1.0s"` case
20412 // (1c55a2a).
20413 let payload = r#"{"rateLimit":"100.0/s"}"#;
20414 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20415 let msg = err.to_string();
20416 assert!(
20417 msg.contains("not a non-negative integer"),
20418 "expected integer-magnitude diagnostic in {msg:?}"
20419 );
20420 assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
20421 }
20422
20423 #[test]
20424 fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
20425 // Non-numeric, non-digit-only input lands on the existing
20426 // narrower `"not a u32"` arm (preserved for diagnostic-shape
20427 // stability on the parser-shape footgun case). Pin this so a
20428 // future relaxation of the numeric-fallback predicate doesn't
20429 // silently collapse garbage onto the canonical-form arm — same
20430 // partition the peer duration codecs draw between
20431 // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
20432 let payload = r#"{"rateLimit":"abc/s"}"#;
20433 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20434 let msg = err.to_string();
20435 assert!(
20436 msg.contains("not a u32"),
20437 "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
20438 );
20439 assert!(
20440 !msg.contains("not a non-negative integer"),
20441 "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
20442 );
20443 }
20444
20445 #[test]
20446 fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
20447 // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
20448 // u32's range. The digit-only gate passes; `u32::from_str`
20449 // fails on overflow. Surface that with the overflow-shaped
20450 // diagnostic naming the offending magnitude verbatim, peer
20451 // with `supervisor::duration_codec`'s overflow arm. Pinning
20452 // the wording so a future refactor doesn't silently collapse
20453 // overflow onto the canonical-form arm.
20454 let payload = r#"{"rateLimit":"4294967296/s"}"#;
20455 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20456 let msg = err.to_string();
20457 assert!(
20458 msg.contains("overflows u32"),
20459 "expected overflow diagnostic in {msg:?}"
20460 );
20461 assert!(
20462 msg.contains("\"4294967296\""),
20463 "missing offending magnitude in {msg:?}"
20464 );
20465 }
20466
20467 #[test]
20468 fn rate_limit_serde_rejects_leading_zero_magnitude() {
20469 // `"0100/s"` is digit-only, so the existing
20470 // non-digit-only / sign / fractional arm doesn't catch it —
20471 // `u32::from_str("0100")` returns `Ok(100)`, so before this
20472 // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
20473 // round-tripped through `render` to `"100/s"` — a *different*
20474 // canonical string on the next emit, breaking the THEORY.md
20475 // Part V render-determinism contract exactly the way the
20476 // peer `"+100/s"` case did before the leading-`+` arm landed.
20477 // This is the load-bearing class the leading-zero gate closes
20478 // beyond what the existing digit-only / sign / fractional
20479 // gates cover, and the peer arm to the leading-`+` test
20480 // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
20481 // canonical-form-drift axis.
20482 let payload = r#"{"rateLimit":"0100/s"}"#;
20483 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20484 let msg = err.to_string();
20485 assert!(
20486 msg.contains("non-canonical leading zero"),
20487 "expected leading-zero diagnostic in {msg:?}"
20488 );
20489 assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
20490 assert!(
20491 msg.contains("THEORY.md"),
20492 "missing render-determinism contract citation in {msg:?}"
20493 );
20494 }
20495
20496 #[test]
20497 fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
20498 // `"00/s"` is the degenerate leading-zero case — every byte
20499 // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
20500 // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
20501 // a *different* canonical string, same render-determinism
20502 // violation. The single-byte `"0/s"` itself is in the
20503 // accepted set (round-trips losslessly through `render`,
20504 // refused downstream by `PolicyRateLimitZero`); the
20505 // multi-byte `"00/s"` is not. Pins the boundary between the
20506 // accepted single-`0` and the rejected leading-zero class.
20507 let payload = r#"{"rateLimit":"00/s"}"#;
20508 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20509 let msg = err.to_string();
20510 assert!(
20511 msg.contains("non-canonical leading zero"),
20512 "expected leading-zero diagnostic in {msg:?}"
20513 );
20514 assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
20515 }
20516
20517 #[test]
20518 fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
20519 // Cross-window pin — the gate is window-agnostic; the
20520 // leading-zero class is a property of the magnitude, not the
20521 // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
20522 // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
20523 // single-window coverage extended across the three canonical
20524 // windows the codec accepts.
20525 let payload = r#"{"rateLimit":"007/h"}"#;
20526 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20527 let msg = err.to_string();
20528 assert!(
20529 msg.contains("non-canonical leading zero"),
20530 "expected leading-zero diagnostic in {msg:?}"
20531 );
20532 assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
20533 }
20534
20535 #[test]
20536 fn rate_limit_serde_rejects_leading_whitespace() {
20537 // `" 100/s"` — the canonical paste-from-aligned-doc /
20538 // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
20539 // the top-level `s.trim()` silently ate the leading space and
20540 // parsed the value to `RateLimit { 100, 1s }`, which then
20541 // round-tripped through `render` to `"100/s"` (a *different*
20542 // canonical string on the next emit) — the exact
20543 // canonical-form-drift class the leading-`+` / leading-zero
20544 // arms already close, extended to the whitespace byte class.
20545 let payload = r#"{"rateLimit":" 100/s"}"#;
20546 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20547 let msg = err.to_string();
20548 assert!(
20549 msg.contains("contains whitespace byte"),
20550 "expected whitespace diagnostic in {msg:?}"
20551 );
20552 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20553 assert!(
20554 msg.contains("THEORY.md"),
20555 "missing render-determinism contract citation in {msg:?}"
20556 );
20557 }
20558
20559 #[test]
20560 fn rate_limit_serde_rejects_trailing_whitespace() {
20561 // `"100/s "` — the canonical shell-history / trailing-space
20562 // paste footgun. Before this gate the top-level `s.trim()`
20563 // silently ate the trailing space and parsed to
20564 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
20565 // next emit — same canonical-form drift as the leading-space
20566 // sibling, closed on the same whitespace-byte arm.
20567 let payload = r#"{"rateLimit":"100/s "}"#;
20568 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20569 let msg = err.to_string();
20570 assert!(
20571 msg.contains("contains whitespace byte"),
20572 "expected whitespace diagnostic in {msg:?}"
20573 );
20574 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20575 }
20576
20577 #[test]
20578 fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
20579 // `"100 / s"` — the canonical typographically-spaced author
20580 // shape (the same idiom every prose reference to a rate limit
20581 // renders as, mistakenly retained when the value is pasted
20582 // into a codec-shaped slot). Before this gate the per-part
20583 // `rate_str.trim()` / `unit.trim()` calls silently ate both
20584 // spaces on either side of `/` and parsed to
20585 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
20586 // codec's *internal* whitespace-tolerance vector, orthogonal
20587 // to the leading / trailing surface but the same canonical-
20588 // form-drift class. Pins the arm as strictly stronger than the
20589 // pre-existing top-level `s.trim()` behavior: it fires on
20590 // whitespace anywhere in the value, not just at the string
20591 // boundary.
20592 let payload = r#"{"rateLimit":"100 / s"}"#;
20593 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20594 let msg = err.to_string();
20595 assert!(
20596 msg.contains("contains whitespace byte"),
20597 "expected whitespace diagnostic in {msg:?}"
20598 );
20599 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20600 }
20601
20602 #[test]
20603 fn rate_limit_serde_rejects_tab_byte() {
20604 // `"\t100/s"` — the canonical paste-from-indented-doc /
20605 // paste-from-YAML-block-scalar footgun where a tab byte leads
20606 // the magnitude. Pins that the gate covers tab (`0x09`) as
20607 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
20608 // members and both would be silently swallowed by `s.trim()`
20609 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
20610 // space alone to the full ASCII-whitespace set (space `0x20`,
20611 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
20612 // the tab arm as a representative of the non-space members.
20613 let payload = r#"{"rateLimit":"\t100/s"}"#;
20614 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20615 let msg = err.to_string();
20616 assert!(
20617 msg.contains("contains whitespace byte"),
20618 "expected whitespace diagnostic in {msg:?}"
20619 );
20620 assert!(
20621 msg.contains("0x09"),
20622 "missing offending tab byte in {msg:?}"
20623 );
20624 }
20625
20626 // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
20627 //
20628 // Successor to the ASCII-whitespace arm (1ad7755) on
20629 // `rate_limit_codec` — closes the strictly-complementary class the
20630 // byte-scan cannot see, through the lifted
20631 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
20632
20633 #[test]
20634 fn rate_limit_serde_rejects_leading_nbsp() {
20635 // NBSP prefix — paste-from-typography footgun. Byte-scan
20636 // misses, `str::trim` silently strips it, value drifts to
20637 // `"100/s"` on next serialize.
20638 let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
20639 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20640 let msg = err.to_string();
20641 assert!(
20642 msg.contains("non-ASCII Unicode whitespace character"),
20643 "expected non-ASCII whitespace diagnostic in {msg:?}"
20644 );
20645 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
20646 }
20647
20648 #[test]
20649 fn rate_limit_serde_rejects_internal_em_space() {
20650 // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
20651 // paste-from-typography footgun on the `<integer>/<unit>`
20652 // shape.
20653 let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
20654 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20655 let msg = err.to_string();
20656 assert!(
20657 msg.contains("non-ASCII Unicode whitespace character"),
20658 "expected non-ASCII whitespace diagnostic in {msg:?}"
20659 );
20660 assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
20661 }
20662
20663 #[test]
20664 fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
20665 // Positive-control pin: every ASCII-only canonical form the
20666 // renderer emits stays accepted through the new arm.
20667 for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
20668 let payload = format!(r#"{{"rateLimit":{lit}}}"#);
20669 let p: MeshPolicy = serde_json::from_str(&payload)
20670 .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
20671 assert!(p.rate_limit.is_some());
20672 }
20673 }
20674
20675 #[test]
20676 fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
20677 // The boundary case — `"0/s"` is the canonical form
20678 // `render(RateLimit { 0, 1s })` emits, so the codec accepts
20679 // it at the parse layer; the downstream
20680 // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
20681 // `rate == 0` at the typed-validate layer above. Pins the
20682 // partition: the leading-zero gate at the codec layer does
20683 // not poach the rate-zero semantic-validation arm at the
20684 // typed-validate layer above (a future stricter codec must
20685 // not reject `"0/s"` here, or it'd collapse the diagnostic
20686 // partitioning that lets `PolicyRateLimitZero` name the
20687 // offending typed slot).
20688 let payload = r#"{"rateLimit":"0/s"}"#;
20689 let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
20690 panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
20691 });
20692 let rl = policy.rate_limit.expect("rate_limit must be Some");
20693 assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
20694 assert_eq!(
20695 rl.window,
20696 Duration::from_secs(1),
20697 "single-`0` magnitude with `s` unit must parse to window=1s"
20698 );
20699 }
20700
20701 #[test]
20702 fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
20703 // The complementary boundary pin — every magnitude
20704 // `render` emits starts with `[1-9]` (or is the single byte
20705 // `"0"`), so the canonical-form predicate is `(len == 1) ||
20706 // (first byte != '0')`. Pinning the `len > 1 && first byte ==
20707 // '1'` case explicitly so a future tightening of the gate
20708 // (e.g. an over-eager "no leading digit < 5" rule, or a
20709 // mistakenly anchored start-of-magnitude byte check) lands
20710 // here before the canonical-forms-iterating test would catch
20711 // it.
20712 let payload = r#"{"rateLimit":"100/s"}"#;
20713 let policy: MeshPolicy = serde_json::from_str(payload)
20714 .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
20715 let rl = policy.rate_limit.expect("rate_limit must be Some");
20716 assert_eq!(
20717 rl.rate, 100,
20718 "canonical-100 magnitude must parse to rate=100"
20719 );
20720 }
20721
20722 #[test]
20723 fn rate_limit_serde_accepts_integer_canonical_forms() {
20724 // Pin the happy-path: every canonical author shape `render`
20725 // ever emits parses cleanly through the codec post-gate. The
20726 // codec's accepted set (post-gate) is exactly its emitted set
20727 // for the integer-magnitude class — same property
20728 // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
20729 // gates guarantee on the peer codecs. Iterating across rate
20730 // magnitudes (including `"0"`, which the codec accepts even
20731 // though `validate_politicas` rejects `rate == 0` at the typed
20732 // layer above) closes the codec contract at the parse layer
20733 // independently of the validate layer.
20734 for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
20735 for unit_lit in ["s", "m", "h"] {
20736 let lit = format!("{rate_lit}/{unit_lit}");
20737 let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
20738 let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
20739 panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
20740 });
20741 let rl = policy.rate_limit.expect("rate_limit must be Some");
20742 assert_eq!(
20743 rl.rate,
20744 rate_lit.parse::<u32>().unwrap(),
20745 "rate mismatch for {lit:?}"
20746 );
20747 }
20748 }
20749 }
20750
20751 #[test]
20752 fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
20753 // The structural property the gate enforces: serialize ∘
20754 // deserialize is the identity on every canonical author shape.
20755 // Peer of `parse_byte_size`'s and `parse_duration`'s
20756 // `_round_trips_through_render_for_every_canonical_form` tests
20757 // on the rate-limit axis. Before the gate, `"+100/s"` violated
20758 // this (`parse` → `RateLimit { 100, 1s }` → `render` →
20759 // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
20760 for rate in [1u32, 100, 5000, 1_000_000] {
20761 for (window, unit) in [
20762 (Duration::from_secs(1), "s"),
20763 (Duration::from_secs(60), "m"),
20764 (Duration::from_secs(3600), "h"),
20765 ] {
20766 let policy = MeshPolicy {
20767 rate_limit: Some(RateLimit { rate, window }),
20768 ..Default::default()
20769 };
20770 let json = serde_json::to_string(&policy).unwrap();
20771 let expected = format!("\"{rate}/{unit}\"");
20772 assert!(
20773 json.contains(&expected),
20774 "expected {expected:?} in {json:?}"
20775 );
20776 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20777 assert_eq!(
20778 back.rate_limit, policy.rate_limit,
20779 "round-trip for {json:?}"
20780 );
20781 }
20782 }
20783 }
20784
20785 // ── self-membership cross-slot gate ──────────────────────────────
20786
20787 #[test]
20788 fn validate_no_self_membership_rejects_self_named_membro() {
20789 // An Aplicacao whose `:membros` lists its own `:nome` is a
20790 // one-node lacre-closure recursion — rejected, naming the parent.
20791 let membros = vec![
20792 membro("catalog", "^0.1"),
20793 membro("checkout", "^0.1"),
20794 membro("cart", "^0.1"),
20795 ];
20796 let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
20797 assert!(
20798 matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
20799 "got {err:?}"
20800 );
20801 }
20802
20803 #[test]
20804 fn validate_no_self_membership_accepts_distinct_membros() {
20805 // Positive control: distinct member names (including a member
20806 // that is itself an Aplicacao — recursive composition is valid,
20807 // MESH-COMPOSITION §V) pass the gate.
20808 let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
20809 validate_no_self_membership(&membros, "checkout").unwrap();
20810 }
20811
20812 #[test]
20813 fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
20814 // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
20815 // `NoMembros` arm (the more-fundamental "graph must have nodes"
20816 // gate), not by this cross-slot self-edge gate. Keeping the
20817 // self-membership predicate vacuously-ok on the empty input
20818 // matches its supervisor-axis peer
20819 // (`validate_no_self_supervision_empty_children_is_ok`) and
20820 // makes the gate composable from any future call site (an M4
20821 // CR materializer's per-membros validator) without re-checking
20822 // emptiness.
20823 validate_no_self_membership(&[], "checkout").unwrap();
20824 }
20825
20826 #[test]
20827 fn validate_no_self_membership_diagnostic_names_offending_caixa() {
20828 // Pinning the Display: the self-membership diagnostic must name
20829 // the offending caixa verbatim + the "lists itself" framing the
20830 // author can grep for, so the cluster-far failure surfaces at
20831 // build time with one-line remediation. Same diagnostic shape
20832 // as the supervisor-axis `ChildSupervisesSelf` peer.
20833 let membros = vec![membro("orquestra", "^0.1")];
20834 let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
20835 let msg = err.to_string();
20836 assert!(
20837 msg.contains("orquestra"),
20838 "diagnostic must name the offending caixa nome (got: {msg:?})"
20839 );
20840 assert!(
20841 msg.contains("lists itself"),
20842 "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
20843 );
20844 }
20845
20846 #[test]
20847 fn default_servico_port_constant_pins_canonical_8080_literal() {
20848 // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
20849 // at the verbatim `8080` literal both consumers (the
20850 // `Entrada::port` serde default via [`default_port`] and the
20851 // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
20852 // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
20853 // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
20854 // discipline (a085b26) on the per-renderer canonical-K8s-axis
20855 // string-constant axis: a future refactor that drifts the
20856 // constant out from under either consumer surfaces here ahead
20857 // of every per-renderer's first emission. The literal value
20858 // matches the well-known HTTP-alt port the `pleme-computeunit`
20859 // library chart already emits as its `trigger.service.port`
20860 // default — by construction the same value the substrate
20861 // assumes about every Servico's in-cluster L4 listener.
20862 assert_eq!(
20863 DEFAULT_SERVICO_PORT, 8080,
20864 "canonical Servico port literal must remain `8080` verbatim — \
20865 this is the value both the `Entrada::port` serde default and the \
20866 caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
20867 );
20868 }
20869
20870 #[test]
20871 fn default_port_helper_returns_canonical_servico_port_constant() {
20872 // The bridge-arm — pins that the [`default_port`] helper
20873 // [`Entrada::port`]'s `#[serde(default = "default_port")]`
20874 // attribute hooks routes through the lifted
20875 // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
20876 // literal. A future refactor that re-introduces the `8080`
20877 // literal at the helper's return site (silently re-opening
20878 // the drift footgun this lift closed) surfaces here ahead of
20879 // every author-side `(:entrada (:host … :para …))` slot
20880 // without an explicit `:port`. Peer with the
20881 // `default_namespace_re_export_points_at_caixa_core_canonical`
20882 // pin on the caixa-mesh-side re-export axis.
20883 assert_eq!(
20884 default_port(),
20885 DEFAULT_SERVICO_PORT,
20886 "the serde-default helper must route through the lifted constant"
20887 );
20888 }
20889
20890 #[test]
20891 fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
20892 // The end-to-end pin — an author-surface `(:entrada (:host …
20893 // :para …))` without an explicit `:port` slot deserializes to
20894 // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
20895 // verbatim. Routes the canonical lifted constant through both
20896 // the serde-default machinery (the `#[serde(default =
20897 // "default_port")]` attribute) and the typed-value-shape
20898 // contract (the resulting [`Entrada::port`] value). A future
20899 // refactor that drifts either axis — replacing the serde
20900 // hook's helper, changing the typed slot's wire shape — would
20901 // surface here before any per-renderer's CNP / Gateway /
20902 // HTTPRoute emission consumed the drifted default.
20903 let entrada: Entrada =
20904 serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
20905 assert_eq!(
20906 entrada.port, DEFAULT_SERVICO_PORT,
20907 "the serde default must materialize as the lifted canonical Servico port"
20908 );
20909 }
20910
20911 #[test]
20912 fn servico_port_min_pins_canonical_accept_set_floor() {
20913 // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
20914 // verbatim `1` literal every typed `:entrada :port` acceptance
20915 // gate keys off. Peer with the
20916 // [`default_servico_port_constant_pins_canonical_8080_literal`]
20917 // discipline on the canonical-Servico-port-constant axis: a
20918 // future refactor that drifts the accept-set floor out from
20919 // under the sole consumer at [`AplicacaoSpec::validate`]'s
20920 // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
20921 // every per-`:entrada` `EntradaPortZero` diagnostic. The
20922 // literal value matches the IANA-registered TCP/UDP port
20923 // space floor (`1..=65535` — port `0` is the "any ephemeral"
20924 // sentinel, not a well-defined destination the substrate's
20925 // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
20926 // axis can honor).
20927 assert_eq!(
20928 SERVICO_PORT_MIN, 1,
20929 "canonical Servico port accept-set floor must remain `1` verbatim — \
20930 this is the value the `AplicacaoSpec::validate` gate at \
20931 `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
20932 );
20933 }
20934
20935 #[test]
20936 fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
20937 // The cross-const invariant pin — the substrate's canonical
20938 // default port must satisfy its own accept-set floor by
20939 // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
20940 // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
20941 // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
20942 // override the operator pins through a future
20943 // `:placement :default-port` slot that lands out-of-range, a
20944 // per-edition Servico-port migration that lifted the floor
20945 // above the previous default without coordinating the pair —
20946 // would silently invalidate the serde-default emission at
20947 // every author-side `(:entrada (:host … :para …))` slot
20948 // without an explicit `:port`: the default port would fall
20949 // below the accept-set floor, the `AplicacaoSpec::validate`
20950 // gate would reject every default-carrying Aplicacao as
20951 // `EntradaPortZero`, and the substrate's typed
20952 // `(defcaixa … :kind Aplicacao)` surface would fail validate
20953 // on every Aplicacao whose author omitted `:entrada :port`
20954 // for the substrate's chosen default — a class of authoring-
20955 // surface footguns the compile-time pin structurally closes.
20956 // Peer with the
20957 // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
20958 // (27f9b34) cross-const invariant pin discipline on the peer
20959 // canonical-Helm-per-values-block child-chart-enablement-toggle
20960 // axis pair.
20961 assert!(
20962 SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
20963 "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
20964 satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
20965 every default-carrying `(:entrada (:host … :para …))` slot without an \
20966 explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
20967 hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
20968 );
20969 }
20970
20971 #[test]
20972 fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
20973 // The gate-site pin — asserts the `AplicacaoSpec::validate`
20974 // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
20975 // `EntradaPortZero` diagnostic on the below-floor input
20976 // `port: 0` (the only below-floor value the `u16` field can
20977 // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
20978 // is the singleton `{0}`). A future refactor that drifts the
20979 // gate off the lifted const (silently re-introducing an
20980 // inline `if e.port == 0` byte-check) surfaces here — the
20981 // pin cannot distinguish `< 1` from `== 0` on the current
20982 // floor, but it *does* pin that the diagnostic fires on `0`
20983 // through whichever gate is wired, so any future accept-set
20984 // floor migration (a hypothetical unprivileged-only
20985 // migration lifting `SERVICO_PORT_MIN` to `1024`) must
20986 // update this test alongside the const declaration —
20987 // structurally guaranteeing the gate + accept-set + pin
20988 // trio move together. Peer with the
20989 // [`rejects_zero_entrada_port`] behavioral pin on the same
20990 // per-`:entrada :port` axis — that pin asserts the pre-lift
20991 // behavioral contract (`port: 0` → `EntradaPortZero`); this
20992 // pin adds the structural link to the lifted floor const.
20993 assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
20994 let mut s = three_member_spec();
20995 s.entrada.as_mut().unwrap().port = 0;
20996 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
20997 }
20998
20999 // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
21000
21001 #[test]
21002 fn membro_serde_keys_match_lifted_membro_key_consts() {
21003 // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
21004 // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
21005 // name the exact camelCase JSON keys the
21006 // `#[serde(rename_all = "camelCase")]` attribute on
21007 // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
21008 // that each canonical byte-sequence appears verbatim in the
21009 // JSON — a future accidental `rename_all = "snake_case"` /
21010 // `"kebab-case"` / verbatim-field-name flip at the derive
21011 // attribute (any of which would silently break every downstream
21012 // JSON consumer that reaches for one of the two consts via
21013 // `Value::get(...)`) surfaces here as a build-time test failure
21014 // at `aplicacao.rs`, not as an apply-time
21015 // `.get(<stale-canonical-const>)` returning `None` far from the
21016 // derive-attr drift's commit. Peer with the sibling
21017 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
21018 // (40cc4e5) pin on the M2 supervision-tree top-level axis —
21019 // same discipline the SupervisorSpec top-level lift established,
21020 // extended here to the M3 [`Membro`] per-`:membros` axis.
21021 let m = Membro {
21022 caixa: "catalog".into(),
21023 versao: "^0.1".into(),
21024 };
21025 let json = serde_json::to_string(&m).unwrap();
21026 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
21027 let quoted = format!("\"{key}\"");
21028 assert!(
21029 json.contains("ed),
21030 "serialized Membro must carry the lifted MEMBRO_KEY_* \
21031 byte-sequence {quoted} verbatim in the JSON emission \
21032 (got: {json})",
21033 );
21034 }
21035 }
21036
21037 #[test]
21038 fn membro_key_consts_are_pairwise_distinct() {
21039 // Cross-axis drift-detection pin: a future collapse of the two
21040 // canonical [`Membro`] per-entry byte-strings onto the same
21041 // value (e.g. an accidental copy-paste flip of
21042 // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
21043 // silently reroute every downstream probe on one axis onto the
21044 // sibling axis's overlay entry and pass every propagation-probe
21045 // test that expected only the stale axis's value. Peer of the
21046 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
21047 // (40cc4e5).
21048 let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
21049 for (i, a) in all.iter().enumerate() {
21050 for b in all.iter().skip(i + 1) {
21051 assert_ne!(
21052 a, b,
21053 "MEMBRO_KEY_* consts must be pairwise-distinct \
21054 canonical byte-sequences — got `{a}` == `{b}`",
21055 );
21056 }
21057 }
21058 }
21059
21060 // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
21061 // URL-path fallback resolver every HTTPRoute-aware renderer
21062 // reaching for a per-rule path-list resolution routes through.
21063 // The four pin tests below fix the four-way accept-set the
21064 // resolver must always honor: (:paths-non-empty-verbatim,
21065 // :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
21066 // :paths-preserves-order-across-multiple-entries) — drift on any
21067 // arm surfaces at caixa-core build time rather than at cluster-
21068 // apply time. Peer discipline with `MeshPolicy::is_empty` on the
21069 // sibling `:politicas` typed-primitive dispatch axis.
21070
21071 fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
21072 Entrada {
21073 host: "example.com".into(),
21074 para: "cart".into(),
21075 paths: paths.into_iter().map(String::from).collect(),
21076 port: DEFAULT_SERVICO_PORT,
21077 }
21078 }
21079
21080 #[test]
21081 fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
21082 // The typed `:entrada :paths` slot carries an author-declared
21083 // list — the resolver returns each entry verbatim, no
21084 // catch-all substitution. The canonical "author declared
21085 // paths, honor them verbatim" arm of the path-list dispatch.
21086 let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
21087 assert_eq!(
21088 e.resolved_paths(),
21089 vec!["/api/cart", "/api/products"],
21090 "resolved_paths must return each `:entrada :paths` entry \
21091 verbatim when the typed slot is non-empty (got {:?})",
21092 e.resolved_paths(),
21093 );
21094 }
21095
21096 #[test]
21097 fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
21098 // Empty `:entrada :paths` slot — the resolver substitutes the
21099 // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
21100 // catch-all fallback verbatim. Pins the empty-arm of the
21101 // resolver's four-way accept-set against a future silent
21102 // detour that returned an empty Vec (which would emit an
21103 // HTTPRoute with zero rules — silently dropping every
21104 // external `:entrada` flow at admission time), routed to a
21105 // different fallback shape, or dropped the catch-all
21106 // altogether.
21107 let e = entrada_with_paths(vec![]);
21108 assert_eq!(
21109 e.resolved_paths(),
21110 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
21111 "resolved_paths on empty `:entrada :paths` must fall back \
21112 to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
21113 all — got {:?}",
21114 e.resolved_paths(),
21115 );
21116 }
21117
21118 #[test]
21119 fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
21120 // Single-entry `:entrada :paths` — the resolver returns the
21121 // single declared path verbatim, NOT the catch-all fallback
21122 // (author declared a path, honor it — the empty-arm and the
21123 // len-1 arm are semantically distinct axes of the resolver's
21124 // accept-set). Pins that the resolver treats "author declared
21125 // one path" as authored input, not as the empty case.
21126 let e = entrada_with_paths(vec!["/api/only"]);
21127 assert_eq!(
21128 e.resolved_paths(),
21129 vec!["/api/only"],
21130 "resolved_paths on single-entry `:entrada :paths` must \
21131 return the declared path verbatim, NOT the catch-all \
21132 fallback (got {:?})",
21133 e.resolved_paths(),
21134 );
21135 }
21136
21137 #[test]
21138 fn resolved_paths_preserves_author_declared_order() {
21139 // The `:entrada :paths` list is author-ordered — the resolver
21140 // preserves the author's declaration order verbatim, since
21141 // per-rule dispatch order at the K8s Gateway API HTTPRoute
21142 // consumer is significant (first-match-wins under the
21143 // path-prefix matcher). Pins against a future silent
21144 // re-sort / dedup / normalize detour that reordered author
21145 // input.
21146 let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
21147 assert_eq!(
21148 e.resolved_paths(),
21149 vec!["/z/last", "/a/first", "/m/mid"],
21150 "resolved_paths must preserve author-declared `:entrada \
21151 :paths` order verbatim — got {:?}",
21152 e.resolved_paths(),
21153 );
21154 }
21155
21156 // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
21157 // slot `&[String]` slice accessor every per-`:entrada` consumer
21158 // that must see the author's declaration verbatim (not the
21159 // fallback-applied projection the sibling `resolved_paths`
21160 // returns) routes through. The three pin tests below fix the
21161 // accept-set the accessor must honor: (:non-empty-byte-equal,
21162 // :empty-projects-empty-slice, :preserves-author-declared-order)
21163 // — drift on any arm surfaces at caixa-core build time rather
21164 // than at cluster-apply time. Peer discipline with the sibling
21165 // [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
21166 // peer M3 mesh-slot `Vec<String>`-carry axis.
21167
21168 #[test]
21169 fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
21170 // Byte-equal pin: [`Entrada::paths`] must project the raw
21171 // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
21172 // slice borrowed from the typed slot's own [`Vec<String>`]
21173 // storage — no re-ordering, no dedup, no per-entry normalization,
21174 // no fallback substitution (the fallback-applying projection is
21175 // the sibling [`Entrada::resolved_paths`] resolver). Pins against
21176 // a future silent detour that re-normalized the list, dropped
21177 // duplicates the [`AplicacaoSpec::validate`]
21178 // `EntradaPathDuplicate` refusal already rejects at build time,
21179 // or (most severe) accidentally routed through the fallback-
21180 // applying sibling and returned the substrate catch-all when
21181 // the author declared an empty list — collapsing the raw-slot
21182 // and fallback-applied axes into one and breaking the
21183 // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
21184 //
21185 // Peer of the sibling
21186 // [`Placement::clusters`]-shape byte-equal pin
21187 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
21188 // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
21189 let fixtures: Vec<Vec<String>> = vec![
21190 Vec::new(),
21191 vec!["/api/cart".into()],
21192 vec!["/api/cart".into(), "/api/products".into()],
21193 vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
21194 ];
21195 for paths in fixtures {
21196 let e = Entrada {
21197 host: "example.com".into(),
21198 para: "cart".into(),
21199 paths: paths.clone(),
21200 port: DEFAULT_SERVICO_PORT,
21201 };
21202 assert_eq!(
21203 e.paths(),
21204 paths.as_slice(),
21205 "Entrada::paths must return :entrada :paths verbatim \
21206 (got {:?}, expected {:?})",
21207 e.paths(),
21208 paths.as_slice(),
21209 );
21210 assert_eq!(
21211 e.paths(),
21212 e.paths.as_slice(),
21213 "Entrada::paths accessor and .paths.as_slice() field \
21214 access must byte-equal — the accessor is the substrate-\
21215 primitive typed dispatch every downstream per-`:entrada` \
21216 raw-slot path-list consumer must route through",
21217 );
21218 assert_eq!(
21219 e.paths().len(),
21220 e.paths.len(),
21221 "Entrada::paths().len() must byte-equal self.paths.len() \
21222 — a length drift would silently split the paired \
21223 pre-flight cascade-head `.is_empty()` probe input in \
21224 the sibling [`Entrada::resolved_paths`] resolver from \
21225 the per-entry validate loop's traversal input in \
21226 [`AplicacaoSpec::validate`]",
21227 );
21228 }
21229 }
21230
21231 #[test]
21232 fn resolved_paths_reads_through_lifted_paths_accessor() {
21233 // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
21234 // pre-flight `.paths().is_empty()` cascade-head probe (which
21235 // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
21236 // catch-all fallback arm when the accessor projects the empty
21237 // slice) and the per-entry `.paths().iter().map(String::as_str)`
21238 // projection (which must reach every entry in the same order
21239 // the accessor projects, so the sibling
21240 // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
21241 // per-entry projection stay in lockstep by construction) must
21242 // both key off the lifted accessor. Pins the two-site coherence
21243 // by exercising each production consumer end-to-end: (1) the
21244 // catch-all-fallback arm under the empty slice, (2) the
21245 // author-declared-verbatim arm under a two-entry cohort whose
21246 // per-entry projection must byte-equal the input's per-entry
21247 // author-declared paths in the author's declared order.
21248 //
21249 // Peer of the sibling M3
21250 // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
21251 // `validate_placement_reads_through_lifted_clusters_accessor`
21252 // on the sibling `Placement::clusters` reader-site convergence.
21253 let empty = entrada_with_paths(vec![]);
21254 assert_eq!(
21255 empty.resolved_paths(),
21256 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
21257 "resolved_paths on empty :entrada :paths must trip the \
21258 lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
21259 catch-all fallback — routing through the lifted paths() \
21260 accessor must not silently drop the fallback arm",
21261 );
21262
21263 let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
21264 assert_eq!(
21265 declared.resolved_paths(),
21266 vec!["/api/cart", "/api/products"],
21267 "resolved_paths on non-empty :entrada :paths must return each \
21268 entry verbatim in the author's declared order — routing \
21269 through the lifted paths() accessor must not silently \
21270 reorder or drop entries",
21271 );
21272 // Byte-equal pin against the raw-slot accessor to keep the
21273 // fallback-applying resolver's per-entry projection input in
21274 // lockstep with the raw-slot accessor's projection.
21275 let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
21276 assert_eq!(
21277 declared.resolved_paths(),
21278 raw_projected,
21279 "resolved_paths non-empty projection must byte-equal the \
21280 lifted paths() accessor's per-entry String::as_str projection \
21281 — the two projections share the same input slice by \
21282 construction, so any drift here would surface a silent \
21283 re-ordering / dedup / normalization detour in the resolver",
21284 );
21285 }
21286
21287 #[test]
21288 fn validate_reads_through_lifted_entrada_paths_accessor() {
21289 // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
21290 // per-entry value-shape gate's `for p in e.paths()` traversal
21291 // (which must reach every entry in the same order the accessor
21292 // projects, so both the per-entry `EntradaPathEmpty` /
21293 // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
21294 // the duplicate-detection HashSet insert that trips
21295 // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
21296 // projection) must route through the lifted accessor. Pins the
21297 // coherence by exercising each production consumer end-to-end:
21298 // (1) the `EntradaPathEmpty` refusal fires on the second entry
21299 // of a two-entry cohort whose head is valid but tail is empty
21300 // (which requires the loop to reach the second entry through
21301 // the accessor), and (2) the `EntradaPathDuplicate` refusal
21302 // fires on the second entry of a two-entry cohort that shares
21303 // a path (which requires the loop to reach both entries — a
21304 // first-entry-only projection would silently pass since the
21305 // dedup HashSet has room for the first insert).
21306 //
21307 // Peer of the sibling
21308 // `validate_placement_reads_through_lifted_clusters_accessor`
21309 // on the sibling `Placement::clusters` reader-site convergence.
21310 let base = crate::AplicacaoSpec {
21311 membros: vec![crate::Membro {
21312 caixa: "cart".into(),
21313 versao: "^0.1".into(),
21314 }],
21315 contratos: Vec::new(),
21316 politicas: crate::MeshPolicy::default(),
21317 placement: crate::Placement {
21318 estrategia: crate::PlacementStrategy::SingleNode,
21319 clusters: vec!["rio".into()],
21320 shard_key: None,
21321 affinity: None,
21322 },
21323 entrada: Some(Entrada {
21324 host: "example.com".into(),
21325 para: "cart".into(),
21326 paths: vec!["/api/cart".into(), String::new()],
21327 port: DEFAULT_SERVICO_PORT,
21328 }),
21329 };
21330 assert_eq!(
21331 base.validate(),
21332 Err(crate::AplicacaoError::EntradaPathEmpty),
21333 "validate must trip EntradaPathEmpty on the second entry of \
21334 a two-entry cohort — routing through the lifted paths() \
21335 accessor must not silently short-circuit the loop at the \
21336 valid head entry",
21337 );
21338
21339 let mut dup = base;
21340 dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
21341 assert_eq!(
21342 dup.validate(),
21343 Err(crate::AplicacaoError::EntradaPathDuplicate {
21344 path: "/api/cart".into(),
21345 }),
21346 "validate must trip EntradaPathDuplicate on the second entry \
21347 of a two-entry cohort that shares a path — routing through \
21348 the lifted paths() accessor must not silently short-circuit \
21349 the dedup HashSet insert at the first entry",
21350 );
21351 }
21352
21353 // ── Entrada::hostname / Entrada::hostnames — the substrate-
21354 // canonical per-`:entrada` DNS-hostname resolver pair every
21355 // Gateway-API-aware renderer reaching for a per-listener
21356 // singular `hostname:` filter (Gateway) or a per-route plural
21357 // `spec.hostnames[]` filter list (HTTPRoute) routes through.
21358 // The three pin tests below fix the two-way accept-set the pair
21359 // must always honor: (:singular-byte-equal-to-host,
21360 // :plural-is-singleton-of-singular, :plural-len-is-one) — drift
21361 // on any arm surfaces at caixa-core build time rather than at
21362 // cluster-apply time when the API server refuses the HTTPRoute
21363 // for non-intersecting hostname filters. Peer discipline with
21364 // the sibling `resolved_paths` accept-set pin block above on the
21365 // per-`:entrada` path-list resolver axis.
21366
21367 fn entrada_with_host(host: &str) -> Entrada {
21368 Entrada {
21369 host: host.into(),
21370 para: "cart".into(),
21371 paths: Vec::new(),
21372 port: DEFAULT_SERVICO_PORT,
21373 }
21374 }
21375
21376 #[test]
21377 fn hostname_returns_entrada_host_byte_equal() {
21378 // The canonical singular-axis pin: [`Entrada::hostname`] must
21379 // return the `:entrada :host` field byte-for-byte, borrowed
21380 // from the typed slot's own [`String`] storage. Pins against a
21381 // future silent detour that re-normalized the host (an
21382 // accidental `.to_lowercase()` — validate_entrada_host already
21383 // enforces lowercase, so any re-normalization is redundant + a
21384 // drift surface between the validator and the accessor), a
21385 // trailing-`.` fully-qualified DNS shape substitution, or a
21386 // Punycode round-trip that lowered a Unicode host through IDNA.
21387 let e = entrada_with_host("checkout.quero.cloud");
21388 assert_eq!(
21389 e.hostname(),
21390 "checkout.quero.cloud",
21391 "Entrada::hostname must return :entrada :host verbatim \
21392 (got {:?})",
21393 e.hostname(),
21394 );
21395 assert_eq!(
21396 e.hostname(),
21397 e.host.as_str(),
21398 "Entrada::hostname must byte-equal the .host field access",
21399 );
21400 }
21401
21402 #[test]
21403 fn hostnames_returns_singleton_of_hostname_accessor() {
21404 // The pair-invariant pin: [`Entrada::hostnames`] must always
21405 // return exactly `vec![hostname()]` — the singleton list whose
21406 // sole entry is the substrate's canonical per-`:entrada`
21407 // singular hostname. Pins the two-consumer coherence axis: the
21408 // Gateway listener's singular `hostname:` filter and the
21409 // HTTPRoute's plural `spec.hostnames[]` filter list must
21410 // agree, else the Gateway API v1.x conformance layer rejects
21411 // the HTTPRoute at attach time with
21412 // `Accepted:False/NoMatchingParent` (the parent Gateway's
21413 // listener hostname doesn't intersect the route's hostname
21414 // filter list) — a divergence whose apply-time symptom is far
21415 // from any single-site commit and never surfaces in the
21416 // emitted YAML. Pinning the pair-invariant here makes any
21417 // future accidental split (an accidental `.to_string() + "."`
21418 // trailing-`.` on the plural side that didn't land on the
21419 // singular side, an accidental prefix stripping on one axis,
21420 // an accidental wildcard prepend the SNI fan-out overlay
21421 // authors on the plural side without a paired singular
21422 // migration) trip at caixa-core build time.
21423 let e = entrada_with_host("checkout.quero.cloud");
21424 assert_eq!(
21425 e.hostnames(),
21426 vec![e.hostname()],
21427 "Entrada::hostnames must return `vec![hostname()]` under \
21428 the pair-invariant — got {:?} vs. singleton {:?}",
21429 e.hostnames(),
21430 vec![e.hostname()],
21431 );
21432 }
21433
21434 #[test]
21435 fn hostnames_is_singleton_under_single_host_author_surface() {
21436 // The singleton-shape pin: under today's single-hostname-per-
21437 // `:entrada` author surface (the `:host` slot is a single
21438 // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
21439 // must always return a list of length exactly one. Pins
21440 // against a future silent detour that returned an empty list
21441 // (which would emit an HTTPRoute with `spec.hostnames: []` —
21442 // matching every incoming Host header regardless of the
21443 // Aplicacao's declared ingress apex, silently over-matching
21444 // every foreign VirtualHost the parent Gateway also fronts) or
21445 // a duplicated entry (which the Gateway API v1.x parser
21446 // accepts as a `[]-length-2 list of equal hostnames]` but
21447 // whose semantics differ from the intended singleton). The
21448 // author-surface extension point ("a future `:entrada
21449 // :alt-hosts` list overlay" the docstring names) is the sole
21450 // future axis that flips this pin — that migration will re-
21451 // author this test to pin the new plural cardinality.
21452 let e = entrada_with_host("checkout.quero.cloud");
21453 assert_eq!(
21454 e.hostnames().len(),
21455 1,
21456 "Entrada::hostnames must be a singleton under today's \
21457 single-hostname-per-`:entrada` author surface — got \
21458 length {}: {:?}",
21459 e.hostnames().len(),
21460 e.hostnames(),
21461 );
21462 }
21463
21464 // ── Entrada::destination — the substrate-canonical per-`:entrada`
21465 // destination-Servico scalar accessor every Gateway-API
21466 // HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
21467 // discriminator arg (HTTPRoute name composer) or a per-rule
21468 // `backendRefs[0].name` axis routes through. The two pin tests
21469 // below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
21470 // either arm surfaces at caixa-core build time rather than at
21471 // cluster-apply time when an HTTPRoute's `metadata.name` and
21472 // `backendRefs[]` silently disagree on which destination Servico
21473 // the ingress fronts. Peer discipline with the sibling
21474 // `resolved_paths` + `hostname` + `hostnames` accept-set pin
21475 // blocks above on the per-`:entrada` path-list / DNS-hostname
21476 // resolver axes.
21477
21478 #[test]
21479 fn destination_returns_entrada_para_byte_equal() {
21480 // The canonical destination-scalar pin: [`Entrada::destination`]
21481 // must return the `:entrada :para` field byte-for-byte, borrowed
21482 // from the typed slot's own [`String`] storage. Pins against a
21483 // future silent detour that re-normalized the destination (an
21484 // accidental `.to_lowercase()` — the destination Servico is
21485 // already validated as a DNS-1123 label upstream, so any
21486 // re-normalization is redundant + a drift surface between the
21487 // validator and the accessor), a namespace-prefix rewrite (an
21488 // accidental `format!("{namespace}/{para}")` per-CR fully-
21489 // qualified rewrite that didn't land on the peer axis), or a
21490 // per-cluster suffix stamp the operator authors on one
21491 // consumer without the other.
21492 for para in ["cart", "checkout", "catalog", "orders-v2"] {
21493 let e = Entrada {
21494 host: "checkout.quero.cloud".into(),
21495 para: para.into(),
21496 paths: Vec::new(),
21497 port: DEFAULT_SERVICO_PORT,
21498 };
21499 assert_eq!(
21500 e.destination(),
21501 para,
21502 "Entrada::destination must return :entrada :para verbatim \
21503 (got {:?}, expected {para:?})",
21504 e.destination(),
21505 );
21506 assert_eq!(
21507 e.destination(),
21508 e.para.as_str(),
21509 "Entrada::destination must byte-equal the .para field access",
21510 );
21511 }
21512 }
21513
21514 #[test]
21515 fn destination_borrows_from_entrada_para_storage() {
21516 // The borrow-not-copy pin: [`Entrada::destination`] must
21517 // return a `&str` slice that borrows from the typed slot's
21518 // own [`String`] storage — same-address invariant with
21519 // `entrada.para.as_str()`. Pins against a future silent detour
21520 // that allocated a fresh `String` (`self.para.clone()` in the
21521 // body would type-check but silently drop the borrow, and
21522 // every downstream consumer that assumed the returned slice
21523 // outlives `&self` would break on a stale-reference use-after-
21524 // free). Peer with the sibling `hostname_returns_entrada_
21525 // host_byte_equal` on the singular-DNS-hostname axis.
21526 let e = entrada_with_host("checkout.quero.cloud");
21527 let dest = e.destination();
21528 let para_slice = e.para.as_str();
21529 assert_eq!(
21530 dest.as_ptr(),
21531 para_slice.as_ptr(),
21532 "Entrada::destination must borrow from the .para String's \
21533 backing storage — a fresh allocation here means the \
21534 accessor no longer names the substrate-primitive typed \
21535 dispatch and every downstream consumer would silently \
21536 carry a detached copy",
21537 );
21538 assert_eq!(
21539 dest.len(),
21540 para_slice.len(),
21541 "Entrada::destination and .para.as_str() must byte-equal in \
21542 length as well as in address",
21543 );
21544 }
21545
21546 #[test]
21547 fn port_returns_entrada_port_verbatim_across_permutations() {
21548 // The canonical L4-port-scalar pin: [`Entrada::port`] must
21549 // return the `:entrada :port` field verbatim as a `u16` across
21550 // every author-declared value in the validated accept-set
21551 // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
21552 // silent detour that clamped the port (an accidental
21553 // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
21554 // land on the peer [`AplicacaoSpec::port_for_destination`]
21555 // resolver), rewrote it through a per-cluster port-remap table
21556 // the operator authors on one consumer without the other, or
21557 // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
21558 // serde-default value (which would silently collapse the
21559 // distinction between "author explicitly declared `:port 8080`"
21560 // and "author omitted the slot and inherited the default" the
21561 // future per-cluster override slot depends on). Peer with the
21562 // sibling `destination_returns_entrada_para_byte_equal` +
21563 // `hostname_returns_entrada_host_byte_equal` pins on the
21564 // per-`:entrada` `&str` scalar axes.
21565 for port in [
21566 SERVICO_PORT_MIN,
21567 DEFAULT_SERVICO_PORT,
21568 8443u16,
21569 9090u16,
21570 u16::MAX,
21571 ] {
21572 let e = Entrada {
21573 host: "checkout.quero.cloud".into(),
21574 para: "cart".into(),
21575 paths: Vec::new(),
21576 port,
21577 };
21578 assert_eq!(
21579 e.port(),
21580 port,
21581 "Entrada::port must return :entrada :port verbatim \
21582 (got {}, expected {port})",
21583 e.port(),
21584 );
21585 assert_eq!(
21586 e.port(),
21587 e.port,
21588 "Entrada::port accessor and .port field access must \
21589 byte-equal — the accessor is the substrate-primitive \
21590 typed dispatch every downstream L4-port consumer must \
21591 route through",
21592 );
21593 }
21594 }
21595
21596 #[test]
21597 fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
21598 // Two-consumer coherence pin: the
21599 // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
21600 // (which reads through [`Entrada::port`] to compare against
21601 // [`SERVICO_PORT_MIN`]) and the
21602 // [`AplicacaoSpec::port_for_destination`] resolver (which reads
21603 // through [`Entrada::port`] to emit the per-destination
21604 // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
21605 // lifted accessor, so any future rebrand on the typed slot's
21606 // reader shape lands at exactly one place. Pins the two-site
21607 // coherence by exercising a below-floor port through validate
21608 // (which must reject) and a validated in-accept-set port through
21609 // port_for_destination (which must emit the same value the
21610 // accessor returns).
21611 let mut spec = three_member_spec();
21612 if let Some(e) = spec.entrada.as_mut() {
21613 e.port = 0;
21614 }
21615 assert_eq!(
21616 spec.validate().unwrap_err(),
21617 AplicacaoError::EntradaPortZero,
21618 "validate must reject `:entrada :port 0` through the lifted \
21619 Entrada::port accessor — port zero lies below \
21620 SERVICO_PORT_MIN and the validator routes through port() \
21621 to name the floor",
21622 );
21623
21624 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
21625 let mut spec = three_member_spec();
21626 if let Some(e) = spec.entrada.as_mut() {
21627 e.port = port;
21628 }
21629 spec.validate().expect(
21630 "entrada with in-accept-set :port must validate — the \
21631 structural-floor gate reads through Entrada::port",
21632 );
21633 let entrada_ref = spec.entrada().expect(":entrada present");
21634 assert_eq!(
21635 spec.port_for_destination(entrada_ref.destination()),
21636 entrada_ref.port(),
21637 "port_for_destination(entrada.destination()) must equal \
21638 entrada.port() — the two consumers of the per-:entrada \
21639 L4-port axis (validator, per-destination resolver) both \
21640 route through Entrada::port",
21641 );
21642 }
21643 }
21644
21645 #[test]
21646 fn wit_contract_source_returns_de_byte_equal_across_permutations() {
21647 // The canonical caller-Servico-scalar pin: [`WitContract::source`]
21648 // must return the `:contratos :de` field byte-for-byte, borrowed
21649 // from the typed slot's own [`String`] storage. Peer of the
21650 // sibling `destination_returns_entrada_para_byte_equal` pin on
21651 // the per-`:entrada` axis — same "the substrate-primitive
21652 // accessor must byte-equal the raw field access verbatim across
21653 // every author-declared value" discipline extended to the
21654 // per-`:contratos` caller arm. Pins against a future silent
21655 // detour that re-normalized the caller (an accidental
21656 // `.to_lowercase()` — every `:contratos :de` is validated as a
21657 // DNS-1123 label upstream via `validate_contrato_caixa`, so any
21658 // re-normalization is redundant + a drift surface between the
21659 // validator and the accessor), a namespace-prefix rewrite (an
21660 // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
21661 // rewrite that didn't land on the peer axis), or a per-cluster
21662 // suffix stamp the operator authors on one consumer without the
21663 // other.
21664 for de in ["cart", "checkout", "catalog", "orders-v2"] {
21665 let c = WitContract {
21666 de: de.into(),
21667 para: "downstream".into(),
21668 wit: "wasi:http/proxy".into(),
21669 endpoint: Some("/lookup".into()),
21670 subject: None,
21671 slot: None,
21672 };
21673 assert_eq!(
21674 c.source(),
21675 de,
21676 "WitContract::source must return :contratos :de verbatim \
21677 (got {:?}, expected {de:?})",
21678 c.source(),
21679 );
21680 assert_eq!(
21681 c.source(),
21682 c.de.as_str(),
21683 "WitContract::source must byte-equal the .de field access",
21684 );
21685 }
21686 }
21687
21688 #[test]
21689 fn wit_contract_source_borrows_from_de_storage() {
21690 // The borrow-not-copy pin: [`WitContract::source`] must return a
21691 // `&str` slice that borrows from the typed slot's own [`String`]
21692 // storage — same-address invariant with `c.de.as_str()`. Pins
21693 // against a future silent detour that allocated a fresh `String`
21694 // (`self.de.clone()` in the body would type-check but silently
21695 // drop the borrow, and every downstream consumer that assumed
21696 // the returned slice outlives `&self` would break on a stale-
21697 // reference use-after-free). Peer of the sibling
21698 // `destination_borrows_from_entrada_para_storage` on the
21699 // per-`:entrada` axis.
21700 let c = WitContract {
21701 de: "cart".into(),
21702 para: "catalog".into(),
21703 wit: "wasi:http/proxy".into(),
21704 endpoint: Some("/lookup".into()),
21705 subject: None,
21706 slot: None,
21707 };
21708 let src = c.source();
21709 let de_slice = c.de.as_str();
21710 assert_eq!(
21711 src.as_ptr(),
21712 de_slice.as_ptr(),
21713 "WitContract::source must borrow from the .de String's \
21714 backing storage — a fresh allocation here means the \
21715 accessor no longer names the substrate-primitive typed \
21716 dispatch and every downstream consumer would silently \
21717 carry a detached copy",
21718 );
21719 assert_eq!(
21720 src.len(),
21721 de_slice.len(),
21722 "WitContract::source and .de.as_str() must byte-equal in \
21723 length as well as in address",
21724 );
21725 }
21726
21727 #[test]
21728 fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
21729 // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
21730 // must return the `:contratos :para` field byte-for-byte,
21731 // borrowed from the typed slot's own [`String`] storage. Peer of
21732 // the sibling `destination_returns_entrada_para_byte_equal` on
21733 // the per-`:entrada` axis — both accessors name "the destination-
21734 // Servico byte-string" concept on their respective mesh-slot
21735 // atoms (per-ingress apex vs. per-typed-edge callee) and both
21736 // must project the underlying `.para` field verbatim so every
21737 // downstream renderer that composes them with peer accessors
21738 // (e.g. `spec.port_for_destination(c.destination())` at the CNP
21739 // per-edge L4 port emit site) reads the same byte-string the
21740 // author declared.
21741 for para in ["catalog", "payment", "orders", "inventory-v3"] {
21742 let c = WitContract {
21743 de: "cart".into(),
21744 para: para.into(),
21745 wit: "wasi:http/proxy".into(),
21746 endpoint: Some("/lookup".into()),
21747 subject: None,
21748 slot: None,
21749 };
21750 assert_eq!(
21751 c.destination(),
21752 para,
21753 "WitContract::destination must return :contratos :para \
21754 verbatim (got {:?}, expected {para:?})",
21755 c.destination(),
21756 );
21757 assert_eq!(
21758 c.destination(),
21759 c.para.as_str(),
21760 "WitContract::destination must byte-equal the .para \
21761 field access",
21762 );
21763 }
21764 }
21765
21766 #[test]
21767 fn wit_contract_destination_borrows_from_para_storage() {
21768 // The borrow-not-copy pin: [`WitContract::destination`] must
21769 // return a `&str` slice that borrows from the typed slot's own
21770 // [`String`] storage — same-address invariant with
21771 // `c.para.as_str()`. Peer of the sibling
21772 // `destination_borrows_from_entrada_para_storage` on the
21773 // per-`:entrada` axis.
21774 let c = WitContract {
21775 de: "cart".into(),
21776 para: "catalog".into(),
21777 wit: "wasi:http/proxy".into(),
21778 endpoint: Some("/lookup".into()),
21779 subject: None,
21780 slot: None,
21781 };
21782 let dest = c.destination();
21783 let para_slice = c.para.as_str();
21784 assert_eq!(
21785 dest.as_ptr(),
21786 para_slice.as_ptr(),
21787 "WitContract::destination must borrow from the .para \
21788 String's backing storage — a fresh allocation here means \
21789 the accessor no longer names the substrate-primitive typed \
21790 dispatch and every downstream consumer would silently \
21791 carry a detached copy",
21792 );
21793 assert_eq!(
21794 dest.len(),
21795 para_slice.len(),
21796 "WitContract::destination and .para.as_str() must byte-equal \
21797 in length as well as in address",
21798 );
21799 }
21800
21801 #[test]
21802 fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
21803 // The canonical per-`:contratos` WIT-world-reference scalar pin:
21804 // [`WitContract::world_ref`] must return the `:contratos :wit`
21805 // field byte-for-byte, borrowed from the typed slot's own
21806 // [`String`] storage. Sibling of the peer per-`:contratos`
21807 // [`WitContract::source`] / [`WitContract::destination`]
21808 // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
21809 // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
21810 // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
21811 // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
21812 // "the substrate-primitive accessor must byte-equal the raw
21813 // field access verbatim across every author-declared value"
21814 // discipline extended to the per-`:contratos` WIT-world arm.
21815 // Pins against a future silent detour that re-canonicalized the
21816 // WIT world reference (an accidental `.to_lowercase()` pass that
21817 // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
21818 // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
21819 // gate is already lowercase-prefixed so any re-normalization is
21820 // redundant + a drift surface between the validator and the
21821 // accessor), an M4-promotion-shape rewrite that formatted a
21822 // typed WIT-world enum through [`Display`] and silently drifted
21823 // the printer output from the source `caixa.lisp`, or a per-
21824 // cluster WIT-alias rewrite that didn't land on the peer field-
21825 // access sites. Five values sweep the shape-dispatch accept-set
21826 // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
21827 // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
21828 // `wasi:keyvalue/`).
21829 for (wit, endpoint, subject, slot) in [
21830 ("wasi:http/proxy", Some("/lookup"), None, None),
21831 ("http:proxy", Some("/health"), None, None),
21832 ("nats:pub-sub", None, Some("orders.paid"), None),
21833 ("kafka:events", None, Some("checkout-events"), None),
21834 ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
21835 ] {
21836 let c = WitContract {
21837 de: "cart".into(),
21838 para: "downstream".into(),
21839 wit: wit.into(),
21840 endpoint: endpoint.map(str::to_string),
21841 subject: subject.map(str::to_string),
21842 slot: slot.map(str::to_string),
21843 };
21844 assert_eq!(
21845 c.world_ref(),
21846 wit,
21847 "WitContract::world_ref must return :contratos :wit \
21848 verbatim (got {:?}, expected {wit:?})",
21849 c.world_ref(),
21850 );
21851 assert_eq!(
21852 c.world_ref(),
21853 c.wit.as_str(),
21854 "WitContract::world_ref must byte-equal the .wit field \
21855 access",
21856 );
21857 }
21858 }
21859
21860 #[test]
21861 fn wit_contract_world_ref_borrows_from_wit_storage() {
21862 // The borrow-not-copy pin: [`WitContract::world_ref`] must
21863 // return a `&str` slice that borrows from the typed slot's own
21864 // [`String`] storage — same-address invariant with
21865 // `c.wit.as_str()`. Pins against a future silent detour that
21866 // allocated a fresh `String` (`self.wit.clone()` in the body
21867 // would type-check but silently drop the borrow, and every
21868 // downstream consumer that assumed the returned slice outlives
21869 // `&self` would break on a stale-reference use-after-free — the
21870 // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
21871 // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
21872 // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
21873 // / [`is_pubsub`][WitContract::is_pubsub] /
21874 // [`is_store`][WitContract::is_store] methods route through —
21875 // each borrow from the WitContract's own storage and each would
21876 // silently misbehave if this accessor produced a detached copy).
21877 // Peer of the sibling per-`:contratos` [`WitContract::source`] /
21878 // [`WitContract::destination`] and per-`:entrada`
21879 // [`Entrada::destination`] / [`Entrada::hostname`] and
21880 // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
21881 // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
21882 let c = WitContract {
21883 de: "cart".into(),
21884 para: "catalog".into(),
21885 wit: "wasi:http/proxy".into(),
21886 endpoint: Some("/lookup".into()),
21887 subject: None,
21888 slot: None,
21889 };
21890 let world = c.world_ref();
21891 let wit_slice = c.wit.as_str();
21892 assert_eq!(
21893 world.as_ptr(),
21894 wit_slice.as_ptr(),
21895 "WitContract::world_ref must borrow from the .wit String's \
21896 backing storage — a fresh allocation here means the \
21897 accessor no longer names the substrate-primitive typed \
21898 dispatch and every downstream consumer would silently carry \
21899 a detached copy",
21900 );
21901 assert_eq!(
21902 world.len(),
21903 wit_slice.len(),
21904 "WitContract::world_ref and .wit.as_str() must byte-equal in \
21905 length as well as in address",
21906 );
21907 }
21908
21909 #[test]
21910 fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
21911 // Sibling-triple invariant pin composing all three per-`:contratos`
21912 // substrate-primitive typed dispatches — [`WitContract::source`]
21913 // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
21914 // [`WitContract::world_ref`] — at the joint
21915 // `(source(), destination(), world_ref())` call shape every
21916 // renderer that fans on per-edge caller-callee-shape identity
21917 // keys off. The invariant, evaluated per-contract:
21918 //
21919 // (c.source(), c.destination(), c.world_ref())
21920 // == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
21921 //
21922 // Closes the last unlifted per-`:contratos` scalar axis — every
21923 // downstream consumer that reads the triple now routes through
21924 // exactly three typed dispatches on the substrate primitive,
21925 // not two typed + one open-coded field access. A future refactor
21926 // that silently split any one accessor's projection (an
21927 // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
21928 // canonicalization that didn't reach the peer `source`/
21929 // `destination` arms, an accidental `source()` per-cluster
21930 // caller-alias rewrite that didn't land on the `world_ref` peer)
21931 // surfaces at caixa-core build time. Peer of the sibling per-
21932 // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
21933 // per-`:entrada` `(hostname(), destination())` (6db982c /
21934 // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
21935 // axes, extended to the per-`:contratos` triple.
21936 for (de, para, wit, endpoint, subject, slot) in [
21937 (
21938 "cart",
21939 "catalog",
21940 "wasi:http/proxy",
21941 Some("/lookup"),
21942 None,
21943 None,
21944 ),
21945 (
21946 "checkout",
21947 "orders",
21948 "nats:pub-sub",
21949 None,
21950 Some("orders.paid"),
21951 None,
21952 ),
21953 (
21954 "cart",
21955 "kv",
21956 "wasi:keyvalue/store",
21957 None,
21958 None,
21959 Some("carts/{cart_id}"),
21960 ),
21961 (
21962 "orders-v2",
21963 "inventory-v3",
21964 "http:proxy",
21965 Some("/reserve"),
21966 None,
21967 None,
21968 ),
21969 ] {
21970 let c = WitContract {
21971 de: de.into(),
21972 para: para.into(),
21973 wit: wit.into(),
21974 endpoint: endpoint.map(str::to_string),
21975 subject: subject.map(str::to_string),
21976 slot: slot.map(str::to_string),
21977 };
21978 assert_eq!(
21979 (c.source(), c.destination(), c.world_ref()),
21980 (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
21981 "(WitContract::source, ::destination, ::world_ref) must \
21982 project (.de, .para, .wit) verbatim across every author-\
21983 declared triple (got ({:?}, {:?}, {:?}), expected \
21984 ({de:?}, {para:?}, {wit:?}))",
21985 c.source(),
21986 c.destination(),
21987 c.world_ref(),
21988 );
21989 }
21990 }
21991
21992 #[test]
21993 fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
21994 // The canonical per-`:contratos` owned-form caller-callee-pair
21995 // pin: [`WitContract::edge_pair`] must return the
21996 // `(source(), destination())` tuple in owned form byte-for-byte,
21997 // projected through the lifted [`WitContract::source`] /
21998 // [`WitContract::destination`] scalar accessors. Pins the
21999 // composite-projection invariant on the per-`:contratos`
22000 // mesh-slot atom — every author-declared `(de, para)` pair must
22001 // round-trip verbatim through the substrate primitive's typed
22002 // dispatch, so the nine [`AplicacaoError`] diagnostic-
22003 // construction sites the accessor now feeds
22004 // ([`AplicacaoError::EmptyWit`],
22005 // [`AplicacaoError::ContratoEndpointEmpty`],
22006 // [`AplicacaoError::ContratoEndpointNotAbsolute`],
22007 // [`AplicacaoError::ContratoEndpointInvalid`],
22008 // [`AplicacaoError::ContratoSubjectEmpty`],
22009 // [`AplicacaoError::ContratoSubjectInvalid`],
22010 // [`AplicacaoError::ContratoSlotEmpty`],
22011 // [`AplicacaoError::ContratoSlotInvalid`],
22012 // [`AplicacaoError::ContratoDuplicate`]) all read the same
22013 // `(de, para)` label pair every author sees at the source
22014 // `caixa.lisp`. Pins against a future silent detour that swapped
22015 // the `.0` / `.1` arms (an accidental `(destination(),
22016 // source())` re-order in the body would silently invert every
22017 // downstream diagnostic's `de:` / `para:` label pair, silently
22018 // reversing the direction of every operator-facing typed error
22019 // arrow), a fresh-allocation shape drift (an accidental
22020 // `.to_string()` on one arm but not the other would leave the
22021 // owned/borrowed pair mismatched vs. the sibling `source()` /
22022 // `destination()` returns), or an M4 per-cluster caller/callee-
22023 // alias rewrite that landed on `source()` without reaching
22024 // `destination()` (or vice versa). Peer of the sibling per-
22025 // `:contratos` `(source, destination, world_ref)` triple
22026 // pin above on the mesh-slot-atom scalar-value axes, extended
22027 // to the owned-form pair-projection axis.
22028 for (de, para, wit, endpoint, subject, slot) in [
22029 (
22030 "cart",
22031 "catalog",
22032 "wasi:http/proxy",
22033 Some("/lookup"),
22034 None,
22035 None,
22036 ),
22037 (
22038 "checkout",
22039 "orders",
22040 "nats:pub-sub",
22041 None,
22042 Some("orders.paid"),
22043 None,
22044 ),
22045 (
22046 "cart",
22047 "kv",
22048 "wasi:keyvalue/store",
22049 None,
22050 None,
22051 Some("carts/{cart_id}"),
22052 ),
22053 (
22054 "orders-v2",
22055 "inventory-v3",
22056 "http:proxy",
22057 Some("/reserve"),
22058 None,
22059 None,
22060 ),
22061 ] {
22062 let c = WitContract {
22063 de: de.into(),
22064 para: para.into(),
22065 wit: wit.into(),
22066 endpoint: endpoint.map(str::to_string),
22067 subject: subject.map(str::to_string),
22068 slot: slot.map(str::to_string),
22069 };
22070 assert_eq!(
22071 c.edge_pair(),
22072 (de.to_string(), para.to_string()),
22073 "WitContract::edge_pair must return (:contratos :de, \
22074 :contratos :para) as an owned tuple verbatim (got {:?}, \
22075 expected ({de:?}, {para:?}))",
22076 c.edge_pair(),
22077 );
22078 }
22079 }
22080
22081 #[test]
22082 fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
22083 // The composition pin: [`WitContract::edge_pair`] must return
22084 // exactly `(source().to_string(), destination().to_string())` —
22085 // the owned form of the sibling accessor pair — so any future
22086 // refactor that silently re-authored the caller-arm / callee-arm
22087 // projection to bypass the lifted scalar accessors (an accidental
22088 // `(self.de.clone(), self.para.clone())` regression back to the
22089 // raw field-access shape, an M4-typed-caller-enum `Display`
22090 // re-canonicalization on `source()` that didn't reach
22091 // `edge_pair()`, a per-cluster alias rewrite the operator lands
22092 // on `destination()` without reaching this composite projection)
22093 // trips at caixa-core build time. Pins the "typed dispatch
22094 // composes with typed dispatch, not with raw field access"
22095 // discipline every downstream diagnostic-construction site now
22096 // routes through — a `de:` / `para:` label pair whose
22097 // projection silently drifted off the substrate primitive's
22098 // scalar accessors would silently split the diagnostic's self-
22099 // locating signal from the source `caixa.lisp` author's view.
22100 // Peer of the sibling per-`:politicas` `is_empty` /
22101 // `validate_politicas` accessor-routing-pin family on the M3
22102 // mesh-slot family (18575, 18739, 18918, 19140, 19371).
22103 let c = WitContract {
22104 de: "cart".into(),
22105 para: "catalog".into(),
22106 wit: "wasi:http/proxy".into(),
22107 endpoint: Some("/lookup".into()),
22108 subject: None,
22109 slot: None,
22110 };
22111 assert_eq!(
22112 c.edge_pair(),
22113 (c.source().to_string(), c.destination().to_string()),
22114 "WitContract::edge_pair must compose exactly \
22115 (source().to_string(), destination().to_string()) — a \
22116 bypass of either sibling accessor here would silently \
22117 decouple the composite-projection axis from the \
22118 substrate-primitive scalar accessors every downstream \
22119 consumer routes through",
22120 );
22121 }
22122
22123 #[test]
22124 fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
22125 {
22126 // The canonical per-`:contratos` owned-form
22127 // caller-callee-world-ref-triple pin:
22128 // [`WitContract::edge_triple`] must return the
22129 // `(source(), destination(), world_ref())` tuple in owned form
22130 // byte-for-byte, projected through the lifted
22131 // [`WitContract::source`] / [`WitContract::destination`] /
22132 // [`WitContract::world_ref`] scalar accessors. Pins the
22133 // composite-projection invariant on the per-`:contratos`
22134 // mesh-slot atom — every author-declared `(de, para, wit)`
22135 // triple must round-trip verbatim through the substrate
22136 // primitive's typed dispatch, so the nine
22137 // [`AplicacaoError`] diagnostic-construction sites the
22138 // accessor now feeds (the [`WitTarget`]-dispatch's eight
22139 // wrong-target / missing-target / invalid-wit / capability-
22140 // with-payload arms in [`WitContract::target`], plus the
22141 // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
22142 // diagnostic constructor in [`AplicacaoSpec::validate`]) all
22143 // read the same `(de, para, wit)` triple every author sees at
22144 // the source `caixa.lisp`. Pins against a future silent
22145 // detour that swapped any two arms (an accidental `(destination(),
22146 // source(), world_ref())` re-order in the body would silently
22147 // invert every downstream diagnostic's `de:` / `para:` label
22148 // pair, silently reversing the direction of every operator-
22149 // facing typed error arrow), a fresh-allocation shape drift
22150 // (an accidental `.to_string()` skipped on one arm would leave
22151 // the owned/borrowed triple mismatched vs. the sibling
22152 // `source()` / `destination()` / `world_ref()` returns), or an
22153 // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
22154 // canonicalization pass that landed on one accessor without
22155 // reaching the peers. Peer of the sibling per-`:contratos`
22156 // caller-callee-pair
22157 // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
22158 // pin on the mesh-slot-atom composite-projection axis,
22159 // extended to the triple-projection axis.
22160 for (de, para, wit, endpoint, subject, slot) in [
22161 (
22162 "cart",
22163 "catalog",
22164 "wasi:http/proxy",
22165 Some("/lookup"),
22166 None,
22167 None,
22168 ),
22169 (
22170 "checkout",
22171 "orders",
22172 "nats:pub-sub",
22173 None,
22174 Some("orders.paid"),
22175 None,
22176 ),
22177 (
22178 "cart",
22179 "kv",
22180 "wasi:keyvalue/store",
22181 None,
22182 None,
22183 Some("carts/{cart_id}"),
22184 ),
22185 (
22186 "orders-v2",
22187 "inventory-v3",
22188 "http:proxy",
22189 Some("/reserve"),
22190 None,
22191 None,
22192 ),
22193 ] {
22194 let c = WitContract {
22195 de: de.into(),
22196 para: para.into(),
22197 wit: wit.into(),
22198 endpoint: endpoint.map(str::to_string),
22199 subject: subject.map(str::to_string),
22200 slot: slot.map(str::to_string),
22201 };
22202 assert_eq!(
22203 c.edge_triple(),
22204 (de.to_string(), para.to_string(), wit.to_string()),
22205 "WitContract::edge_triple must return (:contratos :de, \
22206 :contratos :para, :contratos :wit) as an owned triple \
22207 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
22208 c.edge_triple(),
22209 );
22210 }
22211 }
22212
22213 #[test]
22214 fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
22215 // The composition pin: [`WitContract::edge_triple`] must return
22216 // exactly `(source().to_string(), destination().to_string(),
22217 // world_ref().to_string())` — the owned form of the sibling
22218 // scalar-accessor triple — so any future refactor that silently
22219 // re-authored one arm's projection to bypass the lifted scalar
22220 // accessors (an accidental `(self.de.clone(), self.para.clone(),
22221 // self.wit.clone())` regression back to the raw field-access
22222 // shape the internal `edge` closure and the ContratoDuplicate
22223 // diagnostic both carried before this lift landed, an
22224 // M4-typed-caller-enum `Display` re-canonicalization on
22225 // `source()` that didn't reach `edge_triple()`, a per-cluster
22226 // alias rewrite the operator lands on `destination()` /
22227 // `world_ref()` without reaching this composite projection)
22228 // trips at caixa-core build time. Pins the "typed dispatch
22229 // composes with typed dispatch, not with raw field access"
22230 // discipline every downstream diagnostic-construction site now
22231 // routes through — a `de:` / `para:` / `wit:` triple whose
22232 // projection silently drifted off the substrate primitive's
22233 // scalar accessors would silently split the diagnostic's self-
22234 // locating signal from the source `caixa.lisp` author's view.
22235 // Peer of the sibling per-`:contratos` edge_pair composition-
22236 // pin above on the mesh-slot-atom composite-projection axis.
22237 let c = WitContract {
22238 de: "cart".into(),
22239 para: "catalog".into(),
22240 wit: "wasi:http/proxy".into(),
22241 endpoint: Some("/lookup".into()),
22242 subject: None,
22243 slot: None,
22244 };
22245 assert_eq!(
22246 c.edge_triple(),
22247 (
22248 c.source().to_string(),
22249 c.destination().to_string(),
22250 c.world_ref().to_string(),
22251 ),
22252 "WitContract::edge_triple must compose exactly \
22253 (source().to_string(), destination().to_string(), \
22254 world_ref().to_string()) — a bypass of any sibling accessor \
22255 here would silently decouple the composite-projection axis \
22256 from the substrate-primitive scalar accessors every \
22257 downstream consumer routes through",
22258 );
22259 }
22260
22261 #[test]
22262 fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
22263 // The canonical semantics-pin: [`WitContract::edge_triple`] must
22264 // project the full `(de, para, wit)` identity of a `:contratos`
22265 // edge — the sub-triple every triple-carrying
22266 // [`AplicacaoError::Contrato*`] diagnostic weaves into its
22267 // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
22268 // missing-target, capability-with-payload, invalid-wit, and the
22269 // duplicate-gate). Rejects a drift in shape (an accidental
22270 // silent detour that returned a `(de, para)` pair or added an
22271 // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
22272 // would trip here because the return type would no longer
22273 // pattern-match the eight `let (de, para, wit) = edge();`
22274 // destructures the [`WitContract::target`] dispatch feeds off
22275 // + the paired duplicate-gate `let (de, para, wit) =
22276 // c.edge_triple();` destructure in
22277 // [`AplicacaoSpec::validate`]). Peer of the sibling per-
22278 // `:contratos` caller-callee-pair pin above extended to the
22279 // triple projection surface: closes the "one composite
22280 // accessor per typed diagnostic-construction sub-tuple"
22281 // discipline on the per-`:contratos` mesh-slot-atom axis.
22282 let c = WitContract {
22283 de: "checkout".into(),
22284 para: "orders".into(),
22285 wit: "nats:pub-sub".into(),
22286 endpoint: None,
22287 subject: Some("orders.paid".into()),
22288 slot: None,
22289 };
22290 let (de, para, wit) = c.edge_triple();
22291 assert_eq!(de, "checkout");
22292 assert_eq!(para, "orders");
22293 assert_eq!(wit, "nats:pub-sub");
22294 }
22295
22296 #[test]
22297 fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
22298 {
22299 // The composition pin: [`WitContract::identity`] must return
22300 // exactly `(source(), destination(), world_ref(), endpoint(),
22301 // subject(), slot())` — the borrowed form of the six-scalar-
22302 // accessor identity axis. Any future refactor that silently
22303 // re-authored one arm's projection to bypass a scalar accessor
22304 // (a `self.de.as_str()` regression back to raw field access on
22305 // any of the three required arms, a `self.endpoint.as_deref()`
22306 // regression on any of the three optional arms, an M4 per-
22307 // cluster caller/callee-alias rewrite the operator lands on
22308 // `source()` / `destination()` without reaching this composite
22309 // projection) trips at caixa-core build time. Sweeps four
22310 // permutations of the WIT-shape × payload lattice — HTTP with
22311 // endpoint, pub-sub with subject, store with slot, payload-less
22312 // capability — so every payload arm is exercised. Peer of the
22313 // sibling per-`:contratos`
22314 // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
22315 // composition pin on the mesh-slot-atom composite-projection
22316 // axis; extends the discipline from the (de, para, wit) prefix
22317 // onto the full-identity axis carrying the three payload arms.
22318 for (de, para, wit, endpoint, subject, slot) in [
22319 (
22320 "cart",
22321 "catalog",
22322 "wasi:http/proxy",
22323 Some("/lookup"),
22324 None,
22325 None,
22326 ),
22327 (
22328 "checkout",
22329 "orders",
22330 "nats:pub-sub",
22331 None,
22332 Some("orders.paid"),
22333 None,
22334 ),
22335 (
22336 "cart",
22337 "kv",
22338 "wasi:keyvalue/store",
22339 None,
22340 None,
22341 Some("carts/{cart_id}"),
22342 ),
22343 ("audit", "sink", "wasi:logging", None, None, None),
22344 ] {
22345 let c = WitContract {
22346 de: de.into(),
22347 para: para.into(),
22348 wit: wit.into(),
22349 endpoint: endpoint.map(str::to_owned),
22350 subject: subject.map(str::to_owned),
22351 slot: slot.map(str::to_owned),
22352 };
22353 assert_eq!(
22354 c.identity(),
22355 (
22356 c.source(),
22357 c.destination(),
22358 c.world_ref(),
22359 c.endpoint(),
22360 c.subject(),
22361 c.slot(),
22362 ),
22363 "WitContract::identity must compose exactly \
22364 (source(), destination(), world_ref(), endpoint(), \
22365 subject(), slot()) — a bypass of any sibling accessor \
22366 here would silently decouple the identity-projection \
22367 axis from the substrate-primitive scalar accessors \
22368 every dedup-key consumer routes through",
22369 );
22370 }
22371 }
22372
22373 #[test]
22374 fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
22375 // The canonical semantics-pin: [`WitContract::identity`] must
22376 // project the six-axis (de, para, wit, endpoint, subject, slot)
22377 // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22378 // gate keys off — two `WitContract`s that agree on all six axes
22379 // are the same typed edge declared twice, the graph-edge
22380 // analogue of duplicate `:membros` / `:placement :clusters` /
22381 // `:entrada :paths` entries. Rejects a shape drift (an
22382 // accidental silent detour that returned a prefix tuple or
22383 // added an extra field) by pattern-matching the six-arm shape.
22384 // Peer of the sibling per-`:contratos`
22385 // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
22386 // pin extended from the (de, para, wit) prefix onto the full
22387 // six-axis identity that the dedup key rides.
22388 let c = WitContract {
22389 de: "cart".into(),
22390 para: "catalog".into(),
22391 wit: "wasi:http/proxy".into(),
22392 endpoint: Some("/products/:id".into()),
22393 subject: None,
22394 slot: None,
22395 };
22396 let (de, para, wit, endpoint, subject, slot) = c.identity();
22397 assert_eq!(de, "cart");
22398 assert_eq!(para, "catalog");
22399 assert_eq!(wit, "wasi:http/proxy");
22400 assert_eq!(endpoint, Some("/products/:id"));
22401 assert_eq!(subject, None);
22402 assert_eq!(slot, None);
22403
22404 // Two byte-identical contracts must produce equal identities —
22405 // the dedup key's foundational invariant.
22406 let c2 = c.clone();
22407 assert_eq!(c.identity(), c2.identity());
22408
22409 // Any change on any of the six axes must break the identity —
22410 // sweeps by mutating one axis at a time.
22411 let mut mutated = c.clone();
22412 mutated.de = "search".into();
22413 assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
22414 let mut mutated = c.clone();
22415 mutated.para = "warehouse".into();
22416 assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
22417 let mut mutated = c.clone();
22418 mutated.wit = "http:legacy".into();
22419 assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
22420 let mut mutated = c.clone();
22421 mutated.endpoint = Some("/search".into());
22422 assert_ne!(
22423 c.identity(),
22424 mutated.identity(),
22425 "endpoint axis must partition"
22426 );
22427 let mut mutated = c.clone();
22428 mutated.subject = Some("orders.paid".into());
22429 assert_ne!(
22430 c.identity(),
22431 mutated.identity(),
22432 "subject axis must partition"
22433 );
22434 let mut mutated = c;
22435 mutated.slot = Some("carts/{id}".into());
22436 assert_ne!(mutated.identity().5, None, "slot axis must partition");
22437 }
22438
22439 #[test]
22440 fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
22441 // The canonical per-`:contratos` structural-self-edge pin:
22442 // [`WitContract::is_self_loop`] must return `true` when the
22443 // `:de` and `:para` fields agree byte-for-byte, across every
22444 // WIT-shape variant the per-edge shape family carries. Pins
22445 // the shape-agnostic identity-space partition the
22446 // [`AplicacaoSpec::validate`] self-edge gate at
22447 // caixa-core/src/aplicacao.rs:5559 fires against — all four
22448 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
22449 // under the same one predicate. Four permutations sweep the
22450 // accept-set: HTTP with endpoint, pub-sub with subject, KV
22451 // store with slot, and payload-less capability.
22452 for (nome, wit, endpoint, subject, slot) in [
22453 ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
22454 ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
22455 (
22456 "kv",
22457 "wasi:keyvalue/store",
22458 None,
22459 None,
22460 Some("carts/{cart_id}"),
22461 ),
22462 ("audit", "wasi:logging", None, None, None),
22463 ] {
22464 let c = WitContract {
22465 de: nome.into(),
22466 para: nome.into(),
22467 wit: wit.into(),
22468 endpoint: endpoint.map(str::to_string),
22469 subject: subject.map(str::to_string),
22470 slot: slot.map(str::to_string),
22471 };
22472 assert!(
22473 c.is_self_loop(),
22474 "WitContract::is_self_loop must return true when \
22475 :contratos :de == :contratos :para (got false on \
22476 {nome:?} under {wit:?})",
22477 );
22478 }
22479 }
22480
22481 #[test]
22482 fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
22483 // The complement pin: [`WitContract::is_self_loop`] must return
22484 // `false` on every well-shaped inter-Servico contract (the
22485 // author-intended `:contratos` shape MESH-COMPOSITION §III.1
22486 // names — "Servico A calls Servico B" between two distinct
22487 // graph nodes). Pins against a future silent detour that
22488 // inverted the predicate (an accidental `!= ` swap for `==`
22489 // would silently reject every legitimate inter-Servico edge
22490 // and admit every self-edge — the exact inversion of the
22491 // author-intended shape). Four permutations sweep the same
22492 // WIT-shape accept-set the sibling positive-arm test carries.
22493 for (de, para, wit, endpoint, subject, slot) in [
22494 (
22495 "cart",
22496 "catalog",
22497 "wasi:http/proxy",
22498 Some("/lookup"),
22499 None,
22500 None,
22501 ),
22502 (
22503 "checkout",
22504 "orders",
22505 "nats:pub-sub",
22506 None,
22507 Some("orders.paid"),
22508 None,
22509 ),
22510 (
22511 "cart",
22512 "kv",
22513 "wasi:keyvalue/store",
22514 None,
22515 None,
22516 Some("carts/{cart_id}"),
22517 ),
22518 ("audit", "sink", "wasi:logging", None, None, None),
22519 ] {
22520 let c = WitContract {
22521 de: de.into(),
22522 para: para.into(),
22523 wit: wit.into(),
22524 endpoint: endpoint.map(str::to_string),
22525 subject: subject.map(str::to_string),
22526 slot: slot.map(str::to_string),
22527 };
22528 assert!(
22529 !c.is_self_loop(),
22530 "WitContract::is_self_loop must return false when \
22531 :contratos :de differs from :contratos :para (got true \
22532 on {de:?} → {para:?} under {wit:?})",
22533 );
22534 }
22535 }
22536
22537 #[test]
22538 fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
22539 // The composition pin: [`WitContract::is_self_loop`] must
22540 // resolve to exactly `self.source() == self.destination()` —
22541 // the equality probe of the sibling scalar-accessor pair — so
22542 // any future refactor that silently re-authored the predicate
22543 // to bypass the lifted scalar accessors (an accidental
22544 // `self.de == self.para` regression back to the raw field-
22545 // access shape, an M4-typed-caller-enum identity-comparison
22546 // rule that landed on `source()` without reaching
22547 // `destination()`, a per-cluster alias rewrite the operator
22548 // pins on `destination()` without reaching this predicate)
22549 // trips at caixa-core build time. Pins the "typed dispatch
22550 // composes with typed dispatch, not with raw field access"
22551 // discipline the sibling [`WitContract::edge_pair`] /
22552 // [`WitContract::edge_triple`] composite-projection accessors
22553 // already carry, extended onto the per-edge endpoint-equality
22554 // predicate axis. Positive and complement arms both fire.
22555 let self_edge = WitContract {
22556 de: "cart".into(),
22557 para: "cart".into(),
22558 wit: "wasi:http/proxy".into(),
22559 endpoint: Some("/lookup".into()),
22560 subject: None,
22561 slot: None,
22562 };
22563 assert_eq!(
22564 self_edge.is_self_loop(),
22565 self_edge.source() == self_edge.destination(),
22566 "WitContract::is_self_loop must compose exactly \
22567 `source() == destination()` — a bypass of either sibling \
22568 accessor here would silently decouple the endpoint-\
22569 equality predicate from the substrate-primitive scalar \
22570 accessors every downstream consumer routes through",
22571 );
22572 let inter_edge = WitContract {
22573 de: "cart".into(),
22574 para: "catalog".into(),
22575 wit: "wasi:http/proxy".into(),
22576 endpoint: Some("/lookup".into()),
22577 subject: None,
22578 slot: None,
22579 };
22580 assert_eq!(
22581 inter_edge.is_self_loop(),
22582 inter_edge.source() == inter_edge.destination(),
22583 "WitContract::is_self_loop must compose exactly \
22584 `source() == destination()` on the complement arm too",
22585 );
22586 }
22587
22588 #[test]
22589 fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
22590 // The composition pin: [`WitContract::target`]'s invalid-wit
22591 // value-shape gate must feed the reason string through the
22592 // lifted [`WitContract::world_ref`] scalar accessor — the same
22593 // typed dispatch on the substrate primitive every peer
22594 // per-`:contratos` payload-carrier extraction in the same
22595 // method body already routes through
22596 // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
22597 // [`WitContract::subject`] on the pub-sub-arm target extraction,
22598 // [`WitContract::slot`] on the store-arm target extraction) and
22599 // every peer composite-projection accessor
22600 // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
22601 // [`WitContract::identity`]) already composes from. Any future
22602 // refactor that silently re-authored the gate to bypass the
22603 // lifted accessor (an accidental `&self.wit` regression back to
22604 // the raw field-access shape, an M4-typed-`WitWorld` `Display`
22605 // re-canonicalization on `world_ref()` that didn't reach this
22606 // gate, a per-CR lowercasing canonicalization pass the M4
22607 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
22608 // per-tenant that lands on `world_ref()` without reaching this
22609 // gate) would silently split the invalid-wit diagnostic reason
22610 // from the substrate-primitive projection every downstream
22611 // consumer routes through. Same "typed dispatch composes with
22612 // typed dispatch, not with raw field access" discipline the
22613 // sibling
22614 // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
22615 // pin already carries on the endpoint-equality predicate axis,
22616 // extended onto the invalid-wit value-shape gate axis inside
22617 // the same [`WitContract::target`] body. Closes the last
22618 // unlifted raw-field-access site inside `impl WitContract`.
22619 //
22620 // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
22621 // uppercase-typo footgun the pre-c4213a4 shape silently demoted
22622 // to a capability-only edge; the value-shape gate rejects it
22623 // through [`crate::render::is_wit_world_ref`] on the substrate
22624 // primitive's ASCII-lowercase-only accept-set, with a
22625 // parser-shaped reason string the test asserts round-trips
22626 // byte-for-byte between the direct-dispatch call (through the
22627 // predicate on the accessor's projection) and the
22628 // [`WitContract::target`] gate's produced reason field.
22629 let c = WitContract {
22630 de: "cart".into(),
22631 para: "catalog".into(),
22632 wit: "WASI:HTTP/proxy".into(),
22633 endpoint: Some("/lookup".into()),
22634 subject: None,
22635 slot: None,
22636 };
22637 let err = c.target().unwrap_err();
22638 let AplicacaoError::ContratoWitInvalid {
22639 ref de,
22640 ref para,
22641 ref wit,
22642 ref reason,
22643 } = err
22644 else {
22645 panic!("expected ContratoWitInvalid, got {err:?}");
22646 };
22647 assert_eq!(de, "cart");
22648 assert_eq!(para, "catalog");
22649 assert_eq!(wit, "WASI:HTTP/proxy");
22650 let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
22651 assert_eq!(
22652 *reason, expected_reason,
22653 "WitContract::target's invalid-wit value-shape gate reason \
22654 must compose exactly is_wit_world_ref(self.world_ref()) — \
22655 a bypass here (e.g. a raw `&self.wit` field-access \
22656 regression, or a divergent predicate on a different \
22657 projection) would silently decouple the invalid-wit \
22658 diagnostic's reason field from the substrate-primitive \
22659 scalar accessor every peer per-`:contratos` extraction in \
22660 the same method body already routes through",
22661 );
22662 }
22663
22664 #[test]
22665 fn wit_contract_is_self_loop_predicate_is_const_fn() {
22666 // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
22667 // caller-callee identity-space predicate's `const`-eval-surface
22668 // posture. The wrapper below dispatches through
22669 // [`WitContract::is_self_loop`] and is well-formed only when the
22670 // callee is itself `pub const fn` — any future accidental
22671 // downgrade to non-`const` fails the wrapper at caixa-core build
22672 // time with E0015 (`cannot call non-const method`), strictly
22673 // stronger than a runtime `assert!` and strictly stronger than a
22674 // module-scope `const _: () = assert!(…)` pin (the type's
22675 // `String` / `Option<String>` carriers rule out `const`-context
22676 // value construction; the `const fn` wrapper is the load-bearing
22677 // shape that side-steps the destructor-in-const restriction on
22678 // the value axis while still pinning the `const`-fn posture on
22679 // the callee — mirror of the sibling
22680 // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
22681 // (279823b) and
22682 // [`wit_contract_identity_projection_accessor_is_const_fn`]
22683 // (1ab648c) pins' discipline verbatim on the peer scalar-
22684 // accessor and composite-projection surfaces). Closes the last
22685 // unlifted per-`:contratos` shape/identity predicate on the
22686 // const-eval surface — the peer WIT-shape-partition family
22687 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
22688 // [`WitContract::is_store`] / [`WitContract::is_capability`]
22689 // already carried the `pub const fn` posture on the peer
22690 // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
22691 // this pin extends the same posture onto the caller-callee
22692 // identity-space partition. Sweeps every WIT-shape arm on both
22693 // the equal-endpoints (self-edge) and distinct-endpoints
22694 // (inter-edge) arms of the identity-space partition, plus one
22695 // same-length distinct-byte pair to pin the mid-loop `!=` arm
22696 // past the leading length-mismatch shortcut.
22697 const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
22698 c.is_self_loop()
22699 }
22700 let mk = |de: &str, para: &str, wit: &str| WitContract {
22701 de: de.into(),
22702 para: para.into(),
22703 wit: wit.into(),
22704 endpoint: None,
22705 subject: None,
22706 slot: None,
22707 };
22708 for (nome, wit) in [
22709 ("cart", "wasi:http/proxy"),
22710 ("checkout", "nats:pub-sub"),
22711 ("kv", "wasi:keyvalue/store"),
22712 ("audit", "wasi:logging"),
22713 ] {
22714 let self_edge = mk(nome, nome, wit);
22715 assert!(
22716 is_self_loop_via_const_fn(&self_edge),
22717 "self-edge {nome:?} under {wit:?}"
22718 );
22719 assert_eq!(
22720 is_self_loop_via_const_fn(&self_edge),
22721 self_edge.is_self_loop()
22722 );
22723 }
22724 for (de, para, wit) in [
22725 ("cart", "catalog", "wasi:http/proxy"),
22726 ("checkout", "orders", "nats:pub-sub"),
22727 ("cart", "kv", "wasi:keyvalue/store"),
22728 ("audit", "sink", "wasi:logging"),
22729 ] {
22730 let inter_edge = mk(de, para, wit);
22731 assert!(
22732 !is_self_loop_via_const_fn(&inter_edge),
22733 "inter-edge {de:?}→{para:?} under {wit:?}",
22734 );
22735 assert_eq!(
22736 is_self_loop_via_const_fn(&inter_edge),
22737 inter_edge.is_self_loop()
22738 );
22739 }
22740 // Same-length distinct-byte pair — pins the mid-loop `!=` arm
22741 // past the leading `a.len() != b.len()` shortcut so the const-fn
22742 // wrapper exercises every arm of the byte-slice equality loop.
22743 let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
22744 assert!(
22745 !is_self_loop_via_const_fn(&same_len_pair),
22746 "same-length distinct-byte"
22747 );
22748 assert_eq!(
22749 is_self_loop_via_const_fn(&same_len_pair),
22750 same_len_pair.is_self_loop()
22751 );
22752 }
22753
22754 #[test]
22755 fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
22756 // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
22757 // pin: [`WitContract::endpoint`] must return the `:contratos
22758 // :endpoint` field byte-for-byte, borrowed from the typed slot's
22759 // own `Option<String>` storage. Peer of the sibling
22760 // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
22761 // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
22762 // mesh-slot `Option<String>` optional-scalar axes — same "the
22763 // substrate-primitive accessor must byte-equal the raw field
22764 // access verbatim across every author-declared value" discipline
22765 // extended to the per-`:contratos` HTTP-payload-carrier arm.
22766 // Pins against a future silent detour that re-canonicalized the
22767 // endpoint (an accidental percent-encoding pass that didn't
22768 // reach the peer field-access site at the dedup key, a per-CR
22769 // fully-qualified prefix rewrite the operator authors on one
22770 // consumer without the other, or an M4 typed-path-template
22771 // `Display` re-canonicalization that silently drifted the
22772 // printer output from the source `caixa.lisp`). Four values
22773 // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
22774 // gate upstream admits (short root-path, dashed, param-shaped,
22775 // deep-hierarchy).
22776 for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
22777 let c = WitContract {
22778 de: "cart".into(),
22779 para: "catalog".into(),
22780 wit: "wasi:http/proxy".into(),
22781 endpoint: Some(endpoint.into()),
22782 subject: None,
22783 slot: None,
22784 };
22785 assert_eq!(
22786 c.endpoint(),
22787 Some(endpoint),
22788 "WitContract::endpoint must return :contratos :endpoint \
22789 verbatim (got {:?}, expected Some({endpoint:?}))",
22790 c.endpoint(),
22791 );
22792 assert_eq!(
22793 c.endpoint(),
22794 c.endpoint.as_deref(),
22795 "WitContract::endpoint must byte-equal the .endpoint \
22796 field's `.as_deref()` projection",
22797 );
22798 }
22799 }
22800
22801 #[test]
22802 fn wit_contract_endpoint_none_when_field_is_none() {
22803 // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
22804 // payload-carrier accessor pin: when the typed slot is absent —
22805 // the canonical shape under a non-HTTP `:wit` world per the
22806 // [`WitContract::target`]-enforced shape ↔ target partition
22807 // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
22808 // carries `:slot`, [`WitTarget::Capability`] carries none) —
22809 // [`WitContract::endpoint`] must return `None`. Pins against a
22810 // future silent detour that projected the absent slot to a
22811 // `Some("")` empty-string default (the canonical `Option<String>`
22812 // → `String` collapse footgun the sibling M2
22813 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22814 // emptiness predicates already guard on the peer M2 typed-slot
22815 // surfaces), a `Some("None")` stringified-None round-trip, or a
22816 // `Some` arm whose contents were derived from a sibling slot (an
22817 // accidental fallback to the `:subject` / `:slot` payload that
22818 // read the pub-sub / store payload into the endpoint axis).
22819 // Three contracts sweep the accept-set every non-HTTP `:wit`
22820 // world lands on — pub-sub NATS, key/value, and payload-less
22821 // capability.
22822 for (wit, subject, slot) in [
22823 ("nats:pub-sub", Some("orders.paid"), None),
22824 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22825 ("wasi:cli/environment", None, None),
22826 ] {
22827 let c = WitContract {
22828 de: "cart".into(),
22829 para: "downstream".into(),
22830 wit: wit.into(),
22831 endpoint: None,
22832 subject: subject.map(str::to_string),
22833 slot: slot.map(str::to_string),
22834 };
22835 assert!(
22836 c.endpoint().is_none(),
22837 "WitContract::endpoint must return None when the typed \
22838 slot is absent under :wit {wit:?} (got {:?})",
22839 c.endpoint(),
22840 );
22841 assert_eq!(
22842 c.endpoint(),
22843 c.endpoint.as_deref(),
22844 "WitContract::endpoint must byte-equal the .endpoint \
22845 field's `.as_deref()` projection in the absent arm",
22846 );
22847 }
22848 }
22849
22850 #[test]
22851 fn wit_contract_endpoint_borrows_from_endpoint_storage() {
22852 // The borrow-not-copy pin: [`WitContract::endpoint`] must return
22853 // an `Option<&str>` whose `Some` arm borrows from the typed
22854 // slot's own [`String`] storage — same-address invariant with
22855 // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
22856 // detour that allocated a fresh `String`
22857 // (`self.endpoint.clone().map(...)` in the body would type-check
22858 // but silently drop the borrow, and every downstream consumer
22859 // that assumed the returned slice outlives `&self` would break
22860 // on a stale-reference use-after-free — the [`WitContract::target`]
22861 // Http-arm payload extraction rebinds the returned `Option<&str>`
22862 // through `.ok_or_else(...)` and threads the `&str` payload into
22863 // [`WitTarget::Http { endpoint: &'a str }`], the
22864 // [`AplicacaoSpec::validate`] duplicate-`:contratos`
22865 // [`ContratoIdentity`] dedup key threads the returned
22866 // `Option<&str>` into the six-tuple's HTTP arm — each borrow
22867 // from the WitContract's own storage and each would silently
22868 // misbehave if this accessor produced a detached copy). Peer of
22869 // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
22870 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22871 // shaped optional-scalar axes — first extension of the
22872 // `Option<&str>` borrow-not-copy discipline onto the
22873 // per-`:contratos` HTTP-shaped payload-carrier axis.
22874 let c = WitContract {
22875 de: "cart".into(),
22876 para: "catalog".into(),
22877 wit: "wasi:http/proxy".into(),
22878 endpoint: Some("/lookup".into()),
22879 subject: None,
22880 slot: None,
22881 };
22882 let ep = c.endpoint().expect("Some arm");
22883 let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
22884 assert_eq!(
22885 ep.as_ptr(),
22886 storage_slice.as_ptr(),
22887 "WitContract::endpoint must borrow from the .endpoint \
22888 String's backing storage — a fresh allocation here means \
22889 the accessor no longer names the substrate-primitive typed \
22890 dispatch and every downstream consumer would silently \
22891 carry a detached copy",
22892 );
22893 assert_eq!(
22894 ep.len(),
22895 storage_slice.len(),
22896 "WitContract::endpoint and .endpoint.as_deref() must byte-\
22897 equal in length as well as in address",
22898 );
22899 }
22900
22901 #[test]
22902 fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
22903 // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
22904 // pin: [`WitContract::subject`] must return the `:contratos
22905 // :subject` field byte-for-byte, borrowed from the typed slot's
22906 // own `Option<String>` storage. Peer of the sibling per-`:contratos`
22907 // [`WitContract::endpoint`] (7020470) accessor pin on the M3
22908 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22909 // optional-scalar axis — same "the substrate-primitive accessor
22910 // must byte-equal the raw field access verbatim across every
22911 // author-declared value" discipline extended to the pub-sub arm.
22912 // Pins against a future silent detour that re-canonicalized the
22913 // subject (an accidental `.to_lowercase()` normalization that
22914 // didn't reach the peer field-access site at the dedup key, a
22915 // per-CR fully-qualified prefix rewrite the operator authors on
22916 // one consumer without the other, or an M4 typed-subject-template
22917 // `Display` re-canonicalization that silently drifted the printer
22918 // output from the source `caixa.lisp`). Four values sweep the
22919 // NATS accept-set every pub-sub author-declared subject lands on
22920 // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
22921 for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
22922 let c = WitContract {
22923 de: "cart".into(),
22924 para: "notifier".into(),
22925 wit: "nats:pub-sub".into(),
22926 endpoint: None,
22927 subject: Some(subject.into()),
22928 slot: None,
22929 };
22930 assert_eq!(
22931 c.subject(),
22932 Some(subject),
22933 "WitContract::subject must return :contratos :subject \
22934 verbatim (got {:?}, expected Some({subject:?}))",
22935 c.subject(),
22936 );
22937 assert_eq!(
22938 c.subject(),
22939 c.subject.as_deref(),
22940 "WitContract::subject must byte-equal the .subject \
22941 field's `.as_deref()` projection",
22942 );
22943 }
22944 }
22945
22946 #[test]
22947 fn wit_contract_subject_none_when_field_is_none() {
22948 // The absent-`:subject` arm of the per-`:contratos` pub-sub-
22949 // shaped payload-carrier accessor pin: when the typed slot is
22950 // absent — the canonical shape under a non-pub-sub `:wit` world
22951 // per the [`WitContract::target`]-enforced shape ↔ target
22952 // partition ([`WitTarget::Http`] carries `:endpoint`,
22953 // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
22954 // carries none) — [`WitContract::subject`] must return `None`.
22955 // Pins against a future silent detour that projected the absent
22956 // slot to a `Some("")` empty-string default (the canonical
22957 // `Option<String>` → `String` collapse footgun the sibling M2
22958 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22959 // emptiness predicates already guard on the peer M2 typed-slot
22960 // surfaces), a `Some("None")` stringified-None round-trip, or a
22961 // `Some` arm whose contents were derived from a sibling slot (an
22962 // accidental fallback to the `:endpoint` / `:slot` payload that
22963 // read the HTTP / store payload into the subject axis). Three
22964 // contracts sweep the accept-set every non-pub-sub `:wit` world
22965 // lands on — HTTP proxy, key/value store, and payload-less
22966 // capability.
22967 for (wit, endpoint, slot) in [
22968 ("wasi:http/proxy", Some("/lookup"), None),
22969 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22970 ("wasi:cli/environment", None, None),
22971 ] {
22972 let c = WitContract {
22973 de: "cart".into(),
22974 para: "downstream".into(),
22975 wit: wit.into(),
22976 endpoint: endpoint.map(str::to_string),
22977 subject: None,
22978 slot: slot.map(str::to_string),
22979 };
22980 assert!(
22981 c.subject().is_none(),
22982 "WitContract::subject must return None when the typed \
22983 slot is absent under :wit {wit:?} (got {:?})",
22984 c.subject(),
22985 );
22986 assert_eq!(
22987 c.subject(),
22988 c.subject.as_deref(),
22989 "WitContract::subject must byte-equal the .subject \
22990 field's `.as_deref()` projection in the absent arm",
22991 );
22992 }
22993 }
22994
22995 #[test]
22996 fn wit_contract_subject_borrows_from_subject_storage() {
22997 // The borrow-not-copy pin: [`WitContract::subject`] must return
22998 // an `Option<&str>` whose `Some` arm borrows from the typed
22999 // slot's own [`String`] storage — same-address invariant with
23000 // `c.subject.as_deref().unwrap()`. Pins against a future silent
23001 // detour that allocated a fresh `String`
23002 // (`self.subject.clone().map(...)` in the body would type-check
23003 // but silently drop the borrow, and every downstream consumer
23004 // that assumed the returned slice outlives `&self` would break
23005 // on a stale-reference use-after-free — the [`WitContract::target`]
23006 // PubSub-arm payload extraction rebinds the returned
23007 // `Option<&str>` through `.ok_or_else(...)` and threads the
23008 // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
23009 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
23010 // [`ContratoIdentity`] dedup key threads the returned
23011 // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
23012 // from the WitContract's own storage and each would silently
23013 // misbehave if this accessor produced a detached copy). Peer of
23014 // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
23015 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
23016 // shaped optional-scalar axis — second extension of the
23017 // `Option<&str>` borrow-not-copy discipline onto the
23018 // per-`:contratos` payload-carrier family, this time on the
23019 // pub-sub arm.
23020 let c = WitContract {
23021 de: "cart".into(),
23022 para: "notifier".into(),
23023 wit: "nats:pub-sub".into(),
23024 endpoint: None,
23025 subject: Some("orders.paid".into()),
23026 slot: None,
23027 };
23028 let sub = c.subject().expect("Some arm");
23029 let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
23030 assert_eq!(
23031 sub.as_ptr(),
23032 storage_slice.as_ptr(),
23033 "WitContract::subject must borrow from the .subject \
23034 String's backing storage — a fresh allocation here means \
23035 the accessor no longer names the substrate-primitive typed \
23036 dispatch and every downstream consumer would silently \
23037 carry a detached copy",
23038 );
23039 assert_eq!(
23040 sub.len(),
23041 storage_slice.len(),
23042 "WitContract::subject and .subject.as_deref() must byte-\
23043 equal in length as well as in address",
23044 );
23045 }
23046
23047 #[test]
23048 fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
23049 // The canonical per-`:contratos` key/value-store-shaped
23050 // `:slot`-scalar pin: [`WitContract::slot`] must return the
23051 // `:contratos :slot` field byte-for-byte, borrowed from the
23052 // typed slot's own `Option<String>` storage. Peer of the
23053 // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
23054 // [`WitContract::subject`] (90de675) accessor pins on the M3
23055 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
23056 // optional-scalar axis — same "the substrate-primitive
23057 // accessor must byte-equal the raw field access verbatim
23058 // across every author-declared value" discipline extended to
23059 // the store arm. Pins against a future silent detour that
23060 // re-canonicalized the slot template (an accidental
23061 // `.to_lowercase()` bucket-prefix normalization that didn't
23062 // reach the peer field-access site at the dedup key, a per-CR
23063 // fully-qualified prefix rewrite the operator authors on one
23064 // consumer without the other, or an M4 typed-key-template
23065 // `Display` re-canonicalization that silently drifted the
23066 // printer output from the source `caixa.lisp`). Four values
23067 // sweep the wasi:keyvalue accept-set every store-shaped
23068 // author-declared slot lands on (flat bucket, single-param
23069 // template, multi-param template, nested-hierarchy template).
23070 for slot in [
23071 "sessions",
23072 "carts/{cart_id}",
23073 "orders/{tenant}/{order_id}",
23074 "cache/tenant-a/orders/{id}",
23075 ] {
23076 let c = WitContract {
23077 de: "cart".into(),
23078 para: "kv".into(),
23079 wit: "wasi:keyvalue/store".into(),
23080 endpoint: None,
23081 subject: None,
23082 slot: Some(slot.into()),
23083 };
23084 assert_eq!(
23085 c.slot(),
23086 Some(slot),
23087 "WitContract::slot must return :contratos :slot \
23088 verbatim (got {:?}, expected Some({slot:?}))",
23089 c.slot(),
23090 );
23091 assert_eq!(
23092 c.slot(),
23093 c.slot.as_deref(),
23094 "WitContract::slot must byte-equal the .slot field's \
23095 `.as_deref()` projection",
23096 );
23097 }
23098 }
23099
23100 #[test]
23101 fn wit_contract_slot_none_when_field_is_none() {
23102 // The absent-`:slot` arm of the per-`:contratos` store-shaped
23103 // payload-carrier accessor pin: when the typed slot is absent —
23104 // the canonical shape under a non-store `:wit` world per the
23105 // [`WitContract::target`]-enforced shape ↔ target partition
23106 // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
23107 // carries `:subject`, [`WitTarget::Capability`] carries none) —
23108 // [`WitContract::slot`] must return `None`. Pins against a
23109 // future silent detour that projected the absent slot to a
23110 // `Some("")` empty-string default (the canonical
23111 // `Option<String>` → `String` collapse footgun the sibling M2
23112 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
23113 // emptiness predicates already guard on the peer M2 typed-slot
23114 // surfaces), a `Some("None")` stringified-None round-trip, or
23115 // a `Some` arm whose contents were derived from a sibling
23116 // slot (an accidental fallback to the `:endpoint` / `:subject`
23117 // payload that read the HTTP / pub-sub payload into the store
23118 // axis). Three contracts sweep the accept-set every non-store
23119 // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
23120 // payload-less capability.
23121 for (wit, endpoint, subject) in [
23122 ("wasi:http/proxy", Some("/lookup"), None),
23123 ("nats:pub-sub", None, Some("orders.paid")),
23124 ("wasi:cli/environment", None, None),
23125 ] {
23126 let c = WitContract {
23127 de: "cart".into(),
23128 para: "downstream".into(),
23129 wit: wit.into(),
23130 endpoint: endpoint.map(str::to_string),
23131 subject: subject.map(str::to_string),
23132 slot: None,
23133 };
23134 assert!(
23135 c.slot().is_none(),
23136 "WitContract::slot must return None when the typed \
23137 slot is absent under :wit {wit:?} (got {:?})",
23138 c.slot(),
23139 );
23140 assert_eq!(
23141 c.slot(),
23142 c.slot.as_deref(),
23143 "WitContract::slot must byte-equal the .slot field's \
23144 `.as_deref()` projection in the absent arm",
23145 );
23146 }
23147 }
23148
23149 #[test]
23150 fn wit_contract_slot_borrows_from_slot_storage() {
23151 // The borrow-not-copy pin: [`WitContract::slot`] must return
23152 // an `Option<&str>` whose `Some` arm borrows from the typed
23153 // slot's own [`String`] storage — same-address invariant with
23154 // `c.slot.as_deref().unwrap()`. Pins against a future silent
23155 // detour that allocated a fresh `String`
23156 // (`self.slot.clone().map(...)` in the body would type-check
23157 // but silently drop the borrow, and every downstream consumer
23158 // that assumed the returned slice outlives `&self` would
23159 // break on a stale-reference use-after-free — the
23160 // [`WitContract::target`] Store-arm payload extraction rebinds
23161 // the returned `Option<&str>` through `.ok_or_else(...)` and
23162 // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
23163 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
23164 // [`ContratoIdentity`] dedup key threads the returned
23165 // `Option<&str>` into the six-tuple's store arm — each borrow
23166 // from the WitContract's own storage and each would silently
23167 // misbehave if this accessor produced a detached copy). Peer
23168 // of the sibling per-`:contratos` [`WitContract::endpoint`]
23169 // (7020470) / [`WitContract::subject`] (90de675)
23170 // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
23171 // shaped optional-scalar axis — third and final extension of
23172 // the `Option<&str>` borrow-not-copy discipline onto the
23173 // per-`:contratos` payload-carrier family, this time on the
23174 // store arm.
23175 let c = WitContract {
23176 de: "cart".into(),
23177 para: "kv".into(),
23178 wit: "wasi:keyvalue/store".into(),
23179 endpoint: None,
23180 subject: None,
23181 slot: Some("carts/{cart_id}".into()),
23182 };
23183 let slot = c.slot().expect("Some arm");
23184 let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
23185 assert_eq!(
23186 slot.as_ptr(),
23187 storage_slice.as_ptr(),
23188 "WitContract::slot must borrow from the .slot String's \
23189 backing storage — a fresh allocation here means the \
23190 accessor no longer names the substrate-primitive typed \
23191 dispatch and every downstream consumer would silently \
23192 carry a detached copy",
23193 );
23194 assert_eq!(
23195 slot.len(),
23196 storage_slice.len(),
23197 "WitContract::slot and .slot.as_deref() must byte-equal \
23198 in length as well as in address",
23199 );
23200 }
23201
23202 #[test]
23203 fn membro_nome_returns_caixa_byte_equal_across_permutations() {
23204 // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
23205 // [`Membro::nome`] must return the `:membros :caixa` field
23206 // byte-for-byte, borrowed from the typed slot's own [`String`]
23207 // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
23208 // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
23209 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
23210 // slot-atom scalar-value axes — same "the substrate-primitive
23211 // accessor must byte-equal the raw field access verbatim across
23212 // every author-declared value" discipline extended to the
23213 // per-`:membros` member-identity arm. Pins against a future
23214 // silent detour that re-normalized the member identity (an
23215 // accidental `.to_lowercase()` — every `:membros :caixa` is
23216 // validated as a DNS-1123 label upstream via
23217 // [`validate_membro_caixa`], so any re-normalization is
23218 // redundant + a drift surface between the validator and the
23219 // accessor), a namespace-prefix rewrite (an accidental
23220 // `format!("{namespace}/{caixa}")` per-CR fully-qualified
23221 // rewrite that didn't land on the peer axes), or a per-cluster
23222 // alias stamp the operator authors on one consumer without the
23223 // other. Four values sweep the accept-set the DNS-1123 gate
23224 // upstream admits (short single-word / dashed / v-suffixed
23225 // member names).
23226 for name in ["cart", "checkout", "catalog", "orders-v2"] {
23227 let m = Membro {
23228 caixa: name.into(),
23229 versao: "^0.1".into(),
23230 };
23231 assert_eq!(
23232 m.nome(),
23233 name,
23234 "Membro::nome must return :membros :caixa verbatim \
23235 (got {:?}, expected {name:?})",
23236 m.nome(),
23237 );
23238 assert_eq!(
23239 m.nome(),
23240 m.caixa.as_str(),
23241 "Membro::nome must byte-equal the .caixa field access",
23242 );
23243 }
23244 }
23245
23246 #[test]
23247 fn membro_nome_borrows_from_caixa_storage() {
23248 // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
23249 // slice that borrows from the typed slot's own [`String`]
23250 // storage — same-address invariant with `m.caixa.as_str()`. Pins
23251 // against a future silent detour that allocated a fresh `String`
23252 // (`self.caixa.clone()` in the body would type-check but
23253 // silently drop the borrow, and every downstream consumer that
23254 // assumed the returned slice outlives `&self` would break on a
23255 // stale-reference use-after-free — the `HashSet<&str>` collector
23256 // at [`AplicacaoSpec::validate`]'s `names` seed, the
23257 // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
23258 // [`AplicacaoSpec::detect_sync_cycles`], the
23259 // [`crate::render::insert_first_seen`] dedup key at
23260 // [`AplicacaoSpec::validate_membros`] — each borrow from the
23261 // Membro's own storage and each would silently misbehave if
23262 // this accessor produced a detached copy). Peer of the sibling
23263 // per-`:contratos` [`WitContract::source`] /
23264 // [`WitContract::destination`] and per-`:entrada`
23265 // [`Entrada::destination`] borrow-invariant pins on the mesh-
23266 // slot-atom scalar-value axes.
23267 let m = Membro {
23268 caixa: "checkout".into(),
23269 versao: "^0.1".into(),
23270 };
23271 let name = m.nome();
23272 let caixa_slice = m.caixa.as_str();
23273 assert_eq!(
23274 name.as_ptr(),
23275 caixa_slice.as_ptr(),
23276 "Membro::nome must borrow from the .caixa String's backing \
23277 storage — a fresh allocation here means the accessor no \
23278 longer names the substrate-primitive typed dispatch and \
23279 every downstream consumer would silently carry a detached \
23280 copy",
23281 );
23282 assert_eq!(
23283 name.len(),
23284 caixa_slice.len(),
23285 "Membro::nome and .caixa.as_str() must byte-equal in length \
23286 as well as in address",
23287 );
23288 }
23289
23290 #[test]
23291 fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
23292 // The canonical per-`:membros` member-`:versao`-scalar pin:
23293 // [`Membro::versao_requirement`] must return the
23294 // `:membros :versao` field byte-for-byte, borrowed from the typed
23295 // slot's own [`String`] storage. Sibling of the peer
23296 // `membro_nome_returns_caixa_byte_equal_across_permutations`
23297 // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
23298 // — same "the substrate-primitive accessor must byte-equal the
23299 // raw field access verbatim across every author-declared value"
23300 // discipline extended to the per-`:membros` member-`:versao`
23301 // requirement-string arm. Pins against a future silent detour
23302 // that re-canonicalized the requirement (an accidental
23303 // `.to_string()` via [`parse_requirement`] → [`Display`] round-
23304 // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
23305 // drifted the printer output away from the source `caixa.lisp`,
23306 // an accidental whitespace trim on `"^ 0.1"` that no consumer
23307 // ever produced from the field-access side, an accidental
23308 // per-cluster lacre-projected concrete-version rewrite that
23309 // didn't land on the peer field-access sites). Five values sweep
23310 // the accept-set the shared
23311 // [`crate::render::require_valid_versao_requirement`] gate
23312 // admits (caret / tilde / exact / wildcard / bare-major).
23313 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
23314 let m = Membro {
23315 caixa: "cart".into(),
23316 versao: req.into(),
23317 };
23318 assert_eq!(
23319 m.versao_requirement(),
23320 req,
23321 "Membro::versao_requirement must return :membros :versao \
23322 verbatim (got {:?}, expected {req:?})",
23323 m.versao_requirement(),
23324 );
23325 assert_eq!(
23326 m.versao_requirement(),
23327 m.versao.as_str(),
23328 "Membro::versao_requirement must byte-equal the .versao \
23329 field access",
23330 );
23331 }
23332 }
23333
23334 #[test]
23335 fn membro_versao_requirement_borrows_from_versao_storage() {
23336 // The borrow-not-copy pin: [`Membro::versao_requirement`] must
23337 // return a `&str` slice that borrows from the typed slot's own
23338 // [`String`] storage — same-address invariant with
23339 // `m.versao.as_str()`. Pins against a future silent detour that
23340 // allocated a fresh `String` (`self.versao.clone()` in the body
23341 // would type-check but silently drop the borrow, and every
23342 // downstream consumer that assumed the returned slice outlives
23343 // `&self` would break on a stale-reference use-after-free). Peer
23344 // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
23345 // per-`:contratos` [`WitContract::source`] /
23346 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
23347 // [`Entrada::destination`] (6db982c) borrow-invariant pins on
23348 // the mesh-slot-atom scalar-value axes.
23349 let m = Membro {
23350 caixa: "checkout".into(),
23351 versao: "^0.1".into(),
23352 };
23353 let req = m.versao_requirement();
23354 let versao_slice = m.versao.as_str();
23355 assert_eq!(
23356 req.as_ptr(),
23357 versao_slice.as_ptr(),
23358 "Membro::versao_requirement must borrow from the .versao \
23359 String's backing storage — a fresh allocation here means \
23360 the accessor no longer names the substrate-primitive typed \
23361 dispatch and every downstream consumer would silently carry \
23362 a detached copy",
23363 );
23364 assert_eq!(
23365 req.len(),
23366 versao_slice.len(),
23367 "Membro::versao_requirement and .versao.as_str() must byte-\
23368 equal in length as well as in address",
23369 );
23370 }
23371
23372 #[test]
23373 fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
23374 // Sibling-pair invariant pin composing both per-`:membros`
23375 // substrate-primitive typed dispatches — [`Membro::nome`]
23376 // (4a32abf) and [`Membro::versao_requirement`] — at the joint
23377 // `(nome(), versao_requirement())` call shape every renderer
23378 // that fans on per-member identity + version pin keys off. The
23379 // invariant, evaluated per-member:
23380 //
23381 // (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
23382 //
23383 // Closes the last unlifted per-`:membros` scalar axis — every
23384 // downstream consumer that reads the pair now routes through
23385 // exactly two typed dispatches on the substrate primitive, not
23386 // one typed + one open-coded field access. A future refactor
23387 // that silently split either accessor's projection (an
23388 // accidental `nome()` namespace-prefix rewrite that didn't
23389 // reach the peer, an accidental `versao_requirement()` lacre-
23390 // projected concrete-version rewrite that didn't land on the
23391 // `nome()` peer) surfaces at caixa-core build time. Peer of the
23392 // sibling per-`:entrada` `(hostname(), destination())` and
23393 // per-`:contratos` `(source(), destination())` pair invariants
23394 // on the mesh-slot-atom scalar-value axes.
23395 for (caixa, versao) in [
23396 ("cart", "^0.1"),
23397 ("checkout", "~0.1.2"),
23398 ("catalog", "0.1.0"),
23399 ("orders-v2", "*"),
23400 ] {
23401 let m = Membro {
23402 caixa: caixa.into(),
23403 versao: versao.into(),
23404 };
23405 assert_eq!(
23406 (m.nome(), m.versao_requirement()),
23407 (m.caixa.as_str(), m.versao.as_str()),
23408 "(Membro::nome, Membro::versao_requirement) must project \
23409 (.caixa, .versao) verbatim across every author-declared \
23410 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
23411 m.nome(),
23412 m.versao_requirement(),
23413 );
23414 }
23415 }
23416
23417 #[test]
23418 fn validate_membros_empty_gate_routes_through_nome_accessor() {
23419 // Composition pin: [`AplicacaoSpec::validate_membros`]'s
23420 // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
23421 // not the raw `.caixa` field access. Structurally: setting
23422 // ONLY the `.caixa` field to `""` on an otherwise-well-formed
23423 // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
23424 // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
23425 // (i.e. the empty string) — so the emptiness predicate the
23426 // refusal arm reaches under is the accessor-projected value,
23427 // not a peer field that would silently drift under a future
23428 // accessor-side rewrite.
23429 //
23430 // Pins against a future silent detour that (a) re-derived the
23431 // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
23432 // instead of `self.nome().is_empty()`, silently disagreeing with
23433 // every peer consumer (the `validate_membro_caixa(m.nome())`
23434 // call one line below, the dedup-key `insert_first_seen(&mut
23435 // seen, m.nome(), …)` two lines below, the emit-side per-
23436 // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
23437 // (b) accessor-side introduced a per-tenant alias arm the
23438 // caller was unaware of, silently rewriting an author-declared
23439 // `:caixa "checkout"` to `""` — the raw-field-access gate
23440 // would fail-open while the accessor-routed peer consumers
23441 // would fail-closed, splitting the diagnostic from the actual
23442 // failure surface.
23443 //
23444 // Peer of the sibling
23445 // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
23446 // (c0110f1) composition pin — same "the shape-gate predicate
23447 // must route through the substrate-primitive typed dispatch"
23448 // discipline extended onto the per-`:membros` empty-`:caixa`
23449 // refusal-arm axis. Closes the last unlifted `.caixa` production-
23450 // code read site on `Membro` — after this converge every
23451 // caixa-core `.caixa` field access outside the accessor's own
23452 // body is either a test-side field-setter (in-module tests
23453 // constructing invalid-shape inputs) or a doc-comment reference.
23454 let mut s = three_member_spec();
23455 s.membros[1].caixa = String::new();
23456 assert!(
23457 s.membros[1].nome().is_empty(),
23458 "Membro::nome must byte-equal the .caixa field access — an \
23459 accessor-side detour that no longer projects the raw field \
23460 would silently split this drift-detection test from the \
23461 validate() refusal arm",
23462 );
23463 assert_eq!(
23464 s.membros[1].nome(),
23465 s.membros[1].caixa.as_str(),
23466 "Membro::nome and .caixa.as_str() must byte-equal on an \
23467 empty-`:caixa` entry — the emptiness gate keys off the \
23468 accessor by construction",
23469 );
23470 assert_eq!(
23471 s.validate().unwrap_err(),
23472 AplicacaoError::MembroCaixaEmpty,
23473 "validate_membros' emptiness gate must fire MembroCaixaEmpty \
23474 on an entry whose accessor-projected `nome()` is empty",
23475 );
23476 }
23477
23478 #[test]
23479 fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
23480 // The canonical per-`:placement` Akka-cluster-sharding
23481 // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
23482 // the `:placement :shard-key` field byte-for-byte, borrowed
23483 // from the typed slot's own `Option<String>` storage. Peer of
23484 // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
23485 // per-`:contratos` [`WitContract::source`] /
23486 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
23487 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
23488 // slot-atom scalar-value axes — same "the substrate-primitive
23489 // accessor must byte-equal the raw field access verbatim across
23490 // every author-declared value" discipline extended to the
23491 // per-`:placement` Akka-cluster-sharding key extractor arm.
23492 // Pins against a future silent detour that re-normalized the
23493 // key (an accidental `.to_lowercase()` — every non-empty
23494 // `:shard-key` is validated as a printable-ASCII single-token
23495 // reference upstream via [`validate_placement_shard_key`], so
23496 // any re-normalization is redundant + a drift surface between
23497 // the validator and the accessor), a per-cluster alias rewrite
23498 // the operator authors on one consumer without the other, or an
23499 // accidental variable-prefix strip (`$tenantId` → `tenantId`)
23500 // that didn't land on the peer field-access sites. Four values
23501 // sweep the accept-set the shape gate admits — bare identifier,
23502 // `$`-prefixed variable, dotted path, `${}`-quoted variable —
23503 // the four canonical Akka-style entity-id extractor shapes the
23504 // future M4 cluster-sharding reconciler hashes.
23505 for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
23506 let p = Placement {
23507 estrategia: PlacementStrategy::Sharded,
23508 clusters: vec!["rio".into()],
23509 affinity: None,
23510 shard_key: Some(key.into()),
23511 };
23512 assert_eq!(
23513 p.shard_key(),
23514 Some(key),
23515 "Placement::shard_key must return :placement :shard-key \
23516 verbatim (got {:?}, expected Some({key:?}))",
23517 p.shard_key(),
23518 );
23519 assert_eq!(
23520 p.shard_key(),
23521 p.shard_key.as_deref(),
23522 "Placement::shard_key must byte-equal the .shard_key \
23523 field's `.as_deref()` projection",
23524 );
23525 }
23526 }
23527
23528 #[test]
23529 fn placement_shard_key_none_when_field_is_none() {
23530 // The absent-`:shard-key` arm of the per-`:placement`
23531 // Akka-cluster-sharding accessor pin: when the typed slot is
23532 // absent — the canonical shape under `:estrategia Replicated` /
23533 // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
23534 // enforced `shard_key.is_some() == matches!(estrategia,
23535 // Sharded)` partition — [`Placement::shard_key`] must return
23536 // `None`. Pins against a future silent detour that projected
23537 // the absent slot to a `Some("")` empty-string default (the
23538 // canonical `Option<String>` → `String` collapse footgun the
23539 // sibling M2 [`crate::LimitsSpec::is_empty`] /
23540 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
23541 // already guard on the peer M2 typed-slot surfaces), a
23542 // `Some("None")` stringified-None round-trip, or a `Some` arm
23543 // whose contents were derived from a sibling slot (an
23544 // accidental fallback to `estrategia.as_str()` that read the
23545 // strategy discriminator into the key axis). Two placements
23546 // sweep the accept-set every `validate`-passing non-`Sharded`
23547 // shape lands on — `Replicated` (Erlang/OTP distributed-app
23548 // takeover) and `SingleNode` (single-node hosting).
23549 for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
23550 let p = Placement {
23551 estrategia,
23552 clusters: vec!["rio".into()],
23553 affinity: None,
23554 shard_key: None,
23555 };
23556 assert!(
23557 p.shard_key().is_none(),
23558 "Placement::shard_key must return None when the typed \
23559 slot is absent under :estrategia {estrategia:?} (got {:?})",
23560 p.shard_key(),
23561 );
23562 assert_eq!(
23563 p.shard_key(),
23564 p.shard_key.as_deref(),
23565 "Placement::shard_key must byte-equal the .shard_key \
23566 field's `.as_deref()` projection in the absent arm",
23567 );
23568 }
23569 }
23570
23571 #[test]
23572 fn placement_shard_key_borrows_from_shard_key_storage() {
23573 // The borrow-not-copy pin: [`Placement::shard_key`] must return
23574 // an `Option<&str>` whose `Some` arm borrows from the typed
23575 // slot's own [`String`] storage — same-address invariant with
23576 // `p.shard_key.as_deref().unwrap()`. Pins against a future
23577 // silent detour that allocated a fresh `String`
23578 // (`self.shard_key.clone().map(...)` in the body would type-
23579 // check but silently drop the borrow, and every downstream
23580 // consumer that assumed the returned slice outlives `&self`
23581 // would break on a stale-reference use-after-free — the
23582 // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
23583 // gate's `Some(k)`-bound match arm reads `k: &str` under the
23584 // accessor's return type and would silently misbehave if this
23585 // accessor produced a detached copy). Peer of the sibling
23586 // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
23587 // [`WitContract::source`] / [`WitContract::destination`]
23588 // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
23589 // (6db982c) borrow-invariant pins on the mesh-slot-atom
23590 // scalar-value axes — first extension of the discipline onto
23591 // an `Option<String>`-shaped optional-scalar axis.
23592 let p = Placement {
23593 estrategia: PlacementStrategy::Sharded,
23594 clusters: vec!["rio".into()],
23595 affinity: None,
23596 shard_key: Some("tenantId".into()),
23597 };
23598 let key = p.shard_key().expect("Some arm");
23599 let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
23600 assert_eq!(
23601 key.as_ptr(),
23602 storage_slice.as_ptr(),
23603 "Placement::shard_key must borrow from the .shard_key \
23604 String's backing storage — a fresh allocation here means \
23605 the accessor no longer names the substrate-primitive typed \
23606 dispatch and every downstream consumer would silently \
23607 carry a detached copy",
23608 );
23609 assert_eq!(
23610 key.len(),
23611 storage_slice.len(),
23612 "Placement::shard_key and .shard_key.as_deref() must byte-\
23613 equal in length as well as in address",
23614 );
23615 }
23616
23617 #[test]
23618 fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
23619 // The canonical per-`:placement` M3-Adaptive-compression-hint
23620 // scalar pin: [`Placement::affinity`] must return the
23621 // `:placement :affinity` field byte-for-byte, borrowed from the
23622 // typed slot's own `Option<String>` storage. Peer of the sibling
23623 // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
23624 // pin on the sibling `Option<&str>` optional-scalar axis — same
23625 // "the substrate-primitive accessor must byte-equal the raw
23626 // field access verbatim across every author-declared value"
23627 // discipline extended to the peer per-`:placement` M3-Adaptive-
23628 // compression-hint arm. Pins against a future silent detour
23629 // that re-normalized the hint (an accidental `.to_lowercase()`
23630 // — every `:affinity` is already validated as a DNS-1123 label
23631 // upstream via [`validate_placement_affinity`], so any re-
23632 // normalization is redundant + a drift surface between the
23633 // validator and the accessor), a per-cluster alias rewrite the
23634 // operator authors on one consumer without the other, or an
23635 // accidental hint-family collapse (`low-latency` → `latency`
23636 // that dropped the qualifier prefix). Four values sweep the
23637 // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
23638 // canonical adaptive-compression-weight biases the future M4
23639 // placement engine reads.
23640 for hint in [
23641 "data-locality",
23642 "low-latency",
23643 "high-throughput",
23644 "cost-optimized",
23645 ] {
23646 let p = Placement {
23647 estrategia: PlacementStrategy::Replicated,
23648 clusters: vec!["rio".into()],
23649 affinity: Some(hint.into()),
23650 shard_key: None,
23651 };
23652 assert_eq!(
23653 p.affinity(),
23654 Some(hint),
23655 "Placement::affinity must return :placement :affinity \
23656 verbatim (got {:?}, expected Some({hint:?}))",
23657 p.affinity(),
23658 );
23659 assert_eq!(
23660 p.affinity(),
23661 p.affinity.as_deref(),
23662 "Placement::affinity must byte-equal the .affinity \
23663 field's `.as_deref()` projection",
23664 );
23665 }
23666 }
23667
23668 #[test]
23669 fn placement_affinity_none_when_field_is_none() {
23670 // The absent-`:affinity` arm of the per-`:placement`
23671 // M3-Adaptive-compression-hint accessor pin: when the typed
23672 // slot is absent — the canonical shape of an Aplicacao that
23673 // leaves the compression weighting up to the placement engine's
23674 // cluster-default arm — [`Placement::affinity`] must return
23675 // `None`. Pins against a future silent detour that projected
23676 // the absent slot to a `Some("")` empty-string default (the
23677 // canonical `Option<String>` → `String` collapse footgun the
23678 // sibling M2 [`crate::LimitsSpec::is_empty`] /
23679 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
23680 // already guard on the peer M2 typed-slot surfaces), a
23681 // `Some("None")` stringified-None round-trip, a `Some` arm
23682 // whose contents were derived from a sibling slot (an
23683 // accidental fallback to `estrategia.as_str()` that read the
23684 // strategy discriminator into the hint axis), or a
23685 // `Some("default")` implicit-default that would silently biases
23686 // the routing without the author having written one. Three
23687 // placements sweep the accept-set every `validate`-passing
23688 // `:affinity None` shape lands on — one per PlacementStrategy
23689 // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
23690 // with a shard-key), since `:affinity` is orthogonal to
23691 // `:estrategia` in the typed grammar.
23692 for (estrategia, shard_key) in [
23693 (PlacementStrategy::SingleNode, None),
23694 (PlacementStrategy::Replicated, None),
23695 (PlacementStrategy::Sharded, Some("tenantId".to_string())),
23696 ] {
23697 let p = Placement {
23698 estrategia,
23699 clusters: vec!["rio".into()],
23700 affinity: None,
23701 shard_key,
23702 };
23703 assert!(
23704 p.affinity().is_none(),
23705 "Placement::affinity must return None when the typed \
23706 slot is absent under :estrategia {estrategia:?} (got {:?})",
23707 p.affinity(),
23708 );
23709 assert_eq!(
23710 p.affinity(),
23711 p.affinity.as_deref(),
23712 "Placement::affinity must byte-equal the .affinity \
23713 field's `.as_deref()` projection in the absent arm",
23714 );
23715 }
23716 }
23717
23718 #[test]
23719 fn placement_affinity_borrows_from_affinity_storage() {
23720 // The borrow-not-copy pin: [`Placement::affinity`] must return
23721 // an `Option<&str>` whose `Some` arm borrows from the typed
23722 // slot's own [`String`] storage — same-address invariant with
23723 // `p.affinity.as_deref().unwrap()`. Pins against a future
23724 // silent detour that allocated a fresh `String`
23725 // (`self.affinity.clone().map(...)` in the body would type-
23726 // check but silently drop the borrow, and every downstream
23727 // consumer that assumed the returned slice outlives `&self`
23728 // would break on a stale-reference use-after-free — the
23729 // [`AplicacaoSpec::validate_placement`] per-hint value-shape
23730 // gate reads the accessor's `&str` return through the
23731 // [`validate_placement_affinity`] `&str` parameter and would
23732 // silently misbehave if this accessor produced a detached
23733 // copy). Peer of the sibling per-`:placement`
23734 // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
23735 // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
23736 // extends the discipline onto the sibling per-`:placement`
23737 // M3-Adaptive-compression-hint arm.
23738 let p = Placement {
23739 estrategia: PlacementStrategy::Replicated,
23740 clusters: vec!["rio".into()],
23741 affinity: Some("data-locality".into()),
23742 shard_key: None,
23743 };
23744 let hint = p.affinity().expect("Some arm");
23745 let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
23746 assert_eq!(
23747 hint.as_ptr(),
23748 storage_slice.as_ptr(),
23749 "Placement::affinity must borrow from the .affinity \
23750 String's backing storage — a fresh allocation here means \
23751 the accessor no longer names the substrate-primitive typed \
23752 dispatch and every downstream consumer would silently \
23753 carry a detached copy",
23754 );
23755 assert_eq!(
23756 hint.len(),
23757 storage_slice.len(),
23758 "Placement::affinity and .affinity.as_deref() must byte-\
23759 equal in length as well as in address",
23760 );
23761 }
23762
23763 #[test]
23764 fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
23765 // The canonical per-`:placement` distribution-strategy-scalar
23766 // pin: [`Placement::estrategia`] must return the `:placement
23767 // :estrategia` field verbatim as a [`PlacementStrategy`],
23768 // `Copy`-projected from the typed slot's own `PlacementStrategy`
23769 // storage across every variant in the closed accept-set
23770 // (`SingleNode` — Erlang/OTP distributed-app takeover;
23771 // `Replicated` — active-active across every named cluster;
23772 // `Sharded` — Akka-style hash-keyed entity distribution). Pins
23773 // against a future silent detour that re-derived the strategy
23774 // from a peer axis (an accidental fallback to
23775 // `if shard_key.is_some() { Sharded } else { Replicated }`
23776 // collapse that read the shard-key axis into the strategy
23777 // discriminator), a variant remap the operator authors on one
23778 // consumer without the other, or a stale-derive detour that
23779 // substituted [`PlacementStrategy::default`] when the field
23780 // held any explicit variant (which would silently collapse the
23781 // distinction between "author explicitly declared `:estrategia
23782 // Replicated`" and "author omitted the slot and inherited the
23783 // default" the future per-cluster override slot depends on).
23784 // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
23785 // pin on the `Copy`-return `u16` scalar axis — same "the
23786 // substrate-primitive accessor must byte-equal the raw field
23787 // access verbatim across every author-declared value" discipline
23788 // extended onto the per-`:placement` distribution-strategy
23789 // `Copy`-composite-enum scalar axis.
23790 for estrategia in [
23791 PlacementStrategy::SingleNode,
23792 PlacementStrategy::Replicated,
23793 PlacementStrategy::Sharded,
23794 ] {
23795 // Route the paired `:shard-key` fixture-builder through the
23796 // typed cross-slot invariant predicate
23797 // [`PlacementStrategy::requires_shard_key`] rather than the
23798 // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
23799 // arm-identity predicate — same discipline the sibling
23800 // `placement_strategy_variants_round_trip` fixture builder now
23801 // reads through.
23802 let shard_key = estrategia
23803 .requires_shard_key()
23804 .then(|| "tenantId".to_string());
23805 let p = Placement {
23806 estrategia,
23807 clusters: vec!["rio".into()],
23808 affinity: None,
23809 shard_key,
23810 };
23811 assert_eq!(
23812 p.estrategia(),
23813 estrategia,
23814 "Placement::estrategia must return :placement :estrategia \
23815 verbatim (got {:?}, expected {estrategia:?})",
23816 p.estrategia(),
23817 );
23818 assert_eq!(
23819 p.estrategia(),
23820 p.estrategia,
23821 "Placement::estrategia accessor and .estrategia field \
23822 access must byte-equal — the accessor is the substrate-\
23823 primitive typed dispatch every downstream distribution-\
23824 strategy consumer must route through",
23825 );
23826 }
23827 }
23828
23829 #[test]
23830 fn validate_placement_reads_through_lifted_estrategia_accessor() {
23831 // Three-consumer coherence pin: the
23832 // [`AplicacaoSpec::validate_placement`]
23833 // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
23834 // `estrategia:` field (which reads through
23835 // [`Placement::estrategia`] to name the strategy the empty
23836 // `:clusters` list was declared against), the same method's
23837 // `Sharded ↔ non-Sharded` `match` partition dispatch (which
23838 // reads through [`Placement::estrategia`] to fan across the
23839 // shape-gate cascades), and the non-`Sharded`-arm
23840 // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
23841 // `estrategia:` field (which reads through
23842 // [`Placement::estrategia`] to name the strategy the declared-
23843 // but-inert `:shard-key` was authored under) must all key off
23844 // the lifted accessor, so any future rebrand on the typed
23845 // slot's reader shape lands at exactly one place. Pins the
23846 // three-site coherence by exercising each error surface end-
23847 // to-end and asserting the surfaced `estrategia:` field byte-
23848 // equals the accessor's return. Peer of the sibling per-
23849 // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
23850 // pin on the M3 mesh-slot `Copy`-return scalar axis.
23851
23852 // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
23853 // whose `estrategia:` field must byte-equal the accessor's return
23854 // for every variant in the closed accept-set.
23855 for estrategia in [
23856 PlacementStrategy::SingleNode,
23857 PlacementStrategy::Replicated,
23858 PlacementStrategy::Sharded,
23859 ] {
23860 let mut spec = three_member_spec();
23861 spec.placement.estrategia = estrategia;
23862 spec.placement.clusters = Vec::new();
23863 // Route the paired `:shard-key` spec-mutator through the typed
23864 // cross-slot invariant predicate
23865 // [`PlacementStrategy::requires_shard_key`] rather than the
23866 // [`gen_platform::IsVariant`]-derived
23867 // [`PlacementStrategy::is_sharded`] arm-identity predicate —
23868 // same discipline the sibling
23869 // `placement_strategy_variants_round_trip` and
23870 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
23871 // fixture builders now read through.
23872 spec.placement.shard_key = estrategia
23873 .requires_shard_key()
23874 .then(|| "tenantId".to_string());
23875 let err = spec.validate().unwrap_err();
23876 match err {
23877 AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
23878 assert_eq!(
23879 e,
23880 spec.placement.estrategia(),
23881 "PlacementWithoutClusters.estrategia must byte-equal \
23882 Placement::estrategia() — the error carrier reads \
23883 through the lifted accessor",
23884 );
23885 }
23886 other => panic!(
23887 "expected PlacementWithoutClusters, got {other:?} for \
23888 estrategia={estrategia:?}"
23889 ),
23890 }
23891 }
23892
23893 // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
23894 // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
23895 // must byte-equal the accessor's return for both non-`Sharded`
23896 // strategies.
23897 for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
23898 let mut spec = three_member_spec();
23899 spec.placement.estrategia = estrategia;
23900 spec.placement.shard_key = Some("tenantId".into());
23901 let err = spec.validate().unwrap_err();
23902 match err {
23903 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
23904 assert_eq!(
23905 e,
23906 spec.placement.estrategia(),
23907 "ShardKeyOnNonSharded.estrategia must byte-equal \
23908 Placement::estrategia() — the non-Sharded-arm \
23909 refusal reads through the lifted accessor",
23910 );
23911 }
23912 other => panic!(
23913 "expected ShardKeyOnNonSharded, got {other:?} for \
23914 estrategia={estrategia:?}"
23915 ),
23916 }
23917 }
23918 }
23919
23920 // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
23921 //
23922 // The [`Placement::clusters`] accessor lift is the second slice-return
23923 // (`&[T]`) accessor on any typed slot — sibling to the seed M2
23924 // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
23925 // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
23926 // below cover (1) the accessor's byte-equal projection against the raw
23927 // field access across the empty / singleton / cohort fixtures the
23928 // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
23929 // and the per-cluster validate loop fan between, and (2) the two-
23930 // consumer coherence of the paired pre-flight refusal probe and the
23931 // per-cluster validate loop routing through the accessor on both arms.
23932
23933 #[test]
23934 fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
23935 // The canonical per-`:placement` cluster-pool-scalar-shape pin:
23936 // [`Placement::clusters`] must return the `:placement :clusters`
23937 // typed `Vec<String>` verbatim as a `&[String]` slice-view over
23938 // the same backing buffer the raw `self.clusters.as_slice()`
23939 // field access borrows from, byte-equal across every
23940 // representative fixture in the accept-set — the empty slice
23941 // (the pre-validation sentinel every
23942 // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
23943 // the singleton slice (the minimal `SingleNode`-shape cohort),
23944 // and multi-entry cohorts (the peer `Replicated` / `Sharded`
23945 // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
23946 //
23947 // Pins against a future silent detour that returned
23948 // `&Vec<String>` (which would type-check but leak the storage-
23949 // side `Vec`'s grow/push/reserve surface no consumer of the
23950 // typed view reaches for), a fresh-allocated `Vec<String>` copy
23951 // (which would type-check via a coercion but silently break
23952 // every downstream caller that relied on the slice sharing the
23953 // backing buffer's identity), or an out-of-order or length-
23954 // drifted projection (which would silently split the paired
23955 // pre-flight `.is_empty()` refusal probe's input from the per-
23956 // cluster validate loop's traversal input).
23957 //
23958 // Peer of the sibling M2
23959 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23960 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23961 // `:supervisor` static-child-list axis, extended onto the M3
23962 // per-`:placement` distribution-target-list `Vec`-carry axis.
23963 let fixtures: Vec<Vec<String>> = vec![
23964 Vec::new(),
23965 vec!["rio".into()],
23966 vec!["rio".into(), "mar".into()],
23967 vec!["rio".into(), "mar".into(), "plo".into()],
23968 ];
23969 for clusters in fixtures {
23970 let p = Placement {
23971 clusters: clusters.clone(),
23972 ..Placement::default()
23973 };
23974 assert_eq!(
23975 p.clusters(),
23976 clusters.as_slice(),
23977 "Placement::clusters must return :placement :clusters \
23978 verbatim (got {:?}, expected {:?})",
23979 p.clusters(),
23980 clusters.as_slice(),
23981 );
23982 assert_eq!(
23983 p.clusters(),
23984 p.clusters.as_slice(),
23985 "Placement::clusters accessor and .clusters.as_slice() \
23986 field access must byte-equal — the accessor is the \
23987 substrate-primitive typed dispatch every downstream \
23988 cluster-pool consumer must route through",
23989 );
23990 assert_eq!(
23991 p.clusters().len(),
23992 p.clusters.len(),
23993 "Placement::clusters().len() must byte-equal \
23994 self.clusters.len() — a length-drift would silently \
23995 split the paired pre-flight `.is_empty()` refusal \
23996 probe input from the per-cluster validate loop's \
23997 traversal input",
23998 );
23999 }
24000 }
24001
24002 #[test]
24003 fn validate_placement_reads_through_lifted_clusters_accessor() {
24004 // Two-consumer coherence pin: the
24005 // [`AplicacaoSpec::validate_placement`] pre-flight
24006 // `self.placement.clusters().is_empty()` refusal probe (which
24007 // must trip [`AplicacaoError::PlacementWithoutClusters`] when
24008 // the accessor projects the empty slice) and the per-cluster
24009 // validate loop's `for c in self.placement.clusters()`
24010 // traversal (which must reach every entry in the same order
24011 // the accessor projects, so both the per-entry value-shape
24012 // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
24013 // and the duplicate-detection HashSet insert that trips
24014 // [`AplicacaoError::PlacementClusterDuplicate`] key off the
24015 // accessor's projection) must both key off the lifted
24016 // accessor, so any future rebrand on the typed slot's reader
24017 // shape lands at exactly one place. Pins the two-site
24018 // coherence by exercising each production consumer end-to-end:
24019 // (1) the `PlacementWithoutClusters` refusal under the empty
24020 // slice, (2) the `PlacementClusterInvalid` refusal fires on
24021 // the second entry of a two-cluster cohort whose head is
24022 // valid but tail is not (which requires the loop to reach the
24023 // second entry through the accessor), and (3) the
24024 // `PlacementClusterDuplicate` refusal fires on the second
24025 // entry of a two-cluster cohort that shares a name (which
24026 // requires the loop to reach both entries — a first-entry-only
24027 // projection would silently pass since the dedup HashSet has
24028 // room for the first insert).
24029 //
24030 // Peer of the sibling M2
24031 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
24032 // (bc92bce) coherence pin on the per-`:supervisor` static-
24033 // child-list axis, extended onto the M3 per-`:placement`
24034 // distribution-target-list `Vec`-carry axis.
24035
24036 // (1) Pre-flight `.is_empty()` probe: the empty slice must
24037 // trip `PlacementWithoutClusters`.
24038 let mut spec = three_member_spec();
24039 spec.placement.clusters = Vec::new();
24040 match spec.validate().unwrap_err() {
24041 AplicacaoError::PlacementWithoutClusters { .. } => {}
24042 other => panic!("expected PlacementWithoutClusters, got {other:?}"),
24043 }
24044 assert!(
24045 spec.placement.clusters().is_empty(),
24046 "the pre-flight refusal input must be the empty slice per \
24047 the accessor's projection",
24048 );
24049
24050 // (2) Per-cluster validate loop: a two-cluster cohort with an
24051 // invalid tail entry must trip `PlacementClusterInvalid` on
24052 // the tail — the loop must reach the second entry through
24053 // the accessor.
24054 let mut spec = three_member_spec();
24055 spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
24056 match spec.validate().unwrap_err() {
24057 AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
24058 assert_eq!(
24059 cluster, "BAD_CLUSTER",
24060 "PlacementClusterInvalid.cluster must carry the \
24061 tail entry the loop reached through the accessor",
24062 );
24063 }
24064 other => panic!("expected PlacementClusterInvalid, got {other:?}"),
24065 }
24066 assert_eq!(
24067 spec.placement.clusters().len(),
24068 2,
24069 "the per-cluster validate loop's traversal input must be \
24070 a two-element slice per the accessor's projection",
24071 );
24072
24073 // (3) Per-cluster validate loop: a two-cluster cohort that
24074 // shares a name must trip `PlacementClusterDuplicate` on the
24075 // second entry — the loop must reach both entries through the
24076 // accessor for the dedup HashSet's second insert to collide.
24077 let mut spec = three_member_spec();
24078 spec.placement.clusters = vec!["rio".into(), "rio".into()];
24079 match spec.validate().unwrap_err() {
24080 AplicacaoError::PlacementClusterDuplicate { cluster } => {
24081 assert_eq!(
24082 cluster, "rio",
24083 "PlacementClusterDuplicate.cluster must carry the \
24084 shared cluster name verbatim",
24085 );
24086 }
24087 other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
24088 }
24089 assert_eq!(
24090 spec.placement.clusters().len(),
24091 2,
24092 "the per-cluster validate loop's traversal input must be \
24093 a two-element slice per the accessor's projection",
24094 );
24095 }
24096
24097 #[test]
24098 fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
24099 // The canonical per-`:membros` member-list-slice-shape pin:
24100 // [`AplicacaoSpec::membros`] must return the `:membros` typed
24101 // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
24102 // same backing buffer the raw `self.membros.as_slice()` field
24103 // access borrows from, byte-equal across every representative
24104 // fixture in the accept-set — the empty slice (the pre-
24105 // validation sentinel every [`AplicacaoError::NoMembros`]
24106 // refusal keys off), the singleton slice (the minimal one-
24107 // Servico Aplicacao shape), and multi-entry cohorts (the peer
24108 // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
24109 // load-bearing identity of the application graph).
24110 //
24111 // Pins against a future silent detour that returned
24112 // `&Vec<Membro>` (which would type-check but leak the storage-
24113 // side `Vec`'s grow/push/reserve surface no consumer of the
24114 // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
24115 // (which would type-check via a coercion but silently break
24116 // every downstream caller that relied on the slice sharing the
24117 // backing buffer's identity), or an out-of-order or length-
24118 // drifted projection (which would silently split the paired
24119 // `HashSet<&str>` name-set seed's collect input from the
24120 // pre-flight `.is_empty()` refusal probe's input from the per-
24121 // member validate loop's traversal input from the
24122 // programs.yaml emitter's per-entry fan-out loop's input from
24123 // the `feira app graph` per-member print traversal's input).
24124 //
24125 // Peer of the sibling M2
24126 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
24127 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
24128 // `:supervisor` static-child-list axis and the sibling M3
24129 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
24130 // (a6e18d7) `&[String]` byte-equal pin on the per-
24131 // `:placement` distribution-target-list axis — extends the
24132 // slice-return-accessor byte-equal-projection discipline onto
24133 // the outermost M3 mesh-slot type's per-Aplicacao member-list
24134 // `Vec`-carry axis.
24135 let fixtures: Vec<Vec<Membro>> = vec![
24136 Vec::new(),
24137 vec![membro("catalog", "^0.1")],
24138 vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24139 vec![
24140 membro("catalog", "^0.1"),
24141 membro("cart", "^0.1"),
24142 membro("payment", "^0.2"),
24143 ],
24144 ];
24145 for membros in fixtures {
24146 let s = AplicacaoSpec {
24147 membros: membros.clone(),
24148 contratos: Vec::new(),
24149 politicas: MeshPolicy::default(),
24150 placement: Placement::default(),
24151 entrada: None,
24152 };
24153 assert_eq!(
24154 s.membros(),
24155 membros.as_slice(),
24156 "AplicacaoSpec::membros must return :membros verbatim \
24157 (got {:?}, expected {:?})",
24158 s.membros(),
24159 membros.as_slice(),
24160 );
24161 assert_eq!(
24162 s.membros(),
24163 s.membros.as_slice(),
24164 "AplicacaoSpec::membros accessor and .membros.as_slice() \
24165 field access must byte-equal — the accessor is the \
24166 substrate-primitive typed dispatch every downstream \
24167 member-list consumer must route through",
24168 );
24169 assert_eq!(
24170 s.membros().len(),
24171 s.membros.len(),
24172 "AplicacaoSpec::membros().len() must byte-equal \
24173 self.membros.len() — a length-drift would silently \
24174 split the paired `HashSet<&str>` name-set seed's \
24175 collect input from the pre-flight `.is_empty()` \
24176 refusal probe input from the per-member validate \
24177 loop's traversal input",
24178 );
24179 }
24180 }
24181
24182 #[test]
24183 fn validate_reads_through_lifted_membros_accessor() {
24184 // Three-consumer coherence pin: the
24185 // [`AplicacaoSpec::validate_membros`] pre-flight
24186 // `self.membros().is_empty()` refusal probe (which must trip
24187 // [`AplicacaoError::NoMembros`] when the accessor projects the
24188 // empty slice), the same method's per-member validate loop's
24189 // `for m in self.membros()` traversal (which must reach every
24190 // entry in the same order the accessor projects, so both the
24191 // per-entry empty-`:caixa` gate that trips
24192 // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
24193 // detection `insert_first_seen` that trips
24194 // [`AplicacaoError::MembroDuplicate`] key off the accessor's
24195 // projection), and the peer [`AplicacaoSpec::validate`]'s
24196 // `HashSet<&str>` name-set seed's
24197 // `self.membros().iter().map(Membro::nome).collect()` collect
24198 // input (which every `:contratos` `:de` / `:para` membership
24199 // lookup rejects an unknown name against) must all three key
24200 // off the lifted accessor, so any future rebrand on the typed
24201 // slot's reader shape lands at exactly one place. Pins the
24202 // three-site coherence by exercising each production consumer
24203 // end-to-end: (1) the `NoMembros` refusal under the empty
24204 // slice, (2) the `MembroCaixaEmpty` refusal fires on the
24205 // second entry of a two-member cohort whose head is valid but
24206 // tail has an empty `:caixa` (which requires the loop to
24207 // reach the second entry through the accessor), and (3) the
24208 // `MembroDuplicate` refusal fires on the second entry of a
24209 // two-member cohort that shares a `:caixa` name (which
24210 // requires the loop to reach both entries through the
24211 // accessor for the dedup HashSet's second insert to collide).
24212 //
24213 // Peer of the sibling M2
24214 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
24215 // (bc92bce) coherence pin on the per-`:supervisor` static-
24216 // child-list axis and the sibling M3
24217 // `validate_placement_reads_through_lifted_clusters_accessor`
24218 // (a6e18d7) coherence pin on the per-`:placement` distribution-
24219 // target-list axis — extends the slice-return-accessor
24220 // multi-consumer coherence discipline onto the outermost M3
24221 // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
24222
24223 // (1) Pre-flight `.is_empty()` probe: the empty slice must
24224 // trip `NoMembros`.
24225 let mut spec = three_member_spec();
24226 spec.membros = Vec::new();
24227 assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
24228 assert!(
24229 spec.membros().is_empty(),
24230 "the pre-flight refusal input must be the empty slice per \
24231 the accessor's projection",
24232 );
24233
24234 // (2) Per-member validate loop: a two-member cohort with an
24235 // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
24236 // the tail — the loop must reach the second entry through
24237 // the accessor.
24238 let mut spec = three_member_spec();
24239 spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
24240 assert_eq!(
24241 spec.validate().unwrap_err(),
24242 AplicacaoError::MembroCaixaEmpty,
24243 );
24244 assert_eq!(
24245 spec.membros().len(),
24246 2,
24247 "the per-member validate loop's traversal input must be \
24248 a two-element slice per the accessor's projection",
24249 );
24250
24251 // (3) Per-member validate loop: a two-member cohort that
24252 // shares a `:caixa` name must trip `MembroDuplicate` on the
24253 // second entry — the loop must reach both entries through the
24254 // accessor for the dedup HashSet's second insert to collide.
24255 let mut spec = three_member_spec();
24256 spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
24257 match spec.validate().unwrap_err() {
24258 AplicacaoError::MembroDuplicate { caixa } => {
24259 assert_eq!(
24260 caixa, "catalog",
24261 "MembroDuplicate.caixa must carry the shared \
24262 member name verbatim",
24263 );
24264 }
24265 other => panic!("expected MembroDuplicate, got {other:?}"),
24266 }
24267 assert_eq!(
24268 spec.membros().len(),
24269 2,
24270 "the per-member validate loop's traversal input must be \
24271 a two-element slice per the accessor's projection",
24272 );
24273 }
24274
24275 #[test]
24276 fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
24277 // The canonical per-`:contratos` contract-list-slice-shape pin:
24278 // [`AplicacaoSpec::contratos`] must return the `:contratos`
24279 // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
24280 // slice-view over the same backing buffer the raw
24281 // `self.contratos.as_slice()` field access borrows from, byte-
24282 // equal across every representative fixture in the accept-set —
24283 // the empty slice (the pre-validation "internal-only mesh" shape
24284 // an Aplicacao whose members exchange no typed edges renders
24285 // through), the singleton slice (the minimal one-edge Aplicacao
24286 // shape), and multi-entry cohorts (the peer multi-edge shapes
24287 // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
24288 // of the application graph).
24289 //
24290 // Pins against a future silent detour that returned
24291 // `&Vec<WitContract>` (which would type-check but leak the
24292 // storage-side `Vec`'s grow/push/reserve surface no consumer of
24293 // the typed view reaches for), a fresh-allocated
24294 // `Vec<WitContract>` copy (which would type-check via a coercion
24295 // but silently break every downstream caller that relied on the
24296 // slice sharing the backing buffer's identity), or an out-of-
24297 // order or length-drifted projection (which would silently split
24298 // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
24299 // seed's traversal input from the `detect_sync_cycles` per-edge
24300 // adjacency-list seed's traversal input from the
24301 // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
24302 // BTreeMap grouping loop's traversal input from the
24303 // `feira app graph` per-contract print traversal's input).
24304 //
24305 // Peer of the immediately-adjacent sibling M3
24306 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
24307 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
24308 // node-list axis, the sibling M3
24309 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
24310 // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
24311 // distribution-target-list axis, and the sibling M2
24312 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
24313 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
24314 // `:supervisor` static-child-list axis — extends the slice-
24315 // return-accessor byte-equal-projection discipline onto the
24316 // outermost M3 mesh-slot type's per-Aplicacao contract-list
24317 // `Vec`-carry axis, closing the last unlifted per-
24318 // `AplicacaoSpec` `Vec`-carry axis.
24319 let fixtures: Vec<Vec<WitContract>> = vec![
24320 Vec::new(),
24321 vec![contract_http("cart", "catalog", "/products/:id")],
24322 vec![
24323 contract_http("cart", "catalog", "/products/:id"),
24324 contract_http("cart", "payment", "/charge"),
24325 ],
24326 vec![
24327 contract_http("cart", "catalog", "/products/:id"),
24328 contract_http("cart", "payment", "/charge"),
24329 contract_http("payment", "catalog", "/audit"),
24330 ],
24331 ];
24332 for contratos in fixtures {
24333 let s = AplicacaoSpec {
24334 membros: vec![
24335 membro("catalog", "^0.1"),
24336 membro("cart", "^0.1"),
24337 membro("payment", "^0.2"),
24338 ],
24339 contratos: contratos.clone(),
24340 politicas: MeshPolicy::default(),
24341 placement: Placement::default(),
24342 entrada: None,
24343 };
24344 assert_eq!(
24345 s.contratos(),
24346 contratos.as_slice(),
24347 "AplicacaoSpec::contratos must return :contratos verbatim \
24348 (got {:?}, expected {:?})",
24349 s.contratos(),
24350 contratos.as_slice(),
24351 );
24352 assert_eq!(
24353 s.contratos(),
24354 s.contratos.as_slice(),
24355 "AplicacaoSpec::contratos accessor and \
24356 .contratos.as_slice() field access must byte-equal — \
24357 the accessor is the substrate-primitive typed dispatch \
24358 every downstream contract-list consumer must route \
24359 through",
24360 );
24361 assert_eq!(
24362 s.contratos().len(),
24363 s.contratos.len(),
24364 "AplicacaoSpec::contratos().len() must byte-equal \
24365 self.contratos.len() — a length-drift would silently \
24366 split the paired per-edge validate-loop's traversal \
24367 input from the sync-cycle adjacency-list seed's \
24368 traversal input from the cilium_network_policies \
24369 per-`(:de, :para)` BTreeMap grouping loop's traversal \
24370 input from the `feira app graph` per-contract print \
24371 traversal's input",
24372 );
24373 }
24374 }
24375
24376 #[test]
24377 fn validate_reads_through_lifted_contratos_accessor() {
24378 // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
24379 // per-`:contratos` validate-loop's `for c in self.contratos()`
24380 // traversal (which must reach every entry in the same order the
24381 // accessor projects, so both the per-entry
24382 // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
24383 // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
24384 // dedup `HashSet` insert key off the accessor's projection),
24385 // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
24386 // `for c in self.contratos()` adjacency-list seed (which drives
24387 // the sync-subgraph deadlock-detection gate via
24388 // [`AplicacaoError::SyncCycle`]), and the peer
24389 // [`caixa_mesh::cilium_network_policies`]'s
24390 // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
24391 // grouping loop (which drives the per-CNP fan-out) must all
24392 // three key off the lifted accessor, so any future rebrand on
24393 // the typed slot's reader shape lands at exactly one place. Pins
24394 // the three-site coherence by exercising the two caixa-core
24395 // production consumers end-to-end: (1) the empty-`:contratos`
24396 // slice must validate without a per-edge diagnostic (the
24397 // per-edge loop is a no-op under the empty projection), (2) the
24398 // `ContratoMemberMissing` refusal fires on the second entry of a
24399 // two-edge cohort whose head references a valid member but tail
24400 // references a phantom name (which requires the loop to reach
24401 // the second entry through the accessor), and (3) the
24402 // `SyncCycle` refusal fires on a self-referential two-edge
24403 // cohort through the sync-cycle detector's peer projection
24404 // (which requires the detector to iterate the accessor's
24405 // projection to add the back-edge to its adjacency list).
24406 //
24407 // Peer of the sibling M3
24408 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24409 // three-consumer coherence pin on the per-`:membros` node-list
24410 // axis and the sibling M3
24411 // `validate_placement_reads_through_lifted_clusters_accessor`
24412 // (a6e18d7) coherence pin on the per-`:placement` distribution-
24413 // target-list axis — extends the slice-return-accessor multi-
24414 // consumer coherence discipline onto the outermost M3 mesh-slot
24415 // type's per-Aplicacao contract-list `Vec`-carry axis.
24416
24417 // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
24418 // and no per-edge diagnostic surfaces. Validate succeeds on
24419 // the well-formed `:membros` head.
24420 let mut spec = three_member_spec();
24421 spec.contratos = Vec::new();
24422 assert!(
24423 spec.validate().is_ok(),
24424 "empty :contratos must validate — the per-edge loop is a \
24425 no-op under the accessor's empty projection",
24426 );
24427 assert!(
24428 spec.contratos().is_empty(),
24429 "the per-edge validate loop's traversal input must be the \
24430 empty slice per the accessor's projection",
24431 );
24432
24433 // (2) Per-edge validate loop: a two-edge cohort whose tail
24434 // references a phantom `:para` member must trip
24435 // `ContratoMemberMissing` on the tail — the loop must reach
24436 // the second entry through the accessor for the membership
24437 // lookup to fail on the phantom name.
24438 let mut spec = three_member_spec();
24439 spec.contratos = vec![
24440 contract_http("cart", "catalog", "/products/:id"),
24441 contract_http("cart", "phantom", "/x"),
24442 ];
24443 let err = spec.validate().unwrap_err();
24444 assert!(
24445 matches!(
24446 err,
24447 AplicacaoError::ContratoMemberMissing { ref caixa }
24448 if caixa == "phantom"
24449 ),
24450 "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
24451 );
24452 assert_eq!(
24453 spec.contratos().len(),
24454 2,
24455 "the per-edge validate loop's traversal input must be \
24456 a two-element slice per the accessor's projection",
24457 );
24458
24459 // (3) Sync-cycle detector: a two-edge synchronous cohort
24460 // whose second edge closes the sync-subgraph back onto the
24461 // first must trip [`AplicacaoError::ContratoCycle`] — the
24462 // detector must iterate the accessor's projection to add
24463 // both edges to its adjacency list, so a length-drift on
24464 // the accessor's projection would silently disagree with
24465 // the sync-cycle detector on which edge closes the loop.
24466 // Peer projection to the `validate` per-edge loop above:
24467 // the sync-cycle detector routes through the same lifted
24468 // accessor, so a rebrand of the reader shape lands at one
24469 // place. Uses a two-edge cohort (cart → catalog → cart)
24470 // because the per-edge `ContratoSelfLoop` gate fires before
24471 // the sync-cycle detector on a single self-referential edge
24472 // (`cart → cart`) — the cycle-detector's input must be a
24473 // multi-edge cohort for its per-edge traversal input to be
24474 // observably wider than the per-edge validate loop's input.
24475 let mut spec = three_member_spec();
24476 spec.contratos = vec![
24477 contract_http("cart", "catalog", "/products/:id"),
24478 contract_http("catalog", "cart", "/callback"),
24479 ];
24480 let err = spec.validate().unwrap_err();
24481 assert!(
24482 matches!(err, AplicacaoError::ContratoCycle { .. }),
24483 "expected ContratoCycle from the sync-cycle detector on a \
24484 two-edge back-edge cohort, got {err:?}",
24485 );
24486 assert_eq!(
24487 spec.contratos().len(),
24488 2,
24489 "the sync-cycle detector's traversal input must be a \
24490 two-element slice per the accessor's projection",
24491 );
24492 }
24493
24494 #[test]
24495 fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
24496 // The canonical per-`:politicas` outer-composite-reference-shape
24497 // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
24498 // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
24499 // the same backing storage the raw `&self.politicas` field
24500 // access borrows from, byte-equal across every representative
24501 // fixture in the accept-set — the default `MeshPolicy` (the
24502 // author-empty "no policy on any axis" shape whose
24503 // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
24504 // shapes carrying one axis at a time
24505 // (`{mtls_required, timeout, retries, circuit_breaker,
24506 // rate_limit}` — the minimal five-axis fan-out over the
24507 // per-axis lifted accessor family every downstream mesh-artifact
24508 // emitter dispatches on), and the multi-axis composite (the
24509 // canonical `three_member_spec` fixture's `{timeout, retries,
24510 // mtls_required}` triple — the load-bearing shape every
24511 // Aplicacao-scoped fixture in this suite constructs).
24512 //
24513 // Pins against a future silent detour that returned a fresh-
24514 // cloned `MeshPolicy` copy (which would type-check via a `Clone`
24515 // impl but silently break every downstream caller that relied
24516 // on the reference sharing the composite's backing identity), a
24517 // reference to an operator-resolved overlay (the future
24518 // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
24519 // acknowledges — its resolution must land at exactly this
24520 // accessor body, not silently divert the raw slot away from a
24521 // second consumer), or an axis-shuffled projection (a future
24522 // detour that swapped `timeout` and `retries` through the
24523 // accessor would silently split the paired `validate_politicas`
24524 // per-axis bracket-dispatch's traversal input from the peer
24525 // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
24526 // emitter's fan-out input from the peer
24527 // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
24528 // overlay emitter's fan-out input).
24529 //
24530 // Peer of the sibling M3
24531 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
24532 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
24533 // node-list `Vec`-carry axis and the sibling M3
24534 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
24535 // (0dcc926) `&[WitContract]` byte-equal pin on the per-
24536 // `:contratos` edge-list `Vec`-carry axis — extends the outer-
24537 // accessor byte-equal-projection discipline onto the outermost
24538 // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
24539 // reference axis, the first `&Composite`-return accessor on the
24540 // outer [`AplicacaoSpec`] type.
24541 let fixtures: Vec<MeshPolicy> = vec![
24542 MeshPolicy::default(),
24543 MeshPolicy {
24544 mtls_required: Some(true),
24545 ..MeshPolicy::default()
24546 },
24547 MeshPolicy {
24548 mtls_required: Some(false),
24549 ..MeshPolicy::default()
24550 },
24551 MeshPolicy {
24552 timeout: Some(Duration::from_secs(30)),
24553 ..MeshPolicy::default()
24554 },
24555 MeshPolicy {
24556 retries: Some(3),
24557 ..MeshPolicy::default()
24558 },
24559 MeshPolicy {
24560 circuit_breaker: Some(CircuitBreaker {
24561 max_failures: 5,
24562 window: Duration::from_secs(30),
24563 }),
24564 ..MeshPolicy::default()
24565 },
24566 MeshPolicy {
24567 rate_limit: Some(RateLimit {
24568 rate: 100,
24569 window: Duration::from_secs(1),
24570 }),
24571 ..MeshPolicy::default()
24572 },
24573 MeshPolicy {
24574 timeout: Some(Duration::from_secs(30)),
24575 retries: Some(3),
24576 mtls_required: Some(true),
24577 ..MeshPolicy::default()
24578 },
24579 ];
24580 for politicas in fixtures {
24581 let s = AplicacaoSpec {
24582 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24583 contratos: Vec::new(),
24584 politicas: politicas.clone(),
24585 placement: Placement::default(),
24586 entrada: None,
24587 };
24588 assert_eq!(
24589 *s.politicas(),
24590 politicas,
24591 "AplicacaoSpec::politicas must return :politicas verbatim \
24592 (got {:?}, expected {:?})",
24593 s.politicas(),
24594 politicas,
24595 );
24596 assert!(
24597 std::ptr::eq(s.politicas(), &s.politicas),
24598 "AplicacaoSpec::politicas accessor and &self.politicas \
24599 field access must borrow the same backing storage — \
24600 the accessor is the substrate-primitive typed dispatch \
24601 every downstream mesh-policy composite consumer must \
24602 route through, and a reference-identity split would \
24603 silently break every consumer that relied on the \
24604 borrow sharing the composite's storage",
24605 );
24606 assert_eq!(
24607 s.politicas().is_empty(),
24608 s.politicas.is_empty(),
24609 "AplicacaoSpec::politicas().is_empty() must byte-equal \
24610 self.politicas.is_empty() — an emptiness-drift would \
24611 silently split the paired `validate_politicas` \
24612 per-axis bracket-dispatch's seed from the peer \
24613 caixa-mesh CNP mTLS-overlay emitter's key from the \
24614 peer caixa-mesh HTTPRoute timeout+retry overlay \
24615 emitter's key",
24616 );
24617 }
24618 }
24619
24620 #[test]
24621 fn validate_politicas_reads_through_lifted_politicas_accessor() {
24622 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24623 // per-axis bracket-dispatch seed (`let p = self.politicas();`,
24624 // followed by the per-axis fan-out `p.timeout()` /
24625 // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
24626 // the lifted axis-level accessor family) must key off the
24627 // lifted outer accessor, so any future rebrand on the typed
24628 // slot's outer-composite reader shape lands at exactly one
24629 // place. Pins the multi-axis coherence by exercising each
24630 // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
24631 // a `Some(Duration::ZERO)` timeout under the outer accessor's
24632 // reference projection, (2) `PolicyRetriesZero` fires on a
24633 // `Some(0)` retries under the same projection, and (3) an
24634 // empty [`MeshPolicy::default`] passes `validate_politicas` —
24635 // the outer accessor's reference-projection reaches every
24636 // per-axis branch without silently short-circuiting any.
24637 //
24638 // Peer of the sibling M3
24639 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24640 // three-consumer coherence pin on the per-`:membros` node-list
24641 // axis and the sibling M3
24642 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24643 // three-consumer coherence pin on the per-`:contratos`
24644 // edge-list axis — extends the multi-consumer coherence
24645 // discipline onto the outermost M3 mesh-slot type's per-
24646 // Aplicacao mesh-policy composite-reference axis, the first
24647 // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
24648 // type.
24649
24650 // (1) `PolicyTimeoutZero` refusal under the outer accessor's
24651 // reference projection: a `Some(Duration::ZERO)` timeout must
24652 // trip the zero-floor gate. The bracket-dispatch's first arm
24653 // reads `p.timeout()` on the reference returned by the outer
24654 // accessor.
24655 let mut spec = three_member_spec();
24656 spec.politicas.timeout = Some(Duration::ZERO);
24657 spec.politicas.retries = None;
24658 spec.politicas.circuit_breaker = None;
24659 spec.politicas.rate_limit = None;
24660 assert_eq!(
24661 spec.validate().unwrap_err(),
24662 AplicacaoError::PolicyTimeoutZero,
24663 );
24664 assert!(
24665 std::ptr::eq(spec.politicas(), &spec.politicas),
24666 "the `validate_politicas` per-axis bracket-dispatch's \
24667 traversal input must be the same backing composite the \
24668 accessor's reference projection borrows from",
24669 );
24670
24671 // (2) `PolicyRetriesZero` refusal under the outer accessor's
24672 // reference projection: a `Some(0)` retries must trip the
24673 // zero-floor gate. The bracket-dispatch's second arm reads
24674 // `p.retries()` on the reference returned by the outer accessor.
24675 let mut spec = three_member_spec();
24676 spec.politicas.timeout = None;
24677 spec.politicas.retries = Some(0);
24678 spec.politicas.circuit_breaker = None;
24679 spec.politicas.rate_limit = None;
24680 assert_eq!(
24681 spec.validate().unwrap_err(),
24682 AplicacaoError::PolicyRetriesZero,
24683 );
24684
24685 // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
24686 // — every per-axis arm short-circuits on `None`, so the outer
24687 // accessor's reference projection reaches the fall-through
24688 // `Ok(())` without any per-axis refusal firing.
24689 let mut spec = three_member_spec();
24690 spec.politicas = MeshPolicy::default();
24691 assert!(
24692 spec.validate().is_ok(),
24693 "an empty `MeshPolicy` must pass `validate_politicas` — \
24694 every per-axis arm short-circuits on `None` under the \
24695 outer accessor's reference projection",
24696 );
24697 assert!(
24698 spec.politicas().is_empty(),
24699 "the outer accessor's reference projection must be the \
24700 empty composite per the `MeshPolicy::default()` fixture",
24701 );
24702 }
24703
24704 #[test]
24705 #[allow(clippy::too_many_lines)]
24706 fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
24707 // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24708 // per-axis bracket-dispatch's `:timeout` and `:retries` arms
24709 // must both key off the lifted axis-level accessors
24710 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
24711 // the peer `:circuit-breaker` / `:rate-limit` arms already
24712 // routing through [`MeshPolicy::circuit_breaker`] /
24713 // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
24714 // per axis on the substrate primitive" shape at the fan-out
24715 // (four axes, four accessors, no raw-field-access site
24716 // anywhere on the bracket-dispatch). Pins the per-axis
24717 // coherence at the accept-set boundaries the bracket carves:
24718 // 1. accessor byte-equal to raw field on every representative
24719 // accept-set value (`None`, sub-cap, at-cap, past-cap
24720 // sentinel) — a future accessor drift that no longer
24721 // shipped the raw slot verbatim would surface here,
24722 // 2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
24723 // routed through the accessor's projection, proving the
24724 // first arm reads through the accessor rather than a
24725 // silent-detour peer-axis field access,
24726 // 3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
24727 // through the accessor's projection, proving the second
24728 // arm reads through the accessor,
24729 // 4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
24730 // passes validate under the accessor projection (paired
24731 // with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
24732 // sibling axis), pinning the upper-boundary accept-arm
24733 // also routes through the accessor.
24734 //
24735 // Peer of the sibling M3
24736 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24737 // outer-composite-reference coherence pin (which asserts the
24738 // `let p = self.politicas()` seed); extends the discipline onto
24739 // the per-axis fan-out layer that consumes the seed's
24740 // reference. Same shape as
24741 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24742 // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24743 // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
24744 // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
24745
24746 // (1) Accessor byte-equal to raw field on the `:timeout` axis
24747 // across the accept-set boundaries the bracket dispatch's
24748 // three-arm gate carves out
24749 // ([`crate::render::require_positive_canonical_bounded_duration`]
24750 // — zero-floor + canonical-form + upper-cap).
24751 for timeout in [
24752 None,
24753 Some(Duration::ZERO),
24754 Some(Duration::from_millis(1)),
24755 Some(POLICY_TIMEOUT_MAX),
24756 ] {
24757 let p = MeshPolicy {
24758 timeout,
24759 ..MeshPolicy::default()
24760 };
24761 assert_eq!(
24762 p.timeout(),
24763 p.timeout,
24764 "MeshPolicy::timeout accessor must byte-equal the raw \
24765 .timeout field across every accept-set boundary the \
24766 validate_politicas :timeout arm carves out — a drift \
24767 here would silently split the validate bracket's arm \
24768 from the peer caixa-mesh HTTPRoute timeout-overlay \
24769 emitter's read",
24770 );
24771 }
24772
24773 // (2) Accessor byte-equal to raw field on the `:retries` axis
24774 // across the accept-set boundaries the bracket dispatch's
24775 // two-arm gate carves out
24776 // ([`crate::render::require_positive_bounded_u32`] — zero-floor
24777 // + upper-cap).
24778 for retries in [
24779 None,
24780 Some(0u32),
24781 Some(1u32),
24782 Some(POLICY_RETRIES_MAX),
24783 Some(POLICY_RETRIES_MAX + 1),
24784 Some(u32::MAX),
24785 ] {
24786 let p = MeshPolicy {
24787 retries,
24788 ..MeshPolicy::default()
24789 };
24790 assert_eq!(
24791 p.retries(),
24792 p.retries,
24793 "MeshPolicy::retries accessor must byte-equal the raw \
24794 .retries field across every accept-set boundary the \
24795 validate_politicas :retries arm carves out — a drift \
24796 here would silently split the validate bracket's arm \
24797 from the peer caixa-mesh HTTPRoute retry-overlay \
24798 emitter's read",
24799 );
24800 }
24801
24802 // (3) `PolicyTimeoutZero` fires on the accessor-projected
24803 // zero-floor boundary. A silent detour that no longer read
24804 // through `p.timeout()` (a peer-axis field read, an accidental
24805 // Option::and-then chain that collapsed the None arm to Some,
24806 // an accessor rebrand that clamped the return through the
24807 // upper cap) would fail to refuse here.
24808 let mut spec = three_member_spec();
24809 spec.politicas.timeout = Some(Duration::ZERO);
24810 spec.politicas.retries = None;
24811 spec.politicas.circuit_breaker = None;
24812 spec.politicas.rate_limit = None;
24813 assert_eq!(
24814 spec.politicas().timeout(),
24815 Some(Duration::ZERO),
24816 "the accessor projection must reflect the fixture's \
24817 `Some(Duration::ZERO)` :timeout verbatim",
24818 );
24819 assert_eq!(
24820 spec.validate().unwrap_err(),
24821 AplicacaoError::PolicyTimeoutZero,
24822 "the validate_politicas :timeout zero-floor arm must fire \
24823 through the lifted accessor's projection — a silent \
24824 detour to a peer-axis field would fail to refuse",
24825 );
24826
24827 // (4) `PolicyRetriesZero` fires on the accessor-projected
24828 // zero-floor boundary on the sibling `:retries` axis.
24829 let mut spec = three_member_spec();
24830 spec.politicas.timeout = None;
24831 spec.politicas.retries = Some(0);
24832 spec.politicas.circuit_breaker = None;
24833 spec.politicas.rate_limit = None;
24834 assert_eq!(
24835 spec.politicas().retries(),
24836 Some(0),
24837 "the accessor projection must reflect the fixture's \
24838 `Some(0)` :retries verbatim",
24839 );
24840 assert_eq!(
24841 spec.validate().unwrap_err(),
24842 AplicacaoError::PolicyRetriesZero,
24843 "the validate_politicas :retries zero-floor arm must fire \
24844 through the lifted accessor's projection — a silent \
24845 detour to a peer-axis field would fail to refuse",
24846 );
24847
24848 // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
24849 // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
24850 // must pass validate under the accessor projection — pins the
24851 // upper-boundary accept-arm also routes through the lifted
24852 // accessor (a drift that clamped or short-circuited at the
24853 // upper boundary would fail the whole-spec validate here).
24854 let mut spec = three_member_spec();
24855 spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
24856 spec.politicas.retries = Some(POLICY_RETRIES_MAX);
24857 spec.politicas.circuit_breaker = None;
24858 spec.politicas.rate_limit = None;
24859 assert_eq!(
24860 spec.politicas().timeout(),
24861 Some(POLICY_TIMEOUT_MAX),
24862 "the accessor projection must reflect the fixture's \
24863 at-cap :timeout verbatim",
24864 );
24865 assert_eq!(
24866 spec.politicas().retries(),
24867 Some(POLICY_RETRIES_MAX),
24868 "the accessor projection must reflect the fixture's \
24869 at-cap :retries verbatim",
24870 );
24871 assert!(
24872 spec.validate().is_ok(),
24873 "at-cap :timeout + :retries must pass validate under the \
24874 accessor projection — the upper-boundary accept-arm on \
24875 both axes routes through the lifted accessor",
24876 );
24877 }
24878
24879 #[test]
24880 fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
24881 // The canonical per-`:placement` outer-composite-reference-shape
24882 // pin: [`AplicacaoSpec::placement`] must return the `:placement`
24883 // typed `Placement` verbatim as a `&Placement` reference over the
24884 // same backing storage the raw `&self.placement` field access
24885 // borrows from, byte-equal across every representative fixture in
24886 // the accept-set — the default `Placement` (the substrate seed
24887 // shape whose [`PlacementStrategy::default`] evaluates to
24888 // `SingleNode` with an empty `:clusters` pool and both
24889 // optional-scalar axes `None`), and every canonical strategy /
24890 // cluster-pool / optional-scalar combination the
24891 // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
24892 // three [`PlacementStrategy`] variants — `SingleNode`,
24893 // `Replicated`, `Sharded` — cross-projected with a non-empty
24894 // `:clusters` pool and, on the `Sharded` arm, a non-empty
24895 // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
24896 // canonical `three_member_spec` `Replicated` fixture's
24897 // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
24898 //
24899 // Pins against a future silent detour that returned a fresh-
24900 // cloned `Placement` copy (which would type-check via a `Clone`
24901 // impl but silently break every downstream caller that relied on
24902 // the reference sharing the composite's backing identity), a
24903 // reference to an operator-resolved overlay (the future per-
24904 // cluster `:placement-overrides` slot MESH-COMPOSITION §V
24905 // acknowledges — its resolution must land at exactly this
24906 // accessor body, not silently divert the raw slot away from a
24907 // second consumer), or an axis-shuffled projection (a future
24908 // detour that swapped `clusters` and `affinity` through the
24909 // accessor would silently split the paired `validate_placement`
24910 // per-axis bracket-dispatch's traversal input from the peer
24911 // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
24912 // programs.yaml distribution-annotation emitter's fan-out input
24913 // from the peer `feira app graph` per-Aplicacao print line's
24914 // input).
24915 //
24916 // Peer of the sibling M3
24917 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24918 // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
24919 // outer mesh-policy composite-reference axis, and of the sibling
24920 // slice-return `aplicacao_spec_membros_returns_membros_slice_
24921 // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
24922 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
24923 // across_permutations` (0dcc926) `&[WitContract]` pins — extends
24924 // the outer-accessor byte-equal-projection discipline onto the
24925 // outermost M3 mesh-slot type's per-Aplicacao distribution
24926 // composite-reference axis, the second `&Composite`-return
24927 // accessor on the outer [`AplicacaoSpec`] type.
24928 let fixtures: Vec<Placement> = vec![
24929 Placement::default(),
24930 Placement {
24931 estrategia: PlacementStrategy::SingleNode,
24932 clusters: vec!["rio".into()],
24933 affinity: None,
24934 shard_key: None,
24935 },
24936 Placement {
24937 estrategia: PlacementStrategy::Replicated,
24938 clusters: vec!["rio".into(), "mar".into()],
24939 affinity: None,
24940 shard_key: None,
24941 },
24942 Placement {
24943 estrategia: PlacementStrategy::Replicated,
24944 clusters: vec!["rio".into(), "mar".into()],
24945 affinity: Some("data-locality".into()),
24946 shard_key: None,
24947 },
24948 Placement {
24949 estrategia: PlacementStrategy::Sharded,
24950 clusters: vec!["rio".into(), "mar".into()],
24951 affinity: None,
24952 shard_key: Some("tenantId".into()),
24953 },
24954 Placement {
24955 estrategia: PlacementStrategy::Sharded,
24956 clusters: vec!["rio".into(), "mar".into(), "sol".into()],
24957 affinity: Some("low-latency".into()),
24958 shard_key: Some("metadata.tenantId".into()),
24959 },
24960 ];
24961 for placement in fixtures {
24962 let s = AplicacaoSpec {
24963 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24964 contratos: Vec::new(),
24965 politicas: MeshPolicy::default(),
24966 placement: placement.clone(),
24967 entrada: None,
24968 };
24969 assert_eq!(
24970 *s.placement(),
24971 placement,
24972 "AplicacaoSpec::placement must return :placement verbatim \
24973 (got {:?}, expected {:?})",
24974 s.placement(),
24975 placement,
24976 );
24977 assert!(
24978 std::ptr::eq(s.placement(), &s.placement),
24979 "AplicacaoSpec::placement accessor and &self.placement \
24980 field access must borrow the same backing storage — the \
24981 accessor is the substrate-primitive typed dispatch every \
24982 downstream distribution-composite consumer must route \
24983 through, and a reference-identity split would silently \
24984 break every consumer that relied on the borrow sharing \
24985 the composite's storage",
24986 );
24987 assert_eq!(
24988 s.placement().estrategia(),
24989 s.placement.estrategia,
24990 "AplicacaoSpec::placement().estrategia() must byte-equal \
24991 self.placement.estrategia — a strategy-drift would \
24992 silently split the paired `validate_placement` \
24993 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
24994 peer caixa-mesh programs.yaml `placement.estrategia` \
24995 emitter's key from the peer `feira app graph` printer's \
24996 strategy label",
24997 );
24998 assert_eq!(
24999 s.placement().clusters(),
25000 s.placement.clusters.as_slice(),
25001 "AplicacaoSpec::placement().clusters() must byte-equal \
25002 self.placement.clusters — a cluster-pool drift would \
25003 silently split the paired `validate_placement` \
25004 pre-flight `.is_empty()` refusal probe's traversal from \
25005 the peer caixa-mesh programs.yaml `placement.clusters` \
25006 emitter's fan-out from the peer `feira app graph` \
25007 printer's cluster list",
25008 );
25009 }
25010 }
25011
25012 #[test]
25013 fn validate_placement_reads_through_lifted_placement_accessor() {
25014 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
25015 // per-axis bracket-dispatch seed (`let p = self.placement();`,
25016 // followed by the per-axis fan-out `p.clusters()` /
25017 // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
25018 // lifted axis-level accessor family) must key off the lifted
25019 // outer accessor, so any future rebrand on the typed slot's
25020 // outer-composite reader shape lands at exactly one place. Pins
25021 // the multi-axis coherence by exercising each per-axis refusal
25022 // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
25023 // `:clusters` pool under the outer accessor's reference
25024 // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
25025 // strategy with a `None` `:shard-key` under the same projection,
25026 // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
25027 // with a `Some` `:shard-key` under the same projection, and
25028 // (4) the canonical `three_member_spec` `Replicated` fixture
25029 // passes `validate_placement` under the outer accessor's
25030 // reference projection — the accessor's reference-projection
25031 // reaches every per-axis branch (cluster-pool refusal, `Sharded`
25032 // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
25033 // without silently short-circuiting any.
25034 //
25035 // Peer of the sibling M3
25036 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
25037 // (534dc21) multi-axis coherence pin on the per-`:politicas`
25038 // outer mesh-policy composite-reference axis — extends the
25039 // multi-consumer coherence discipline onto the outermost M3
25040 // mesh-slot type's per-Aplicacao distribution composite-
25041 // reference axis, the second `&Composite`-return accessor on
25042 // the outer [`AplicacaoSpec`] type.
25043
25044 // (1) `PlacementWithoutClusters` refusal under the outer
25045 // accessor's reference projection: an empty `:clusters` pool
25046 // must trip the pre-flight refusal probe. The bracket-dispatch's
25047 // first arm reads `p.clusters()` on the reference returned by
25048 // the outer accessor.
25049 let mut spec = three_member_spec();
25050 spec.placement.clusters = Vec::new();
25051 assert_eq!(
25052 spec.validate().unwrap_err(),
25053 AplicacaoError::PlacementWithoutClusters {
25054 estrategia: PlacementStrategy::Replicated,
25055 },
25056 );
25057 assert!(
25058 std::ptr::eq(spec.placement(), &spec.placement),
25059 "the `validate_placement` per-axis bracket-dispatch's \
25060 traversal input must be the same backing composite the \
25061 accessor's reference projection borrows from",
25062 );
25063
25064 // (2) `ShardedWithoutKey` refusal under the outer accessor's
25065 // reference projection: a `Sharded` strategy with a `None`
25066 // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
25067 // The bracket-dispatch's third arm reads `p.estrategia()` for
25068 // the match scrutinee then `p.shard_key()` for the cascade
25069 // scrutinee, both on the reference returned by the outer
25070 // accessor.
25071 let mut spec = three_member_spec();
25072 spec.placement.estrategia = PlacementStrategy::Sharded;
25073 spec.placement.shard_key = None;
25074 assert_eq!(
25075 spec.validate().unwrap_err(),
25076 AplicacaoError::ShardedWithoutKey,
25077 );
25078
25079 // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
25080 // reference projection: a non-`Sharded` strategy with a `Some`
25081 // `:shard-key` must trip the declared-but-inert refusal. The
25082 // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
25083 // + `p.estrategia()` for the diagnostic on the reference
25084 // returned by the outer accessor.
25085 let mut spec = three_member_spec();
25086 spec.placement.estrategia = PlacementStrategy::Replicated;
25087 spec.placement.shard_key = Some("tenantId".into());
25088 assert_eq!(
25089 spec.validate().unwrap_err(),
25090 AplicacaoError::ShardKeyOnNonSharded {
25091 estrategia: PlacementStrategy::Replicated,
25092 shard_key: "tenantId".into(),
25093 },
25094 );
25095
25096 // (4) Canonical `three_member_spec` `Replicated` fixture passes
25097 // `validate_placement` — every per-axis arm reaches the fall-
25098 // through `Ok(())` without any per-axis refusal firing under the
25099 // outer accessor's reference projection.
25100 let spec = three_member_spec();
25101 assert!(
25102 spec.validate().is_ok(),
25103 "the canonical Replicated placement fixture must pass \
25104 `validate_placement` — every per-axis arm short-circuits on \
25105 valid input under the outer accessor's reference projection",
25106 );
25107 assert_eq!(
25108 spec.placement().estrategia(),
25109 PlacementStrategy::Replicated,
25110 "the outer accessor's reference projection must be the \
25111 canonical Replicated fixture's strategy",
25112 );
25113 assert_eq!(
25114 spec.placement().clusters(),
25115 &["rio", "mar"],
25116 "the outer accessor's reference projection must be the \
25117 canonical Replicated fixture's cluster pool",
25118 );
25119 }
25120
25121 #[test]
25122 fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
25123 // The canonical per-`:entrada` outer-composite-optional-
25124 // reference-shape pin: [`AplicacaoSpec::entrada`] must return
25125 // the `:entrada` typed `Option<Entrada>` verbatim as an
25126 // `Option<&Entrada>` reference over the same backing storage
25127 // the raw `self.entrada.as_ref()` field access borrows from,
25128 // byte-equal across every representative fixture in the
25129 // accept-set — the author-omitted `None` shape (the
25130 // "internal-only mesh" partition every downstream external-
25131 // gateway emitter treats as "emit nothing"), the minimal
25132 // singleton `:entrada` composite (host + destination + empty
25133 // paths + default port), the paths-carrying composite (the
25134 // canonical `three_member_spec` fixture's ["/api" "/health"]
25135 // path-list shape every HTTPRoute per-rule fan-out emitter
25136 // reads), and the non-default port composite (the canonical
25137 // custom-port shape the port-fallback resolver reads).
25138 //
25139 // Pins against a future silent detour that returned a fresh-
25140 // cloned `Entrada` copy (which would type-check via a `Clone`
25141 // impl but silently break every downstream caller that
25142 // relied on the reference sharing the composite's backing
25143 // identity), a reference to an operator-resolved overlay
25144 // (the future per-cluster `:entrada-overrides` slot the
25145 // MESH-COMPOSITION §V federation roadmap acknowledges — its
25146 // resolution must land at exactly this accessor body, not
25147 // silently divert the raw slot away from a second consumer),
25148 // a `None` → `Some(Entrada::default)` cluster-default
25149 // projection (which would collapse the load-bearing
25150 // "author-omitted `:entrada` ⇒ internal-only mesh" partition
25151 // the peer `gateway_routes` early-return + `feira app graph`
25152 // internal-only-mesh partition both read), or an axis-
25153 // shuffled projection (a future detour that swapped
25154 // `host` and `para` through the accessor would silently
25155 // split the paired `validate` per-`:entrada` shape-and-
25156 // membership gate's traversal input from the peer
25157 // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
25158 // fan-out input from the peer `feira app graph` external-
25159 // gateway summary line).
25160 //
25161 // Peer of the sibling M3
25162 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
25163 // (534dc21) `&MeshPolicy` byte-equal pin on the per-
25164 // `:politicas` outer mesh-policy composite-reference axis
25165 // and of the sibling M3
25166 // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
25167 // (9abb8f0) `&Placement` byte-equal pin on the per-
25168 // `:placement` outer distribution-composite composite-
25169 // reference axis — extends the outer-accessor byte-equal-
25170 // projection discipline onto the last unlifted outermost M3
25171 // mesh-slot type's per-Aplicacao external-gateway composite-
25172 // reference axis, the third and final `&Composite`-return
25173 // accessor on the outer [`AplicacaoSpec`] type.
25174 let fixtures: Vec<Option<Entrada>> = vec![
25175 None,
25176 Some(Entrada {
25177 host: "checkout.quero.cloud".into(),
25178 para: "cart".into(),
25179 paths: Vec::new(),
25180 port: DEFAULT_SERVICO_PORT,
25181 }),
25182 Some(Entrada {
25183 host: "checkout.quero.cloud".into(),
25184 para: "cart".into(),
25185 paths: vec!["/api".into(), "/health".into()],
25186 port: DEFAULT_SERVICO_PORT,
25187 }),
25188 Some(Entrada {
25189 host: "checkout.quero.cloud".into(),
25190 para: "cart".into(),
25191 paths: vec!["/api".into()],
25192 port: 9443,
25193 }),
25194 ];
25195 for entrada in fixtures {
25196 let s = AplicacaoSpec {
25197 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
25198 contratos: Vec::new(),
25199 politicas: MeshPolicy::default(),
25200 placement: Placement::default(),
25201 entrada: entrada.clone(),
25202 };
25203 assert_eq!(
25204 s.entrada(),
25205 entrada.as_ref(),
25206 "AplicacaoSpec::entrada must return :entrada verbatim \
25207 (got {:?}, expected {:?})",
25208 s.entrada(),
25209 entrada.as_ref(),
25210 );
25211 match (s.entrada(), s.entrada.as_ref()) {
25212 (Some(a), Some(b)) => assert!(
25213 std::ptr::eq(a, b),
25214 "AplicacaoSpec::entrada accessor and \
25215 self.entrada.as_ref() field access must borrow \
25216 the same backing storage — the accessor is the \
25217 substrate-primitive typed dispatch every \
25218 downstream external-gateway composite consumer \
25219 must route through, and a reference-identity \
25220 split would silently break every consumer that \
25221 relied on the borrow sharing the composite's \
25222 storage",
25223 ),
25224 (None, None) => {}
25225 _ => panic!(
25226 "AplicacaoSpec::entrada presence bit must byte-\
25227 equal self.entrada.is_some() — a presence-bit \
25228 drift would silently split the paired `validate` \
25229 per-`:entrada` shape-and-membership gate's \
25230 traversal head from the peer \
25231 caixa-mesh gateway_routes early-return partition \
25232 from the peer `feira app graph` internal-only-\
25233 mesh partition",
25234 ),
25235 }
25236 assert_eq!(
25237 s.entrada().is_some(),
25238 s.entrada.is_some(),
25239 "AplicacaoSpec::entrada().is_some() must byte-equal \
25240 self.entrada.is_some() — a presence-bit drift would \
25241 silently split every downstream `Option<&Entrada>` \
25242 consumer's partition on the internal-only-mesh arm",
25243 );
25244 }
25245 }
25246
25247 #[test]
25248 fn validate_reads_through_lifted_entrada_accessor() {
25249 // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
25250 // per-`:entrada` shape-and-membership gate (`if let Some(e) =
25251 // self.entrada() { … }`, followed by the per-axis fan-out
25252 // `validate_entrada_para(&e.para)` /
25253 // `EntradaMemberMissing` membership lookup /
25254 // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
25255 // per-`e.paths` `validate_entrada_path` traversal) must key
25256 // off the lifted outer accessor, so any future rebrand on
25257 // the typed slot's outer-composite reader shape lands at
25258 // exactly one place. Pins the multi-axis coherence by
25259 // exercising each per-axis refusal end-to-end: (1) the
25260 // author-omitted `None` shape short-circuits past every
25261 // per-`:entrada` refusal (the internal-only mesh partition
25262 // the accessor's `None` arm names), (2) `EntradaMemberMissing`
25263 // fires on a well-shaped but phantom `:para` under the outer
25264 // accessor's reference projection, and (3) the canonical
25265 // `three_member_spec` `:entrada` fixture passes `validate`
25266 // under the outer accessor's reference projection.
25267 //
25268 // Peer of the sibling M3
25269 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
25270 // (534dc21) multi-axis coherence pin on the per-`:politicas`
25271 // outer mesh-policy composite-reference axis and the sibling
25272 // M3
25273 // [`validate_placement_reads_through_lifted_placement_accessor`]
25274 // (9abb8f0) multi-axis coherence pin on the per-`:placement`
25275 // outer distribution-composite composite-reference axis —
25276 // extends the multi-consumer coherence discipline onto the
25277 // last unlifted outermost M3 mesh-slot type's per-Aplicacao
25278 // external-gateway composite-reference axis, the third and
25279 // final `&Composite`-return accessor on the outer
25280 // [`AplicacaoSpec`] type.
25281
25282 // (1) `None` :entrada — the internal-only-mesh partition
25283 // short-circuits past every per-`:entrada` refusal. The outer
25284 // accessor's reference projection reaches the fall-through
25285 // `Ok(())` on the `None` arm without any per-axis refusal
25286 // firing.
25287 let mut spec = three_member_spec();
25288 spec.entrada = None;
25289 assert!(
25290 spec.validate().is_ok(),
25291 "an author-omitted `:entrada` must pass `validate` — the \
25292 internal-only-mesh partition short-circuits past every \
25293 per-`:entrada` refusal under the outer accessor's \
25294 reference projection",
25295 );
25296 assert!(
25297 spec.entrada().is_none(),
25298 "the outer accessor's reference projection must name the \
25299 internal-only-mesh partition per the `None` fixture",
25300 );
25301
25302 // (2) `EntradaMemberMissing` refusal under the outer accessor's
25303 // reference projection: a well-shaped but phantom `:para` must
25304 // trip the membership-lookup refusal. The gate's second arm
25305 // reads `e.para` on the reference returned by the outer
25306 // accessor.
25307 let mut spec = three_member_spec();
25308 if let Some(e) = spec.entrada.as_mut() {
25309 e.para = "phantom".into();
25310 }
25311 assert_eq!(
25312 spec.validate().unwrap_err(),
25313 AplicacaoError::EntradaMemberMissing {
25314 para: "phantom".into(),
25315 },
25316 );
25317 match (spec.entrada(), spec.entrada.as_ref()) {
25318 (Some(a), Some(b)) => assert!(
25319 std::ptr::eq(a, b),
25320 "the `validate` per-`:entrada` gate's traversal head \
25321 must be the same backing composite the accessor's \
25322 reference projection borrows from",
25323 ),
25324 _ => panic!("fixture must carry Some(:entrada)"),
25325 }
25326
25327 // (3) Canonical `three_member_spec` `:entrada` fixture passes
25328 // `validate` — every per-axis arm reaches the fall-through
25329 // `Ok(())` without any per-axis refusal firing under the
25330 // outer accessor's reference projection.
25331 let spec = three_member_spec();
25332 assert!(
25333 spec.validate().is_ok(),
25334 "the canonical `:entrada` fixture must pass `validate` — \
25335 every per-axis arm short-circuits on valid input under \
25336 the outer accessor's reference projection",
25337 );
25338 assert!(
25339 spec.entrada().is_some(),
25340 "the outer accessor's reference projection must be the \
25341 canonical `:entrada` fixture's composite",
25342 );
25343 }
25344
25345 #[test]
25346 fn port_for_destination_reads_through_lifted_entrada_accessor() {
25347 // Peer coherence pin: the
25348 // [`AplicacaoSpec::port_for_destination`] per-destination
25349 // L4-port fallback resolver's composite-projection seed
25350 // (`self.entrada().filter(…).map_or(…)`) must key off the
25351 // lifted outer accessor. Pins the coherence by exercising
25352 // the resolver end-to-end: (1) the `None` `:entrada` shape
25353 // falls through to `DEFAULT_SERVICO_PORT` under the outer
25354 // accessor's reference projection, (2) a non-matching
25355 // destination falls through to `DEFAULT_SERVICO_PORT` under
25356 // the outer accessor's reference projection, and (3) the
25357 // matching destination resolves to the `:entrada :port`
25358 // value under the outer accessor's reference projection.
25359 //
25360 // Peer of the sibling
25361 // [`validate_reads_through_lifted_entrada_accessor`] multi-
25362 // consumer coherence pin on the same per-`:entrada` outer-
25363 // composite axis — extends the multi-consumer coherence
25364 // discipline onto the second per-`:entrada` production
25365 // consumer, the L4-port fallback resolver.
25366
25367 // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
25368 // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
25369 // arm under the outer accessor's reference projection.
25370 let mut spec = three_member_spec();
25371 spec.entrada = None;
25372 assert_eq!(
25373 spec.port_for_destination("cart"),
25374 DEFAULT_SERVICO_PORT,
25375 "the port-fallback resolver must fall through to \
25376 DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
25377 under the outer accessor's reference projection",
25378 );
25379
25380 // (2) Non-matching destination — the resolver's `filter(…)`
25381 // arm rejects a mismatched destination and falls through
25382 // to `DEFAULT_SERVICO_PORT` under the outer accessor's
25383 // reference projection.
25384 let mut spec = three_member_spec();
25385 if let Some(e) = spec.entrada.as_mut() {
25386 e.para = "cart".into();
25387 e.port = 9443;
25388 }
25389 assert_eq!(
25390 spec.port_for_destination("catalog"),
25391 DEFAULT_SERVICO_PORT,
25392 "the port-fallback resolver must fall through to \
25393 DEFAULT_SERVICO_PORT on a non-matching destination \
25394 under the outer accessor's reference projection",
25395 );
25396
25397 // (3) Matching destination — the resolver's `map_or(…)` arm
25398 // returns the `:entrada :port` value under the outer
25399 // accessor's reference projection.
25400 let mut spec = three_member_spec();
25401 if let Some(e) = spec.entrada.as_mut() {
25402 e.para = "cart".into();
25403 e.port = 9443;
25404 }
25405 assert_eq!(
25406 spec.port_for_destination("cart"),
25407 9443,
25408 "the port-fallback resolver must return the \
25409 `:entrada :port` value on a matching destination \
25410 under the outer accessor's reference projection",
25411 );
25412 }
25413
25414 #[test]
25415 fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
25416 // The canonical per-`:politicas` `:mtls-required` mTLS-
25417 // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
25418 // must return the `:politicas :mtls-required` typed bool
25419 // verbatim as an `Option<bool>`, byte-equal to the raw field
25420 // access across every value in the three-way accept-set —
25421 // `None` (cluster default applies), `Some(true)` (mTLS
25422 // handshake enforced — the sandboxing-by-default arm the
25423 // MeshPolicy's docstring names), `Some(false)` (handshake
25424 // skipped — the explicit debug-edge opt-out).
25425 //
25426 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
25427 // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
25428 // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
25429 // shape — first `Option<Copy-T>`-return accessor on the M3
25430 // mesh-slot family. Pins against a future silent detour that
25431 // re-derived the toggle from a peer axis (an accidental
25432 // `.circuit_breaker.is_some()` collapse that assumed mTLS on
25433 // whenever a breaker is set), a `None` → `Some(false)` cluster-
25434 // default projection (the canonical `Option<bool>` → `bool`
25435 // collapse footgun the surrounding `is_empty()` predicate
25436 // guards on the peer emptiness axis), or a `Some(true)` /
25437 // `Some(false)` variant swap that landed on one consumer
25438 // without the other.
25439 for required in [None, Some(true), Some(false)] {
25440 let p = MeshPolicy {
25441 mtls_required: required,
25442 ..MeshPolicy::default()
25443 };
25444 assert_eq!(
25445 p.mtls_required(),
25446 required,
25447 "MeshPolicy::mtls_required must return :politicas \
25448 :mtls-required verbatim (got {:?}, expected {required:?})",
25449 p.mtls_required(),
25450 );
25451 assert_eq!(
25452 p.mtls_required(),
25453 p.mtls_required,
25454 "MeshPolicy::mtls_required must byte-equal the raw \
25455 .mtls_required field access across every value in the \
25456 three-way accept-set",
25457 );
25458 }
25459 }
25460
25461 #[test]
25462 fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
25463 // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
25464 // arm must key off [`MeshPolicy::mtls_required`], not the raw
25465 // `.mtls_required` field access. Structurally: toggling ONLY
25466 // the `mtls_required` slot on an otherwise-default MeshPolicy
25467 // must flip `is_empty()` from `true` (all-`None`) to `false`
25468 // (one axis carries a value); the flip must be observed for
25469 // both `Some(true)` and `Some(false)` since the emptiness
25470 // semantic reads "any axis carries a value" — not "any axis
25471 // carries a truthy value" — the same non-collapsing shape the
25472 // sibling M2 [`crate::LimitsSpec::is_empty`] /
25473 // [`crate::BehaviorSpec::is_empty`] predicates carry on their
25474 // peer `Option<T>`-typed slot surfaces.
25475 //
25476 // Pins against a future silent detour that re-derived the
25477 // emptiness predicate off a peer axis (an accidental
25478 // `.rate_limit.is_none()`-only chain that dropped the
25479 // `mtls_required` arm entirely), a `mtls_required == Some(_)`
25480 // collapse to a truthy-only check (which would silently
25481 // classify `Some(false)` as empty), or an accessor-side
25482 // detour that no longer names the substrate-primitive typed
25483 // dispatch (an accidental `self.mtls_required.unwrap_or(false)
25484 // == false` fallback in the accessor that would silently
25485 // classify both `None` and `Some(false)` as the same value).
25486 //
25487 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
25488 // (7cd2a28) accessor-composition pin on the sibling optional-
25489 // scalar axis — same "the emptiness / shape-gate predicate
25490 // must route through the substrate-primitive typed dispatch"
25491 // discipline extended onto the peer per-`:politicas` emptiness
25492 // predicate.
25493 let empty = MeshPolicy::default();
25494 assert!(
25495 empty.is_empty(),
25496 "MeshPolicy::default() must be is_empty() — every axis \
25497 defaults to None",
25498 );
25499 for required in [Some(true), Some(false)] {
25500 let p = MeshPolicy {
25501 mtls_required: required,
25502 ..MeshPolicy::default()
25503 };
25504 assert!(
25505 !p.is_empty(),
25506 "MeshPolicy::is_empty must return false when \
25507 :mtls-required is {required:?} — the emptiness \
25508 predicate reads \"any axis carries a value\", not \
25509 \"any axis carries a truthy value\"",
25510 );
25511 assert_eq!(
25512 p.mtls_required().is_none(),
25513 p.is_empty(),
25514 "when :mtls-required is the only set axis, \
25515 is_empty() must equal mtls_required().is_none() — \
25516 the accessor and the emptiness predicate must \
25517 route through the same substrate-primitive typed \
25518 dispatch on the :mtls-required arm",
25519 );
25520 }
25521 }
25522
25523 #[test]
25524 fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
25525 // The by-copy pin: [`MeshPolicy::mtls_required`] returns
25526 // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
25527 // accessor must return by value, not by reference. Peer of the
25528 // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
25529 // borrow-invariant pin on the sibling `Option<String>` slot,
25530 // but extended onto the peer `Option<bool>` copy-invariant
25531 // shape — the accessor's returned `Option<bool>` must outlive
25532 // `&self` (multiple calls must return equal values from a
25533 // dropped-`&self` copy, since the returned Option carries no
25534 // borrow), and calling the accessor twice on the same
25535 // MeshPolicy must yield the same `Option<bool>` verbatim
25536 // (idempotent, no side effects on `&self`).
25537 //
25538 // Pins against a future silent detour that returned
25539 // `Option<&bool>` (which would type-check but silently break
25540 // every downstream caller — [`single_field_overlay`]'s first
25541 // parameter is `Option<T: Clone>`, and `&bool` would fold to a
25542 // detached copy at the call site), an accidental
25543 // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
25544 // would also type-check but return `Option<&bool>`), or a
25545 // one-arm-only accessor that reads `Some(*b)` in the Some arm
25546 // but reads a fresh Default::default() in the None arm.
25547 for required in [None, Some(true), Some(false)] {
25548 let p = MeshPolicy {
25549 mtls_required: required,
25550 ..MeshPolicy::default()
25551 };
25552 let first = p.mtls_required();
25553 let second = p.mtls_required();
25554 assert_eq!(
25555 first, second,
25556 "MeshPolicy::mtls_required must be idempotent — two \
25557 successive calls on the same &self must return the \
25558 same Option<bool>",
25559 );
25560 assert_eq!(
25561 first, required,
25562 "MeshPolicy::mtls_required must return :politicas \
25563 :mtls-required verbatim by copy — got {first:?}, \
25564 expected {required:?}",
25565 );
25566 }
25567 }
25568
25569 #[test]
25570 fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
25571 // The canonical per-`:politicas` `:retries` transient-failure-
25572 // retry-budget scalar pin: [`MeshPolicy::retries`] must return
25573 // the `:politicas :retries` typed `u32` verbatim as an
25574 // `Option<u32>`, byte-equal to the raw field access across every
25575 // representative value in the accept-set — `None` (cluster
25576 // default applies — typically "no retries beyond a single
25577 // dispatch attempt" the caixa-mesh `retry_overlay` builder
25578 // documents), `Some(1)` (the lower boundary of the
25579 // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
25580 // `AplicacaoSpec::validate_politicas` gate carves out on the
25581 // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
25582 // (the upper boundary the same gate carves out on the sibling
25583 // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
25584 // past-the-guard sentinel that pins the accessor doesn't perform
25585 // a silent bounds-collapse at the return path).
25586 //
25587 // Sibling of the peer per-`:politicas`
25588 // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
25589 // sibling `Option<Copy-T>` optional-scalar axis, extended to the
25590 // peer per-`:politicas` `Option<u32>` shape — second
25591 // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
25592 // Pins against a future silent detour that re-derived the retry
25593 // cap from a peer axis (an accidental `.circuit_breaker
25594 // .as_ref().map(|b| b.max_failures)` collapse that read the
25595 // breaker's max-failure count as a retry budget), a
25596 // `None → Some(0)` cluster-default projection (which would
25597 // silently re-introduce the `PolicyRetriesZero` refusal case at
25598 // the emit boundary), or a bounds-collapsing accessor that
25599 // clamped the return through `POLICY_RETRIES_MAX` (the
25600 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25601 // must ship the raw slot verbatim so a validate-time gate
25602 // regression surfaces at the emit boundary rather than being
25603 // silently absorbed).
25604 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25605 let p = MeshPolicy {
25606 retries,
25607 ..MeshPolicy::default()
25608 };
25609 assert_eq!(
25610 p.retries(),
25611 retries,
25612 "MeshPolicy::retries must return :politicas :retries \
25613 verbatim (got {:?}, expected {retries:?})",
25614 p.retries(),
25615 );
25616 assert_eq!(
25617 p.retries(),
25618 p.retries,
25619 "MeshPolicy::retries must byte-equal the raw .retries \
25620 field access across every value in the accept-set",
25621 );
25622 }
25623 }
25624
25625 #[test]
25626 fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
25627 // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
25628 // must key off [`MeshPolicy::retries`], not the raw `.retries`
25629 // field access. Structurally: toggling ONLY the `retries` slot
25630 // on an otherwise-default MeshPolicy must flip `is_empty()`
25631 // from `true` (all-`None`) to `false` (one axis carries a
25632 // value); the flip must be observed for every value in the
25633 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25634 // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
25635 // the emptiness semantic reads "any axis carries a value" —
25636 // not "any axis carries a value the validate gate accepts" —
25637 // the same non-collapsing shape the peer M2
25638 // [`crate::LimitsSpec::is_empty`] /
25639 // [`crate::BehaviorSpec::is_empty`] predicates carry.
25640 //
25641 // Pins against a future silent detour that re-derived the
25642 // emptiness predicate off a peer axis (an accidental
25643 // `.rate_limit.is_none()`-only chain that dropped the
25644 // `retries` arm entirely), a `retries == Some(_)` collapse
25645 // that key-off a validate-gate-clamped bounds check (which
25646 // would silently classify a past-the-guard `Some(u32::MAX)`
25647 // as empty because it fails the `1..=POLICY_RETRIES_MAX`
25648 // check), or an accessor-side detour that no longer names the
25649 // substrate-primitive typed dispatch.
25650 //
25651 // Sibling of the peer per-`:politicas`
25652 // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
25653 // pin on the sibling `Option<Copy-T>` optional-scalar axis —
25654 // same "the emptiness predicate must route through the
25655 // substrate-primitive typed dispatch" discipline extended onto
25656 // the peer per-`:politicas` `Option<u32>` axis.
25657 let empty = MeshPolicy::default();
25658 assert!(
25659 empty.is_empty(),
25660 "MeshPolicy::default() must be is_empty() — every axis \
25661 defaults to None",
25662 );
25663 for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
25664 let p = MeshPolicy {
25665 retries,
25666 ..MeshPolicy::default()
25667 };
25668 assert!(
25669 !p.is_empty(),
25670 "MeshPolicy::is_empty must return false when \
25671 :retries is {retries:?} — the emptiness \
25672 predicate reads \"any axis carries a value\", not \
25673 \"any axis carries a value the validate gate \
25674 accepts\"",
25675 );
25676 assert_eq!(
25677 p.retries().is_none(),
25678 p.is_empty(),
25679 "when :retries is the only set axis, is_empty() \
25680 must equal retries().is_none() — the accessor and \
25681 the emptiness predicate must route through the same \
25682 substrate-primitive typed dispatch on the :retries \
25683 arm",
25684 );
25685 }
25686 }
25687
25688 #[test]
25689 fn mesh_policy_retries_projects_option_u32_by_copy() {
25690 // The by-copy pin: [`MeshPolicy::retries`] returns
25691 // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
25692 // accessor must return by value, not by reference. Sibling of
25693 // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
25694 // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
25695 // extended onto the sibling `Option<u32>` copy-invariant
25696 // shape — the accessor's returned `Option<u32>` must outlive
25697 // `&self` (multiple calls must return equal values from a
25698 // dropped-`&self` copy, since the returned Option carries no
25699 // borrow), and calling the accessor twice on the same
25700 // MeshPolicy must yield the same `Option<u32>` verbatim
25701 // (idempotent, no side effects on `&self`).
25702 //
25703 // Pins against a future silent detour that returned
25704 // `Option<&u32>` (which would type-check but silently break
25705 // every downstream caller — [`crate::render::single_field_overlay`]'s
25706 // first parameter is `Option<T: Clone>`, and `&u32` would
25707 // fold to a detached copy at the call site), an accidental
25708 // `Option::as_ref()` projection (`self.retries.as_ref()` would
25709 // also type-check but return `Option<&u32>`), or a one-arm-
25710 // only accessor that reads `Some(*n)` in the Some arm but
25711 // reads a fresh `Default::default()` (`0_u32`) in the None
25712 // arm.
25713 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25714 let p = MeshPolicy {
25715 retries,
25716 ..MeshPolicy::default()
25717 };
25718 let first = p.retries();
25719 let second = p.retries();
25720 assert_eq!(
25721 first, second,
25722 "MeshPolicy::retries must be idempotent — two \
25723 successive calls on the same &self must return the \
25724 same Option<u32>",
25725 );
25726 assert_eq!(
25727 first, retries,
25728 "MeshPolicy::retries must return :politicas :retries \
25729 verbatim by copy — got {first:?}, expected {retries:?}",
25730 );
25731 }
25732 }
25733
25734 #[test]
25735 fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
25736 // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
25737 // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
25738 // return the `:politicas :timeout` typed [`Duration`] verbatim
25739 // as an `Option<Duration>`, byte-equal to the raw field access
25740 // across every representative value in the accept-set — `None`
25741 // (cluster default applies — typically the gateway class's
25742 // implementation-side per-request wall-clock cap the caixa-mesh
25743 // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
25744 // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
25745 // set the surrounding `AplicacaoSpec::validate_politicas` gate
25746 // carves out on the sibling `PolicyTimeoutZero` /
25747 // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
25748 // (the upper boundary the same gate carves out on the sibling
25749 // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
25750 // (a past-the-guard sentinel that pins the accessor doesn't
25751 // perform a silent bounds-collapse into `None` on the zero-
25752 // Duration arm — validate rejects zero but the accessor must
25753 // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
25754 // past-the-guard sentinel that pins the accessor doesn't
25755 // perform a silent bounds-collapse at the return path).
25756 //
25757 // Sibling of the peer per-`:politicas`
25758 // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
25759 // `Option<u32>` optional-scalar axis and the peer per-
25760 // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
25761 // pin on the sibling `Option<bool>` optional-scalar axis,
25762 // extended onto the peer per-`:politicas` `Option<Duration>`
25763 // shape — third `Option<Copy-T>`-return accessor on the M3
25764 // mesh-slot family. Pins against a future silent detour that
25765 // re-derived the per-call cap from a peer axis (an accidental
25766 // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
25767 // read the breaker's rolling-window duration as a per-call
25768 // deadline), a `None → Some(Duration::MAX)` cluster-default
25769 // projection (which would silently re-introduce the
25770 // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
25771 // blocking" arm at the emit boundary), or a bounds-collapsing
25772 // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
25773 // (the `AplicacaoSpec::validate` gate owns the bounds; the
25774 // accessor must ship the raw slot verbatim so a validate-time
25775 // gate regression surfaces at the emit boundary rather than
25776 // being silently absorbed).
25777 for timeout in [
25778 None,
25779 Some(Duration::from_millis(1)),
25780 Some(POLICY_TIMEOUT_MAX),
25781 Some(Duration::ZERO),
25782 Some(Duration::MAX),
25783 ] {
25784 let p = MeshPolicy {
25785 timeout,
25786 ..MeshPolicy::default()
25787 };
25788 assert_eq!(
25789 p.timeout(),
25790 timeout,
25791 "MeshPolicy::timeout must return :politicas :timeout \
25792 verbatim (got {:?}, expected {timeout:?})",
25793 p.timeout(),
25794 );
25795 assert_eq!(
25796 p.timeout(),
25797 p.timeout,
25798 "MeshPolicy::timeout must byte-equal the raw .timeout \
25799 field access across every value in the accept-set",
25800 );
25801 }
25802 }
25803
25804 #[test]
25805 fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
25806 // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
25807 // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
25808 // field access. Structurally: toggling ONLY the `timeout` slot
25809 // on an otherwise-default MeshPolicy must flip `is_empty()`
25810 // from `true` (all-`None`) to `false` (one axis carries a
25811 // value); the flip must be observed for every value in the
25812 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25813 // gate accepts (`Some(Duration::from_millis(1))`,
25814 // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
25815 // reads "any axis carries a value" — not "any axis carries a
25816 // value the validate gate accepts" — the same non-collapsing
25817 // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
25818 // [`crate::BehaviorSpec::is_empty`] predicates carry.
25819 //
25820 // Pins against a future silent detour that re-derived the
25821 // emptiness predicate off a peer axis (an accidental
25822 // `.rate_limit.is_none()`-only chain that dropped the
25823 // `timeout` arm entirely), a `timeout == Some(_)` collapse
25824 // that key-off a validate-gate-clamped bounds check (which
25825 // would silently classify a past-the-guard `Some(Duration::MAX)`
25826 // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
25827 // check), or an accessor-side detour that no longer names the
25828 // substrate-primitive typed dispatch.
25829 //
25830 // Sibling of the peer per-`:politicas`
25831 // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
25832 // the sibling `Option<u32>` optional-scalar axis and the peer
25833 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25834 // accessor-composition pin on the sibling `Option<bool>`
25835 // optional-scalar axis — same "the emptiness predicate must
25836 // route through the substrate-primitive typed dispatch"
25837 // discipline extended onto the peer per-`:politicas`
25838 // `Option<Duration>` axis.
25839 let empty = MeshPolicy::default();
25840 assert!(
25841 empty.is_empty(),
25842 "MeshPolicy::default() must be is_empty() — every axis \
25843 defaults to None",
25844 );
25845 for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
25846 let p = MeshPolicy {
25847 timeout,
25848 ..MeshPolicy::default()
25849 };
25850 assert!(
25851 !p.is_empty(),
25852 "MeshPolicy::is_empty must return false when \
25853 :timeout is {timeout:?} — the emptiness \
25854 predicate reads \"any axis carries a value\", not \
25855 \"any axis carries a value the validate gate \
25856 accepts\"",
25857 );
25858 assert_eq!(
25859 p.timeout().is_none(),
25860 p.is_empty(),
25861 "when :timeout is the only set axis, is_empty() \
25862 must equal timeout().is_none() — the accessor and \
25863 the emptiness predicate must route through the same \
25864 substrate-primitive typed dispatch on the :timeout \
25865 arm",
25866 );
25867 }
25868 }
25869
25870 #[test]
25871 fn mesh_policy_timeout_projects_option_duration_by_copy() {
25872 // The by-copy pin: [`MeshPolicy::timeout`] returns
25873 // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
25874 // and the accessor must return by value, not by reference.
25875 // Sibling of the peer per-`:politicas`
25876 // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
25877 // sibling `Option<u32>` optional-scalar axis and the peer
25878 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25879 // by-copy pin on the sibling `Option<bool>` optional-scalar
25880 // axis, extended onto the peer per-`:politicas`
25881 // `Option<Duration>` copy-invariant shape — the accessor's
25882 // returned `Option<Duration>` must outlive `&self` (multiple
25883 // calls must return equal values from a dropped-`&self`
25884 // copy, since the returned Option carries no borrow), and
25885 // calling the accessor twice on the same MeshPolicy must
25886 // yield the same `Option<Duration>` verbatim (idempotent, no
25887 // side effects on `&self`).
25888 //
25889 // Pins against a future silent detour that returned
25890 // `Option<&Duration>` (which would type-check but silently
25891 // break every downstream caller — [`crate::render::single_field_overlay`]'s
25892 // first parameter is `Option<T: Clone>`, and `&Duration`
25893 // would fold to a detached copy at the call site), an
25894 // accidental `Option::as_ref()` projection
25895 // (`self.timeout.as_ref()` would also type-check but return
25896 // `Option<&Duration>`), or a one-arm-only accessor that
25897 // reads `Some(*d)` in the Some arm but reads a fresh
25898 // `Default::default()` (`Duration::ZERO`) in the None arm
25899 // (which would silently re-classify every unset `:timeout`
25900 // as the `PolicyTimeoutZero`-refused zero-Duration value at
25901 // the accessor boundary).
25902 for timeout in [
25903 None,
25904 Some(Duration::from_millis(1)),
25905 Some(POLICY_TIMEOUT_MAX),
25906 Some(Duration::ZERO),
25907 Some(Duration::MAX),
25908 ] {
25909 let p = MeshPolicy {
25910 timeout,
25911 ..MeshPolicy::default()
25912 };
25913 let first = p.timeout();
25914 let second = p.timeout();
25915 assert_eq!(
25916 first, second,
25917 "MeshPolicy::timeout must be idempotent — two \
25918 successive calls on the same &self must return the \
25919 same Option<Duration>",
25920 );
25921 assert_eq!(
25922 first, timeout,
25923 "MeshPolicy::timeout must return :politicas :timeout \
25924 verbatim by copy — got {first:?}, expected {timeout:?}",
25925 );
25926 }
25927 }
25928
25929 #[test]
25930 fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
25931 // The canonical per-`:politicas` `:rate-limit` Envoy-
25932 // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
25933 // [`MeshPolicy::rate_limit`] must return the `:politicas
25934 // :rate-limit` typed [`RateLimit`] verbatim as an
25935 // `Option<RateLimit>`, byte-equal to the raw field access
25936 // across every representative value in the accept-set — `None`
25937 // (cluster default applies — no per-Aplicacao rate declaration,
25938 // the gateway-class per-listener default arm the future caixa-
25939 // mesh `local_rate_limit_overlay` emitter documents),
25940 // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
25941 // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
25942 // accept-set the surrounding
25943 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25944 // sibling `PolicyRateLimitZero` refusal, paired with the
25945 // canonical-window "1 second" arm of the three-unit
25946 // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
25947 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
25948 // (the upper boundary the same gate carves out on the sibling
25949 // `PolicyRateLimitExceedsCap` refusal, paired with the
25950 // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
25951 // (a past-the-guard sentinel that pins the accessor doesn't
25952 // perform a silent bounds-collapse into `None` on the
25953 // zero-rate/zero-window arm — validate rejects zero but the
25954 // accessor must ship the raw slot verbatim so a validate-time
25955 // gate regression surfaces at the emit boundary rather than
25956 // being silently absorbed), and
25957 // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
25958 // (a past-the-guard sentinel that pins the accessor doesn't
25959 // perform a silent bounds-collapse at the return path).
25960 //
25961 // First `Option<Copy-composite-T>`-return accessor pin on the
25962 // M3 mesh-slot family (peer of the sibling per-`:politicas`
25963 // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
25964 // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
25965 // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
25966 // Copy accessor pins, extended onto the peer per-`:politicas`
25967 // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
25968 // and the accessor returns by value). Pins against a future
25969 // silent detour that re-derived the rate declaration from a
25970 // peer axis (an accidental
25971 // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
25972 // collapse that read the breaker's trip threshold + rolling
25973 // window as a rate declaration), a `None → Some(default())`
25974 // cluster-default projection (which would silently re-
25975 // introduce a "cluster default is 0/s" arm the emit boundary
25976 // would take as "declared but inert" — the canonical
25977 // declared-but-inert footgun the sibling
25978 // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
25979 // amplification-shape axis), a bounds-collapsing accessor
25980 // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
25981 // clamped `rl.window` through [`is_canonical_rate_limit_window`]
25982 // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
25983 // accessor must ship the raw slot verbatim), or a
25984 // by-reference detour (`Option<&RateLimit>`) that broke every
25985 // downstream consumer keying off `Option<RateLimit>` by-copy.
25986 for rl in [
25987 None,
25988 Some(RateLimit {
25989 rate: 1,
25990 window: Duration::from_secs(1),
25991 }),
25992 Some(RateLimit {
25993 rate: POLICY_RATE_LIMIT_MAX,
25994 window: Duration::from_secs(3600),
25995 }),
25996 Some(RateLimit {
25997 rate: 0,
25998 window: Duration::ZERO,
25999 }),
26000 Some(RateLimit {
26001 rate: u32::MAX,
26002 window: Duration::MAX,
26003 }),
26004 ] {
26005 let p = MeshPolicy {
26006 rate_limit: rl,
26007 ..MeshPolicy::default()
26008 };
26009 assert_eq!(
26010 p.rate_limit(),
26011 rl,
26012 "MeshPolicy::rate_limit must return :politicas :rate-limit \
26013 verbatim (got {:?}, expected {rl:?})",
26014 p.rate_limit(),
26015 );
26016 assert_eq!(
26017 p.rate_limit(),
26018 p.rate_limit,
26019 "MeshPolicy::rate_limit must byte-equal the raw \
26020 .rate_limit field access across every value in the \
26021 accept-set",
26022 );
26023 }
26024 }
26025
26026 #[test]
26027 fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
26028 // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
26029 // must key off [`MeshPolicy::rate_limit`], not the raw
26030 // `.rate_limit` field access. Structurally: toggling ONLY the
26031 // `rate_limit` slot on an otherwise-default MeshPolicy must
26032 // flip `is_empty()` from `true` (all-`None`) to `false` (one
26033 // axis carries a value); the flip must be observed for every
26034 // representative value in the accept-set the surrounding
26035 // [`AplicacaoSpec::validate_politicas`] gate accepts
26036 // (`Some(RateLimit { rate: 1, window: 1s })`,
26037 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
26038 // since the emptiness semantic reads "any axis carries a
26039 // value" — not "any axis carries a value the validate gate
26040 // accepts" — the same non-collapsing shape the peer M2
26041 // [`crate::LimitsSpec::is_empty`] /
26042 // [`crate::BehaviorSpec::is_empty`] predicates carry.
26043 //
26044 // Pins against a future silent detour that re-derived the
26045 // emptiness predicate off a peer axis (an accidental
26046 // `.timeout.is_none()`-only chain that dropped the
26047 // `rate_limit` arm entirely — the last unlifted inline field
26048 // access on `is_empty` before this lift), a `rate_limit ==
26049 // Some(_)` collapse that key-off a validate-gate-clamped
26050 // bounds check (which would silently classify a past-the-
26051 // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
26052 // because it fails the value-shape gate), or an accessor-
26053 // side detour that no longer names the substrate-primitive
26054 // typed dispatch.
26055 //
26056 // Fourth "the emptiness predicate must route through the
26057 // substrate-primitive typed dispatch" composition pin on the
26058 // M3 mesh-slot family — closes the last unlifted composition
26059 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
26060 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
26061 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
26062 // 7073d0f is_empty-composition pins on the sibling primitive-
26063 // Copy axes, extended onto the peer per-`:politicas`
26064 // composite-Copy `Option<RateLimit>` axis).
26065 let empty = MeshPolicy::default();
26066 assert!(
26067 empty.is_empty(),
26068 "MeshPolicy::default() must be is_empty() — every axis \
26069 defaults to None",
26070 );
26071 for rl in [
26072 RateLimit {
26073 rate: 1,
26074 window: Duration::from_secs(1),
26075 },
26076 RateLimit {
26077 rate: POLICY_RATE_LIMIT_MAX,
26078 window: Duration::from_secs(3600),
26079 },
26080 ] {
26081 let p = MeshPolicy {
26082 rate_limit: Some(rl),
26083 ..MeshPolicy::default()
26084 };
26085 assert!(
26086 !p.is_empty(),
26087 "MeshPolicy::is_empty must return false when \
26088 :rate-limit is {rl:?} — the emptiness predicate \
26089 reads \"any axis carries a value\", not \"any axis \
26090 carries a value the validate gate accepts\"",
26091 );
26092 assert_eq!(
26093 p.rate_limit().is_none(),
26094 p.is_empty(),
26095 "when :rate-limit is the only set axis, is_empty() \
26096 must equal rate_limit().is_none() — the accessor \
26097 and the emptiness predicate must route through the \
26098 same substrate-primitive typed dispatch on the \
26099 :rate-limit arm",
26100 );
26101 }
26102 }
26103
26104 #[test]
26105 fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
26106 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26107 // `:rate-limit` value-shape gate must key off
26108 // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
26109 // field bind. Structurally: a `MeshPolicy` whose only set
26110 // axis is a `Some(RateLimit { rate: 0, .. })` must surface
26111 // the `PolicyRateLimitZero` refusal exactly, and the same
26112 // MeshPolicy with the rate at the canonical lower boundary
26113 // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
26114 // The pair jointly pins the accessor + validate-gate
26115 // composition: any future silent detour that had the accessor
26116 // omit the `Some(RateLimit { rate: 0, .. })` arm (a
26117 // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
26118 // silently absorb the `PolicyRateLimitZero` refusal at the
26119 // accessor boundary — the composition pin catches that at
26120 // caixa-core build time.
26121 //
26122 // Sibling of the peer [`validate_politicas`]
26123 // `:mtls-required` / `:retries` / `:timeout` composition pins
26124 // on the sibling primitive-Copy optional-scalar axes — same
26125 // "the validate / shape-gate predicate must route through the
26126 // substrate-primitive typed dispatch" discipline extended
26127 // onto the peer per-`:politicas` composite-Copy
26128 // `Option<RateLimit>` axis. Second composition-with-accessor
26129 // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
26130 // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
26131 let mut spec = three_member_spec();
26132 spec.politicas = MeshPolicy {
26133 rate_limit: Some(RateLimit {
26134 rate: 0,
26135 window: Duration::from_secs(1),
26136 }),
26137 ..MeshPolicy::default()
26138 };
26139 assert!(
26140 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
26141 "validate_politicas must reject rate == 0 with \
26142 PolicyRateLimitZero — the accessor and the validate gate \
26143 must route through the same substrate-primitive typed \
26144 dispatch on the :rate-limit zero-floor arm",
26145 );
26146 spec.politicas = MeshPolicy {
26147 rate_limit: Some(RateLimit {
26148 rate: 1,
26149 window: Duration::from_secs(1),
26150 }),
26151 ..MeshPolicy::default()
26152 };
26153 assert!(
26154 spec.validate().is_ok(),
26155 "validate_politicas must accept rate == 1 (the canonical \
26156 lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
26157 set) with a canonical 1s window",
26158 );
26159 }
26160
26161 #[test]
26162 fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
26163 // The canonical per-`:politicas` `:circuit-breaker` Envoy-
26164 // `outlier_detection`-mesh consecutive-failure-ejection scalar
26165 // pin: [`MeshPolicy::circuit_breaker`] must return the
26166 // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
26167 // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
26168 // raw field access across every representative value in the
26169 // accept-set — `None` (cluster default applies — no
26170 // per-Aplicacao breaker declaration, the gateway-class per-
26171 // listener default arm the future caixa-mesh
26172 // `outlier_detection_overlay` emitter documents),
26173 // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
26174 // (the lower boundary of the accept-set the surrounding
26175 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
26176 // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
26177 // refusals),
26178 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
26179 // (the upper boundary the same gate carves out on the sibling
26180 // `PolicyBreakerMaxFailuresExceedsCap` /
26181 // `PolicyBreakerWindowExceedsCap` refusals),
26182 // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
26183 // (a past-the-guard sentinel that pins the accessor doesn't
26184 // perform a silent bounds-collapse into `None` on the
26185 // zero-failures/zero-window arm — validate rejects zero but
26186 // the accessor must ship the raw slot verbatim so a validate-
26187 // time gate regression surfaces at the emit boundary rather
26188 // than being silently absorbed), and
26189 // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
26190 // (a past-the-guard sentinel that pins the accessor doesn't
26191 // perform a silent bounds-collapse at the return path).
26192 //
26193 // Second `Option<Copy-composite-T>`-return accessor pin on the
26194 // M3 mesh-slot family (peer of the sibling per-`:politicas`
26195 // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
26196 // composite-Copy accessor pin, and of the sibling per-
26197 // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
26198 // [`MeshPolicy::retries`] bdfb399 /
26199 // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
26200 // accessor pins). Pins against a future silent detour that
26201 // re-derived the breaker declaration from a peer axis (an
26202 // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
26203 // collapse that read the rate-limit's bucket capacity + refill
26204 // period as a breaker declaration), a `None → Some(default())`
26205 // cluster-default projection (which would silently re-
26206 // introduce the `PolicyBreakerZeroFailures` /
26207 // `PolicyBreakerZeroWindow` refusal cases at the emit
26208 // boundary), a bounds-collapsing accessor that clamped
26209 // `cb.max_failures` through
26210 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
26211 // through [`POLICY_BREAKER_WINDOW_MAX`] (the
26212 // [`AplicacaoSpec::validate`] gate owns the bounds; the
26213 // accessor must ship the raw slot verbatim), or a
26214 // by-reference detour (`Option<&CircuitBreaker>`) that broke
26215 // every downstream consumer keying off `Option<CircuitBreaker>`
26216 // by-copy.
26217 for cb in [
26218 None,
26219 Some(CircuitBreaker {
26220 max_failures: 1,
26221 window: Duration::from_millis(1),
26222 }),
26223 Some(CircuitBreaker {
26224 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
26225 window: POLICY_BREAKER_WINDOW_MAX,
26226 }),
26227 Some(CircuitBreaker {
26228 max_failures: 0,
26229 window: Duration::ZERO,
26230 }),
26231 Some(CircuitBreaker {
26232 max_failures: u32::MAX,
26233 window: Duration::MAX,
26234 }),
26235 ] {
26236 let p = MeshPolicy {
26237 circuit_breaker: cb,
26238 ..MeshPolicy::default()
26239 };
26240 assert_eq!(
26241 p.circuit_breaker(),
26242 cb,
26243 "MeshPolicy::circuit_breaker must return :politicas \
26244 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
26245 p.circuit_breaker(),
26246 );
26247 assert_eq!(
26248 p.circuit_breaker(),
26249 p.circuit_breaker,
26250 "MeshPolicy::circuit_breaker must byte-equal the raw \
26251 .circuit_breaker field access across every value in \
26252 the accept-set",
26253 );
26254 }
26255 }
26256
26257 #[test]
26258 fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
26259 // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
26260 // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
26261 // `.circuit_breaker` field access. Structurally: toggling ONLY
26262 // the `circuit_breaker` slot on an otherwise-default MeshPolicy
26263 // must flip `is_empty()` from `true` (all-`None`) to `false`
26264 // (one axis carries a value); the flip must be observed for
26265 // every representative value in the accept-set the surrounding
26266 // [`AplicacaoSpec::validate_politicas`] gate accepts
26267 // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
26268 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
26269 // since the emptiness semantic reads "any axis carries a
26270 // value" — not "any axis carries a value the validate gate
26271 // accepts" — the same non-collapsing shape the peer M2
26272 // [`crate::LimitsSpec::is_empty`] /
26273 // [`crate::BehaviorSpec::is_empty`] predicates carry.
26274 //
26275 // Pins against a future silent detour that re-derived the
26276 // emptiness predicate off a peer axis (an accidental
26277 // `.rate_limit.is_none()`-only chain that dropped the
26278 // `circuit_breaker` arm entirely — the last unlifted inline
26279 // field access on `is_empty` before this lift), a
26280 // `circuit_breaker == Some(_)` collapse that key-off a
26281 // validate-gate-clamped bounds check (which would silently
26282 // classify a past-the-guard `Some(CircuitBreaker { max_failures:
26283 // 0, window: 0s })` as empty because it fails the value-shape
26284 // gate), or an accessor-side detour that no longer names the
26285 // substrate-primitive typed dispatch.
26286 //
26287 // Fifth "the emptiness predicate must route through the
26288 // substrate-primitive typed dispatch" composition pin on the
26289 // M3 mesh-slot family — closes the last unlifted composition
26290 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
26291 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
26292 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
26293 // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
26294 // composition pins on the sibling primitive-Copy + composite-
26295 // Copy axes, extended onto the peer per-`:politicas`
26296 // composite-Copy `Option<CircuitBreaker>` axis).
26297 let empty = MeshPolicy::default();
26298 assert!(
26299 empty.is_empty(),
26300 "MeshPolicy::default() must be is_empty() — every axis \
26301 defaults to None",
26302 );
26303 for cb in [
26304 CircuitBreaker {
26305 max_failures: 1,
26306 window: Duration::from_millis(1),
26307 },
26308 CircuitBreaker {
26309 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
26310 window: POLICY_BREAKER_WINDOW_MAX,
26311 },
26312 ] {
26313 let p = MeshPolicy {
26314 circuit_breaker: Some(cb),
26315 ..MeshPolicy::default()
26316 };
26317 assert!(
26318 !p.is_empty(),
26319 "MeshPolicy::is_empty must return false when \
26320 :circuit-breaker is {cb:?} — the emptiness predicate \
26321 reads \"any axis carries a value\", not \"any axis \
26322 carries a value the validate gate accepts\"",
26323 );
26324 assert_eq!(
26325 p.circuit_breaker().is_none(),
26326 p.is_empty(),
26327 "when :circuit-breaker is the only set axis, \
26328 is_empty() must equal circuit_breaker().is_none() — \
26329 the accessor and the emptiness predicate must route \
26330 through the same substrate-primitive typed dispatch \
26331 on the :circuit-breaker arm",
26332 );
26333 }
26334 }
26335
26336 #[test]
26337 fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
26338 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26339 // `:circuit-breaker` value-shape gate must key off
26340 // [`MeshPolicy::circuit_breaker`], not the raw
26341 // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
26342 // whose only set axis is a `Some(CircuitBreaker { max_failures:
26343 // 0, .. })` must surface the `PolicyBreakerZeroFailures`
26344 // refusal exactly, and the same MeshPolicy with the breaker at
26345 // the canonical lower boundary
26346 // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
26347 // pass validate. The pair jointly pins the accessor +
26348 // validate-gate composition: any future silent detour that had
26349 // the accessor omit the `Some(CircuitBreaker { max_failures:
26350 // 0, .. })` arm (a
26351 // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
26352 // collapse) would silently absorb the
26353 // `PolicyBreakerZeroFailures` refusal at the accessor
26354 // boundary — the composition pin catches that at caixa-core
26355 // build time.
26356 //
26357 // Sibling of the peer [`validate_politicas`]
26358 // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
26359 // composition pins on the sibling primitive-Copy + composite-
26360 // Copy optional-scalar axes — same "the validate / shape-gate
26361 // predicate must route through the substrate-primitive typed
26362 // dispatch" discipline extended onto the peer per-`:politicas`
26363 // composite-Copy `Option<CircuitBreaker>` axis. Second
26364 // composition-with-accessor pin on the M3 mesh-slot
26365 // `Option<CircuitBreaker>` arm alongside the
26366 // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
26367 let mut spec = three_member_spec();
26368 spec.politicas = MeshPolicy {
26369 circuit_breaker: Some(CircuitBreaker {
26370 max_failures: 0,
26371 window: Duration::from_millis(1),
26372 }),
26373 ..MeshPolicy::default()
26374 };
26375 assert!(
26376 matches!(
26377 spec.validate(),
26378 Err(AplicacaoError::PolicyBreakerZeroFailures)
26379 ),
26380 "validate_politicas must reject max_failures == 0 with \
26381 PolicyBreakerZeroFailures — the accessor and the validate \
26382 gate must route through the same substrate-primitive \
26383 typed dispatch on the :circuit-breaker zero-floor arm",
26384 );
26385 spec.politicas = MeshPolicy {
26386 circuit_breaker: Some(CircuitBreaker {
26387 max_failures: 1,
26388 window: Duration::from_millis(1),
26389 }),
26390 ..MeshPolicy::default()
26391 };
26392 assert!(
26393 spec.validate().is_ok(),
26394 "validate_politicas must accept a CircuitBreaker at the \
26395 canonical lower boundary (max_failures = 1, window = \
26396 1ms) — the accessor and the validate gate must route \
26397 through the same substrate-primitive typed dispatch on \
26398 the :circuit-breaker arm",
26399 );
26400 }
26401
26402 #[test]
26403 fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
26404 // The canonical per-`:politicas :circuit-breaker` `:max-failures`
26405 // Envoy-outlier-detection trip-threshold scalar pin:
26406 // [`CircuitBreaker::max_failures`] must return the
26407 // `:politicas :circuit-breaker :max-failures` typed `u32`
26408 // verbatim, byte-equal to the raw field access across every
26409 // representative value in the accept-set — `1` (the lower
26410 // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
26411 // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
26412 // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
26413 // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
26414 // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
26415 // refusal), `0` (a past-the-guard sentinel that pins the accessor
26416 // doesn't perform a silent bounds-collapse into `1` on the zero
26417 // arm — validate rejects zero but the accessor must ship the
26418 // raw slot verbatim so a validate-time gate regression surfaces
26419 // at the emit boundary rather than being silently absorbed),
26420 // `u32::MAX` (a past-the-guard sentinel that pins the accessor
26421 // doesn't perform a silent bounds-collapse through
26422 // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
26423 //
26424 // First sub-struct required-scalar accessor pin on the M3
26425 // mesh-slot family — sibling in shape to the peer per-`:membros`
26426 // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
26427 // (a40b0e3) required-`String`-carry accessor pins and the peer
26428 // per-`:contratos` [`WitContract::source`] /
26429 // [`WitContract::destination`] (7f0fd43) required-`String`-carry
26430 // accessor pins, extended onto the peer per-`CircuitBreaker`
26431 // required-`u32` scalar-value axis. Pins against a future silent
26432 // detour that re-derived the trip threshold from a peer axis (an
26433 // accidental `self.window.as_secs() as u32` collapse that read
26434 // the breaker's rolling-window duration as a failure count), a
26435 // `0 → 1` cluster-default projection (which would silently absorb
26436 // the `PolicyBreakerZeroFailures` refusal case at the accessor
26437 // boundary), or a bounds-collapsing accessor that clamped the
26438 // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
26439 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
26440 // must ship the raw slot verbatim).
26441 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
26442 let cb = CircuitBreaker {
26443 max_failures,
26444 window: Duration::from_secs(60),
26445 };
26446 assert_eq!(
26447 cb.max_failures(),
26448 max_failures,
26449 "CircuitBreaker::max_failures must return :politicas \
26450 :circuit-breaker :max-failures verbatim (got {}, \
26451 expected {max_failures})",
26452 cb.max_failures(),
26453 );
26454 assert_eq!(
26455 cb.max_failures(),
26456 cb.max_failures,
26457 "CircuitBreaker::max_failures must byte-equal the raw \
26458 .max_failures field access across every value in the \
26459 u32 accept-set",
26460 );
26461 }
26462 }
26463
26464 #[test]
26465 fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
26466 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26467 // `:circuit-breaker :max-failures` zero-floor arm must key off
26468 // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
26469 // field access. Structurally: a `CircuitBreaker { max_failures:
26470 // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
26471 // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
26472 // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
26473 // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
26474 // pass validate. The pair jointly pins the accessor +
26475 // validate-gate composition: any future silent detour that had
26476 // the accessor return a fresh `1` on the zero arm (a
26477 // `.max_failures().max(1)` collapse) would silently absorb the
26478 // `PolicyBreakerZeroFailures` refusal at the accessor boundary
26479 // and the validate gate would accept a struct-literal
26480 // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
26481 // catches that at caixa-core build time.
26482 //
26483 // Peer of the sibling per-`:politicas`
26484 // [`MeshPolicy::mtls_required`] (c0110f1) /
26485 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
26486 // (7073d0f) accessor-composition pins on the sibling optional-
26487 // scalar axes — same "the validate / shape-gate predicate must
26488 // route through the substrate-primitive typed dispatch"
26489 // discipline extended onto the peer per-`CircuitBreaker`
26490 // required-scalar composition axis.
26491 let mut spec = three_member_spec();
26492 spec.politicas = MeshPolicy {
26493 circuit_breaker: Some(CircuitBreaker {
26494 max_failures: 0,
26495 window: Duration::from_secs(60),
26496 }),
26497 ..MeshPolicy::default()
26498 };
26499 assert!(
26500 matches!(
26501 spec.validate(),
26502 Err(AplicacaoError::PolicyBreakerZeroFailures)
26503 ),
26504 "validate_politicas must reject max_failures == 0 with \
26505 PolicyBreakerZeroFailures — the accessor and the validate \
26506 gate must route through the same substrate-primitive typed \
26507 dispatch on the :max-failures zero-floor arm",
26508 );
26509 spec.politicas = MeshPolicy {
26510 circuit_breaker: Some(CircuitBreaker {
26511 max_failures: 1,
26512 window: Duration::from_secs(60),
26513 }),
26514 ..MeshPolicy::default()
26515 };
26516 assert!(
26517 spec.validate().is_ok(),
26518 "validate_politicas must accept max_failures == 1 (the \
26519 lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
26520 accept-set)",
26521 );
26522 }
26523
26524 #[test]
26525 fn circuit_breaker_max_failures_projects_u32_by_copy() {
26526 // The by-copy pin: [`CircuitBreaker::max_failures`] returns
26527 // `u32` by copy — `u32` is `Copy` and the accessor must return
26528 // by value, not by reference. Peer of the sibling
26529 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
26530 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
26531 // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
26532 // optional-scalar axes, extended onto the peer
26533 // per-`CircuitBreaker` required-`u32` copy-invariant shape —
26534 // the accessor's returned `u32` must outlive `&self` (multiple
26535 // calls must return equal values from a dropped-`&self` copy,
26536 // since the returned scalar carries no borrow), and calling
26537 // the accessor twice on the same CircuitBreaker must yield the
26538 // same `u32` verbatim (idempotent, no side effects on `&self`).
26539 //
26540 // Pins against a future silent detour that returned `&u32`
26541 // (which would type-check but silently break every downstream
26542 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
26543 // first parameter is `u32`, and `&u32` would fold to a detached
26544 // copy at the call site with a `*` deref the sibling accessors
26545 // don't need), an accidental `.max_failures.wrapping_add(0)`
26546 // detour that returned a fresh copy through an arithmetic
26547 // no-op (breaking a future `const fn` regression), or a
26548 // one-arm-only accessor that returned a saturating value on
26549 // some sentinel input (breaking the pass-through invariant the
26550 // sibling required-scalar accessors carry).
26551 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
26552 let cb = CircuitBreaker {
26553 max_failures,
26554 window: Duration::from_secs(60),
26555 };
26556 let first = cb.max_failures();
26557 let second = cb.max_failures();
26558 assert_eq!(
26559 first, second,
26560 "CircuitBreaker::max_failures must be idempotent — two \
26561 successive calls on the same &self must return the \
26562 same u32",
26563 );
26564 assert_eq!(
26565 first, max_failures,
26566 "CircuitBreaker::max_failures must return :politicas \
26567 :circuit-breaker :max-failures verbatim by copy — \
26568 got {first}, expected {max_failures}",
26569 );
26570 }
26571 }
26572
26573 #[test]
26574 fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
26575 // The canonical per-`:politicas :circuit-breaker` `:window`
26576 // Envoy-outlier-detection rolling-observation-interval scalar
26577 // pin: [`CircuitBreaker::window`] must return the
26578 // `:politicas :circuit-breaker :window` typed `Duration`
26579 // verbatim, byte-equal to the raw field access across every
26580 // representative value in the accept-set — `Duration::from_millis(1)`
26581 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
26582 // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
26583 // gate carves out on the sibling `PolicyBreakerZeroWindow`
26584 // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
26585 // same gate carves out on the sibling
26586 // `PolicyBreakerWindowExceedsCap` refusal),
26587 // `Duration::ZERO` (a past-the-guard sentinel that pins the
26588 // accessor doesn't perform a silent bounds-collapse into
26589 // `Duration::from_millis(1)` on the zero arm — validate rejects
26590 // zero but the accessor must ship the raw slot verbatim so a
26591 // validate-time gate regression surfaces at the emit boundary
26592 // rather than being silently absorbed),
26593 // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
26594 // far above the 1h cap — that pins the accessor doesn't perform
26595 // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
26596 // at the return path).
26597 //
26598 // Second sub-struct required-scalar accessor pin on the M3
26599 // mesh-slot family — sibling in shape to the just-landed
26600 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26601 // (3a74062) required-`u32` accessor pin on the peer
26602 // per-`CircuitBreaker` required-axis, extended onto the
26603 // per-sub-struct required-`Duration` axis. Pins against a
26604 // future silent detour that re-derived the observation window
26605 // from a peer axis (an accidental
26606 // `Duration::from_secs(self.max_failures as u64)` collapse that
26607 // read the breaker's trip count as an observation-interval
26608 // duration), a `Duration::ZERO → Duration::from_millis(1)`
26609 // cluster-default projection (which would silently absorb the
26610 // `PolicyBreakerZeroWindow` refusal case at the accessor
26611 // boundary), or a bounds-collapsing accessor that clamped the
26612 // return through `POLICY_BREAKER_WINDOW_MAX` (the
26613 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
26614 // must ship the raw slot verbatim).
26615 for window in [
26616 Duration::from_millis(1),
26617 POLICY_BREAKER_WINDOW_MAX,
26618 Duration::ZERO,
26619 Duration::from_secs(86_400),
26620 ] {
26621 let cb = CircuitBreaker {
26622 max_failures: 5,
26623 window,
26624 };
26625 assert_eq!(
26626 cb.window(),
26627 window,
26628 "CircuitBreaker::window must return :politicas \
26629 :circuit-breaker :window verbatim (got {:?}, \
26630 expected {window:?})",
26631 cb.window(),
26632 );
26633 assert_eq!(
26634 cb.window(),
26635 cb.window,
26636 "CircuitBreaker::window must byte-equal the raw \
26637 .window field access across every value in the \
26638 Duration accept-set",
26639 );
26640 }
26641 }
26642
26643 #[test]
26644 fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
26645 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26646 // `:circuit-breaker :window` zero-floor arm must key off
26647 // [`CircuitBreaker::window`], not the raw `.window` field
26648 // access. Structurally: a `CircuitBreaker { window:
26649 // Duration::ZERO, .. }` embedded in a
26650 // `:politicas :circuit-breaker` slot must surface the
26651 // `PolicyBreakerZeroWindow` refusal exactly, and a
26652 // `CircuitBreaker { window: Duration::from_millis(1), .. }`
26653 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
26654 // accept-set) must pass validate. The pair jointly pins the
26655 // accessor + validate-gate composition: any future silent
26656 // detour that had the accessor return a fresh
26657 // `Duration::from_millis(1)` on the zero arm (a
26658 // `.window().max(Duration::from_millis(1))` collapse) would
26659 // silently absorb the `PolicyBreakerZeroWindow` refusal at the
26660 // accessor boundary and the validate gate would accept a
26661 // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
26662 // — the composition pin catches that at caixa-core build time.
26663 //
26664 // Peer of the sibling per-`CircuitBreaker`
26665 // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
26666 // pin on the peer required-scalar `:max-failures` axis — same
26667 // "the validate / shape-gate predicate must route through the
26668 // substrate-primitive typed dispatch" discipline extended onto
26669 // the peer per-`CircuitBreaker` required-`Duration` composition
26670 // axis.
26671 let mut spec = three_member_spec();
26672 spec.politicas = MeshPolicy {
26673 circuit_breaker: Some(CircuitBreaker {
26674 max_failures: 5,
26675 window: Duration::ZERO,
26676 }),
26677 ..MeshPolicy::default()
26678 };
26679 assert!(
26680 matches!(
26681 spec.validate(),
26682 Err(AplicacaoError::PolicyBreakerZeroWindow)
26683 ),
26684 "validate_politicas must reject window == Duration::ZERO \
26685 with PolicyBreakerZeroWindow — the accessor and the \
26686 validate gate must route through the same substrate-\
26687 primitive typed dispatch on the :window zero-floor arm",
26688 );
26689 spec.politicas = MeshPolicy {
26690 circuit_breaker: Some(CircuitBreaker {
26691 max_failures: 5,
26692 window: Duration::from_millis(1),
26693 }),
26694 ..MeshPolicy::default()
26695 };
26696 assert!(
26697 spec.validate().is_ok(),
26698 "validate_politicas must accept window == \
26699 Duration::from_millis(1) (the lower boundary of the \
26700 1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
26701 );
26702 }
26703
26704 #[test]
26705 fn circuit_breaker_window_projects_duration_by_copy() {
26706 // The by-copy pin: [`CircuitBreaker::window`] returns
26707 // `Duration` by copy — `Duration` is `Copy` and the accessor
26708 // must return by value, not by reference. Peer of the sibling
26709 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26710 // (3a74062) by-copy pin on the peer required-scalar
26711 // `:max-failures` axis, extended onto the peer
26712 // per-`CircuitBreaker` required-`Duration` copy-invariant shape
26713 // — the accessor's returned `Duration` must outlive `&self`
26714 // (multiple calls must return equal values from a
26715 // dropped-`&self` copy, since the returned scalar carries no
26716 // borrow), and calling the accessor twice on the same
26717 // CircuitBreaker must yield the same `Duration` verbatim
26718 // (idempotent, no side effects on `&self`).
26719 //
26720 // Pins against a future silent detour that returned
26721 // `&Duration` (which would type-check but silently break every
26722 // downstream `Duration`-by-value consumer —
26723 // [`crate::render::require_positive_canonical_bounded_duration`]'s
26724 // first parameter is `Duration`, and `&Duration` would fold to
26725 // a detached copy at the call site with a `*` deref the sibling
26726 // accessors don't need), an accidental `.window + Duration::ZERO`
26727 // detour that returned a fresh copy through an arithmetic
26728 // no-op (breaking a future `const fn` regression), or a
26729 // one-arm-only accessor that returned a saturating value on
26730 // some sentinel input (breaking the pass-through invariant the
26731 // sibling required-scalar accessors carry).
26732 for window in [
26733 Duration::from_millis(1),
26734 POLICY_BREAKER_WINDOW_MAX,
26735 Duration::ZERO,
26736 Duration::from_secs(86_400),
26737 ] {
26738 let cb = CircuitBreaker {
26739 max_failures: 5,
26740 window,
26741 };
26742 let first = cb.window();
26743 let second = cb.window();
26744 assert_eq!(
26745 first, second,
26746 "CircuitBreaker::window must be idempotent — two \
26747 successive calls on the same &self must return the \
26748 same Duration",
26749 );
26750 assert_eq!(
26751 first, window,
26752 "CircuitBreaker::window must return :politicas \
26753 :circuit-breaker :window verbatim by copy — \
26754 got {first:?}, expected {window:?}",
26755 );
26756 }
26757 }
26758
26759 #[test]
26760 fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
26761 // Apex-identity pair-invariant pin composing both substrate-
26762 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26763 // and [`WitContract::destination`] — at the emit-side call shape
26764 // every per-`(:de, :para)` CNP L4 port reader now takes. The
26765 // invariant, evaluated per-edge:
26766 //
26767 // spec.port_for_destination(c.destination()) == expected_port
26768 //
26769 // where `expected_port` is `entrada.port` when
26770 // `c.destination() == entrada.destination()` and
26771 // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
26772 // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
26773 // pin on the per-`:entrada` axis — that pin encodes the apex
26774 // ingress L4 identity via `entrada.destination()`; this pin
26775 // encodes the per-edge L4 identity via `c.destination()`, and
26776 // both compose on the same substrate-primitive resolver so a
26777 // future refactor that silently split either accessor's apex
26778 // behavior surfaces at caixa-core build time.
26779 let mut spec = three_member_spec();
26780 if let Some(e) = spec.entrada.as_mut() {
26781 e.para = "cart".into();
26782 e.port = 8443;
26783 }
26784 let apex_contract = WitContract {
26785 de: "checkout".into(),
26786 para: "cart".into(),
26787 wit: "wasi:http/proxy".into(),
26788 endpoint: Some("/hello".into()),
26789 subject: None,
26790 slot: None,
26791 };
26792 assert_eq!(
26793 spec.port_for_destination(apex_contract.destination()),
26794 8443,
26795 "`spec.port_for_destination(c.destination())` must equal \
26796 `entrada.port` when the contract callee names the ingress \
26797 apex — the CNP per-edge L4 port and the HTTPRoute apex \
26798 backendRef port share this substrate-primitive resolver.",
26799 );
26800 let non_apex_contract = WitContract {
26801 de: "cart".into(),
26802 para: "payment".into(),
26803 wit: "wasi:http/proxy".into(),
26804 endpoint: Some("/charge".into()),
26805 subject: None,
26806 slot: None,
26807 };
26808 assert_eq!(
26809 spec.port_for_destination(non_apex_contract.destination()),
26810 DEFAULT_SERVICO_PORT,
26811 "`spec.port_for_destination(c.destination())` must fall back \
26812 to the substrate-canonical port floor when the contract \
26813 callee is not the ingress apex — the resolver's non-apex \
26814 arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
26815 );
26816 }
26817
26818 #[test]
26819 fn membro_key_consts_are_lower_camel_case_shape() {
26820 // Shape-pin: every `MEMBRO_KEY_*` const must be a
26821 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26822 // `kebab-case` hyphens, no leading colon, no `PascalCase`
26823 // leading capital, no whitespace / dots) — the canonical shape
26824 // the `#[serde(rename_all = "camelCase")]` derive produces on
26825 // [`Membro`]. A future flip to a non-camelCase attribute at
26826 // the derive surfaces both here (this test fails on the
26827 // stale-constant shape) and at
26828 // `membro_serde_keys_match_lifted_membro_key_consts` (that test
26829 // fails on the mismatch between const and derive). Peer with
26830 // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
26831 // on the sibling `SupervisorSpec` top-level axis.
26832 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
26833 assert!(
26834 !key.is_empty(),
26835 "MEMBRO_KEY_* must be non-empty (got {key:?})"
26836 );
26837 let first = key.chars().next().unwrap();
26838 assert!(
26839 first.is_ascii_lowercase(),
26840 "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
26841 (got {key:?}, leads with {first:?})",
26842 );
26843 assert!(
26844 key.chars().all(|c| c.is_ascii_alphanumeric()),
26845 "MEMBRO_KEY_* must be ASCII-alphanumeric only \
26846 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26847 );
26848 }
26849 }
26850
26851 // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
26852
26853 #[test]
26854 fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
26855 // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
26856 // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
26857 // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
26858 // keys the `#[serde(rename_all = "camelCase")]` attribute on
26859 // [`WitContract`] emits for the required-triad. The three
26860 // sibling payload-arm keys already pin under
26861 // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
26862 // `STORE_FIELD_NAME` — pin all six alongside so a future
26863 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26864 // verbatim-field-name flip at the derive attribute (any of which
26865 // would silently break every downstream JSON consumer that
26866 // reaches for one of the six via `Value::get(...)`) surfaces
26867 // here as a build-time test failure at `aplicacao.rs`, not as an
26868 // apply-time `.get(<stale-canonical-const>)` returning `None`
26869 // far from the derive-attr drift's commit. Peer with the sibling
26870 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26871 // pin on the M3 `:membros` per-entry axis — same discipline the
26872 // `Membro` per-entry lift established, extended here to the
26873 // sibling M3 `WitContract` per-`:contratos` entry axis, the last
26874 // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
26875 // axis on the Aplicacao surface without a lifted serde-key peer.
26876 let c = WitContract {
26877 de: "cart".into(),
26878 para: "catalog".into(),
26879 wit: "wasi:http/proxy".into(),
26880 endpoint: Some("/lookup".into()),
26881 subject: None,
26882 slot: None,
26883 };
26884 let json = serde_json::to_string(&c).unwrap();
26885 for key in [
26886 crate::CONTRATO_KEY_DE,
26887 crate::CONTRATO_KEY_PARA,
26888 crate::CONTRATO_KEY_WIT,
26889 WitTarget::HTTP_FIELD_NAME,
26890 ] {
26891 let quoted = format!("\"{key}\"");
26892 assert!(
26893 json.contains("ed),
26894 "serialized WitContract must carry the lifted \
26895 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
26896 {quoted} verbatim in the JSON emission (got: {json})",
26897 );
26898 }
26899
26900 // Pin the two remaining payload-arm keys by round-tripping a
26901 // `WitContract` under each payload-shape (pub-sub, store) — the
26902 // required-triad appears on every emission but the payload arms
26903 // only surface when their `Option<String>` field is `Some`.
26904 let pubsub = WitContract {
26905 de: "cart".into(),
26906 para: "events".into(),
26907 wit: "nats:pub-sub".into(),
26908 endpoint: None,
26909 subject: Some("orders.placed".into()),
26910 slot: None,
26911 };
26912 let pubsub_json = serde_json::to_string(&pubsub).unwrap();
26913 let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
26914 assert!(
26915 pubsub_json.contains(&pubsub_quoted),
26916 "serialized pub-sub WitContract must carry the lifted \
26917 WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
26918 verbatim in the JSON emission (got: {pubsub_json})",
26919 );
26920 let store = WitContract {
26921 de: "cart".into(),
26922 para: "sessions".into(),
26923 wit: "wasi:keyvalue/store".into(),
26924 endpoint: None,
26925 subject: None,
26926 slot: Some("cart/$id".into()),
26927 };
26928 let store_json = serde_json::to_string(&store).unwrap();
26929 let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
26930 assert!(
26931 store_json.contains(&store_quoted),
26932 "serialized store WitContract must carry the lifted \
26933 WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
26934 verbatim in the JSON emission (got: {store_json})",
26935 );
26936 }
26937
26938 #[test]
26939 fn contrato_key_consts_are_pairwise_distinct() {
26940 // Cross-axis drift-detection pin: a future collapse of the six
26941 // canonical [`WitContract`] per-entry byte-strings onto the same
26942 // value (e.g. an accidental copy-paste flip of
26943 // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
26944 // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
26945 // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
26946 // every downstream probe on one axis onto the sibling axis's
26947 // overlay entry and pass every propagation-probe test that
26948 // expected only the stale axis's value. Peer of the sibling
26949 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
26950 // widened here to the six-way axis the `WitContract`
26951 // required-triad + `WitTarget` payload-triad jointly cover.
26952 let all = [
26953 crate::CONTRATO_KEY_DE,
26954 crate::CONTRATO_KEY_PARA,
26955 crate::CONTRATO_KEY_WIT,
26956 WitTarget::HTTP_FIELD_NAME,
26957 WitTarget::PUBSUB_FIELD_NAME,
26958 WitTarget::STORE_FIELD_NAME,
26959 ];
26960 for (i, a) in all.iter().enumerate() {
26961 for b in all.iter().skip(i + 1) {
26962 assert_ne!(
26963 a, b,
26964 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
26965 must be pairwise-distinct canonical byte-sequences \
26966 — got `{a}` == `{b}`",
26967 );
26968 }
26969 }
26970 }
26971
26972 #[test]
26973 fn contrato_key_consts_are_lower_camel_case_shape() {
26974 // Shape-pin: every `CONTRATO_KEY_*` (and every peer
26975 // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
26976 // byte-sequence (no `snake_case` underscores, no `kebab-case`
26977 // hyphens, no leading colon, no `PascalCase` leading capital, no
26978 // whitespace / dots) — the canonical shape the
26979 // `#[serde(rename_all = "camelCase")]` derive produces on
26980 // [`WitContract`]. A future flip to a non-camelCase attribute at
26981 // the derive surfaces both here (this test fails on the
26982 // stale-constant shape) and at
26983 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26984 // (that test fails on the mismatch between const and derive).
26985 // Peer with `membro_key_consts_are_lower_camel_case_shape`
26986 // (ce80ca0) on the sibling `Membro` per-entry axis.
26987 for key in [
26988 crate::CONTRATO_KEY_DE,
26989 crate::CONTRATO_KEY_PARA,
26990 crate::CONTRATO_KEY_WIT,
26991 WitTarget::HTTP_FIELD_NAME,
26992 WitTarget::PUBSUB_FIELD_NAME,
26993 WitTarget::STORE_FIELD_NAME,
26994 ] {
26995 assert!(
26996 !key.is_empty(),
26997 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26998 non-empty (got {key:?})"
26999 );
27000 let first = key.chars().next().unwrap();
27001 assert!(
27002 first.is_ascii_lowercase(),
27003 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
27004 with an ASCII-lowercase byte (got {key:?}, leads with \
27005 {first:?})",
27006 );
27007 assert!(
27008 key.chars().all(|c| c.is_ascii_alphanumeric()),
27009 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
27010 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
27011 whitespace (got {key:?})",
27012 );
27013 }
27014 }
27015
27016 // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
27017
27018 #[test]
27019 fn entrada_serde_keys_match_lifted_entrada_key_consts() {
27020 // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
27021 // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
27022 // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
27023 // name the exact camelCase JSON keys the
27024 // `#[serde(rename_all = "camelCase")]` attribute on
27025 // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
27026 // pin that each canonical byte-sequence appears verbatim in the
27027 // JSON — a future accidental `rename_all = "snake_case"` /
27028 // `"kebab-case"` / verbatim-field-name flip at the derive
27029 // attribute (any of which would silently break every downstream
27030 // JSON consumer that reaches for one of the four consts via
27031 // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
27032 // emitter's per-Aplicacao hostname/paths/port projection, the
27033 // future `app-operator` reconciler's per-Aplicacao ingress
27034 // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
27035 // materializer's admission-time cross-check) surfaces here as
27036 // a build-time test failure at `aplicacao.rs`, not as an
27037 // apply-time `.get(<stale-canonical-const>)` returning `None`
27038 // far from the derive-attr drift's commit. Peer with the
27039 // sibling
27040 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
27041 // (ca463a4) and
27042 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
27043 // pins on the M3 collection-slot atom axes — same discipline
27044 // both collection-slot lifts established, extended here to the
27045 // singleton `:entrada` mesh-slot atom axis, the last M3
27046 // typed-struct top-level `#[serde(rename_all = "camelCase")]`
27047 // axis on the Aplicacao surface without a lifted serde-key
27048 // peer.
27049 let e = Entrada {
27050 host: "checkout.quero.cloud".into(),
27051 para: "cart".into(),
27052 paths: vec!["/cart".into()],
27053 port: 8080,
27054 };
27055 let json = serde_json::to_string(&e).unwrap();
27056 for key in [
27057 crate::ENTRADA_KEY_HOST,
27058 crate::ENTRADA_KEY_PARA,
27059 crate::ENTRADA_KEY_PATHS,
27060 crate::ENTRADA_KEY_PORT,
27061 ] {
27062 let quoted = format!("\"{key}\"");
27063 assert!(
27064 json.contains("ed),
27065 "serialized Entrada must carry the lifted ENTRADA_KEY_* \
27066 byte-sequence {quoted} verbatim in the JSON emission \
27067 (got: {json})",
27068 );
27069 }
27070 }
27071
27072 #[test]
27073 fn entrada_key_consts_are_pairwise_distinct() {
27074 // Cross-axis drift-detection pin: a future collapse of the four
27075 // canonical [`Entrada`] singleton byte-strings onto the same
27076 // value (e.g. an accidental copy-paste flip of
27077 // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
27078 // silently reroute every downstream probe on one axis onto the
27079 // sibling axis's overlay entry and pass every propagation-probe
27080 // test that expected only the stale axis's value — the
27081 // Gateway/HTTPRoute emitter would read the hostname string
27082 // where the destination-Servico name was expected (or vice
27083 // versa), the admission-webhook cross-check would compare the
27084 // wrong pair of values, and the resulting Gateway resource
27085 // would either be admitted with garbage or rejected at the
27086 // controller far from the rebrand commit's source. Peer of the
27087 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
27088 // tetrad (40cc4e5), the two-way distinct pin on the
27089 // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
27090 // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
27091 // triad (ca463a4).
27092 let all = [
27093 crate::ENTRADA_KEY_HOST,
27094 crate::ENTRADA_KEY_PARA,
27095 crate::ENTRADA_KEY_PATHS,
27096 crate::ENTRADA_KEY_PORT,
27097 ];
27098 for (i, a) in all.iter().enumerate() {
27099 for b in all.iter().skip(i + 1) {
27100 assert_ne!(
27101 a, b,
27102 "ENTRADA_KEY_* consts must be pairwise-distinct \
27103 canonical byte-sequences — got `{a}` == `{b}`",
27104 );
27105 }
27106 }
27107 }
27108
27109 #[test]
27110 fn entrada_key_consts_are_lower_camel_case_shape() {
27111 // Shape-pin: every `ENTRADA_KEY_*` const must be a
27112 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27113 // `kebab-case` hyphens, no leading colon, no `PascalCase`
27114 // leading capital, no whitespace / dots) — the canonical shape
27115 // the `#[serde(rename_all = "camelCase")]` derive produces on
27116 // [`Entrada`]. A future flip to a non-camelCase attribute at
27117 // the derive surfaces both here (this test fails on the
27118 // stale-constant shape) and at
27119 // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
27120 // test fails on the mismatch between const and derive). Peer
27121 // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
27122 // and `contrato_key_consts_are_lower_camel_case_shape`
27123 // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
27124 // entry axes.
27125 for key in [
27126 crate::ENTRADA_KEY_HOST,
27127 crate::ENTRADA_KEY_PARA,
27128 crate::ENTRADA_KEY_PATHS,
27129 crate::ENTRADA_KEY_PORT,
27130 ] {
27131 assert!(
27132 !key.is_empty(),
27133 "ENTRADA_KEY_* must be non-empty (got {key:?})"
27134 );
27135 let first = key.chars().next().unwrap();
27136 assert!(
27137 first.is_ascii_lowercase(),
27138 "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
27139 (got {key:?}, leads with {first:?})",
27140 );
27141 assert!(
27142 key.chars().all(|c| c.is_ascii_alphanumeric()),
27143 "ENTRADA_KEY_* must be ASCII-alphanumeric only \
27144 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27145 );
27146 }
27147 }
27148
27149 // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
27150
27151 #[test]
27152 fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
27153 // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
27154 // ([`crate::POLITICAS_KEY_TIMEOUT`] /
27155 // [`crate::POLITICAS_KEY_RETRIES`] /
27156 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
27157 // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
27158 // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
27159 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
27160 // on [`MeshPolicy`] emits. Three of the five axes
27161 // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
27162 // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
27163 // camelCase transforms — the derive-attribute is load-bearing
27164 // on those, unlike the sibling `Entrada` / `Membro` /
27165 // `WitContract` structs whose fields are all lowercase-single-
27166 // word and where the derive is a no-op on every axis.
27167 // Serialize a fully-populated [`MeshPolicy`] (every axis
27168 // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
27169 // on none of the five slots) and pin that each canonical
27170 // byte-sequence appears verbatim in the JSON — a future
27171 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
27172 // verbatim-field-name flip at the derive attribute (any of
27173 // which would silently break every downstream JSON consumer
27174 // that reaches for one of the five consts via
27175 // `Value::get(...)` — the future M4 per-edge `:politicas`
27176 // overlay projection onto Cilium `L7Rules` and Gateway API
27177 // `HTTPRoute` backend timeouts, the future
27178 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
27179 // admission-time mesh-policy cross-check, the future
27180 // `feira lint` per-`:politicas` bound-check gate) surfaces here
27181 // as a build-time test failure at `aplicacao.rs`, not as an
27182 // apply-time `.get(<stale-canonical-const>)` returning `None`
27183 // far from the derive-attr drift's commit. Peer with the
27184 // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
27185 // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
27186 // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
27187 // (ce80ca0) pins on the M3 collection-slot / singleton-slot
27188 // atom axes — same discipline every M3 sibling lift
27189 // established, extended here to the singleton `:politicas`
27190 // mesh-slot atom axis, closing the last M3 typed-struct
27191 // top-level `#[serde(rename_all = "camelCase")]` axis on the
27192 // Aplicacao surface without a lifted serde-key peer.
27193 let p = MeshPolicy {
27194 timeout: Some(Duration::from_secs(30)),
27195 retries: Some(3),
27196 circuit_breaker: Some(CircuitBreaker {
27197 max_failures: 5,
27198 window: Duration::from_secs(60),
27199 }),
27200 mtls_required: Some(true),
27201 rate_limit: Some(RateLimit {
27202 rate: 100,
27203 window: Duration::from_secs(1),
27204 }),
27205 };
27206 let json = serde_json::to_string(&p).unwrap();
27207 for key in [
27208 crate::POLITICAS_KEY_TIMEOUT,
27209 crate::POLITICAS_KEY_RETRIES,
27210 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
27211 crate::POLITICAS_KEY_MTLS_REQUIRED,
27212 crate::POLITICAS_KEY_RATE_LIMIT,
27213 ] {
27214 let quoted = format!("\"{key}\"");
27215 assert!(
27216 json.contains("ed),
27217 "serialized MeshPolicy must carry the lifted \
27218 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
27219 JSON emission (got: {json})",
27220 );
27221 }
27222 }
27223
27224 #[test]
27225 fn politicas_key_consts_are_pairwise_distinct() {
27226 // Cross-axis drift-detection pin: a future collapse of the five
27227 // canonical [`MeshPolicy`] singleton byte-strings onto the same
27228 // value (e.g. an accidental copy-paste flip of
27229 // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
27230 // would silently reroute every downstream probe on one axis
27231 // onto the sibling axis's overlay entry and pass every
27232 // propagation-probe test that expected only the stale axis's
27233 // value — the M4 per-edge `:politicas` overlay projection would
27234 // read the retry-count string where the timeout duration was
27235 // expected (or vice versa), the CR materializer's admission
27236 // cross-check would compare the wrong pair of values, and the
27237 // resulting mesh reconciler would either bind the wrong axis
27238 // or reject the resource at reconcile far from the rebrand
27239 // commit's source. Peer of the sibling four-way distinct pin
27240 // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
27241 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
27242 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
27243 // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
27244 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27245 let all = [
27246 crate::POLITICAS_KEY_TIMEOUT,
27247 crate::POLITICAS_KEY_RETRIES,
27248 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
27249 crate::POLITICAS_KEY_MTLS_REQUIRED,
27250 crate::POLITICAS_KEY_RATE_LIMIT,
27251 ];
27252 for (i, a) in all.iter().enumerate() {
27253 for b in all.iter().skip(i + 1) {
27254 assert_ne!(
27255 a, b,
27256 "POLITICAS_KEY_* consts must be pairwise-distinct \
27257 canonical byte-sequences — got `{a}` == `{b}`",
27258 );
27259 }
27260 }
27261 }
27262
27263 #[test]
27264 fn politicas_key_consts_are_lower_camel_case_shape() {
27265 // Shape-pin: every `POLITICAS_KEY_*` const must be a
27266 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27267 // `kebab-case` hyphens, no leading colon, no `PascalCase`
27268 // leading capital, no whitespace / dots) — the canonical shape
27269 // the `#[serde(rename_all = "camelCase")]` derive produces on
27270 // [`MeshPolicy`]. A future flip to a non-camelCase attribute
27271 // at the derive surfaces both here (this test fails on the
27272 // stale-constant shape) and at
27273 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27274 // (that test fails on the mismatch between const and derive).
27275 // Peer with `entrada_key_consts_are_lower_camel_case_shape`
27276 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27277 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27278 // (ca463a4) on the sibling M3 typed-struct axes.
27279 for key in [
27280 crate::POLITICAS_KEY_TIMEOUT,
27281 crate::POLITICAS_KEY_RETRIES,
27282 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
27283 crate::POLITICAS_KEY_MTLS_REQUIRED,
27284 crate::POLITICAS_KEY_RATE_LIMIT,
27285 ] {
27286 assert!(
27287 !key.is_empty(),
27288 "POLITICAS_KEY_* must be non-empty (got {key:?})"
27289 );
27290 let first = key.chars().next().unwrap();
27291 assert!(
27292 first.is_ascii_lowercase(),
27293 "POLITICAS_KEY_* must lead with an ASCII-lowercase \
27294 byte (got {key:?}, leads with {first:?})",
27295 );
27296 assert!(
27297 key.chars().all(|c| c.is_ascii_alphanumeric()),
27298 "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
27299 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27300 );
27301 }
27302 }
27303
27304 // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
27305
27306 #[test]
27307 fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
27308 // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
27309 // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
27310 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
27311 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
27312 // [`CircuitBreaker`] emits inside the
27313 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
27314 // two axes (`max_failures` → `maxFailures`) is a non-trivial
27315 // camelCase transform — the derive-attribute is load-bearing on
27316 // that axis, unlike the sibling `window` field where the derive
27317 // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
27318 // pin that each canonical byte-sequence appears verbatim in the
27319 // JSON — a future accidental `rename_all = "snake_case"` /
27320 // `"kebab-case"` / verbatim-field-name flip at the derive
27321 // attribute (any of which would silently break every downstream
27322 // JSON consumer that reaches for one of the two consts via
27323 // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
27324 // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
27325 // per-edge `:politicas` overlay projection onto the mesh's
27326 // per-backend consecutive-failure-counter tripping threshold, the
27327 // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
27328 // admission-time breaker cross-check, the future `feira lint`
27329 // per-`:politicas :circuit-breaker` bound-check gate) surfaces
27330 // here as a build-time test failure at `aplicacao.rs`, not as an
27331 // apply-time `.get(<stale-canonical-const>)` returning `None`
27332 // far from the derive-attr drift's commit. Peer with the sibling
27333 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27334 // (b55cca7) parent-axis pin — that test pins the outer
27335 // sub-block key the derive on [`MeshPolicy`] emits, this test
27336 // pins the inner keys the derive on the payload type emits, so
27337 // the two together lock the whole [`MeshPolicy`] breaker-tuning
27338 // shape end-to-end at build time.
27339 let cb = CircuitBreaker {
27340 max_failures: 5,
27341 window: Duration::from_secs(60),
27342 };
27343 let json = serde_json::to_string(&cb).unwrap();
27344 for key in [
27345 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27346 crate::CIRCUIT_BREAKER_KEY_WINDOW,
27347 ] {
27348 let quoted = format!("\"{key}\"");
27349 assert!(
27350 json.contains("ed),
27351 "serialized CircuitBreaker must carry the lifted \
27352 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
27353 in the JSON emission (got: {json})",
27354 );
27355 }
27356 }
27357
27358 #[test]
27359 fn circuit_breaker_key_consts_are_pairwise_distinct() {
27360 // Cross-axis drift-detection pin: a future collapse of the two
27361 // canonical [`CircuitBreaker`] sub-block byte-strings onto the
27362 // same value (e.g. an accidental copy-paste flip of
27363 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
27364 // `"maxFailures"`) would silently reroute every downstream
27365 // probe on one axis onto the sibling axis's overlay entry and
27366 // pass every propagation-probe test that expected only the
27367 // stale axis's value — the M4 per-edge `:politicas` overlay
27368 // projection would read the failure-count where the window
27369 // duration was expected (or vice versa), the CR materializer's
27370 // admission cross-check would compare the wrong pair of values,
27371 // and the resulting mesh reconciler would either bind the wrong
27372 // axis or reject the resource at reconcile far from the rebrand
27373 // commit's source. Peer of the sibling five-way distinct pin on
27374 // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
27375 // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
27376 // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
27377 // six-way distinct pin on the `CONTRATO_KEY_*` triad +
27378 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27379 let all = [
27380 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27381 crate::CIRCUIT_BREAKER_KEY_WINDOW,
27382 ];
27383 for (i, a) in all.iter().enumerate() {
27384 for b in all.iter().skip(i + 1) {
27385 assert_ne!(
27386 a, b,
27387 "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
27388 canonical byte-sequences — got `{a}` == `{b}`",
27389 );
27390 }
27391 }
27392 }
27393
27394 #[test]
27395 fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
27396 // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
27397 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27398 // `kebab-case` hyphens, no leading colon, no `PascalCase`
27399 // leading capital, no whitespace / dots) — the canonical shape
27400 // the `#[serde(rename_all = "camelCase")]` derive produces on
27401 // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
27402 // at the derive surfaces both here (this test fails on the
27403 // stale-constant shape) and at
27404 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
27405 // (that test fails on the mismatch between const and derive).
27406 // Peer with `politicas_key_consts_are_lower_camel_case_shape`
27407 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
27408 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27409 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27410 // (ca463a4) on the sibling M3 typed-struct axes.
27411 for key in [
27412 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27413 crate::CIRCUIT_BREAKER_KEY_WINDOW,
27414 ] {
27415 assert!(
27416 !key.is_empty(),
27417 "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
27418 );
27419 let first = key.chars().next().unwrap();
27420 assert!(
27421 first.is_ascii_lowercase(),
27422 "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
27423 byte (got {key:?}, leads with {first:?})",
27424 );
27425 assert!(
27426 key.chars().all(|c| c.is_ascii_alphanumeric()),
27427 "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
27428 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27429 );
27430 }
27431 }
27432
27433 // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
27434
27435 #[test]
27436 fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
27437 // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
27438 // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
27439 // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
27440 // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
27441 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
27442 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
27443 // [`Placement`] emits. One of the four axes (`shard_key` →
27444 // `shardKey`) is a non-trivial camelCase transform — the
27445 // derive-attribute is load-bearing on that axis, unlike the
27446 // sibling `estrategia` / `clusters` / `affinity` axes whose
27447 // source-side field names carry no `_` and where the derive is a
27448 // no-op. Serialize a fully-populated [`Placement`] (both
27449 // `Option`-carrying axes `Some(_)` so
27450 // `skip_serializing_if = "Option::is_none"` fires on neither of
27451 // the two optional slots) and pin that each canonical
27452 // byte-sequence appears verbatim in the JSON — a future
27453 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
27454 // verbatim-field-name flip at the derive attribute (any of which
27455 // would silently break every downstream consumer that reaches
27456 // for one of the four consts via
27457 // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
27458 // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
27459 // aggregator's per-cluster fanout filter keying off
27460 // `placement.clusters`, the M3 shard-pool dispatch materializer
27461 // keying off `placement.shardKey`, the M3 Adaptive compression
27462 // pass weighting off `placement.affinity`, every downstream
27463 // dispatcher branching on `placement.estrategia`, the future
27464 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
27465 // admission-time placement cross-check, the future `feira lint`
27466 // per-`:placement` bound-check gate) surfaces here as a
27467 // build-time test failure at `aplicacao.rs`, not as an
27468 // apply-time `.get(<stale-canonical-const>)` returning `None`
27469 // far from the derive-attr drift's commit. Peer with the sibling
27470 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27471 // (b55cca7),
27472 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
27473 // (468e959),
27474 // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
27475 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
27476 // (ca463a4), and
27477 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
27478 // pins on the M3 collection-slot / singleton-slot atom axes —
27479 // closes the last M3 typed-struct top-level
27480 // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
27481 // surface without a drift-detection pin.
27482 let p = Placement {
27483 estrategia: PlacementStrategy::Sharded,
27484 clusters: vec!["rio".into(), "mar".into()],
27485 affinity: Some("data-locality".into()),
27486 shard_key: Some("$tenantId".into()),
27487 };
27488 let json = serde_json::to_string(&p).unwrap();
27489 for key in [
27490 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27491 crate::M3_PLACEMENT_KEY_CLUSTERS,
27492 crate::M3_PLACEMENT_KEY_AFFINITY,
27493 crate::M3_PLACEMENT_KEY_SHARD_KEY,
27494 ] {
27495 let quoted = format!("\"{key}\"");
27496 assert!(
27497 json.contains("ed),
27498 "serialized Placement must carry the lifted \
27499 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
27500 the JSON emission (got: {json})",
27501 );
27502 }
27503 }
27504
27505 #[test]
27506 fn m3_placement_key_consts_are_pairwise_distinct() {
27507 // Cross-axis drift-detection pin: a future collapse of the four
27508 // canonical [`Placement`] sub-block byte-strings onto the same
27509 // value (e.g. an accidental copy-paste flip of
27510 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
27511 // `"affinity"`) would silently reroute every downstream probe on
27512 // one axis onto the sibling axis's overlay entry and pass every
27513 // propagation-probe test that expected only the stale axis's
27514 // value — the M3 shard-pool dispatch materializer would read the
27515 // affinity placement-hint where the shard-selection template was
27516 // expected (or vice versa), the M3 Adaptive compression pass's
27517 // cross-check would compare the wrong pair of values, and the
27518 // resulting placement engine would either bind the wrong axis or
27519 // reject the resource at reconcile far from the rebrand commit's
27520 // source. Peer of the sibling two-way distinct pin on the
27521 // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
27522 // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
27523 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
27524 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
27525 // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
27526 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27527 let all = [
27528 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27529 crate::M3_PLACEMENT_KEY_CLUSTERS,
27530 crate::M3_PLACEMENT_KEY_AFFINITY,
27531 crate::M3_PLACEMENT_KEY_SHARD_KEY,
27532 ];
27533 for (i, a) in all.iter().enumerate() {
27534 for b in all.iter().skip(i + 1) {
27535 assert_ne!(
27536 a, b,
27537 "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
27538 canonical byte-sequences — got `{a}` == `{b}`",
27539 );
27540 }
27541 }
27542 }
27543
27544 #[test]
27545 fn m3_placement_key_consts_are_lower_camel_case_shape() {
27546 // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
27547 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27548 // `kebab-case` hyphens, no leading colon, no `PascalCase`
27549 // leading capital, no whitespace / dots) — the canonical shape
27550 // the `#[serde(rename_all = "camelCase")]` derive produces on
27551 // [`Placement`]. A future flip to a non-camelCase attribute at
27552 // the derive surfaces both here (this test fails on the stale-
27553 // constant shape) and at
27554 // `placement_serde_keys_match_lifted_m3_placement_key_consts`
27555 // (that test fails on the mismatch between const and derive).
27556 // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
27557 // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
27558 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
27559 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27560 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27561 // (ca463a4) on the sibling M3 typed-struct axes.
27562 for key in [
27563 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27564 crate::M3_PLACEMENT_KEY_CLUSTERS,
27565 crate::M3_PLACEMENT_KEY_AFFINITY,
27566 crate::M3_PLACEMENT_KEY_SHARD_KEY,
27567 ] {
27568 assert!(
27569 !key.is_empty(),
27570 "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
27571 );
27572 let first = key.chars().next().unwrap();
27573 assert!(
27574 first.is_ascii_lowercase(),
27575 "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
27576 byte (got {key:?}, leads with {first:?})",
27577 );
27578 assert!(
27579 key.chars().all(|c| c.is_ascii_alphanumeric()),
27580 "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
27581 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27582 );
27583 }
27584 }
27585
27586 // ── AplicacaoSpec::port_for_destination — the substrate-canonical
27587 // destination-facing L4 port resolver every per-Aplicacao renderer
27588 // reaching for a per-destination Servico TCP port axis routes
27589 // through. The four pin tests below fix the four-way accept-set
27590 // the resolver must always honor: (:entrada-para-matches,
27591 // :entrada-para-mismatches, :entrada-none-so-fallback,
27592 // :entrada-port-non-default-honored) — drift on any arm surfaces
27593 // at caixa-core build time rather than at cluster-apply time.
27594
27595 #[test]
27596 fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
27597 // The typed `:entrada` block's `:para "cart"` matches the
27598 // queried destination, so the resolver returns the author-
27599 // declared `:port` scalar verbatim — the canonical "the
27600 // destination Servico IS the ingress apex, honor the typed
27601 // listener port" arm of the port-resolution dispatch.
27602 let mut spec = three_member_spec();
27603 if let Some(e) = spec.entrada.as_mut() {
27604 e.para = "cart".into();
27605 e.port = 9090;
27606 }
27607 assert_eq!(
27608 spec.port_for_destination("cart"),
27609 9090,
27610 "port_for_destination(entrada.para) must return entrada.port \
27611 verbatim, not the DEFAULT_SERVICO_PORT fallback"
27612 );
27613 }
27614
27615 #[test]
27616 fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
27617 // The typed `:entrada` block names `:para "cart"`, but the
27618 // queried destination is `"payment"` — a Servico that
27619 // participates in the mesh graph but is not the ingress apex.
27620 // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
27621 // canonical port floor, closing the "non-apex destination reads
27622 // the substrate default" arm. Same fixture the peer
27623 // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
27624 // pin at caixa-mesh exercises through the CNP emit-side path;
27625 // this pin exercises the shared underlying resolver directly.
27626 let spec = three_member_spec();
27627 assert_eq!(
27628 spec.port_for_destination("payment"),
27629 DEFAULT_SERVICO_PORT,
27630 "port_for_destination(non-apex-destination) must route \
27631 through the lifted DEFAULT_SERVICO_PORT canonical port floor"
27632 );
27633 }
27634
27635 #[test]
27636 fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
27637 // Internal-only Aplicacao — no `:entrada` block declared. Every
27638 // per-destination port query falls back to the lifted
27639 // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
27640 // the Aplicacao surface admits `:entrada None` (internal mesh
27641 // with no external gateway); every downstream renderer's per-
27642 // destination port axis must still resolve to a well-defined
27643 // scalar even without an ingress apex.
27644 let mut spec = three_member_spec();
27645 spec.entrada = None;
27646 assert_eq!(
27647 spec.port_for_destination("cart"),
27648 DEFAULT_SERVICO_PORT,
27649 "port_for_destination on an internal-only Aplicacao must \
27650 fall back to the lifted DEFAULT_SERVICO_PORT floor for \
27651 every destination"
27652 );
27653 assert_eq!(
27654 spec.port_for_destination("payment"),
27655 DEFAULT_SERVICO_PORT,
27656 "port_for_destination on an internal-only Aplicacao must \
27657 fall back uniformly across every destination — the fallback \
27658 is not entrada-shape-conditional"
27659 );
27660 }
27661
27662 #[test]
27663 fn port_for_destination_honors_non_default_entrada_port_verbatim() {
27664 // Structural pin against a hypothetical future refactor that
27665 // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
27666 // the resolver (a "normalize to the default when the author's
27667 // port matches the substrate default" collapse) — that would
27668 // break renderer sites that carry meaning on the emitted port
27669 // value beyond bare equality (a future per-cluster listener-
27670 // audit that keys off the author-declared port, not the
27671 // resolved-with-fallback port). Pin that a non-default
27672 // entrada.port is returned verbatim so drift here surfaces at
27673 // caixa-core build time.
27674 let mut spec = three_member_spec();
27675 if let Some(e) = spec.entrada.as_mut() {
27676 e.para = "cart".into();
27677 e.port = 8443;
27678 }
27679 assert_ne!(
27680 8443, DEFAULT_SERVICO_PORT,
27681 "test fixture must probe a port distinct from \
27682 DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
27683 );
27684 assert_eq!(
27685 spec.port_for_destination("cart"),
27686 8443,
27687 "port_for_destination(entrada.para) must return entrada.port \
27688 verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
27689 );
27690 }
27691
27692 #[test]
27693 fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
27694 // Apex-identity pair-invariant pin composing both substrate-
27695 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
27696 // and [`Entrada::destination`] — at the emit-side call shape
27697 // every per-Aplicacao renderer's ingress-apex L4 port reader
27698 // now takes. The invariant:
27699 //
27700 // spec.port_for_destination(entrada.destination()) == entrada.port
27701 //
27702 // holds by construction under today's single-destination
27703 // `:entrada` slot (`destination()` returns `entrada.para`, and
27704 // the resolver's apex arm matches `para == destination` and
27705 // returns `entrada.port`), and every downstream consumer that
27706 // composes the two accessors at the ingress apex — the
27707 // `caixa_mesh::gateway_routes` HTTPRoute per-rule
27708 // `backendRefs[0].port` emit-site path, the peer future M4 CR
27709 // materializer's admission-webhook that promotes the scalar to
27710 // a per-CR override overlay, every future per-Aplicacao snapshot
27711 // renderer's apex-facing L4 port reader — reaches through the
27712 // same composition. Pin the identity across four permutations
27713 // (`:para` × `:port` including a non-default port to exercise
27714 // the honor-verbatim arm and a non-cart `:para` to exercise
27715 // destination-agnostic identity) so a future refactor that
27716 // silently split either accessor's apex behavior surfaces at
27717 // caixa-core build time — a subtle `destination()` renaming
27718 // that returned `entrada.host.as_str()` instead of
27719 // `entrada.para.as_str()` would blow this pin loudly, closing
27720 // the last quiet failure mode the two lifts admit in composition.
27721 //
27722 // Peer discipline with the sibling caixa-mesh cross-crate pin
27723 // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
27724 // on the two-renderer pair-invariant axis; this pin encodes the
27725 // same two-consumer coherence rule at the substrate-primitive
27726 // level so the invariant survives even if every renderer is
27727 // deleted.
27728 for (para, port) in [
27729 ("cart", DEFAULT_SERVICO_PORT),
27730 ("cart", 8443u16),
27731 ("payment", 9090u16),
27732 ("catalog", 443u16),
27733 ] {
27734 let mut spec = three_member_spec();
27735 if let Some(e) = spec.entrada.as_mut() {
27736 e.para = para.into();
27737 e.port = port;
27738 }
27739 let expected_port = spec
27740 .entrada()
27741 .expect("three_member_spec carries a typed `:entrada` block")
27742 .port();
27743 let composed_port = {
27744 let entrada = spec.entrada().expect("entrada present");
27745 spec.port_for_destination(entrada.destination())
27746 };
27747 assert_eq!(
27748 composed_port, expected_port,
27749 "`spec.port_for_destination(entrada.destination())` must \
27750 equal `entrada.port` under today's single-destination \
27751 `:entrada` slot — this is the apex-identity contract \
27752 every downstream ingress-apex L4 port reader relies on. \
27753 Input :entrada :para: {para:?}, :entrada :port: {port}"
27754 );
27755 }
27756 }
27757
27758 #[test]
27759 fn port_for_destination_apex_arm_routes_through_destination_accessor() {
27760 // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
27761 // per-`:entrada` apex-arm membership probe must key off
27762 // [`Entrada::destination`], not the raw `.para` field access.
27763 // Structurally: setting ONLY the `:entrada :para` field to a
27764 // fresh non-cart destination on an otherwise-well-formed
27765 // Aplicacao must (1) leave `e.destination()` byte-equal to
27766 // `e.para.as_str()` (the accessor is byte-projective by
27767 // definition), and (2) cause the resolver's apex arm to fire
27768 // and return `entrada.port` at exactly that new destination
27769 // while every other destination string falls through to
27770 // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
27771 // membership check. Pins against a future silent detour that
27772 // (a) re-derived the apex-arm membership probe off
27773 // `e.para == destination` in `port_for_destination` instead of
27774 // `e.destination() == destination`, silently disagreeing with
27775 // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
27776 // consumers (`entrada.destination()` at
27777 // caixa-mesh/src/lib.rs:3173, `c.destination()` at
27778 // caixa-mesh/src/lib.rs:2739) that already reach through the
27779 // accessor, (b) accessor-side introduced a per-tenant alias
27780 // arm the caller was unaware of, silently rewriting an
27781 // author-declared `:para "cart"` value to a canary-aliased
27782 // form — the raw-field-access resolver would fall through to
27783 // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
27784 // while the peer emit-site consumers landed on the aliased
27785 // destination, splitting the ingress-apex L4 port at
27786 // cluster-apply time.
27787 //
27788 // Peer of the sibling
27789 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
27790 // (d0de220) composition pin on the per-`:membros` refusal-arm
27791 // axis — same "the shape-gate predicate must route through the
27792 // substrate-primitive typed dispatch" discipline extended onto
27793 // the per-`:entrada` apex-arm membership-probe axis. Closes
27794 // the last unlifted `.para` production-code read site on
27795 // `Entrada` in `caixa-core` — after this converge every
27796 // `caixa-core` `.para` field access outside the accessor's own
27797 // body and outside the `WitContract` per-`:contratos` sibling
27798 // axis is either a test-side field-setter or a doc-comment
27799 // reference.
27800 for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
27801 let mut spec = three_member_spec();
27802 if let Some(e) = spec.entrada.as_mut() {
27803 e.para = para.into();
27804 e.port = port;
27805 }
27806 let e = spec
27807 .entrada
27808 .as_ref()
27809 .expect("three_member_spec carries a typed `:entrada` block");
27810 assert_eq!(
27811 e.destination(),
27812 e.para.as_str(),
27813 "Entrada::destination must byte-equal the .para field \
27814 access — an accessor-side detour that no longer \
27815 projects the raw field would silently split this \
27816 drift-detection test from the port_for_destination \
27817 apex-arm membership probe",
27818 );
27819 assert_eq!(
27820 spec.port_for_destination(para),
27821 port,
27822 "port_for_destination must key off the accessor-projected \
27823 destination and return `entrada.port` on the apex arm — \
27824 input :entrada :para: {para:?}, :entrada :port: {port}",
27825 );
27826 assert_eq!(
27827 spec.port_for_destination("ghost-destination-never-a-member"),
27828 DEFAULT_SERVICO_PORT,
27829 "port_for_destination must fall through to \
27830 DEFAULT_SERVICO_PORT on a non-matching destination \
27831 under the accessor-projected membership check — input \
27832 :entrada :para: {para:?}, :entrada :port: {port}",
27833 );
27834 }
27835 }
27836
27837 #[test]
27838 fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
27839 // The canonical per-`:politicas :rate-limit` `:rate`
27840 // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
27841 // [`RateLimit::rate`] must return the `:politicas :rate-limit`
27842 // typed `u32` verbatim, byte-equal to the raw field access
27843 // across every representative value in the accept-set — `1` (the
27844 // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
27845 // the surrounding [`AplicacaoSpec::validate_politicas`] gate
27846 // carves out on the sibling `PolicyRateLimitZero` refusal),
27847 // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
27848 // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
27849 // `0` (a past-the-guard sentinel that pins the accessor doesn't
27850 // perform a silent bounds-collapse into `1` on the zero arm —
27851 // validate rejects zero but the accessor must ship the raw slot
27852 // verbatim so a validate-time gate regression surfaces at the
27853 // emit boundary rather than being silently absorbed), `u32::MAX`
27854 // (a past-the-guard sentinel that pins the accessor doesn't
27855 // perform a silent bounds-collapse through
27856 // `POLICY_RATE_LIMIT_MAX` at the return path).
27857 //
27858 // First sub-struct required-scalar accessor pin on the
27859 // `RateLimit` axis — sibling in shape to the peer
27860 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
27861 // required-`u32` accessor pin on the peer per-sub-struct
27862 // required-axis. Pins against a future silent detour that
27863 // re-derived the token capacity from a peer axis (an accidental
27864 // `self.window.as_secs() as u32` collapse that read the
27865 // rate-limit window duration as a token count), a `0 → 1`
27866 // cluster-default projection (which would silently absorb the
27867 // `PolicyRateLimitZero` refusal case at the accessor boundary),
27868 // or a bounds-collapsing accessor that clamped the return
27869 // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
27870 // gate owns the bounds; the accessor must ship the raw slot
27871 // verbatim).
27872 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27873 let rl = RateLimit {
27874 rate,
27875 window: Duration::from_secs(1),
27876 };
27877 assert_eq!(
27878 rl.rate(),
27879 rate,
27880 "RateLimit::rate must return :politicas :rate-limit :rate \
27881 verbatim (got {}, expected {rate})",
27882 rl.rate(),
27883 );
27884 assert_eq!(
27885 rl.rate(),
27886 rl.rate,
27887 "RateLimit::rate must byte-equal the raw .rate field \
27888 access across every value in the u32 accept-set",
27889 );
27890 }
27891 }
27892
27893 #[test]
27894 fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
27895 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27896 // `:rate-limit :rate` zero-floor arm must key off
27897 // [`RateLimit::rate`], not the raw `.rate` field access.
27898 // Structurally: a `RateLimit { rate: 0, window:
27899 // Duration::from_secs(1) }` embedded in a `:politicas
27900 // :rate-limit` slot must surface the `PolicyRateLimitZero`
27901 // refusal exactly, and a `RateLimit { rate: 1, window:
27902 // Duration::from_secs(1) }` (the lower boundary of the
27903 // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
27904 // The pair jointly pins the accessor + validate-gate composition:
27905 // any future silent detour that had the accessor return a fresh
27906 // `1` on the zero arm (a `.rate().max(1)` collapse) would
27907 // silently absorb the `PolicyRateLimitZero` refusal at the
27908 // accessor boundary and the validate gate would accept a
27909 // struct-literal `RateLimit { rate: 0, .. }` — the composition
27910 // pin catches that at caixa-core build time.
27911 //
27912 // Peer of the sibling per-`CircuitBreaker`
27913 // [`CircuitBreaker::max_failures`] (3a74062) /
27914 // [`CircuitBreaker::window`] (373957f) accessor-composition
27915 // pins on the peer required-scalar axes — same "the validate /
27916 // shape-gate predicate must route through the substrate-primitive
27917 // typed dispatch" discipline extended onto the peer
27918 // per-`RateLimit` required-`u32` composition axis.
27919 let mut spec = three_member_spec();
27920 spec.politicas = MeshPolicy {
27921 rate_limit: Some(RateLimit {
27922 rate: 0,
27923 window: Duration::from_secs(1),
27924 }),
27925 ..MeshPolicy::default()
27926 };
27927 assert!(
27928 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
27929 "validate_politicas must reject rate == 0 with \
27930 PolicyRateLimitZero — the accessor and the validate gate \
27931 must route through the same substrate-primitive typed \
27932 dispatch on the :rate zero-floor arm",
27933 );
27934 spec.politicas = MeshPolicy {
27935 rate_limit: Some(RateLimit {
27936 rate: 1,
27937 window: Duration::from_secs(1),
27938 }),
27939 ..MeshPolicy::default()
27940 };
27941 assert!(
27942 spec.validate().is_ok(),
27943 "validate_politicas must accept rate == 1 (the lower \
27944 boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
27945 );
27946 }
27947
27948 #[test]
27949 fn rate_limit_rate_projects_u32_by_copy() {
27950 // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
27951 // `u32` is `Copy` and the accessor must return by value, not by
27952 // reference. Peer of the sibling per-`CircuitBreaker`
27953 // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
27954 // peer required-scalar `:max-failures` axis, extended onto the
27955 // peer per-`RateLimit` required-`u32` copy-invariant shape —
27956 // the accessor's returned `u32` must outlive `&self` (multiple
27957 // calls must return equal values from a dropped-`&self` copy,
27958 // since the returned scalar carries no borrow), and calling the
27959 // accessor twice on the same RateLimit must yield the same
27960 // `u32` verbatim (idempotent, no side effects on `&self`).
27961 //
27962 // Pins against a future silent detour that returned `&u32`
27963 // (which would type-check but silently break every downstream
27964 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
27965 // first parameter is `u32`, and `&u32` would fold to a detached
27966 // copy at the call site with a `*` deref the sibling accessors
27967 // don't need), an accidental `.rate.wrapping_add(0)` detour that
27968 // returned a fresh copy through an arithmetic no-op (breaking a
27969 // future `const fn` regression), or a one-arm-only accessor
27970 // that returned a saturating value on some sentinel input
27971 // (breaking the pass-through invariant the sibling required-
27972 // scalar accessors carry).
27973 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27974 let rl = RateLimit {
27975 rate,
27976 window: Duration::from_secs(1),
27977 };
27978 let first = rl.rate();
27979 let second = rl.rate();
27980 assert_eq!(
27981 first, second,
27982 "RateLimit::rate must be idempotent — two successive \
27983 calls on the same &self must return the same u32",
27984 );
27985 assert_eq!(
27986 first, rate,
27987 "RateLimit::rate must return :politicas :rate-limit :rate \
27988 verbatim by copy — got {first}, expected {rate}",
27989 );
27990 }
27991 }
27992
27993 #[test]
27994 fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
27995 // The canonical per-`:politicas :rate-limit` `:window`
27996 // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
27997 // pin: [`RateLimit::window`] must return the
27998 // `:politicas :rate-limit :window` typed `Duration` verbatim,
27999 // byte-equal to the raw field access across every
28000 // representative value in the accept-set — `Duration::from_secs(1)`
28001 // (the `"s"` canonical window, the lower row of
28002 // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
28003 // [`AplicacaoSpec::validate_politicas`] gate accepts via
28004 // [`is_canonical_rate_limit_window`]),
28005 // `Duration::from_secs(60)` (the `"m"` canonical window, the
28006 // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
28007 // window, the upper row), `Duration::ZERO` (a past-the-guard
28008 // sentinel that pins the accessor doesn't perform a silent
28009 // bounds-collapse into `Duration::from_secs(1)` on the zero
28010 // arm — validate rejects an off-set window through
28011 // `PolicyRateLimitWindowNotCanonical` but the accessor must
28012 // ship the raw slot verbatim so a validate-time gate
28013 // regression surfaces at the emit boundary rather than being
28014 // silently absorbed), `Duration::from_millis(500)` (a
28015 // sub-canonical past-the-guard sentinel that pins the accessor
28016 // doesn't silently normalize a non-canonical fractional
28017 // magnitude onto the nearest canonical row).
28018 //
28019 // Second sub-struct required-scalar accessor pin on the
28020 // `RateLimit` axis — sibling in shape to the just-landed
28021 // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
28022 // accessor pin on the peer per-sub-struct required-axis,
28023 // extended onto the per-`RateLimit` required-`Duration` axis.
28024 // Pins against a future silent detour that re-derived the
28025 // refill period from a peer axis (an accidental
28026 // `Duration::from_secs(self.rate as u64)` collapse that read
28027 // the rate-limit token capacity as a refill-interval
28028 // duration), a `Duration::ZERO → Duration::from_secs(1)`
28029 // canonical-default projection (which would silently absorb
28030 // the `PolicyRateLimitWindowNotCanonical` refusal case at the
28031 // accessor boundary), or a canonical-set-collapsing accessor
28032 // that clamped the return through [`rate_limit_window_unit`]
28033 // (the `AplicacaoSpec::validate` gate owns the canonical-set
28034 // membership; the accessor must ship the raw slot verbatim).
28035 for window in [
28036 Duration::from_secs(1),
28037 Duration::from_secs(60),
28038 Duration::from_secs(3600),
28039 Duration::ZERO,
28040 Duration::from_millis(500),
28041 ] {
28042 let rl = RateLimit { rate: 100, window };
28043 assert_eq!(
28044 rl.window(),
28045 window,
28046 "RateLimit::window must return :politicas :rate-limit :window \
28047 verbatim (got {:?}, expected {window:?})",
28048 rl.window(),
28049 );
28050 assert_eq!(
28051 rl.window(),
28052 rl.window,
28053 "RateLimit::window must byte-equal the raw .window field \
28054 access across every value in the Duration accept-set",
28055 );
28056 }
28057 }
28058
28059 #[test]
28060 fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
28061 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
28062 // `:rate-limit :window` canonical-set arm must key off
28063 // [`RateLimit::window`], not the raw `.window` field access.
28064 // Structurally: a `RateLimit { window: Duration::from_millis(500),
28065 // .. }` embedded in a `:politicas :rate-limit` slot must
28066 // surface the `PolicyRateLimitWindowNotCanonical` refusal
28067 // exactly (with the sub-canonical `Duration::from_millis(500)`
28068 // magnitude carried through verbatim), and a `RateLimit
28069 // { window: Duration::from_secs(1), .. }` (the lower row of
28070 // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
28071 // The pair jointly pins the accessor + validate-gate
28072 // composition: any future silent detour that had the accessor
28073 // normalize the off-set window to the nearest canonical row
28074 // (a `.window().max(Duration::from_secs(1))` collapse, or a
28075 // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
28076 // collapse) would silently absorb the
28077 // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
28078 // boundary — including a drift in the error's `window` payload
28079 // (the emit-side diagnostic reader keys off the offending
28080 // magnitude verbatim, so a normalization at the accessor
28081 // boundary would silently pin the wrong magnitude in the
28082 // refusal). The composition pin catches that at caixa-core
28083 // build time.
28084 //
28085 // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
28086 // (7f81a60) accessor-composition pin on the peer required-
28087 // scalar `:rate` axis — same "the validate / shape-gate
28088 // predicate must route through the substrate-primitive typed
28089 // dispatch, and the error payload must project through the
28090 // same accessor" discipline extended onto the peer
28091 // per-`RateLimit` required-`Duration` composition axis.
28092 let mut spec = three_member_spec();
28093 spec.politicas = MeshPolicy {
28094 rate_limit: Some(RateLimit {
28095 rate: 100,
28096 window: Duration::from_millis(500),
28097 }),
28098 ..MeshPolicy::default()
28099 };
28100 match spec.validate() {
28101 Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
28102 assert_eq!(
28103 window,
28104 Duration::from_millis(500),
28105 "PolicyRateLimitWindowNotCanonical must carry the \
28106 offending :window magnitude verbatim through the \
28107 accessor — got {window:?}, expected 500ms",
28108 );
28109 }
28110 other => panic!(
28111 "validate_politicas must reject non-canonical :window \
28112 with PolicyRateLimitWindowNotCanonical — the accessor \
28113 and the validate gate must route through the same \
28114 substrate-primitive typed dispatch on the :window \
28115 canonical-set arm; got {other:?}",
28116 ),
28117 }
28118 spec.politicas = MeshPolicy {
28119 rate_limit: Some(RateLimit {
28120 rate: 100,
28121 window: Duration::from_secs(1),
28122 }),
28123 ..MeshPolicy::default()
28124 };
28125 assert!(
28126 spec.validate().is_ok(),
28127 "validate_politicas must accept window == Duration::from_secs(1) \
28128 (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
28129 );
28130 }
28131
28132 #[test]
28133 fn rate_limit_window_projects_duration_by_copy() {
28134 // The by-copy pin: [`RateLimit::window`] returns `Duration`
28135 // by copy — `Duration` is `Copy` and the accessor must return
28136 // by value, not by reference. Peer of the sibling per-`RateLimit`
28137 // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
28138 // required-scalar `:rate` axis, extended onto the peer
28139 // per-`RateLimit` required-`Duration` copy-invariant shape —
28140 // the accessor's returned `Duration` must outlive `&self`
28141 // (multiple calls must return equal values from a
28142 // dropped-`&self` copy, since the returned scalar carries no
28143 // borrow), and calling the accessor twice on the same
28144 // RateLimit must yield the same `Duration` verbatim
28145 // (idempotent, no side effects on `&self`).
28146 //
28147 // Pins against a future silent detour that returned
28148 // `&Duration` (which would type-check but silently break every
28149 // downstream `Duration`-by-value consumer —
28150 // [`is_canonical_rate_limit_window`]'s first parameter is
28151 // `Duration`, and `&Duration` would fold to a detached copy at
28152 // the call site with a `*` deref the sibling accessors don't
28153 // need), an accidental `.window + Duration::ZERO` detour that
28154 // returned a fresh copy through an arithmetic no-op (breaking
28155 // a future `const fn` regression), or a one-arm-only accessor
28156 // that returned a canonical fallback on some sentinel input
28157 // (breaking the pass-through invariant the sibling required-
28158 // scalar accessors carry).
28159 for window in [
28160 Duration::from_secs(1),
28161 Duration::from_secs(60),
28162 Duration::from_secs(3600),
28163 Duration::ZERO,
28164 Duration::from_millis(500),
28165 ] {
28166 let rl = RateLimit { rate: 100, window };
28167 let first = rl.window();
28168 let second = rl.window();
28169 assert_eq!(
28170 first, second,
28171 "RateLimit::window must be idempotent — two successive \
28172 calls on the same &self must return the same Duration",
28173 );
28174 assert_eq!(
28175 first, window,
28176 "RateLimit::window must return :politicas :rate-limit :window \
28177 verbatim by copy — got {first:?}, expected {window:?}",
28178 );
28179 }
28180 }
28181
28182 #[test]
28183 fn placement_estrategia_default_pins_m3_canonical_value() {
28184 // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
28185 // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
28186 // active-active-across-every-named-cluster arm, the closest
28187 // canonical M3 production reference the substrate carries and
28188 // the arm the caixa-mesh `programs.yaml` fan-out already keys off
28189 // for every un-`:placement`-declared Aplicacao. Pinning the arm
28190 // here surfaces a future rebrand of the M3-canonical
28191 // distribution default (a widening to `Sharded` once the
28192 // substrate discovers hash-keyed distribution as the more
28193 // common production shape, a tightening to `SingleNode` for
28194 // stateful Erlang/OTP distributed-app-takeover semantics
28195 // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
28196 // operator pins through a future `:placement-overrides` slot)
28197 // as a deliberate test edit, not a silent contract migration.
28198 // Peer of the sibling M2 per-supervisor value pins
28199 // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
28200 // /
28201 // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
28202 // extended onto the M3 mesh-primitive-defining `:placement
28203 // :estrategia` axis.
28204 assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
28205 }
28206
28207 #[test]
28208 fn placement_strategy_default_routes_through_lifted_default() {
28209 // Composition pin: the [`Default for PlacementStrategy`] impl's
28210 // return arm must route through the substrate-canonical
28211 // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
28212 // a raw `Self::Replicated` arm. Prior to the lift the impl
28213 // carried an inline `Self::Replicated` arm with no compile-time
28214 // link back to the shared M3-canonical `Replicated` arm the
28215 // paired [`Default for Placement`] impl's struct-literal
28216 // `estrategia` field, the serde-side `#[serde(default)]` on
28217 // [`Placement::estrategia`] that resolves an author-omitted
28218 // wire-form `:placement :estrategia` scalar through the impl,
28219 // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
28220 // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
28221 // routes through [`Placement::default`] which routes through the
28222 // strategy default) all key off — so a future rebrand of the
28223 // M3-canonical distribution default would have had to be threaded
28224 // through the `Default` impl and the three peer routes in
28225 // lockstep or the four consumers would silently split. Byte-
28226 // parity against the lifted constant closes the split. Peer of
28227 // the sibling
28228 // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
28229 // /
28230 // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
28231 // composition pins on the M2 per-supervisor axes.
28232 assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
28233 }
28234
28235 #[test]
28236 fn placement_default_estrategia_routes_through_lifted_default() {
28237 // Composition pin: the [`Default for Placement`] impl's
28238 // struct-literal `estrategia` field must route through the
28239 // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
28240 // `pub const` (either directly, or via the [`PlacementStrategy::default`]
28241 // impl that the sibling
28242 // `placement_strategy_default_routes_through_lifted_default` pin
28243 // already routes onto the constant). Structurally: every
28244 // `Placement::default()` call must yield an `estrategia` field
28245 // byte-equal to the lifted constant so the two paired defaults —
28246 // the [`Default for PlacementStrategy`] impl arm and the
28247 // struct-literal default arm here — cannot silently split on any
28248 // future M3-canonical distribution-default rebrand. Peer of the
28249 // sibling M2
28250 // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
28251 // byte-parity pin on the [`Default for SupervisorSpec`]
28252 // struct-literal `estrategia` field extended onto the M3
28253 // mesh-primitive-defining slot family.
28254 assert_eq!(
28255 Placement::default().estrategia,
28256 PLACEMENT_ESTRATEGIA_DEFAULT,
28257 );
28258 }
28259
28260 #[test]
28261 fn placement_serde_default_estrategia_routes_through_lifted_default() {
28262 // Composition pin: the serde-side `#[serde(default)]` on
28263 // [`Placement::estrategia`] — the wire-format author-omitted
28264 // `:placement :estrategia` arm — must resolve onto the substrate-
28265 // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
28266 // (via the [`Default for PlacementStrategy`] impl the sibling
28267 // `placement_strategy_default_routes_through_lifted_default` pin
28268 // already routes onto the constant). Structurally: a `Placement`
28269 // deserialized from a payload that omits the `estrategia` key
28270 // must yield an `estrategia` field byte-equal to the lifted
28271 // constant, so the wire-format author-omitted arm and the
28272 // [`PlacementStrategy::default`] impl arm cannot silently split
28273 // on any future M3-canonical distribution-default rebrand. Peer
28274 // of the sibling M2
28275 // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
28276 // byte-parity pin on the wire-format author-omitted `:children
28277 // :restart` scalar extended onto the M3 mesh-primitive-defining
28278 // slot family.
28279 let omitted: Placement = serde_json::from_str("{}")
28280 .expect("Placement must deserialize with the estrategia key omitted");
28281 assert_eq!(
28282 omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
28283 "an author-omitted :placement :estrategia slot must degrade onto \
28284 the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
28285 {:?}, expected {:?})",
28286 omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
28287 );
28288 }
28289}