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#[must_use]
135pub fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
136 prefixes.iter().any(|p| wit.starts_with(p))
137}
138
139/// True when `wit` — a raw `:contratos :wit` value — targets an
140/// HTTP-shaped WIT world (starts with any prefix in
141/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
142/// consumer routes L7-HTTP emission through, whether they carry a
143/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
144/// here) or only the raw `wit` string (the positive-sweep test's
145/// payload-dispatch helper, future renderers that classify off a
146/// bare `&str`). Lifting to a free function makes the shape-dispatch
147/// arm reachable without materializing a scratch [`WitContract`] at
148/// every classification point, and pins the six-prefix accept-set at
149/// one place so future additions (e.g. an `"https:"` peer of
150/// `"http:"`) reach every consumer by construction. Routes through
151/// the lifted [`wit_shape_matches`] combinator so the
152/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
153/// canonical primitive, not one open-coded copy per peer arm.
154#[must_use]
155pub fn wit_shape_is_http(wit: &str) -> bool {
156 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES)
157}
158
159/// True when `wit` — a raw `:contratos :wit` value — targets a
160/// pub-sub-shaped WIT world (starts with any prefix in
161/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
162/// [`wit_shape_is_store`] on the shape-dispatch axis; see
163/// [`wit_shape_is_http`] for the lift rationale. Routes through the
164/// lifted [`wit_shape_matches`] combinator.
165#[must_use]
166pub fn wit_shape_is_pubsub(wit: &str) -> bool {
167 wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES)
168}
169
170/// True when `wit` — a raw `:contratos :wit` value — targets a
171/// key/value-store-shaped WIT world (starts with any prefix in
172/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
173/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
174/// [`wit_shape_is_http`] for the lift rationale. Routes through the
175/// lifted [`wit_shape_matches`] combinator.
176#[must_use]
177pub fn wit_shape_is_store(wit: &str) -> bool {
178 wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES)
179}
180
181/// True when `wit` — a raw `:contratos :wit` value — targets *none* of
182/// the three known payload-shape WIT worlds; the payload-less
183/// capability arm of the 4-way WIT-shape partition on the raw
184/// `:contratos :wit` axis. Peer of [`wit_shape_is_http`] /
185/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] on the shape-
186/// dispatch axis — closes the free-function classifier family the
187/// three payload-arm predicates opened onto the exact-inverse
188/// disjunction of the trio, so any downstream consumer that must
189/// classify a raw `:wit` `&str` onto the payload-less capability arm
190/// (a future substrate-side capability-shape-only emitter — the M4
191/// per-Aplicacao WIT-registry capability-import materializer, the
192/// future `feira app graph --capability` filter, the future per-
193/// cluster capability-scope reconciler that skips L4/L7 emission for
194/// payload-less edges, the future `mesh.pleme.io/v1alpha1/Aplicacao`
195/// CR admission webhook's per-shape histogram) reaches for exactly
196/// one typed dispatch at the substrate primitive rather than an
197/// open-coded per-consumer `!wit_shape_is_http(wit) &&
198/// !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)` triplet
199/// negation — each of which would silently misclassify a future 4th
200/// payload-arm addition (a hypothetical `wasi:sockets/*` transport-
201/// layer shape, an `oci:*` capability-import carrier per the sibling
202/// [`wit_shape_matches`] docstring's trajectory bullet) as
203/// capability without a compile-time signal at the consumer site.
204///
205/// Fourth arm on the free-function WIT-shape-predicate family — closes
206/// the {[`wit_shape_is_http`], [`wit_shape_is_pubsub`],
207/// [`wit_shape_is_store`]} trio into a 4-way partition witness on the
208/// raw `:contratos :wit` `&str` axis, mirroring the paired sibling
209/// [`WitContract`]-surface [`WitContract::is_capability`] predicate and
210/// the post-projection [`WitTarget`]-side
211/// `gen_platform::IsVariant`-derived [`WitTarget::is_capability`]
212/// (7f6aa98 `IsVariant` derive lift on the peer arm-set). Every
213/// [`WitTarget`] variant now carries a matched peer predicate on both
214/// the raw `&str` axis (this function + [`wit_shape_is_http`] /
215/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`]) and the
216/// [`WitContract`] surface (the sibling 4-arm predicate family
217/// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
218/// [`WitContract::is_store`] / [`WitContract::is_capability`]),
219/// pinned in load-bearing by the sibling
220/// [`tests::wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis`]
221/// partition-witness pin and the peer
222/// [`tests::wit_contract_shape_methods_delegate_to_free_functions`]
223/// delegation pin.
224///
225/// Prior to this lift the "not one of the three known payload shapes"
226/// classification only reached the raw `&str` axis by materializing a
227/// scratch [`WitContract`] and delegating through
228/// [`WitContract::is_capability`] — a five-field constructor at every
229/// classification point for a pure `&str → bool` question, and a
230/// dependency on the payload-carrier scalar layout the classifier
231/// does not read. Same "one canonical combinator, thin per-arm
232/// projections" discipline the peer [`wit_shape_is_http`] /
233/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] trio already
234/// established, extended to close the 4-arm partition on the raw
235/// `&str` axis.
236///
237/// Note: purely syntactic classification on the negated `:wit` prefix-
238/// set — unlike [`WitContract::target`], which additionally rejects
239/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
240/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
241/// payload-shape mismatches. An empty or structurally malformed `wit`
242/// string returns `true` here (the prefix set matches nothing), and
243/// the surrounding validate-side gate cascade is where the
244/// [`AplicacaoError::EmptyWit`] / [`AplicacaoError::ContratoWitInvalid`]
245/// diagnostic surfaces — this function is the classifier, not the
246/// validator.
247#[must_use]
248pub fn wit_shape_is_capability(wit: &str) -> bool {
249 !wit_shape_is_http(wit) && !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)
250}
251
252impl WitContract {
253 /// Substrate-canonical per-`:contratos` caller-Servico scalar
254 /// accessor every consumer that reads the edge's source endpoint
255 /// keys off — returns the author-declared `:contratos :de`
256 /// byte-string verbatim as a `&str`, borrowed from the typed slot's
257 /// own [`String`] storage.
258 ///
259 /// The `:contratos :de` slot names the caller-side member Servico
260 /// on a typed inter-Servico edge (validated by
261 /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
262 /// Aplicacao declares — a stray `:de` that doesn't name a member is
263 /// [`AplicacaoError::ContratoMemberMissing`], not a silent
264 /// caller-attachment miss at cluster-apply time). Peer of the
265 /// sibling [`WitContract::destination`] accessor on the same
266 /// per-`:contratos` entry — the pair `( source(), destination() )`
267 /// jointly names the typed edge every renderer that fans on the
268 /// caller-callee identity keys off (the
269 /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
270 /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
271 /// map, the per-edge dedup key, the per-edge membership-lookup
272 /// diagnostic).
273 ///
274 /// Prior to this lift the `.de` byte-string was accessed inline at
275 /// four caixa-core sites (the two validate-side membership lookups
276 /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
277 /// tuple's caller-arm at
278 /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
279 /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
280 /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
281 /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
282 /// — five open-coded `.de.as_str()` field-accesses that expressed
283 /// no compile-time link back to the typed slot. A future extension
284 /// of the `:contratos :de` axis to a richer author surface (a
285 /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
286 /// canary flow, a per-cluster caller-alias table the operator pins
287 /// through a future `:placement`-scoped slot, the M4
288 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
289 /// admission-webhook that promotes the scalar to a caller-set
290 /// projection) would have had to be threaded through every
291 /// open-coded copy in lockstep or one consumer would silently
292 /// disagree with the peers on which caller Servico a given edge
293 /// resolves to. Lifting the resolution rule to a typed method on
294 /// the substrate primitive means every downstream caller-facing
295 /// consumer reaches for one typed dispatch — the resolver's
296 /// accept-set migrates as a unit on any future axis addition.
297 ///
298 /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
299 /// (6db982c) accessor on the analogous per-ingress-Servico scalar
300 /// axis — same "one typed dispatch on the substrate primitive,
301 /// thin projections at each consumer" discipline extended onto the
302 /// per-`:contratos` caller-Servico byte-string axis.
303 #[must_use]
304 pub fn source(&self) -> &str {
305 self.de.as_str()
306 }
307
308 /// Substrate-canonical per-`:contratos` callee-Servico scalar
309 /// accessor every consumer that reads the edge's destination
310 /// endpoint keys off — returns the author-declared
311 /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
312 /// from the typed slot's own [`String`] storage.
313 ///
314 /// The `:contratos :para` slot names the callee-side member Servico
315 /// on a typed inter-Servico edge (validated by
316 /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
317 /// Aplicacao declares — a stray `:para` that doesn't name a member
318 /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
319 /// callee-attachment miss at cluster-apply time). Callee-side twin
320 /// of the sibling [`WitContract::source`] accessor — the pair
321 /// jointly names the typed edge every renderer that fans on the
322 /// caller-callee identity keys off, and this accessor is also the
323 /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
324 /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
325 /// composes with `destination()` at every emit site that projects a
326 /// per-edge destination Servico's L4 listener port.
327 ///
328 /// Prior to this lift the `.para` byte-string was accessed inline
329 /// at five sites — four caixa-core (the validate-side membership
330 /// lookup at `!names.contains(c.para.as_str())`, the per-edge
331 /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
332 /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
333 /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
334 /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
335 /// — with no compile-time link back to the typed slot. A future
336 /// extension of the `:contratos :para` axis to a richer author
337 /// surface (a multi-callee weighted-fan-out overlay for canary /
338 /// blue-green routing on typed edges, a per-cluster callee-alias
339 /// table the operator pins through a future `:placement`-scoped
340 /// slot, the M4 CR materializer's per-CR admission-webhook that
341 /// promotes the scalar to a callee-set projection) would have had
342 /// to be threaded through every open-coded copy in lockstep or one
343 /// consumer would silently disagree on which callee Servico a given
344 /// edge resolves to (a per-CNP `endpointSelector` that names a
345 /// different destination than its L4 port resolver reads for, a
346 /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
347 /// as distinct while the adjacency map collapses them, or vice
348 /// versa). Lifting to a typed method on the substrate primitive
349 /// means every downstream callee-facing consumer reaches for one
350 /// typed dispatch.
351 ///
352 /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
353 /// (6db982c) accessor — both name the "destination-Servico
354 /// byte-string" concept on their respective mesh-slot atoms (per-
355 /// ingress apex vs. per-typed-edge callee), and both extend the
356 /// substrate-primitive-owns-the-resolver discipline onto the
357 /// per-slot destination-Servico scalar axis. Composes with
358 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
359 /// emit-side per-edge L4 port reader — the composition
360 /// `spec.port_for_destination(c.destination())` pins the CNP per-
361 /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
362 /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
363 /// `spec.port_for_destination(entrada.destination())`.
364 #[must_use]
365 pub fn destination(&self) -> &str {
366 self.para.as_str()
367 }
368
369 /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
370 /// accessor every consumer that reads the edge's WIT world
371 /// discriminator keys off — returns the author-declared
372 /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
373 /// the typed slot's own [`String`] storage.
374 ///
375 /// The `:contratos :wit` slot names the WIT world the typed edge
376 /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
377 /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
378 /// be a well-shaped WIT world reference via
379 /// [`crate::render::is_wit_world_ref`] and by
380 /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
381 /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
382 /// [`WitContract::source`] / [`WitContract::destination`] accessors
383 /// on the same per-`:contratos` entry — the triple
384 /// `( source(), destination(), world_ref() )` jointly names the
385 /// typed edge every renderer that fans on the caller-callee-shape
386 /// identity keys off (the per-edge dedup key at
387 /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
388 /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
389 /// [`caixa_mesh::cilium_network_policies`], the
390 /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
391 /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
392 /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
393 ///
394 /// Prior to this lift the `.wit` byte-string was accessed inline at
395 /// five sites — three caixa-core (the `WitContract::is_*` shape-
396 /// dispatch predicates' `&self.wit` arg, the validate-side empty
397 /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
398 /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
399 /// printer's `{}` format-slot at `c.wit`) — five open-coded
400 /// `.wit` field-accesses that expressed no compile-time link back to
401 /// the typed slot. A future extension of the `:contratos :wit` axis
402 /// to a richer author surface (an M4 promotion from `String` to a
403 /// typed WIT-world enum once the WIT registry stabilizes in tatara-
404 /// lisp per this struct's own `:wit` field docstring, a per-cluster
405 /// WIT-alias table the operator pins through a future
406 /// `:placement`-scoped slot, a canonicalization pass that lowercases
407 /// `wasi:*` prefixes) would have had to be threaded through every
408 /// open-coded copy in lockstep or one consumer would silently
409 /// disagree with the peers on which WIT shape a given edge resolves
410 /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
411 /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
412 /// empty-check that missed a whitespace-only string a peer accessor
413 /// stripped, or vice versa). Lifting to a typed method on the
414 /// substrate primitive means every downstream WIT-shape-facing
415 /// consumer reaches for one typed dispatch — the resolver's
416 /// accept-set migrates as a unit on any future axis addition.
417 ///
418 /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
419 /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
420 /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
421 /// 6db982c), per-`:membros` [`Membro::nome`] /
422 /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
423 /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
424 /// on the substrate primitive, thin projections at each consumer"
425 /// discipline extended onto the last unlifted per-`:contratos`
426 /// scalar (the WIT-world-reference arm).
427 ///
428 /// [fag]: caixa-feira/src/cmd/app.rs
429 #[must_use]
430 pub fn world_ref(&self) -> &str {
431 self.wit.as_str()
432 }
433
434 /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
435 /// payload-target scalar accessor every consumer that reads the
436 /// edge's L7 HTTP request path payload keys off — returns the
437 /// author-declared `:contratos :endpoint` byte-string verbatim as
438 /// an `Option<&str>`, borrowed from the typed slot's own
439 /// `Option<String>` storage; `None` when the slot is absent (the
440 /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
441 /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
442 /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
443 /// [`WitTarget::Capability`] edge carries none of the three).
444 ///
445 /// The `:contratos :endpoint` slot carries the HTTP request path
446 /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
447 /// — same shape required of `:entrada :paths`, gated by the shared
448 /// [`crate::render::is_gateway_api_http_path`] predicate) that
449 /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
450 /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
451 /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
452 /// downstream consumer that reads the payload keys off this scalar
453 /// (the [`WitContract::target`] Http-arm payload extraction that
454 /// materializes [`WitTarget::Http { endpoint }`] under the paired
455 /// [`WitTarget::HTTP_FIELD_NAME`] label, the
456 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
457 /// key's endpoint arm that pins the payload as part of the six-tuple
458 /// dedup key alongside the sibling `:subject`/`:slot` arms, the
459 /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
460 /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
461 /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
462 /// emission path that lands the payload verbatim as a Cilium L7
463 /// `path:` rule).
464 ///
465 /// Prior to this lift the `.endpoint` field was accessed inline at
466 /// two production sites in `caixa-core/src/aplicacao.rs` — the
467 /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
468 /// self.endpoint.as_deref();` binding at the top of the method, and
469 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
470 /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
471 /// field-accesses that expressed no compile-time link back to the
472 /// typed slot. A future extension of the `:contratos :endpoint`
473 /// axis to a richer author surface (an M4 promotion from
474 /// `Option<String>` to a typed HTTP path-template enum once the
475 /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
476 /// this struct's own `:wit` field docstring, a per-cluster endpoint-
477 /// alias table the operator pins through a future `:placement`-
478 /// scoped slot, a canonicalization pass that percent-encodes non-
479 /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
480 /// materializer applies per-tenant) would have had to be threaded
481 /// through both open-coded copies in lockstep or the two consumers
482 /// would silently disagree on which HTTP path a given edge resolves
483 /// to — the [`WitContract::target`] payload-extraction reading
484 /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
485 /// the operator-resolved `"/tenant-a/lookup"` would silently split
486 /// the [`WitTarget::Http`]-arm rendered payload from the actual
487 /// dedup-key uniqueness axis, a two-consumer split at the validator
488 /// far from the source `caixa.lisp` with no field naming the
489 /// payload-drift root cause. Lifting the resolution rule to a typed
490 /// method on the substrate primitive means every downstream
491 /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
492 /// L7-payload surface reaches for exactly one typed dispatch — the
493 /// resolver's accept-set migrates as a unit on any future axis
494 /// addition.
495 ///
496 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
497 /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
498 /// accessors on the M3 mesh-slot family — same "one typed dispatch
499 /// on the substrate primitive, thin projections at each consumer"
500 /// discipline extended onto the per-`:contratos` HTTP-shaped
501 /// payload-carrier `Option<String>` optional-scalar axis. First
502 /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
503 /// atom — opens the "optional per-slot payload-carrier scalar"
504 /// projection pattern the sibling per-`:contratos` `:subject` /
505 /// `:slot` future lifts fold on, matching the closed
506 /// per-`:contratos` scalar-value accessor family
507 /// ([`WitContract::source`] / [`WitContract::destination`] /
508 /// [`WitContract::world_ref`]) already lifted onto the mandatory-
509 /// scalar `String` axes. Named `endpoint()` to match the storage
510 /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
511 /// author-facing label const; the accessor's identity name maps
512 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
513 /// docstring already carries.
514 #[must_use]
515 pub fn endpoint(&self) -> Option<&str> {
516 self.endpoint.as_deref()
517 }
518
519 /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
520 /// payload-target scalar accessor every consumer that reads the
521 /// edge's NATS / Kafka publish subject payload keys off — returns
522 /// the author-declared `:contratos :subject` byte-string verbatim
523 /// as an `Option<&str>`, borrowed from the typed slot's own
524 /// `Option<String>` storage; `None` when the slot is absent (the
525 /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
526 /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
527 /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
528 /// [`WitTarget::Capability`] edge carries none of the three).
529 ///
530 /// The `:contratos :subject` slot carries the NATS / Kafka publish
531 /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
532 /// per-edge target selector — `orders.paid`, `events.>`, whatever
533 /// subject namespace the author names on the pub-sub edge) that
534 /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
535 /// arm's `subject: &'a str` payload when the edge's `:wit` world
536 /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
537 /// downstream consumer that reads the payload keys off this scalar
538 /// (the [`WitContract::target`] PubSub-arm payload extraction that
539 /// materializes [`WitTarget::PubSub { subject }`] under the paired
540 /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
541 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
542 /// key's subject arm that pins the payload as part of the six-tuple
543 /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
544 /// future M4 per-edge WIT registry resolver's pub-sub-arm
545 /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
546 /// materializer's per-edge NATS admission webhook, the future
547 /// caixa-mesh L4 CNP emission path that lands the payload verbatim
548 /// as a NATS subject the operator pins per-CR).
549 ///
550 /// Prior to this lift the `.subject` field was accessed inline at
551 /// two production sites in `caixa-core/src/aplicacao.rs` — the
552 /// [`WitContract::target`] payload-shape dispatch's `let subject =
553 /// self.subject.as_deref();` binding at the top of the method, and
554 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
555 /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
556 /// field-accesses that expressed no compile-time link back to the
557 /// typed slot. A future extension of the `:contratos :subject` axis
558 /// to a richer author surface (an M4 promotion from `Option<String>`
559 /// to a typed NATS-subject-template enum once the WIT registry
560 /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
561 /// struct's own `:wit` field docstring, a per-cluster subject-alias
562 /// table the operator pins through a future `:placement`-scoped
563 /// slot, a canonicalization pass that lowercases / dedupes wildcard
564 /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
565 /// applies per-tenant) would have had to be threaded through both
566 /// open-coded copies in lockstep or the two consumers would silently
567 /// disagree on which NATS subject a given edge resolves to — the
568 /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
569 /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
570 /// resolved `"tenant-a.orders.paid"` would silently split the
571 /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
572 /// key uniqueness axis, a two-consumer split at the validator far
573 /// from the source `caixa.lisp` with no field naming the payload-
574 /// drift root cause. Lifting the resolution rule to a typed method
575 /// on the substrate primitive means every downstream pub-sub-payload-
576 /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
577 /// surface reaches for exactly one typed dispatch — the resolver's
578 /// accept-set migrates as a unit on any future axis addition.
579 ///
580 /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
581 /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
582 /// carrier axis — second `Option<&str>`-return accessor on the
583 /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
584 /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
585 /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
586 /// key/value-store arm as the last unlifted per-`:contratos`
587 /// `Option<String>` axis. Named `subject()` to match the storage
588 /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
589 /// author-facing label const; the accessor's identity name maps
590 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
591 /// docstring already carries.
592 #[must_use]
593 pub fn subject(&self) -> Option<&str> {
594 self.subject.as_deref()
595 }
596
597 /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
598 /// shaped payload-target scalar accessor every consumer that reads
599 /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
600 /// off — returns the author-declared `:contratos :slot` byte-string
601 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
602 /// own `Option<String>` storage; `None` when the slot is absent
603 /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
604 /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
605 /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
606 /// [`WitTarget::Capability`] edge carries none of the three).
607 ///
608 /// The `:contratos :slot` slot carries the key/value store
609 /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
610 /// arm's per-edge target selector — `carts/{cart_id}`,
611 /// `sessions/{tenant}/{sid}`, whatever key-template the author
612 /// names on the store edge) that [`WitContract::target`] projects
613 /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
614 /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
615 /// accept-set. Every downstream consumer that reads the payload
616 /// keys off this scalar (the [`WitContract::target`] Store-arm
617 /// payload extraction that materializes [`WitTarget::Store { slot }`]
618 /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
619 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
620 /// key's store arm that pins the payload as part of the six-tuple
621 /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
622 /// the future M4 per-edge WIT registry resolver's store-arm
623 /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
624 /// materializer's per-edge key/value admission webhook, the future
625 /// caixa-mesh L4 CNP emission path that lands the payload verbatim
626 /// as a key-template the operator pins per-CR).
627 ///
628 /// Prior to this lift the `.slot` field was accessed inline at two
629 /// production sites in `caixa-core/src/aplicacao.rs` — the
630 /// [`WitContract::target`] payload-shape dispatch's `let slot =
631 /// self.slot.as_deref();` binding at the top of the method, and
632 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
633 /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
634 /// field-accesses that expressed no compile-time link back to the
635 /// typed slot. A future extension of the `:contratos :slot` axis
636 /// to a richer author surface (an M4 promotion from `Option<String>`
637 /// to a typed key-template enum once the WIT registry stabilizes
638 /// key-template parameter shapes in tatara-lisp per this struct's
639 /// own `:wit` field docstring, a per-cluster slot-alias table the
640 /// operator pins through a future `:placement`-scoped slot, a
641 /// canonicalization pass that lowercases the bucket prefix, a
642 /// per-CR fully-qualified rewrite the M4 CR materializer applies
643 /// per-tenant) would have had to be threaded through both
644 /// open-coded copies in lockstep or the two consumers would
645 /// silently disagree on which key-template a given edge resolves
646 /// to — the [`WitContract::target`] payload-extraction reading
647 /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
648 /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
649 /// would silently split the [`WitTarget::Store`]-arm rendered
650 /// payload from the actual dedup-key uniqueness axis, a
651 /// two-consumer split at the validator far from the source
652 /// `caixa.lisp` with no field naming the payload-drift root cause.
653 /// Lifting the resolution rule to a typed method on the substrate
654 /// primitive means every downstream store-payload-facing consumer
655 /// of the Aplicacao's per-`:contratos` payload surface reaches for
656 /// exactly one typed dispatch — the resolver's accept-set migrates
657 /// as a unit on any future axis addition.
658 ///
659 /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
660 /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
661 /// accessors on the M3 mesh-slot payload-carrier axis — third and
662 /// final `Option<&str>`-return accessor on the per-`:contratos`
663 /// mesh-slot atom, closes the last unlifted per-`:contratos`
664 /// `Option<String>` axis and completes the "optional per-slot
665 /// payload-carrier scalar" projection pattern the peer HTTP /
666 /// pub-sub arms established across the three payload-shape
667 /// dispatch arms. Named `slot()` to match the storage field's
668 /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
669 /// author-facing label const; the accessor's identity name maps
670 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
671 /// docstring already carries.
672 #[must_use]
673 pub fn slot(&self) -> Option<&str> {
674 self.slot.as_deref()
675 }
676
677 /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
678 /// caller-callee-pair accessor every consumer that constructs an
679 /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
680 /// caller-callee pair keys off — returns the author-declared
681 /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
682 /// owned `(String, String)` tuple, projected through the lifted
683 /// [`WitContract::source`] / [`WitContract::destination`] scalar
684 /// accessors so any future rebrand on the caller-arm / callee-arm
685 /// projection axis (an M4 per-cluster caller-alias table the
686 /// operator pins through a future `:placement`-scoped slot, a
687 /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
688 /// a per-`:membros` alias overlay from the future `:membros
689 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
690 /// acknowledges) reaches every diagnostic-construction site by
691 /// construction.
692 ///
693 /// The `(de, para)` pair is the "typed-edge caller-callee identity in
694 /// owned form" primitive every per-`:contratos` diagnostic variant on
695 /// [`AplicacaoError`] carries alongside its payload-shape arm — the
696 /// nine variants [`AplicacaoError::EmptyWit`],
697 /// [`AplicacaoError::ContratoEndpointEmpty`],
698 /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
699 /// [`AplicacaoError::ContratoEndpointInvalid`],
700 /// [`AplicacaoError::ContratoSubjectEmpty`],
701 /// [`AplicacaoError::ContratoSubjectInvalid`],
702 /// [`AplicacaoError::ContratoSlotEmpty`],
703 /// [`AplicacaoError::ContratoSlotInvalid`], and
704 /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
705 /// para: String` field pair the constructor site reads verbatim off
706 /// the [`WitContract`] the diagnostic points at, so a diagnostic
707 /// whose `de:` and `para:` labels silently drift off the source
708 /// caller/callee — a per-cluster caller-alias rewrite that landed on
709 /// one variant's inline `de: c.de.clone()` field access but not on
710 /// its sibling variant's, an accidental swap of the `de:` and `para:`
711 /// arms in a copy-paste of the constructor block — would emit a
712 /// build-time error whose "which caixa is at fault" question the
713 /// operator answers wrongly, far from the source `caixa.lisp`.
714 ///
715 /// Prior to this lift the `(self.de.clone(), self.para.clone())`
716 /// pair was inlined at seven [`WitContract::target`] error-
717 /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
718 /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
719 /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
720 /// the [`AplicacaoError::ContratoSubjectEmpty`] /
721 /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
722 /// the [`AplicacaoError::ContratoSlotEmpty`] /
723 /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
724 /// two [`AplicacaoSpec::validate`] error-construction sites (the
725 /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
726 /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
727 /// insert-first-seen closure) — nine open-coded `.de.clone() +
728 /// .para.clone()` pairs that expressed no compile-time contract that
729 /// the caller-arm and callee-arm arms of the same diagnostic
730 /// construction reach for the same [`WitContract`] instance or that
731 /// the `de:` and `para:` label pair binds to the fields the author
732 /// declared. Any future rebrand on the axis — an M4 per-cluster
733 /// caller/callee-alias rewrite the operator pins through a future
734 /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
735 /// per-CR fully-qualified namespace prefix the M4
736 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
737 /// per-tenant, a canonicalization pass that lowercases the caller +
738 /// callee identifiers post-parse — would have had to be threaded
739 /// through every open-coded copy in lockstep or one variant's
740 /// diagnostic would silently name a different caller/callee pair
741 /// than its peer, silently degrading the "which caixa is at fault"
742 /// self-locating signal every operator-facing typed diagnostic
743 /// exists to carry. Lifting the pair to a typed method on the
744 /// substrate primitive means every downstream diagnostic-construction
745 /// site reaches for exactly one typed dispatch — the resolver's
746 /// projection migrates as a unit on any future axis addition.
747 ///
748 /// Peer of the sibling per-`:contratos` scalar accessor family
749 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
750 /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
751 /// scalar-value axes — first composite-projection accessor on the
752 /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
753 /// form `.clone()` field-accesses that pair the sibling
754 /// caller/callee accessors' `&str`-return borrowed-form outputs onto
755 /// one typed dispatch. Named `edge_pair()` to reflect the identity
756 /// name of the projected tuple (the typed-edge caller-callee pair,
757 /// distinct from the sibling triple-projection
758 /// [`WitContract::edge_triple`] accessor that folds the local `edge`
759 /// closure in [`WitContract::target`] + the paired
760 /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
761 /// site's `(de, para, wit)` triple onto one typed dispatch).
762 #[must_use]
763 pub fn edge_pair(&self) -> (String, String) {
764 (self.source().to_string(), self.destination().to_string())
765 }
766
767 /// Owned form of the `(:contratos :de, :contratos :para, :contratos
768 /// :wit)` triple every per-edge diagnostic constructor that names
769 /// all three axes threads verbatim into its `de:` / `para:` /
770 /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
771 /// / missing-target / invalid-wit / capability-with-payload arms
772 /// (eight sites all shape `let (de, para, wit) = edge();
773 /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
774 /// accessor landed) and the sibling
775 /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
776 /// constructor (which paired `edge_pair()` for the `(de, para)`
777 /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
778 /// typed-dispatch + raw-field-access shape the sibling accessor
779 /// family already flagged as a drift risk). Nine total call sites
780 /// collapse onto this helper.
781 ///
782 /// Lifted with the same one-source-of-truth discipline
783 /// [`WitContract::edge_pair`] carries on the paired
784 /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
785 /// arms compose through the lifted [`WitContract::source`] /
786 /// [`WitContract::destination`] / [`WitContract::world_ref`]
787 /// scalar accessors byte-for-byte (pinned by the paired
788 /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
789 /// composition-pin), so any future rebrand on the per-`:contratos`
790 /// caller / callee / world-ref axis (an M4 per-cluster
791 /// caller/callee-alias rewrite the operator pins through a future
792 /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
793 /// per-CR fully-qualified namespace prefix the M4
794 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
795 /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
796 /// on `source()` / `destination()`, a per-CR canonicalization pass
797 /// that lowercases the WIT world ref post-parse) migrates as a
798 /// single caixa-core edit rather than a coordinated rewrite of
799 /// nine open-coded triple-constructors.
800 ///
801 /// Peer of the sibling per-`:contratos` composite-projection
802 /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
803 /// composite-value axes — closes the last unlifted owned-form
804 /// composite-tuple axis on the per-`:contratos` diagnostic-
805 /// construction surface. Named `edge_triple()` to reflect the
806 /// identity name of the projected tuple (the typed-edge
807 /// caller-callee-wit triple, sibling to the caller-callee-only
808 /// pair `edge_pair()` returns).
809 #[must_use]
810 pub fn edge_triple(&self) -> (String, String, String) {
811 (
812 self.source().to_string(),
813 self.destination().to_string(),
814 self.world_ref().to_string(),
815 )
816 }
817
818 /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
819 /// dedups typed edges keys off — routes through the lifted
820 /// [`WitContract::source`] / [`WitContract::destination`] /
821 /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
822 /// [`WitContract::subject`] / [`WitContract::slot`] scalar
823 /// accessors so the tuple's six arms and the [`ContratoIdentity`]
824 /// type alias's six axes migrate as a unit on any future axis
825 /// addition (adding a seventh field to [`WitContract`] is one
826 /// [`ContratoIdentity`] alias edit + one accessor addition + one
827 /// arm here, not a coordinated rewrite of every open-coded
828 /// six-tuple builder that dedups on the identity axis).
829 ///
830 /// Sibling of [`WitContract::edge_pair`] /
831 /// [`WitContract::edge_triple`] on the composite-projection axis:
832 /// the pair projects the caller-callee axes, the triple extends it
833 /// with the world-ref, this method extends it with the three
834 /// payload-carrier axes. Every projection returns the same six
835 /// scalar accessors' outputs; the three methods differ only in
836 /// which arms they surface.
837 #[must_use]
838 pub fn identity(&self) -> ContratoIdentity<'_> {
839 (
840 self.source(),
841 self.destination(),
842 self.world_ref(),
843 self.endpoint(),
844 self.subject(),
845 self.slot(),
846 )
847 }
848
849 /// True when this contract targets an HTTP-shaped WIT world.
850 #[must_use]
851 pub fn is_http(&self) -> bool {
852 wit_shape_is_http(self.world_ref())
853 }
854
855 /// True when this contract targets a pub-sub-shaped WIT world.
856 #[must_use]
857 pub fn is_pubsub(&self) -> bool {
858 wit_shape_is_pubsub(self.world_ref())
859 }
860
861 /// True when this contract targets a key/value-shaped WIT world.
862 #[must_use]
863 pub fn is_store(&self) -> bool {
864 wit_shape_is_store(self.world_ref())
865 }
866
867 /// True when this contract targets *none* of the three known payload-
868 /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
869 /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
870 /// open on the [`WitContract`] surface. Returns the exact-inverse
871 /// disjunction of the peer trio — `true` when none of the three
872 /// prefix-set predicates matches the raw `:contratos :wit` value; the
873 /// author-declared WIT world is a pure typed capability edge with no
874 /// payload selector (the shape [`WitContract::target`] projects onto
875 /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
876 /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
877 ///
878 /// The `:contratos :wit` shape-space is closed at four arms
879 /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
880 /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
881 /// everything else on the payload-less capability arm), and every
882 /// downstream consumer that must filter contratos by shape-class
883 /// keys off the four sibling predicates (the [`WitContract::target`]
884 /// dispatch's implicit `else` after the three payload-shape arm
885 /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
886 /// every future substrate-side capability-shape-only emitter — the
887 /// M4 per-Aplicacao WIT-registry capability-import materializer, the
888 /// future `feira app graph --capability` per-Aplicacao capability-
889 /// column filter, the future per-cluster capability-scope reconciler
890 /// that skips L4/L7 emission for payload-less edges since Cilium
891 /// can't introspect WASI capability calls, the future
892 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
893 /// shape shape-count histogram). Every such consumer reaches for one
894 /// typed dispatch on the substrate primitive so the "which arm
895 /// carries the capability-only shape?" answer lives at one caixa-core
896 /// edit rather than open-coded across per-consumer
897 /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
898 /// negations, each of which would silently drop a future fourth
899 /// payload-arm addition without a compile-time signal at the
900 /// consumer site.
901 ///
902 /// Prior to this lift the "not one of the three known payload
903 /// shapes" classification sat inline at [`WitContract::target`]'s
904 /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
905 /// [`WitTarget::Capability`] admission arm after the three `if
906 /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
907 /// { … }` guards) with no named accessor for downstream consumers
908 /// to reach through. A future substrate-side capability-only
909 /// filter or a future capability-scope reconciler would have had to
910 /// re-inline the same triplet negation at every emit site with no
911 /// compile-time link back to the sibling trio, and a future arm
912 /// addition (a hypothetical fourth payload-shape prefix set — a
913 /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
914 /// import carrier per the sibling [`wit_shape_matches`] docstring's
915 /// trajectory bullet) would land the new predicate on the payload-
916 /// carrying trio and silently misclassify the new shape as
917 /// capability at every triplet-negation consumer site, propagating
918 /// the drift far from the caixa-core prefix-set commit.
919 ///
920 /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
921 /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
922 /// trio into a 4-way partition witness on the raw `:contratos :wit`
923 /// axis, mirroring the paired post-projection [`WitTarget`]
924 /// `gen_platform::IsVariant`-derived 4-way predicate set
925 /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
926 /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
927 /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
928 /// arm-set). The two typed axes — pre-projection on the raw
929 /// `:contratos :wit` string, post-projection on the validated typed
930 /// view — now carry a matched 4-arm predicate discipline: every
931 /// arm on the closed [`WitTarget`] set has a peer pre-projection
932 /// predicate on the [`WitContract`] surface, and any future
933 /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
934 /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
935 /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
936 /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
937 /// pre-projection axis through a matching peer prefix-set + peer
938 /// predicate lift by construction — the compile-time exhaustiveness
939 /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
940 /// the post-projection accessor family stays in sync, and the sibling
941 /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
942 /// partition-witness pin locks the pre-projection classification in
943 /// load-bearing so a peer prefix-set addition that widened one arm's
944 /// accept-set without shrinking the [`Self::is_capability`] accept-set
945 /// surfaces as a test failure at caixa-core build time rather than a
946 /// silent per-consumer split at renderer emit time.
947 ///
948 /// Composes byte-for-byte through the lifted peer trio
949 /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
950 /// any future rebrand of any prefix-set const flows through this
951 /// method by construction without a coordinated per-consumer rewrite
952 /// (pinned by the sibling
953 /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
954 /// composition-witness).
955 ///
956 /// Note: purely syntactic classification on the `:wit` prefix-set —
957 /// unlike [`Self::target`], which additionally rejects value-shape-
958 /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
959 /// package) via [`crate::render::is_wit_world_ref`] and payload-
960 /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
961 /// structurally malformed returns `true` from `is_capability()` (the
962 /// prefix set matches nothing), and the surrounding
963 /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
964 /// is where the [`AplicacaoError::EmptyWit`] /
965 /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
966 /// predicate is the classifier, not the validator.
967 #[must_use]
968 pub fn is_capability(&self) -> bool {
969 wit_shape_is_capability(self.world_ref())
970 }
971
972 /// True when this contract's caller equals its callee — a
973 /// structurally degenerate typed edge that no `:contratos` entry can
974 /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
975 /// Servico B" is an *inter*-Servico contract between two distinct
976 /// graph nodes). A Servico contracting with itself resolves to an
977 /// in-process call the wasm-engine never routes through the mesh at
978 /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
979 /// per-edge policy can express the intended shape — the pub-sub
980 /// path silently rendered a self-allow rule that is a no-op (intra-
981 /// pod traffic bypasses the mesh entirely), and the synchronous
982 /// paths surfaced as a misleading `ContratoCycle` whose path was
983 /// `["cart", "cart"]` — framing a self-edge as a multi-node
984 /// deadlock. Every downstream consumer that must reject the shape
985 /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
986 /// gate at caixa-core/src/aplicacao.rs:5559, every future
987 /// per-`:contratos`-edge policy resolver on the M4 CR materializer
988 /// axis, every future adjacency-graph builder that must skip self-
989 /// edges rather than fold them into an incidental cycle) now keys
990 /// off exactly one typed dispatch on the substrate primitive, so
991 /// any future rebrand on the axis (an M4-typed-caller enum whose
992 /// identity comparison rule the accessor could route through, an
993 /// operator-side per-cluster caller/callee-alias table the
994 /// materializer resolves per-CR before the equality probe, a
995 /// promotion of the pointwise `==` to a set-membership check once
996 /// SimpleOneForOne-shaped dynamic replicas come into typed scope
997 /// so a per-replica self-edge is rejected under the same predicate)
998 /// migrates as a single caixa-core edit rather than a coordinated
999 /// rewrite of every downstream self-edge consumer. Composes
1000 /// byte-for-byte through the lifted [`Self::source`] /
1001 /// [`Self::destination`] scalar accessors — the accessor pair every
1002 /// per-`:contratos` scalar-value axis already routes through — so
1003 /// any future rebrand of the underlying `:de` / `:para` storage
1004 /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1005 /// a per-Aplicacao interning arena the M4 CR materializer authors,
1006 /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1007 /// same one body without a coordinated per-consumer rewrite.
1008 ///
1009 /// Sibling in shape to the peer per-`:contratos` shape-predicate
1010 /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1011 /// on the `:wit` world-ref axis — extended onto the per-edge
1012 /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1013 /// partition the WIT-shape-space; `is_self_loop` partitions the
1014 /// caller-callee identity-space. Named `is_self_loop()` to reflect
1015 /// the graph-theoretic identity of the shape (a loop from a graph
1016 /// node to itself, distinct from the sibling multi-node
1017 /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1018 /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1019 /// variant already carrying the term.
1020 #[must_use]
1021 pub fn is_self_loop(&self) -> bool {
1022 self.source() == self.destination()
1023 }
1024
1025 /// Typed view of the contract's payload target. Enforces that the
1026 /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1027 /// fields agree, and that each carried value is itself
1028 /// value-shape valid:
1029 ///
1030 /// - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1031 /// non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1032 /// `PathPrefix` invariant — same shape required of `:entrada
1033 /// :paths`)
1034 /// - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1035 /// non-empty (NATS / Kafka publish without a subject is a
1036 /// no-op subscribe, never the author's intent)
1037 /// - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1038 /// non-empty (an empty slot template addresses the bucket
1039 /// root, defeating the per-key isolation the slot exists for)
1040 /// - Anything else ⇒ none of the three; the contract is a pure
1041 /// typed capability edge with no payload selector.
1042 ///
1043 /// Translates the Apollo Federation discipline ("conflicts are
1044 /// errors at compile time, not warnings at runtime";
1045 /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1046 /// a contract whose WIT shape disagrees with its target field, or
1047 /// whose target field carries a value-shape-invalid string, is a
1048 /// build error — not a silent renderer drop. The returned
1049 /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1050 /// non-empty (and absolute, for `Http`); every downstream consumer
1051 /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1052 /// the M4 per-edge policy resolver) can rely on that without
1053 /// re-checking.
1054 pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1055 // Route the HTTP-shaped payload-target extraction through the
1056 // lifted [`WitContract::endpoint`] accessor rather than the raw
1057 // `self.endpoint.as_deref()` field access — the two production
1058 // consumers of the per-`:contratos :endpoint` HTTP-shaped
1059 // payload-carrier scalar (this method's Http-arm payload
1060 // extraction, the [`AplicacaoSpec::validate`] duplicate-
1061 // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1062 // off exactly one typed dispatch on the substrate primitive, so
1063 // any future rebrand on the axis (an M4 per-cluster endpoint-
1064 // alias rewrite, a per-CR fully-qualified path prefix the M4
1065 // materializer applies per-tenant, an M4 promotion from
1066 // `Option<String>` to a typed HTTP path-template enum) migrates
1067 // as a single caixa-core edit rather than a coordinated rewrite
1068 // of the two call sites — peer of the sibling M3 per-`:placement`
1069 // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1070 // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1071 // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1072 let endpoint = self.endpoint();
1073 let subject = self.subject();
1074 // Route the store-arm payload-carrier scalar through the
1075 // lifted [`WitContract::slot`] accessor rather than the raw
1076 // `self.slot.as_deref()` field access — the two production
1077 // consumers of the per-`:contratos :slot` key/value-store-
1078 // shaped payload-carrier scalar (this method's Store-arm
1079 // payload extraction, the [`AplicacaoSpec::validate`]
1080 // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1081 // arm) now key off exactly one typed dispatch on the substrate
1082 // primitive. Closes the last unlifted per-`:contratos`
1083 // `Option<String>` axis, completing the payload-carrier
1084 // accessor family peer of the sibling per-`:contratos`
1085 // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1086 // (90de675) lifts across the HTTP / pub-sub arms.
1087 let slot = self.slot();
1088 // Route the local `(de, para, wit)` triple-projection closure
1089 // through the lifted [`WitContract::edge_triple`] typed accessor
1090 // rather than re-inlining `(self.de.clone(), self.para.clone(),
1091 // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1092 // triple-carrying diagnostic constructors below (wrong-target /
1093 // missing-target on all three payload arms + capability-with-
1094 // payload + invalid-wit) now key off exactly one typed dispatch
1095 // on the substrate-primitive composite projection, sibling to
1096 // the peer [`WitContract::edge_pair`]-routed
1097 // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1098 // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1099 // diagnostic constructors on the same per-`:contratos`
1100 // diagnostic-construction surface.
1101 let edge = || self.edge_triple();
1102
1103 // The `:wit` value drives every downstream dispatch — the
1104 // is_http/is_pubsub/is_store prefix matchers below, the
1105 // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1106 // exclusion. Until this gate landed `target()` accepted any
1107 // non-empty string and silently demoted unrecognized shapes to
1108 // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1109 // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1110 // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1111 // package, the paste-from-binary footgun a multi-line blob
1112 // accidentally landing in the slot, the un-percent-encoded
1113 // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1114 // routing, got L4-only" footgun. Empty is still pre-checked at
1115 // the [`AplicacaoSpec::validate`] call site via the narrower
1116 // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1117 // validate layer); the value-shape gate here picks up the
1118 // structurally-invalid non-empty cases the empty check misses,
1119 // and remains correct under direct `target()` calls outside
1120 // validate (the predicate's defensive empty arm returns a
1121 // parser-shaped reason rather than silently falling through to
1122 // the Capability arm). Same trajectory as c4213a4 (WitContract
1123 // endpoint/subject/slot value-shape gates lifted into
1124 // `target()`) on the peer payload axes.
1125 if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
1126 let (de, para, wit) = edge();
1127 return Err(AplicacaoError::ContratoWitInvalid {
1128 de,
1129 para,
1130 wit,
1131 reason,
1132 });
1133 }
1134
1135 if self.is_http() {
1136 if subject.is_some() || slot.is_some() {
1137 let (de, para, wit) = edge();
1138 return Err(AplicacaoError::ContratoWrongTarget {
1139 de,
1140 para,
1141 wit,
1142 expected: WitTarget::HTTP_FIELD_NAME,
1143 });
1144 }
1145 let ep = endpoint.ok_or_else(|| {
1146 let (de, para, wit) = edge();
1147 AplicacaoError::ContratoMissingTarget {
1148 de,
1149 para,
1150 wit,
1151 expected: WitTarget::HTTP_FIELD_NAME,
1152 }
1153 })?;
1154 if ep.is_empty() {
1155 let (de, para) = self.edge_pair();
1156 return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
1157 }
1158 if !ep.starts_with('/') {
1159 let (de, para) = self.edge_pair();
1160 return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1161 de,
1162 para,
1163 endpoint: ep.to_string(),
1164 });
1165 }
1166 // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1167 // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1168 // API v1 HTTPPathMatch.value admission grammar with the
1169 // sibling `:entrada :paths` axis. Until this gate landed
1170 // `target()` only refused the empty string + the missing-
1171 // leading-`/` form; a structurally invalid endpoint
1172 // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1173 // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1174 // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1175 // path-traversal segment, the >1024-byte slug) silently
1176 // passed validate and the failure surfaced at apply time
1177 // as a Cilium policy rejection / silent traffic drop, far
1178 // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1179 // grammar `:entrada :paths` already gates (55410e4), now
1180 // shared with `:contratos :endpoint` through the lifted
1181 // `crate::render::is_gateway_api_http_path` predicate.
1182 if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1183 let (de, para) = self.edge_pair();
1184 return Err(AplicacaoError::ContratoEndpointInvalid {
1185 de,
1186 para,
1187 endpoint: ep.to_string(),
1188 reason,
1189 });
1190 }
1191 return Ok(WitTarget::Http { endpoint: ep });
1192 }
1193 if self.is_pubsub() {
1194 if endpoint.is_some() || slot.is_some() {
1195 let (de, para, wit) = edge();
1196 return Err(AplicacaoError::ContratoWrongTarget {
1197 de,
1198 para,
1199 wit,
1200 expected: WitTarget::PUBSUB_FIELD_NAME,
1201 });
1202 }
1203 let s = subject.ok_or_else(|| {
1204 let (de, para, wit) = edge();
1205 AplicacaoError::ContratoMissingTarget {
1206 de,
1207 para,
1208 wit,
1209 expected: WitTarget::PUBSUB_FIELD_NAME,
1210 }
1211 })?;
1212 if s.is_empty() {
1213 let (de, para) = self.edge_pair();
1214 return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1215 }
1216 // The `:subject` lands at runtime as the NATS subject the
1217 // producer publishes to and the consumer subscribes from.
1218 // Until this gate landed `target()` only refused the
1219 // empty string; a structurally invalid subject
1220 // (`"foo..bar"` — empty token between separators,
1221 // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1222 // server's subject parser rejects, `"foo bar"` —
1223 // un-percent-encoded whitespace, `"foo.café"` —
1224 // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1225 // empty leading/trailing tokens, the >256-byte
1226 // paste-from-binary slug) silently passed validate and
1227 // the failure surfaced at runtime as a NATS server-side
1228 // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1229 // a silent message drop, far from the source caixa.lisp.
1230 // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1231 // trajectory `:contratos :endpoint` (4f0390b) and
1232 // `:contratos :wit` (6226bf4) already gate, now shared
1233 // with `:contratos :subject` through the lifted
1234 // `crate::render::is_nats_subject` predicate.
1235 if let Err(reason) = crate::render::is_nats_subject(s) {
1236 let (de, para) = self.edge_pair();
1237 return Err(AplicacaoError::ContratoSubjectInvalid {
1238 de,
1239 para,
1240 subject: s.to_string(),
1241 reason,
1242 });
1243 }
1244 return Ok(WitTarget::PubSub { subject: s });
1245 }
1246 if self.is_store() {
1247 if endpoint.is_some() || subject.is_some() {
1248 let (de, para, wit) = edge();
1249 return Err(AplicacaoError::ContratoWrongTarget {
1250 de,
1251 para,
1252 wit,
1253 expected: WitTarget::STORE_FIELD_NAME,
1254 });
1255 }
1256 let sl = slot.ok_or_else(|| {
1257 let (de, para, wit) = edge();
1258 AplicacaoError::ContratoMissingTarget {
1259 de,
1260 para,
1261 wit,
1262 expected: WitTarget::STORE_FIELD_NAME,
1263 }
1264 })?;
1265 if sl.is_empty() {
1266 let (de, para) = self.edge_pair();
1267 return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1268 }
1269 // Value-shape gate on the third (and last) typed payload
1270 // axis the `WitContract::target` dispatch carries — the
1271 // peer of [`crate::render::is_gateway_api_http_path`] for
1272 // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1273 // for `:subject` (63e18a0). Until this gate landed
1274 // `target()` only refused the empty string; a structurally
1275 // invalid slot (`"check out/$order"` — un-percent-encoded
1276 // whitespace whose runtime behavior varies unpredictably
1277 // across kv backends, `"checkout/\x01order"` — control
1278 // character that Redis admits but corrupts on next read
1279 // and DynamoDB rejects outright, `"chéckout/$order"` —
1280 // un-percent-encoded non-ASCII byte each backend re-encodes
1281 // differently, `"checkout\n/$order"` — embedded newline,
1282 // the 513-byte paste-from-binary slug) silently passed
1283 // validate and surfaced at runtime as a per-backend kv
1284 // write rejection (DynamoDB / etcd) or as a silent
1285 // next-read corruption (Redis-via-RESP3), far from the
1286 // source caixa.lisp with no field naming which `:contratos`
1287 // edge carried the typo. The lifted predicate makes the
1288 // kv-backend intersection-floor a substrate-level
1289 // invariant at validate time, not a runtime "this passed
1290 // validate but the kv backend rejected on first write"
1291 // surprise — closes the typed payload-axis value-shape
1292 // trajectory across all three legs of the four
1293 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1294 // that caixa-mesh + the future kv emitters land in.
1295 if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1296 let (de, para) = self.edge_pair();
1297 return Err(AplicacaoError::ContratoSlotInvalid {
1298 de,
1299 para,
1300 slot: sl.to_string(),
1301 reason,
1302 });
1303 }
1304 return Ok(WitTarget::Store { slot: sl });
1305 }
1306
1307 // Unrecognized WIT world — must not carry any payload target.
1308 if endpoint.is_some() || subject.is_some() || slot.is_some() {
1309 let (de, para, wit) = edge();
1310 return Err(AplicacaoError::ContratoWrongTarget {
1311 de,
1312 para,
1313 wit,
1314 expected: WitTarget::CAPABILITY_EXPECTED,
1315 });
1316 }
1317 Ok(WitTarget::Capability)
1318 }
1319
1320 /// Substrate-canonical post-validation projection of the typed
1321 /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1322 /// downstream of an [`AplicacaoSpec`] that has already crossed the
1323 /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1324 /// [`typed_view`]-shaped entry point that composes `validate` into
1325 /// the projection) reaches through when it needs the typed
1326 /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1327 /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1328 /// coherence for every `:contratos` entry. The peer accessor to the
1329 /// [`Self::target`] `Result`-returning validator on the same
1330 /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1331 /// pre-validation validator that computes the projection *and* raises
1332 /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1333 /// (`:wit`, payload) mismatch; this method is the post-validation
1334 /// projection every downstream consumer reaches through once the
1335 /// pre-validation gate has succeeded.
1336 ///
1337 /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1338 ///
1339 /// Prior to this lift the "call `.target()` then `.expect(…)` with
1340 /// the same message" pattern sat inline at two production sites with
1341 /// no compile-time link between them: the
1342 /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1343 /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1344 /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1345 /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1346 /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1347 /// (`c.target().expect("validated by typed_view").graph_label()`),
1348 /// each open-coding the same `.target().expect("validated by
1349 /// typed_view")` pair with the message spelled twice. A future
1350 /// vocabulary shift on the panic-message axis (a tightening from
1351 /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1352 /// validate"` as the substrate's validator entry-point vocabulary
1353 /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1354 /// panic to a `debug_assert` under a `--release` build profile) would
1355 /// have had to be threaded through both open-coded call sites in
1356 /// lockstep or one consumer would silently disagree with the peer on
1357 /// which invariant the panic message names. Same "same shape written
1358 /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1359 /// discipline the sibling [`Self::edge_pair`] /
1360 /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1361 /// lifts already establish on the paired composite-projection axis;
1362 /// this lift extends it onto the post-validation typed-view axis.
1363 ///
1364 /// Every future downstream consumer of the projected typed view
1365 /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1366 /// CR materializer's per-edge admission webhook, the future
1367 /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1368 /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1369 /// resolver, the future `feira app graph --l7` / `--pubsub` /
1370 /// `--kv` per-shape column emitters) reaches through this one typed
1371 /// dispatch on the substrate primitive rather than an open-coded
1372 /// per-consumer `.target().expect(…)` pair with the message
1373 /// re-inlined. The invariant the accessor's panic path pins — "this
1374 /// call is only reachable after [`AplicacaoSpec::validate`] has
1375 /// succeeded on the containing spec" — is the substrate's answer to
1376 /// give exactly once, at the primitive, not once per consumer.
1377 ///
1378 /// # Panics
1379 ///
1380 /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1381 /// would return an `Err` — i.e. if this contract's
1382 /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1383 /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1384 /// this accessor only from a code path that has already reached the
1385 /// containing [`AplicacaoSpec`] through a validating entry-point
1386 /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1387 /// [`typed_view`] compose, the future M4 CR admission webhook's
1388 /// per-CR validate). Use [`Self::target`] instead on any pre-
1389 /// validation code path.
1390 ///
1391 /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1392 #[must_use]
1393 pub fn target_projected(&self) -> WitTarget<'_> {
1394 self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1395 }
1396
1397 /// Canonical panic message the [`Self::target_projected`]
1398 /// post-validation projection accessor threads through when the
1399 /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1400 /// has succeeded" precondition. Lifted as a `pub const` on the
1401 /// [`WitContract`] surface so the byte-string lives in one place
1402 /// across the substrate — the [`Self::target_projected`] method
1403 /// body, the two prior production call sites' comments now naming
1404 /// the const, and every future consumer that must format-match the
1405 /// panic-message shape (a future test suite that asserts the panic-
1406 /// message byte-string across a fuzzed invalid-contract corpus,
1407 /// a future custom-panic hook in `caixa-operator` that surfaces the
1408 /// message with per-`:contratos` telemetry, the future admission
1409 /// webhook's per-CR validate-error report) reaches through the same
1410 /// canonical `&'static str`. A future rebrand on the panic-message
1411 /// axis (a tightening from `"validated by typed_view"` to `"validated
1412 /// by AplicacaoSpec::validate"` as the substrate's validator
1413 /// entry-point vocabulary sharpens once caixa-core grows a
1414 /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1415 /// [`typed_view`]) lands at one caixa-core edit rather than a
1416 /// coordinated per-consumer sweep — same "one canonical declaration
1417 /// per axis, next to the accessor that reads it" discipline the peer
1418 /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1419 /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1420 /// const family already establishes on the paired per-consumer-axis
1421 /// diagnostic-scalar surface.
1422 pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1423}
1424
1425/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1426/// gate (see [`AplicacaoSpec::validate`]): every field that
1427/// distinguishes one contract from another, in declaration order
1428/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1429/// with equal [`ContratoIdentity`]s are the same typed edge declared
1430/// twice — the graph-edge analogue of duplicate `:membros` /
1431/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1432/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1433/// clippy's `type_complexity` lint (and so a future axis added to
1434/// `WitContract` is one alias edit, not a coordinated rewrite of
1435/// every set instantiation).
1436pub type ContratoIdentity<'a> = (
1437 &'a str,
1438 &'a str,
1439 &'a str,
1440 Option<&'a str>,
1441 Option<&'a str>,
1442 Option<&'a str>,
1443);
1444
1445/// Typed view of a [`WitContract`]'s payload target. Each variant
1446/// carries the field its WIT shape requires; constructing a `Http`
1447/// view without an endpoint is impossible by the type system.
1448///
1449/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1450/// instead of probing `Option<String>` fields one by one — the
1451/// "which payload field is set?" question is answered once, at
1452/// validation time.
1453#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1454pub enum WitTarget<'a> {
1455 /// HTTP-shaped WIT world. Carries the configured request path.
1456 Http { endpoint: &'a str },
1457 /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1458 ///
1459 /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1460 /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1461 /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1462 /// method name byte-identical to the sibling
1463 /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1464 /// arm-discriminator that routes through
1465 /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1466 /// through `matches!` on the variant), so the two arm-discriminator
1467 /// axes — target-side variant-arm and shape-side ref-prefix — reach
1468 /// every downstream consumer through the same `is_pubsub()` name.
1469 #[is_variant(name = "pubsub")]
1470 PubSub { subject: &'a str },
1471 /// Key-value-shaped WIT world. Carries the slot template.
1472 Store { slot: &'a str },
1473 /// A typed capability edge with no payload selector — the WIT
1474 /// world stands on its own (rare; reserved for plain capability
1475 /// imports or M4-and-later WIT worlds we haven't shaped yet).
1476 Capability,
1477}
1478
1479impl<'a> WitTarget<'a> {
1480 /// Canonical author-facing `:contratos` payload field name for the
1481 /// HTTP-shaped arm — the `expected: &'static str` scalar the
1482 /// [`AplicacaoError::ContratoMissingTarget`] /
1483 /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1484 /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1485 /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1486 /// the `feira app graph` verb prints. Peer of
1487 /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1488 /// on the payload-field-name axis; declared as a peer const next
1489 /// to the [`WitTarget::Http`] variant so a future rename on the
1490 /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1491 /// :endpoint …)))` field lands in exactly one place, not scattered
1492 /// across the [`WitContract::target`] gate's six `expected:`
1493 /// literals, the label template, and every downstream consumer
1494 /// that prints a per-arm prefix. Same trajectory as the peer
1495 /// [`WitTarget::label`] lift (174e96a): a single source of truth
1496 /// for the arm's shape, next to the variant declaration.
1497 pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1498 /// Canonical author-facing `:contratos` payload field name for the
1499 /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1500 /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1501 /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1502 pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1503 /// Canonical author-facing `:contratos` payload field name for the
1504 /// key/value-store-shaped arm. Peer of
1505 /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1506 /// on the payload-field-name axis; see
1507 /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1508 pub const STORE_FIELD_NAME: &'static str = "slot";
1509
1510 /// Canonical stable human-readable label the payload-less
1511 /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1512 /// the byte-string every consumer that formats a payload-less
1513 /// typed capability edge as text lands on (the
1514 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1515 /// naming which identical edge was declared twice, the future
1516 /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1517 /// policy resolver's audit view, the operator's mesh-graph audit).
1518 /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1519 /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1520 /// author-facing label-scalar consts — the same
1521 /// "one canonical declaration per arm, next to the variant, so a
1522 /// future rename lands in one place" discipline extended to the
1523 /// payload-less arm. Until this lift landed the byte-string sat
1524 /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1525 /// match arm, once in the pin test asserting the label's
1526 /// [`WitTarget::Capability`] output — with no compile-time link
1527 /// between the two: a rebrand on either side (an operator-facing
1528 /// vocabulary shift, a per-consumer disambiguation like
1529 /// `"(capability — no payload; typed edge only)"`) would silently
1530 /// desynchronize until a downstream consumer surfaced the drift at
1531 /// runtime.
1532 pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1533
1534 /// Canonical `expected:` scalar the
1535 /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1536 /// through for the payload-less [`WitTarget::Capability`] arm — the
1537 /// byte-string authors read as "this WIT world's shape is not one
1538 /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1539 /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1540 /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1541 /// [`Self::STORE_FIELD_NAME`] consts on the
1542 /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1543 /// same "which payload field name goes in the diagnostic" dispatch
1544 /// the three payload-arm consts cover, extended to the payload-less
1545 /// arm. Until this lift landed the byte-string sat twice — once
1546 /// inline in the [`Self::target`] Capability-arm rejection at the
1547 /// production dispatch, once in the pin test asserting the
1548 /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1549 /// no compile-time link between the two: a rebrand on either side
1550 /// (an author-facing vocabulary shift to `"capability"` /
1551 /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1552 /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1553 /// [`WitTarget::Capability`] into per-shape peers) would silently
1554 /// desynchronize until a downstream consumer surfaced the drift at
1555 /// runtime. Same "one canonical declaration per arm, next to the
1556 /// variant, so a future rename lands in one place" discipline the
1557 /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1558 /// established for the payload-less arm's human-readable label
1559 /// axis; this lift extends it onto the peer diagnostic-scalar axis
1560 /// so both halves of the "how does the Capability arm surface at
1561 /// its two consumer axes (human-readable label, wrong-target
1562 /// diagnostic)" pipeline route through peer consts declared next
1563 /// to the variant.
1564 ///
1565 /// Pairwise-distinctness against the three payload-arm scalars
1566 /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1567 /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1568 /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1569 /// test — the 4-way closure of the 3-way
1570 /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1571 /// the `ContratoWrongTarget::expected` axis, matching the peer
1572 /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1573 /// scalar-value distinctness discipline the sibling M3 typed-enum
1574 /// discriminator axis already carries.
1575 pub const CAPABILITY_EXPECTED: &'static str = "none";
1576
1577 /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1578 /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1579 /// as under [`Self::graph_label`] — the sibling
1580 /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1581 /// payload-column axis (the graph verb spells payload-less as
1582 /// `(capability-only)`, distinct from the duplicate-`:contratos`
1583 /// diagnostic's `(capability — no payload)` on the human-readable
1584 /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1585 /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1586 /// family — extends the "one canonical declaration per arm, next to
1587 /// the variant, so a future rename lands in one place" discipline
1588 /// onto the third payload-less-arm consumer axis (`feira app graph`
1589 /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1590 /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1591 /// axis).
1592 ///
1593 /// Until this lift landed the byte-string sat inline in
1594 /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1595 /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1596 /// `"(capability-only)".to_string()` literal, with no compile-time link
1597 /// back to the [`WitTarget::Capability`] variant declaration nor to
1598 /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1599 /// peer consts already carrying the "one canonical declaration per
1600 /// payload-less-arm consumer axis" discipline. A rebrand on either
1601 /// side (the graph verb's operator-facing vocabulary tightening from
1602 /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1603 /// the WIT registry vocabulary sharpens, an M4 split of
1604 /// [`Self::Capability`] into per-shape peers) would silently
1605 /// desynchronize the graph-verb byte-string from the paired
1606 /// per-arm-adjacent const and land two spellings of the same axis in
1607 /// two spots.
1608 pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1609
1610 /// The `(author-facing field name, payload)` pair this typed target
1611 /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1612 /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1613 /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1614 /// [`Self::Store`], `None` for the payload-less
1615 /// [`Self::Capability`] arm.
1616 ///
1617 /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1618 /// (formats `":{field} {payload:?}"` on `Some`, falls to
1619 /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1620 /// (returns the first component) route through, so a future
1621 /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1622 /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1623 /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1624 /// exactly one new match-arm here (a compile-time exhaustiveness
1625 /// error otherwise), not a coordinated three-way rewrite of the
1626 /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1627 /// + every downstream consumer that reaches for the pair.
1628 ///
1629 /// Until this lift landed the three payload arms sat in
1630 /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1631 /// invocations (one per variant, each hand-quoting the paired
1632 /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1633 /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1634 /// "same shape, written N times" duplication THEORY.md §I.3.5
1635 /// ("Generation first, composition second, hand-authoring last;
1636 /// the duplication budget is zero") promotes to a build-time
1637 /// concern, with each per-arm site paired to its own const with no
1638 /// compile-time link between the format template and the arm's
1639 /// payload extraction.
1640 #[must_use]
1641 pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1642 match *self {
1643 WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1644 WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1645 WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1646 WitTarget::Capability => None,
1647 }
1648 }
1649
1650 /// The canonical author-facing `:contratos` payload field name
1651 /// this typed target arm carries (`Http` → `Some("endpoint")`,
1652 /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1653 /// `None` for the payload-less `Capability` arm.
1654 ///
1655 /// Routes through [`Self::payload_pair`] — the single 4-arm
1656 /// dispatch [`Self::label`] also reads — so a future variant
1657 /// addition is one match-arm edit at [`Self::payload_pair`], not a
1658 /// per-consumer rewrite. Same "exhaustive-match at one canonical
1659 /// dispatch, thin projections at each consumer" trajectory the
1660 /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1661 /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1662 #[must_use]
1663 pub const fn field_name(&self) -> Option<&'static str> {
1664 match self.payload_pair() {
1665 Some((f, _)) => Some(f),
1666 None => None,
1667 }
1668 }
1669
1670 /// The underlying scalar the payload-carrying arm carries — the
1671 /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1672 /// subject ([`Self::PubSub`] `:subject`), or slot template
1673 /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1674 /// `&'a str` storage — or `None` on the payload-less
1675 /// [`Self::Capability`] arm.
1676 ///
1677 /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1678 /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1679 /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1680 /// the paired sub-selector axis. Both per-half accessors read from
1681 /// one authoritative match, so a future [`WitTarget`] variant
1682 /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1683 /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1684 /// on [`Self::payload_pair`] and both per-half projections + every
1685 /// downstream consumer picks the new arm up by construction — no
1686 /// coordinated N-way rewrite across the paired accessor dispatches,
1687 /// the [`Self::label`] / [`Self::graph_label`] format templates,
1688 /// and every future WIT-registry-shaped consumer.
1689 ///
1690 /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
1691 /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
1692 /// controller `spec.ref.<field>` axis — same "one paired dispatch,
1693 /// both per-half projections as thin readers, every downstream
1694 /// consumer through the same match" discipline extended onto the
1695 /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
1696 /// gap between the two paired-dispatch surfaces: the peer
1697 /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
1698 /// the first-component projection until this lift; the second-
1699 /// component sibling now sits alongside so both halves reach every
1700 /// future consumer through the same substrate-primitive dispatch.
1701 ///
1702 /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
1703 #[must_use]
1704 pub const fn payload(&self) -> Option<&'a str> {
1705 match self.payload_pair() {
1706 Some((_, p)) => Some(p),
1707 None => None,
1708 }
1709 }
1710
1711 /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
1712 /// consumer that fans on the L7-HTTP-shaped payload keys off —
1713 /// returns the [`Self::Http`]-arm's author-declared request path
1714 /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
1715 /// projected target is [`Self::Http { endpoint }`], `None` on the
1716 /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
1717 /// [`Self::Capability`], each of which carries no HTTP endpoint by
1718 /// definition).
1719 ///
1720 /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
1721 /// `path:` rule payload every substrate-side L7-introspecting
1722 /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
1723 /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
1724 /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
1725 /// on the L7 introspection branch; every peer WIT shape stays
1726 /// L4-only because Cilium can't introspect NATS / key-value / plain
1727 /// capability edges), and every future L7-introspecting consumer
1728 /// of the projected target's HTTP endpoint (the future M4
1729 /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
1730 /// materializer's per-edge L7 admission-webhook overlay, the
1731 /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
1732 /// path bucket-key resolver, the future per-`:contratos`-edge
1733 /// mTLS-required overlay's HTTP-shape scope filter, the future
1734 /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
1735 /// through the same typed dispatch.
1736 ///
1737 /// Prior to this lift the sole production consumer of the projected-
1738 /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
1739 /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
1740 /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
1741 /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
1742 /// }`) — reached the payload through a raw per-arm `if let` pattern-
1743 /// match that expressed no compile-time link back to the substrate
1744 /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
1745 /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
1746 /// scalar accessor on the peer per-`:contratos` raw-field axis but
1747 /// with no post-projection peer on the typed-view surface. A future
1748 /// [`WitTarget`] variant addition that splits [`Self::Http`] into
1749 /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
1750 /// gRPC-shaped worlds per this enum's own docstring at
1751 /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
1752 /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
1753 /// would have had to be threaded through the caixa-mesh L7 emit
1754 /// branch's raw `if let` in lockstep — either coalescing the two
1755 /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
1756 /// emit path per-arm — with no substrate-primitive dispatch making
1757 /// the "which arms count as L7-HTTP-shaped for path-emission
1758 /// purposes" question the substrate's answer to give. Lifting the
1759 /// resolution to a typed method on the substrate primitive means
1760 /// every downstream L7-HTTP-facing consumer of the Aplicacao's
1761 /// projected-target HTTP endpoint reaches for exactly one typed
1762 /// dispatch — the resolver's accept-set migrates as a unit on any
1763 /// future arm-family widening, and the caixa-mesh L7 emit branch
1764 /// reads through the same substrate primitive.
1765 ///
1766 /// Peer of the sibling pre-projection [`WitContract::endpoint`]
1767 /// (7020470) `Option<&str>` scalar accessor on the raw
1768 /// `:contratos :endpoint` field-access axis — same "one typed
1769 /// dispatch on the substrate primitive, thin projections at each
1770 /// consumer" discipline extended onto the peer post-projection typed-
1771 /// view surface (the [`WitContract::endpoint`] pre-projection
1772 /// accessor returns `Some` for any author-declared `:endpoint`
1773 /// value regardless of the paired `:wit` world's HTTP-shape
1774 /// classification — the raw slot before validation crosses it —
1775 /// while this post-projection [`Self::http_endpoint`] accessor
1776 /// returns `Some` iff the target has been projected onto the
1777 /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
1778 /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
1779 /// coherence; the two accessors close the pre-projection /
1780 /// post-projection pair on the HTTP-endpoint axis). Sibling of the
1781 /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
1782 /// the three payload-carrying arms) — extends the per-arm
1783 /// projection family onto the [`Self::Http`] specialization axis
1784 /// that the pan-arm accessor's shape blends into a single arm-
1785 /// agnostic view; paired with [`Self::pubsub_subject`] /
1786 /// [`Self::store_slot`] on the sibling per-arm axes so every
1787 /// per-payload-arm shape carries a named post-projection accessor
1788 /// on the same shape as `http_endpoint`, closing the per-arm-shape
1789 /// accept-set the substrate primitive owns.
1790 #[must_use]
1791 pub const fn http_endpoint(&self) -> Option<&'a str> {
1792 match *self {
1793 WitTarget::Http { endpoint } => Some(endpoint),
1794 WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1795 }
1796 }
1797
1798 /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
1799 /// consumer that fans on the pub-sub-shaped payload keys off —
1800 /// returns the [`Self::PubSub`]-arm's author-declared event-stream
1801 /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
1802 /// the projected target is [`Self::PubSub { subject }`], `None` on
1803 /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
1804 /// [`Self::Capability`], each of which carries no NATS-shaped
1805 /// subject by definition).
1806 ///
1807 /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
1808 /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
1809 /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
1810 /// CR materializer's `spec.subjects[]` projection, the future
1811 /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
1812 /// bucket-key resolver, the future `feira app graph --pubsub`
1813 /// per-Aplicacao subject column, any future substrate-lifted
1814 /// pub-sub-shape emitter that reads a projected `WitTarget` in the
1815 /// same shape [`caixa_mesh::cilium_network_policies`] reads the
1816 /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
1817 /// future pub-sub-shape consumer reaches for the same typed
1818 /// dispatch this accessor exposes so the "which arm carries the
1819 /// subject scalar?" answer lives at one caixa-core edit rather
1820 /// than open-coded across per-consumer `if let WitTarget::PubSub
1821 /// { subject } = c.target()…` pattern-matches.
1822 ///
1823 /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
1824 /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
1825 /// the pre-projection [`WitContract::subject`] scalar accessor on
1826 /// the raw `:contratos :subject` field-access axis — same "one
1827 /// typed dispatch on the substrate primitive, thin projections at
1828 /// each consumer" discipline extended onto the per-arm pub-sub
1829 /// post-projection axis. The pre-projection accessor returns
1830 /// `Some` for any author-declared `:subject` value regardless of
1831 /// the paired `:wit` world's pub-sub-shape classification (the raw
1832 /// slot before validation crosses it); this post-projection
1833 /// accessor returns `Some` iff the target has been projected onto
1834 /// the [`Self::PubSub`] arm, i.e. only after the
1835 /// [`WitContract::target`] gate has admitted the
1836 /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
1837 /// the pre-/post-projection pair on the pub-sub-subject axis to
1838 /// match the pair the [`WitContract::endpoint`] +
1839 /// [`Self::http_endpoint`] surfaces already close on the peer
1840 /// HTTP-endpoint axis.
1841 ///
1842 /// Sibling of the unified pan-arm [`Self::payload`]
1843 /// (`Option<&'a str>` for any of the three payload-carrying arms) —
1844 /// extends the per-arm projection family onto the [`Self::PubSub`]
1845 /// specialization axis that the pan-arm accessor's shape blends
1846 /// into a single arm-agnostic view; the pair
1847 /// (`pubsub_subject`, `store_slot`) closes the trio
1848 /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
1849 /// payload arm now carries its own per-arm-shape post-projection
1850 /// accessor.
1851 #[must_use]
1852 pub const fn pubsub_subject(&self) -> Option<&'a str> {
1853 match *self {
1854 WitTarget::PubSub { subject } => Some(subject),
1855 WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1856 }
1857 }
1858
1859 /// Substrate-canonical per-arm key/value-store-slot scalar accessor
1860 /// every consumer that fans on the store-shaped payload keys off —
1861 /// returns the [`Self::Store`]-arm's author-declared slot template
1862 /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
1863 /// projected target is [`Self::Store { slot }`], `None` on the
1864 /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
1865 /// [`Self::Capability`], each of which carries no
1866 /// key/value-store slot by definition).
1867 ///
1868 /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
1869 /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
1870 /// every future substrate-side store-introspecting per-`(:de,
1871 /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
1872 /// namespace / prefix reconciler's per-slot projection, the future
1873 /// per-store-backend routing overlay's slot-shape gate, the future
1874 /// `feira app graph --store` per-Aplicacao slot column, any future
1875 /// substrate-lifted store-shape emitter that reads a projected
1876 /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
1877 /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
1878 /// Every future store-shape consumer reaches for the same typed
1879 /// dispatch this accessor exposes so the "which arm carries the
1880 /// slot scalar?" answer lives at one caixa-core edit rather than
1881 /// open-coded across per-consumer
1882 /// `if let WitTarget::Store { slot } = c.target()…`
1883 /// pattern-matches.
1884 ///
1885 /// Peer of the sibling [`Self::http_endpoint`] +
1886 /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
1887 /// axes and of the pre-projection [`WitContract::slot`] scalar
1888 /// accessor on the raw `:contratos :slot` field-access axis — same
1889 /// "one typed dispatch on the substrate primitive, thin projections
1890 /// at each consumer" discipline extended onto the per-arm store
1891 /// post-projection axis. Closes the pre-/post-projection pair on
1892 /// the store-slot axis to match the pairs the
1893 /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
1894 /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
1895 /// already close on the peer HTTP-endpoint and pub-sub-subject
1896 /// axes; the substrate-side pre-/post-projection accessor family
1897 /// now spans all three payload arms as a matched trio, so any
1898 /// future arm-shape widening (a `Rest`/`Grpc` split of
1899 /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
1900 /// lands one accessor without threading through the sibling
1901 /// pre-projection or the peer per-arm post-projection surfaces a
1902 /// compile-time exhaustiveness error at the substrate primitive,
1903 /// not a silent per-consumer split at renderer emit time.
1904 ///
1905 /// Sibling of the unified pan-arm [`Self::payload`]
1906 /// (`Option<&'a str>` for any of the three payload-carrying arms) —
1907 /// closes the per-arm projection family onto the [`Self::Store`]
1908 /// specialization axis that the pan-arm accessor's shape blends
1909 /// into a single arm-agnostic view. The trio
1910 /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
1911 /// pan-arm accept-set on every payload-carrying arm: exactly one
1912 /// per-arm accessor returns `Some(payload)` and the two peers
1913 /// return `None`, and every payload-less [`Self::Capability`]
1914 /// input returns `None` on all three — the partition the sibling
1915 /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
1916 /// pin locks in load-bearing.
1917 #[must_use]
1918 pub const fn store_slot(&self) -> Option<&'a str> {
1919 match *self {
1920 WitTarget::Store { slot } => Some(slot),
1921 WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
1922 }
1923 }
1924
1925 /// Render this typed target as a stable human-readable label
1926 /// (`:endpoint "/charge"`, `:subject "events.x"`,
1927 /// `:slot "checkout/$order"`, or `(capability — no payload)` when
1928 /// the WIT world is a pure capability edge).
1929 ///
1930 /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
1931 /// gate so the diagnostic names *which* identical edge was
1932 /// declared twice (not just which `(de, para, wit)` triple).
1933 /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1934 /// on the payload-carrying arms (`Some((field, payload)) →
1935 /// format!(":{field} {payload:?}")`) and through the lifted
1936 /// [`Self::CAPABILITY_LABEL`] const on the payload-less
1937 /// [`Self::Capability`] arm — so a future variant addition (the
1938 /// M4-and-later per-edge WIT registry may split [`Self::Http`]
1939 /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1940 /// `Queue`-shaped peer) becomes a single new match-arm on
1941 /// [`Self::payload_pair`] rather than a rewrite of this template
1942 /// (and every downstream consumer that reaches for the label
1943 /// shape: the per-edge policy resolver in M4, the `feira app
1944 /// graph` view, the operator's mesh-graph audit). Until this
1945 /// lift landed the three payload arms carried three near-identical
1946 /// per-arm `format!(":{} {…:?}", …)` invocations, and the
1947 /// [`Self::Capability`] arm carried the payload-less byte-string
1948 /// twice (once inline here, once in the pin test) — closing the
1949 /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
1950 /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
1951 /// / 4a1e490) peer-const lifts already established for the
1952 /// payload-carrying arms.
1953 #[must_use]
1954 pub fn label(&self) -> String {
1955 match self.payload_pair() {
1956 Some((field, payload)) => format!(":{field} {payload:?}"),
1957 None => Self::CAPABILITY_LABEL.to_string(),
1958 }
1959 }
1960
1961 /// Render this typed target as the `feira app graph` per-`:contratos`
1962 /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
1963 /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
1964 /// payload-less arm).
1965 ///
1966 /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1967 /// on the payload-carrying arms (`Some((field, payload)) →
1968 /// format!("{field}={payload}")`) and through the lifted
1969 /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
1970 /// [`Self::Capability`] arm — so a future variant addition
1971 /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
1972 /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1973 /// `Queue`-shaped peer) becomes one match-arm edit at
1974 /// [`Self::payload_pair`], propagating through this graph-verb
1975 /// projection at zero call-site cost, sibling to the peer
1976 /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
1977 /// same 4-arm dispatch.
1978 ///
1979 /// Until this lift landed the [`caixa-feira`]
1980 /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
1981 /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
1982 /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
1983 /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
1984 /// `format!("{}={endpoint}", ...)` template and hard-coding
1985 /// `"(capability-only)"` as a fifth payload-less scalar with no link
1986 /// back to the paired [`WitTarget::Capability`] variant declaration.
1987 /// A future variant addition would have had to be threaded through
1988 /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
1989 /// verb's inline match in lockstep or the two projections would
1990 /// silently disagree on the arm-set the graph verb prints — the
1991 /// duplicate-`:contratos` diagnostic reading one shape while the
1992 /// graph verb's payload column silently dropped the new arm to
1993 /// `(capability-only)`. Lifting the graph-verb projection onto the
1994 /// same substrate-primitive [`Self::payload_pair`] dispatch closes
1995 /// the axis: both projections migrate as a unit.
1996 ///
1997 /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
1998 /// quoting) shape is graph-verb-canonical — distinct from the
1999 /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2000 /// duplicate-`:contratos` diagnostic seeds (see
2001 /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2002 /// on the payload-less axis for the paired distinction).
2003 #[must_use]
2004 pub fn graph_label(&self) -> String {
2005 match self.payload_pair() {
2006 Some((field, payload)) => format!("{field}={payload}"),
2007 None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2008 }
2009 }
2010}
2011
2012/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2013/// pretty-printed byte-string every consumer that formats a typed
2014/// payload target as user-facing text lands on (the
2015/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2016/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2017/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2018/// graph` per-`:contratos`-edge payload column that reaches the graph
2019/// verb through `format!("{target}")`, the future M4 per-edge policy
2020/// resolver's per-edge audit-log line, the operator's mesh-graph
2021/// per-edge inspection view) reaches for the same lifted
2022/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2023/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2024/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2025/// routes through — extending the three-path-convergence
2026/// (`Debug` for structural inspection, `Display` for user-facing text,
2027/// per-arm typed accessor for the canonical byte-string) discipline the
2028/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2029/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2030/// onto the fourth (and only remaining) typed-shape-discriminator axis
2031/// on the caixa surface.
2032///
2033/// Pre-lift the two paths were structurally independent — every consumer
2034/// reaching for a payload byte-string past the [`WitTarget::label`]
2035/// helper had to pick between three paths ([`WitTarget::label`],
2036/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2037/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2038/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2039/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2040/// that reached for `format!("{target}")` — the canonical shape every
2041/// user-facing pretty-print site on the sibling typed-enum axes already
2042/// uses — would silently land on the `Debug` derive's structural output
2043/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2044/// than the `label()` helper's stable byte-string (`:endpoint
2045/// "/charge"` — the author-facing `:contratos` keyword form) the
2046/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2047/// already threads through. The two spellings would diverge silently in
2048/// every downstream diagnostic / graph / audit line reached through
2049/// `format!` rather than through the `label()` helper. Routing
2050/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2051/// path: every `format!("{v}")` call reaches the same
2052/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2053/// and the duplicate-`:contratos` gate already route through, so a
2054/// future variant addition (the M4-and-later per-edge WIT registry may
2055/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2056/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2057/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2058/// match — rather than fanning out through hand-rolled per-arm
2059/// [`std::fmt::Display`] arms.
2060///
2061/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2062/// is the typed view returned by [`WitContract::target`], not a
2063/// closed-set discriminator enum with a gen-platform Discriminant
2064/// registration, so the `Debug` derive's structural output (which every
2065/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2066/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2067/// shape for structural inspection; `Display` (via `label`) reveals the
2068/// stable author-facing payload projection.
2069///
2070/// Pin tests
2071/// [`tests::wit_target_display_routes_through_label_helper`] and
2072/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2073/// assert the two paths agree byte-for-byte on every variant, so a
2074/// future variant addition or `label()` reimplementation that hand-rolls
2075/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2076/// build error visible at caixa-core test time, not a silent
2077/// per-consumer dispatch miss at diagnostic / audit / graph time.
2078impl std::fmt::Display for WitTarget<'_> {
2079 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2080 f.write_str(&self.label())
2081 }
2082}
2083
2084// ── one Aplicacao member ─────────────────────────────────────────────
2085
2086/// A Servico participating in the Aplicacao. Same shape as
2087/// `crate::supervisor::ChildSpec` but without a restart policy —
2088/// supervision is per-Servico (each member has its own
2089/// `:supervisor`), the Aplicacao orchestrates *placement*.
2090#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2091#[serde(rename_all = "camelCase")]
2092pub struct Membro {
2093 /// Member caixa's `:nome`. Resolves through the same dep
2094 /// resolution path as `crate::dep::Dep`.
2095 pub caixa: String,
2096
2097 /// Semver constraint.
2098 pub versao: String,
2099}
2100
2101impl Membro {
2102 /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2103 /// accessor every consumer that reads the member's Servico identity
2104 /// keys off — returns the author-declared `:membros :caixa`
2105 /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2106 /// own [`String`] storage.
2107 ///
2108 /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2109 /// participating in the Aplicacao — validated by
2110 /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2111 /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2112 /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2113 /// [`validate_no_self_membership`]) — and every downstream consumer
2114 /// that fans on the member's identity keys off this scalar (the
2115 /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2116 /// lookup, the per-`:membros` duplicate gate's dedup key, the
2117 /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2118 /// identity, the self-membership gate, the
2119 /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2120 /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2121 /// CR materializer's per-member resolver).
2122 ///
2123 /// Prior to this lift the `.caixa` byte-string was read inline at
2124 /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2125 /// set collector at
2126 /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2127 /// [`validate_membros`] validation-side member-caixa gate at
2128 /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2129 /// per-member duplicate-gate dedup key at
2130 /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2131 /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2132 /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2133 /// [`validate_no_self_membership`] self-loop gate at
2134 /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2135 /// expressed no compile-time link back to the typed slot. Every
2136 /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2137 /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2138 /// `name:` axis, so a future extension of the `:membros :caixa`
2139 /// axis to a richer author surface — a per-cluster alias table the
2140 /// operator pins through a future `:placement`-scoped slot, a
2141 /// namespace-qualified rewrite the M4 CR materializer applies
2142 /// per-CR, a per-member overlay from the future `:membros
2143 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2144 /// acknowledges — would have had to be threaded through every
2145 /// open-coded copy in lockstep or one consumer would silently
2146 /// disagree with the peers on which caixa a given member resolves
2147 /// to. A member-set lookup that treated the name as `"cart"` while
2148 /// the peer adjacency map treated it as `"tenant-a/cart"` would
2149 /// silently split the `:contratos` membership-lookup diagnostic from
2150 /// the cycle-detector's node identity — a two-consumer split at the
2151 /// validator far from the source `caixa.lisp` with no field naming
2152 /// the identity-drift root cause. Lifting the resolution rule to a
2153 /// typed method on the substrate primitive means every downstream
2154 /// consumer of the Aplicacao's per-`:membros` identity surface
2155 /// reaches for exactly one typed dispatch — the resolver's
2156 /// accept-set migrates as a unit on any future axis addition.
2157 ///
2158 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2159 /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2160 /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2161 /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2162 /// destination-Servico scalar accessors — same "one typed dispatch
2163 /// on the substrate primitive, thin projections at each consumer"
2164 /// discipline extended onto the per-`:membros` member-caixa `:nome`
2165 /// byte-string axis. Named `nome()` to match the tatara-lisp
2166 /// author-surface term the field's docstring already reaches for
2167 /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2168 /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2169 /// already carries — the accessor's name maps directly onto the
2170 /// canonical caixa-identity vocabulary rather than shadowing the
2171 /// field's storage-side `caixa` label.
2172 #[must_use]
2173 pub fn nome(&self) -> &str {
2174 self.caixa.as_str()
2175 }
2176
2177 /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2178 /// requirement scalar accessor every consumer that reads the
2179 /// member's version pin keys off — returns the author-declared
2180 /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2181 /// from the typed slot's own [`String`] storage.
2182 ///
2183 /// The `:membros :versao` slot carries the Cargo-shaped semver
2184 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2185 /// pins which release of the member-caixa the Aplicacao composes
2186 /// against — the same requirement grammar the peer `:deps :versao`
2187 /// / `:children :versao` axes carry, resolved through the shared
2188 /// [`crate::render::require_valid_versao_requirement`] cascade and
2189 /// the shared [`crate::version::parse_requirement`] parser. Every
2190 /// downstream consumer that fans on the member's version pin keys
2191 /// off this scalar (the [`validate_membros`] per-member requirement
2192 /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2193 /// …)`, the [`feira app graph`] per-member `println!(" - {} {}",
2194 /// m.nome(), m.versao_requirement())` line, every future per-cluster
2195 /// version-lock overlay the operator pins through a future
2196 /// `:placement`-scoped slot, the future
2197 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2198 /// version resolver, the future `feira app deploy` pipeline's
2199 /// per-member lacre BLAKE3-closure lookup).
2200 ///
2201 /// Prior to this lift the `.versao` byte-string was accessed inline
2202 /// at two `&str`-shaped sites — the [`validate_membros`]
2203 /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2204 /// …)` and the `feira app graph` per-member printer's `println!(
2205 /// " - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2206 /// prior to this lift) — two open-coded field-accesses that expressed
2207 /// no compile-time link back to the typed slot. A future extension of
2208 /// the `:membros :versao` axis to a richer author surface (a
2209 /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2210 /// flow, a lacre-projected concrete-version rewrite the operator
2211 /// materializes at CR-admission time, a future `:membros :versao-lock`
2212 /// per-cluster override slot) would have had to be threaded through
2213 /// every open-coded copy in lockstep or one consumer would silently
2214 /// disagree with the peers on which release constraint a given
2215 /// member resolves to. Lifting the resolution rule to a typed method
2216 /// on the substrate primitive means every downstream requirement-
2217 /// facing consumer reaches for exactly one typed dispatch — the
2218 /// resolver's accept-set migrates as a unit on any future axis
2219 /// addition.
2220 ///
2221 /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2222 /// member-caixa `:nome` scalar accessor — the pair
2223 /// `(nome(), versao_requirement())` jointly projects the
2224 /// `(caixa, versao)` field pair every renderer that fans on
2225 /// per-member identity + version pin keys off, closing the last
2226 /// unlifted per-`:membros` scalar axis so every downstream
2227 /// per-`:membros` reader now routes through a typed dispatch on the
2228 /// substrate primitive. Named `versao_requirement()` rather than
2229 /// `versao()` because the field's storage-side `.versao` label is
2230 /// already the author-surface term (`:versao`); the accessor's name
2231 /// carries the semantic role — the semver *requirement* string the
2232 /// shared [`crate::version::parse_requirement`] entry-point consumes
2233 /// — so a raw field access and a typed dispatch read differently at
2234 /// every consumer site.
2235 ///
2236 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2237 /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2238 /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2239 /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2240 /// destination-Servico scalar accessors — same "one typed dispatch
2241 /// on the substrate primitive, thin projections at each consumer"
2242 /// discipline extended onto the per-`:membros` member-`:versao`
2243 /// semver-requirement byte-string axis.
2244 #[must_use]
2245 pub fn versao_requirement(&self) -> &str {
2246 self.versao.as_str()
2247 }
2248}
2249
2250// ── mesh-level policies ──────────────────────────────────────────────
2251
2252/// Mesh policies that apply to every `:contratos` edge unless
2253/// overridden per-edge in M4. V0 is a single global policy block.
2254#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2255#[serde(rename_all = "camelCase")]
2256pub struct MeshPolicy {
2257 /// Per-call timeout. Authored as a duration string (`"30s"`).
2258 #[serde(
2259 default,
2260 skip_serializing_if = "Option::is_none",
2261 with = "supervisor::duration_codec"
2262 )]
2263 pub timeout: Option<Duration>,
2264
2265 /// Number of retries on transient failure. None = no retries.
2266 #[serde(default, skip_serializing_if = "Option::is_none")]
2267 pub retries: Option<u32>,
2268
2269 /// Circuit breaker config. Trips after N failures within W
2270 /// duration; closes after a cooldown.
2271 #[serde(default, skip_serializing_if = "Option::is_none")]
2272 pub circuit_breaker: Option<CircuitBreaker>,
2273
2274 /// Whether mTLS is required for every contrato. Default: true
2275 /// (sandboxing-by-default; explicit opt-out only).
2276 #[serde(default, skip_serializing_if = "Option::is_none")]
2277 pub mtls_required: Option<bool>,
2278
2279 /// Token-bucket rate limit. Authored as `"100/s"` or
2280 /// `"5000/m"`; stored as `(rate, window)`.
2281 #[serde(
2282 default,
2283 skip_serializing_if = "Option::is_none",
2284 with = "rate_limit_codec"
2285 )]
2286 pub rate_limit: Option<RateLimit>,
2287}
2288
2289impl MeshPolicy {
2290 /// True when no `:politicas` axis carries a value — every field is
2291 /// `None`. The same emptiness contract every other M2/M3 typed
2292 /// surface carries ([`crate::LimitsSpec::is_empty`],
2293 /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2294 /// typed slot onto a cluster artifact key off this predicate to
2295 /// decide "emit the slot" vs "skip the slot entirely", so an
2296 /// authored-but-unset `:politicas (())` round-trips to a rendered
2297 /// artifact that's structurally identical to one that omits the
2298 /// slot. Lifted as a typed predicate (rather than per-renderer
2299 /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2300 /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2301 /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2302 /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2303 /// not a coordinated rewrite of every consumer that's reaching
2304 /// for the emptiness semantic.
2305 #[must_use]
2306 pub const fn is_empty(&self) -> bool {
2307 self.timeout().is_none()
2308 && self.retries().is_none()
2309 && self.circuit_breaker().is_none()
2310 && self.mtls_required().is_none()
2311 && self.rate_limit().is_none()
2312 }
2313
2314 /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
2315 /// per-call-deadline scalar accessor every consumer of the
2316 /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
2317 /// returns the author-declared `:politicas :timeout` typed
2318 /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
2319 /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
2320 /// is `Copy`, so the accessor returns by value; no borrow of
2321 /// `&self` past the call). `None` when the slot is absent (the
2322 /// "cluster default applies — typically the gateway class's
2323 /// implementation-side per-request wall-clock cap" arm caixa-mesh's
2324 /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
2325 /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
2326 /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
2327 /// round-trips to a rendered `HTTPRoute` structurally identical to
2328 /// one that omits the slot).
2329 ///
2330 /// The `:politicas :timeout` slot carries the "no infinite blocking"
2331 /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
2332 /// the typed slot's `Option<Duration>` accept-set (zero-floor
2333 /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
2334 /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
2335 /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
2336 /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
2337 /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
2338 /// Every downstream consumer that reads the per-call cap keys off
2339 /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2340 /// renderers key off to decide "emit :politicas overlay" vs "skip
2341 /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2342 /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
2343 /// fans the deadline into every rule via
2344 /// [`crate::render::single_field_overlay`], the future M4 per-
2345 /// Aplicacao Gateway API reconciler materialization pass, the
2346 /// future per-`:contratos`-edge timeout-override overlay the
2347 /// MESH-COMPOSITION §III.2 roadmap acknowledges).
2348 ///
2349 /// Prior to this lift the `.timeout` field was accessed inline at
2350 /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
2351 /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
2352 /// …)` call — two open-coded field-accesses that expressed no
2353 /// compile-time link back to the typed slot. A future extension of
2354 /// the `:politicas :timeout` axis to a richer author surface — a
2355 /// per-`:contratos`-edge timeout override the operator pins through
2356 /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
2357 /// roadmap acknowledges, a per-cluster timeout-default overlay the
2358 /// M4 CR materializer resolves per-CR, a split of the single
2359 /// per-call `Duration` into a richer `{request, backendRequest}`
2360 /// pair once the Gateway API's per-rule `timeouts` block grows the
2361 /// upstream-facing backendRequest arm alongside the client-facing
2362 /// request arm — would have had to be threaded through both open-
2363 /// coded copies in lockstep or the emptiness predicate and the
2364 /// caixa-mesh emit path would silently disagree on which per-call
2365 /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
2366 /// whose only axis is a `Some :timeout` would satisfy `is_empty()
2367 /// == false` while the renderer's overlay-emit path silently read
2368 /// a drifted other value, or vice versa: an author's `:timeout
2369 /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
2370 /// the emptiness predicate still classified the policy as non-
2371 /// empty, and every `kubectl -n tatara-system get httproute -o yaml
2372 /// | grep -A2 timeouts` audit would land on a route whose author's
2373 /// typed slot value silently vanished at the renderer layer).
2374 /// Lifting the resolution to a typed method on the substrate
2375 /// primitive means every downstream consumer of the Aplicacao's
2376 /// per-`:politicas` deadline surface reaches for exactly one typed
2377 /// dispatch — the resolver's accept-set migrates as a unit on any
2378 /// future axis addition.
2379 ///
2380 /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
2381 /// family (sibling of the peer per-`:politicas`
2382 /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
2383 /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
2384 /// `Option<bool>` accessor — same "one typed dispatch on the
2385 /// substrate primitive, thin projections at each consumer"
2386 /// discipline extended onto the peer per-`:politicas` typed-
2387 /// [`Duration`] optional-scalar axis; closes the "optional per-slot
2388 /// numeric-Copy-T scalar" projection pattern the sibling
2389 /// `Option<u32>` / `Option<bool>` lifts opened, since every
2390 /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
2391 /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
2392 /// than a scalar). Named `timeout()` to match the storage field's
2393 /// name; the accessor's identity maps onto the canonical MESH-
2394 /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
2395 #[must_use]
2396 pub const fn timeout(&self) -> Option<Duration> {
2397 self.timeout
2398 }
2399
2400 /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
2401 /// retry-budget scalar accessor every consumer of the Aplicacao's
2402 /// Gateway API v1.x per-rule retry-cap keys off — returns the
2403 /// author-declared `:politicas :retries` typed `u32` verbatim as an
2404 /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
2405 /// storage (`Option<u32>` is `Copy`, so the accessor returns by
2406 /// value; no borrow of `&self` past the call). `None` when the slot
2407 /// is absent (the "cluster default applies — typically 'no retries
2408 /// beyond a single dispatch attempt'" arm the caixa-mesh
2409 /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2410 /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2411 /// this predicate too, so an authored-but-unset `:politicas
2412 /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2413 /// identical to one that omits the slot).
2414 ///
2415 /// The `:politicas :retries` slot carries the "transient failure
2416 /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2417 /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2418 /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2419 /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2420 /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2421 /// count scalar the caixa-mesh `retry_overlay` builder writes.
2422 /// Every downstream consumer that reads the retry cap keys off this
2423 /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2424 /// renderers key off to decide "emit :politicas overlay" vs "skip
2425 /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2426 /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2427 /// the value into every rule via [`crate::render::single_field_overlay`],
2428 /// the future M4 per-Aplicacao Gateway API reconciler
2429 /// materialization pass, the future per-`:contratos`-edge retry-
2430 /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2431 /// acknowledges).
2432 ///
2433 /// Prior to this lift the `.retries` field was accessed inline at
2434 /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2435 /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2436 /// …)` call — two open-coded field-accesses that expressed no
2437 /// compile-time link back to the typed slot. A future extension of
2438 /// the `:politicas :retries` axis to a richer author surface — a
2439 /// per-`:contratos`-edge retry override the operator pins through a
2440 /// future `:contratos :retries` slot, a per-cluster retry-default
2441 /// overlay the M4 CR materializer resolves per-CR, a promotion of
2442 /// the plain `u32` attempt-count to a richer `{attempts, codes,
2443 /// backoff}` sub-block once the Gateway API grows the peer
2444 /// `retry.codes` / `retry.backoff` axes — would have had to be
2445 /// threaded through both open-coded copies in lockstep or the
2446 /// emptiness predicate and the caixa-mesh emit path would silently
2447 /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2448 /// (a `:politicas` block whose only axis is a `Some :retries` would
2449 /// satisfy `is_empty() == false` while the renderer's overlay-emit
2450 /// path silently read a drifted other value, or vice versa: an
2451 /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2452 /// block while the emptiness predicate still classified the policy
2453 /// as non-empty). Lifting the resolution to a typed method on the
2454 /// substrate primitive means every downstream consumer of the
2455 /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2456 /// one typed dispatch — the resolver's accept-set migrates as a
2457 /// unit on any future axis addition.
2458 ///
2459 /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2460 /// family (sibling of the peer per-`:politicas`
2461 /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2462 /// same "one typed dispatch on the substrate primitive, thin
2463 /// projections at each consumer" discipline extended onto the
2464 /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2465 /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2466 /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2467 /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2468 /// fold on). Named `retries()` to match the storage field's name;
2469 /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2470 /// §III.2 vocabulary the slot's docstring already carries.
2471 #[must_use]
2472 pub const fn retries(&self) -> Option<u32> {
2473 self.retries
2474 }
2475
2476 /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2477 /// enforcement-toggle scalar accessor every consumer of the
2478 /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2479 /// — returns the author-declared `:politicas :mtls-required` typed
2480 /// bool verbatim as an `Option<bool>`, copied out of the typed
2481 /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2482 /// the accessor returns by value; no borrow of `&self` past the
2483 /// call). `None` when the slot is absent (the "cluster default
2484 /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2485 /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2486 /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2487 /// this predicate too, so an authored-but-unset `:politicas
2488 /// (:mtls-required ())` round-trips to a rendered
2489 /// `CiliumNetworkPolicy` structurally identical to one that omits
2490 /// the slot).
2491 ///
2492 /// The `:politicas :mtls-required` slot carries the "explicit opt-
2493 /// out only, sandboxing-by-default" mTLS-enforcement toggle
2494 /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2495 /// `{None, Some(true), Some(false)}` accept-set maps onto the
2496 /// Cilium `authentication.mode` bijection through
2497 /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2498 /// handshake enforced), `Some(false) → "disabled"` (handshake
2499 /// skipped — the debug-edge opt-out), `None` → omit the block
2500 /// (cluster default applies). Every downstream consumer that
2501 /// reads the toggle keys off this scalar (the
2502 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2503 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2504 /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2505 /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2506 /// ingress rule via [`crate::render::single_field_overlay`], the
2507 /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2508 /// materialization pass, the future per-`:contratos`-edge mTLS
2509 /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2510 ///
2511 /// Prior to this lift the `.mtls_required` field was accessed
2512 /// inline at two sites — [`MeshPolicy::is_empty`]'s
2513 /// `self.mtls_required.is_none()` arm and caixa-mesh's
2514 /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2515 /// two open-coded field-accesses that expressed no compile-time
2516 /// link back to the typed slot. A future extension of the
2517 /// `:politicas :mtls-required` axis to a richer author surface —
2518 /// a per-`:contratos`-edge mTLS override the operator pins through
2519 /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2520 /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2521 /// M4 CR materializer resolves per-CR, a three-valued
2522 /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2523 /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2524 /// would have had to be threaded through both open-coded copies in
2525 /// lockstep or the emptiness predicate and the caixa-mesh emit
2526 /// path would silently disagree on which toggle a given
2527 /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2528 /// axis is a `Some`
2529 /// `:mtls-required` would satisfy `is_empty() == false` while the
2530 /// renderer's overlay-emit path silently read a drifted other
2531 /// value, or vice versa). Lifting the resolution to a typed method
2532 /// on the substrate primitive means every downstream consumer of
2533 /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2534 /// for exactly one typed dispatch — the resolver's accept-set
2535 /// migrates as a unit on any future axis addition.
2536 ///
2537 /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2538 /// family (peer of the sibling per-`:placement`
2539 /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2540 /// same "one typed dispatch on the substrate primitive, thin
2541 /// projections at each consumer" discipline extended onto the
2542 /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2543 /// the "optional per-slot Copy-T scalar" projection pattern the
2544 /// sibling per-`:politicas` `:retries` (Option<u32>) /
2545 /// `:timeout` (Option<Duration>) future lifts fold on). Named
2546 /// `mtls_required()` to match the storage field's name; the
2547 /// accessor's identity maps onto the canonical MESH-COMPOSITION
2548 /// §III.2 vocabulary the slot's docstring already carries.
2549 #[must_use]
2550 pub const fn mtls_required(&self) -> Option<bool> {
2551 self.mtls_required
2552 }
2553
2554 /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2555 /// `local_rate_limit`-mesh token-bucket-declaration scalar
2556 /// accessor every consumer of the Aplicacao's per-`:politicas`
2557 /// per-`(rate, window)` rate-limit surface keys off — returns the
2558 /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2559 /// verbatim as an `Option<RateLimit>`, copied out of the typed
2560 /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2561 /// `Copy`, so the accessor returns by value; no borrow of `&self`
2562 /// past the call). `None` when the slot is absent (the "cluster
2563 /// default applies — typically 'no per-Aplicacao rate declaration,
2564 /// gateway-class per-listener default applies'" arm the future
2565 /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2566 /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2567 /// `rate_limit().is_none()` arm reads this predicate too, so an
2568 /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2569 /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2570 /// identical to one that omits the slot).
2571 ///
2572 /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2573 /// token-bucket rate declaration" contract (MESH-COMPOSITION
2574 /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2575 /// (rate lower-bounded by 1 through
2576 /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2577 /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2578 /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2579 /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2580 /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2581 /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2582 /// `:politicas` overlay emits. Every downstream consumer that
2583 /// reads the rate declaration keys off this scalar (the
2584 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2585 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2586 /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2587 /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2588 /// `rl.window` against [`is_canonical_rate_limit_window`], the
2589 /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2590 /// the future per-`:contratos`-edge rate-limit override the
2591 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2592 ///
2593 /// Prior to this lift the `.rate_limit` field was accessed inline
2594 /// at two sites — [`MeshPolicy::is_empty`]'s
2595 /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2596 /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2597 /// field-accesses that expressed no compile-time link back to the
2598 /// typed slot. A future extension of the `:politicas :rate-limit`
2599 /// axis to a richer author surface — a per-`:contratos`-edge
2600 /// rate-limit override the operator pins through a future
2601 /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2602 /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2603 /// the M4 CR materializer resolves per-CR, a promotion of the
2604 /// plain `(rate, window)` scalar pair to a richer
2605 /// `{rate, window, burst, key}` sub-block once Envoy's
2606 /// `local_rate_limit` grows the peer `burst_size` /
2607 /// `descriptor_key` axes — would have had to be threaded through
2608 /// both open-coded copies in lockstep or the emptiness predicate
2609 /// and the validate gate would silently disagree on which rate
2610 /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2611 /// block whose only axis is a `Some :rate-limit` would satisfy
2612 /// `is_empty() == false` while the validate path silently read a
2613 /// drifted other value, or vice versa: an author's
2614 /// `:rate-limit "100/s"` would omit the value-shape gate while the
2615 /// emptiness predicate still classified the policy as non-empty).
2616 /// Lifting the resolution to a typed method on the substrate
2617 /// primitive means every downstream consumer of the Aplicacao's
2618 /// per-`:politicas` rate-limit surface reaches for exactly one
2619 /// typed dispatch — the resolver's accept-set migrates as a unit
2620 /// on any future axis addition.
2621 ///
2622 /// First `Option<Copy-composite-T>`-return accessor on the M3
2623 /// mesh-slot family — closes the last un-lifted per-`:politicas`
2624 /// scalar-value axis. Peer of the sibling per-`:politicas`
2625 /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2626 /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2627 /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2628 /// "one typed dispatch on the substrate primitive, thin
2629 /// projections at each consumer" discipline extended onto the
2630 /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2631 /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2632 /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2633 /// sub-accessors rather than a top-level accessor because
2634 /// consumers reach for the axes not the aggregate). Named
2635 /// `rate_limit()` to match the storage field's name; the
2636 /// accessor's identity maps onto the canonical MESH-COMPOSITION
2637 /// §III.2 vocabulary the slot's docstring already carries.
2638 #[must_use]
2639 pub const fn rate_limit(&self) -> Option<RateLimit> {
2640 self.rate_limit
2641 }
2642
2643 /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2644 /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2645 /// declaration scalar accessor every consumer of the Aplicacao's
2646 /// per-`:politicas` breaker declaration keys off — returns the
2647 /// author-declared `:politicas :circuit-breaker` typed
2648 /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2649 /// copied out of the typed slot's own `Option<CircuitBreaker>`
2650 /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2651 /// by value; no borrow of `&self` past the call). `None` when the
2652 /// slot is absent (the "cluster default applies — typically 'no
2653 /// per-Aplicacao breaker declaration, gateway-class per-listener
2654 /// default applies'" arm the future caixa-mesh
2655 /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2656 /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2657 /// arm reads this predicate too, so an authored-but-unset
2658 /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2659 /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2660 /// that omits the slot).
2661 ///
2662 /// The `:politicas :circuit-breaker` slot carries the
2663 /// "per-Aplicacao consecutive-transient-failure trip declaration"
2664 /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2665 /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2666 /// zero-floor rejected through
2667 /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2668 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2669 /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2670 /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2671 /// canonical-form pinned through
2672 /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2673 /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2674 /// bijection the future `CiliumClusterwideEnvoyConfig`
2675 /// per-`:politicas` overlay emits. Every downstream consumer that
2676 /// reads the breaker declaration keys off this scalar (the
2677 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2678 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2679 /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2680 /// that brackets `cb.max_failures()` against
2681 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2682 /// [`POLICY_BREAKER_WINDOW_MAX`] via
2683 /// [`crate::render::require_positive_canonical_bounded_duration`],
2684 /// the future M4 per-Aplicacao Envoy reconciler materialization
2685 /// pass, the future per-`:contratos`-edge breaker override the
2686 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2687 ///
2688 /// Prior to this lift the `.circuit_breaker` field was accessed
2689 /// inline at two sites — [`MeshPolicy::is_empty`]'s
2690 /// `self.circuit_breaker.is_none()` arm and the
2691 /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2692 /// bind — two open-coded field-accesses that expressed no
2693 /// compile-time link back to the typed slot. A future extension of
2694 /// the `:politicas :circuit-breaker` axis to a richer author
2695 /// surface — a per-`:contratos`-edge breaker override the operator
2696 /// pins through a future `:contratos :circuit-breaker` slot the
2697 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2698 /// breaker-default overlay the M4 CR materializer resolves per-CR,
2699 /// a promotion of the plain `(max_failures, window)` scalar pair to
2700 /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2701 /// sub-block once Envoy's `outlier_detection` grows the peer
2702 /// ejection-percentage / ejection-time axes — would have had to be
2703 /// threaded through both open-coded copies in lockstep or the
2704 /// emptiness predicate and the validate gate would silently
2705 /// disagree on which breaker declaration a given [`MeshPolicy`]
2706 /// resolves to (a `:politicas` block whose only axis is a
2707 /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2708 /// the validate path silently read a drifted other value, or vice
2709 /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2710 /// "60s"))` would omit the value-shape gate while the emptiness
2711 /// predicate still classified the policy as non-empty). Lifting
2712 /// the resolution to a typed method on the substrate primitive
2713 /// means every downstream consumer of the Aplicacao's
2714 /// per-`:politicas` breaker surface reaches for exactly one typed
2715 /// dispatch — the resolver's accept-set migrates as a unit on any
2716 /// future axis addition.
2717 ///
2718 /// Second `Option<Copy-composite-T>`-return accessor on the M3
2719 /// mesh-slot family (sibling of the peer per-`:politicas`
2720 /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2721 /// on the same composite-Copy shape, and of the sibling per-
2722 /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2723 /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2724 /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2725 /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2726 /// same "one typed dispatch on the substrate primitive, thin
2727 /// projections at each consumer" discipline extended onto the last
2728 /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2729 /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2730 /// match the storage field's name; the accessor's identity maps
2731 /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2732 /// docstring already carries. Closes the last unlifted
2733 /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2734 /// reader now routes through a typed dispatch on the substrate
2735 /// primitive.
2736 #[must_use]
2737 pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2738 self.circuit_breaker
2739 }
2740}
2741
2742#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2743#[serde(rename_all = "camelCase")]
2744pub struct CircuitBreaker {
2745 pub max_failures: u32,
2746 #[serde(with = "supervisor::duration_codec_required")]
2747 pub window: Duration,
2748}
2749
2750impl CircuitBreaker {
2751 /// Substrate-canonical per-`:politicas :circuit-breaker`
2752 /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2753 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2754 /// breaker trip-count keys off — returns the author-declared
2755 /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2756 /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2757 /// so the accessor returns by value; no borrow of `&self` past the
2758 /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2759 /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2760 /// axis; a `CircuitBreaker` past pattern-match is definitionally
2761 /// present, and its `:max-failures` field carries the trip count as a
2762 /// required-axis scalar).
2763 ///
2764 /// The `:politicas :circuit-breaker :max-failures` axis carries the
2765 /// "consecutive-transient-failure trip threshold" contract
2766 /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2767 /// (zero-floor rejected through
2768 /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2769 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2770 /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2771 /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2772 /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2773 /// Every downstream consumer that reads the trip threshold keys off
2774 /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2775 /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2776 /// canonical `require_positive_bounded_u32` helper, the future M4
2777 /// per-Aplicacao Envoy config reconciler materialization pass, the
2778 /// future per-`:contratos`-edge breaker-override overlay the
2779 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2780 ///
2781 /// Prior to this lift the `.max_failures` field was accessed inline
2782 /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2783 /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2784 /// open-coded field-access that expressed no compile-time link back
2785 /// to the typed sub-struct axis. A future extension of the
2786 /// `:max-failures` axis to a richer author surface — a
2787 /// per-`:contratos`-edge breaker override the operator pins through a
2788 /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2789 /// #3 roadmap acknowledges, a per-cluster max-failures-default
2790 /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2791 /// plain `u32` trip count to a richer
2792 /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2793 /// tuple once Envoy's `outlier_detection` block's peer axes come into
2794 /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2795 /// count arms — would have had to be threaded through every open-
2796 /// coded copy in lockstep or the validate gate and the future M4
2797 /// emit path would silently disagree on which trip threshold a given
2798 /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2799 /// would satisfy validate while the emit path silently read a drifted
2800 /// other value, or vice versa: a validated typed slot would land at
2801 /// the emit boundary as a no-op breaker whose trip threshold is
2802 /// structurally never reached). Lifting the resolution to a typed
2803 /// method on the substrate primitive means every downstream consumer
2804 /// of the Aplicacao's per-`:politicas :circuit-breaker`
2805 /// trip-threshold surface reaches for exactly one typed dispatch —
2806 /// the resolver's accept-set migrates as a unit on any future axis
2807 /// addition.
2808 ///
2809 /// First sub-struct scalar accessor on the M3 mesh-slot family
2810 /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2811 /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2812 /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2813 /// closes the last unlifted per-`:politicas` scalar-value axis after
2814 /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
2815 /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
2816 /// Same "one typed dispatch on the substrate primitive, thin
2817 /// projections at each consumer" discipline the peer
2818 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2819 /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2820 /// [`Membro::versao_requirement`] (a40b0e3),
2821 /// [`Entrada::destination`] (6db982c) accessors carry on their
2822 /// respective per-mesh-slot-atom scalar-value axes, extended onto the
2823 /// per-sub-struct required-`u32` axis. Named `max_failures()` to
2824 /// match the storage field's name; the accessor's identity maps onto
2825 /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2826 /// docstring already carries.
2827 #[must_use]
2828 pub const fn max_failures(&self) -> u32 {
2829 self.max_failures
2830 }
2831
2832 /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
2833 /// Envoy-outlier-detection rolling-observation-interval scalar
2834 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2835 /// breaker rolling-window duration keys off — returns the
2836 /// author-declared `:politicas :circuit-breaker :window` typed
2837 /// `Duration` verbatim, copied out of the typed slot's own
2838 /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
2839 /// by value; no borrow of `&self` past the call). Non-optional (the
2840 /// surrounding `Option<CircuitBreaker>` is the "slot present?"
2841 /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
2842 /// `CircuitBreaker` past pattern-match is definitionally present,
2843 /// and its `:window` field carries the rolling-observation interval
2844 /// as a required-axis scalar).
2845 ///
2846 /// The `:politicas :circuit-breaker :window` axis carries the
2847 /// "consecutive-transient-failure rolling-observation interval"
2848 /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2849 /// `Duration` accept-set (zero-floor rejected through
2850 /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
2851 /// residue rejected through
2852 /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
2853 /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
2854 /// Envoy `outlier_detection.interval` per-cluster
2855 /// ejection-observation-interval scalar (equivalently the future
2856 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2857 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2858 /// consumer that reads the rolling-observation interval keys off
2859 /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2860 /// integer-millisecond canonical-form + cap bracket at
2861 /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
2862 /// [`crate::render::require_positive_canonical_bounded_duration`]
2863 /// helper, the future M4 per-Aplicacao Envoy config reconciler
2864 /// materialization pass, the future per-`:contratos`-edge
2865 /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2866 /// acknowledges).
2867 ///
2868 /// Prior to this lift the `.window` field was accessed inline at
2869 /// one production site — [`AplicacaoSpec::validate_politicas`]'s
2870 /// `require_positive_canonical_bounded_duration(cb.window, …)`
2871 /// call — one open-coded field-access that expressed no compile-
2872 /// time link back to the typed sub-struct axis. A future extension
2873 /// of the `:window` axis to a richer author surface — a
2874 /// per-`:contratos`-edge window override the operator pins through
2875 /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
2876 /// #3 roadmap acknowledges, a per-cluster window-default overlay
2877 /// the M4 CR materializer resolves per-CR, a promotion of the plain
2878 /// `Duration` observation interval to a richer
2879 /// `{interval, base_ejection_time, max_ejection_percent}` tuple
2880 /// once Envoy's `outlier_detection` block's peer axes come into
2881 /// scope, a per-Envoy-cluster minimum-request-volume gate before
2882 /// the window arms — would have had to be threaded through every
2883 /// open-coded copy in lockstep or the validate gate and the future
2884 /// M4 emit path would silently disagree on which observation
2885 /// interval a given [`CircuitBreaker`] resolves to (an author's
2886 /// `:window "60s"` would satisfy validate while the emit path
2887 /// silently read a drifted other value, or vice versa: a validated
2888 /// typed slot would land at the emit boundary as a breaker whose
2889 /// observation window is structurally so wide that no realistic
2890 /// failure-rate shape can trip it). Lifting the resolution to a
2891 /// typed method on the substrate primitive means every downstream
2892 /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
2893 /// observation-window surface reaches for exactly one typed
2894 /// dispatch — the resolver's accept-set migrates as a unit on any
2895 /// future axis addition.
2896 ///
2897 /// Second sub-struct scalar accessor on the M3 mesh-slot family —
2898 /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
2899 /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
2900 /// required-axis, extended onto the per-sub-struct required-`Duration`
2901 /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
2902 /// axis. Same "one typed dispatch on the substrate primitive, thin
2903 /// projections at each consumer" discipline the peer
2904 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2905 /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2906 /// [`Membro::versao_requirement`] (a40b0e3),
2907 /// [`Entrada::destination`] (6db982c) accessors carry on their
2908 /// respective per-mesh-slot-atom scalar-value axes, extended onto
2909 /// the per-sub-struct required-`Duration` axis. Named `window()` to
2910 /// match the storage field's name; the accessor's identity maps onto
2911 /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2912 /// docstring already carries.
2913 #[must_use]
2914 pub const fn window(&self) -> Duration {
2915 self.window
2916 }
2917}
2918
2919#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2920pub struct RateLimit {
2921 /// Requests per window.
2922 pub rate: u32,
2923 /// Window duration.
2924 pub window: Duration,
2925}
2926
2927impl RateLimit {
2928 /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
2929 /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
2930 /// every consumer of the Aplicacao's per-`:contratos`-edge
2931 /// rate-limit-bucket capacity keys off — returns the author-declared
2932 /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
2933 /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
2934 /// returns by value; no borrow of `&self` past the call). Non-optional
2935 /// (the surrounding `Option<RateLimit>` is the "slot present?"
2936 /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
2937 /// `RateLimit` past pattern-match is definitionally present, and its
2938 /// `:rate` field carries the token-bucket capacity as a required-axis
2939 /// scalar).
2940 ///
2941 /// The `:politicas :rate-limit` `:rate` axis carries the
2942 /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
2943 /// the typed slot's `u32` accept-set (zero-floor rejected through
2944 /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
2945 /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
2946 /// `local_rate_limit.token_bucket.max_tokens` per-cluster
2947 /// token-bucket-capacity scalar (equivalently the future
2948 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2949 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2950 /// consumer that reads the token-bucket capacity keys off this
2951 /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2952 /// cap bracket that gates on the canonical
2953 /// [`crate::render::require_positive_bounded_u32`] helper, the
2954 /// [`rate_limit_codec::render`] `Duration → unit` projection that
2955 /// emits the `<n>/<s|m|h>` author surface, the future M4
2956 /// per-Aplicacao Envoy config reconciler materialization pass, the
2957 /// future per-`:contratos`-edge rate-limit-override overlay the
2958 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2959 ///
2960 /// Prior to this lift the `.rate` field was accessed inline at three
2961 /// production sites — [`AplicacaoSpec::validate_politicas`]'s
2962 /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
2963 /// [`rate_limit_codec::render`] format-arm arms (canonical-window
2964 /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
2965 /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
2966 /// field-accesses that expressed no compile-time link back to the
2967 /// typed sub-struct axis. A future extension of the `:rate` axis
2968 /// to a richer author surface — a per-`:contratos`-edge rate
2969 /// override the operator pins through a future `:contratos :rate`
2970 /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
2971 /// per-cluster rate-default overlay the M4 CR materializer resolves
2972 /// per-CR, a promotion of the plain `u32` token capacity to a
2973 /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
2974 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2975 /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
2976 /// before the token arms — would have had to be threaded through
2977 /// every open-coded copy in lockstep or the validate gate, the
2978 /// codec's render path, and the future M4 emit path would silently
2979 /// disagree on which token capacity a given [`RateLimit`] resolves
2980 /// to (an author's `:rate-limit "100/s"` would satisfy validate
2981 /// while the render / emit paths silently read a drifted other
2982 /// value, or vice versa: a validated typed slot would land at the
2983 /// emit boundary as a no-op limiter whose token capacity is
2984 /// structurally so high that no realistic per-edge traffic shape
2985 /// can drain it). Lifting the resolution to a typed method on the
2986 /// substrate primitive means every downstream consumer of the
2987 /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
2988 /// reaches for exactly one typed dispatch — the resolver's
2989 /// accept-set migrates as a unit on any future axis addition.
2990 ///
2991 /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
2992 /// in shape to the peer per-`CircuitBreaker`
2993 /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
2994 /// on the peer per-sub-struct required-axis, extended onto the
2995 /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
2996 /// required-axis scalar" projection pattern the sibling
2997 /// [`RateLimit::window`] future lift folds on. Same "one typed
2998 /// dispatch on the substrate primitive, thin projections at each
2999 /// consumer" discipline the peer [`WitContract::source`] /
3000 /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3001 /// (0804823), [`Membro::nome`] (4a32abf),
3002 /// [`Membro::versao_requirement`] (a40b0e3),
3003 /// [`Entrada::destination`] (6db982c),
3004 /// [`CircuitBreaker::max_failures`] (3a74062),
3005 /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3006 /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3007 /// to match the storage field's name; the accessor's identity maps
3008 /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3009 /// docstring already carries.
3010 #[must_use]
3011 pub const fn rate(&self) -> u32 {
3012 self.rate
3013 }
3014
3015 /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3016 /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3017 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3018 /// rate-limit-bucket refill period keys off — returns the
3019 /// author-declared `:politicas :rate-limit` typed `Duration`
3020 /// verbatim, copied out of the typed slot's own `Duration` storage
3021 /// (`Duration` is `Copy`, so the accessor returns by value; no
3022 /// borrow of `&self` past the call). Non-optional (the surrounding
3023 /// `Option<RateLimit>` is the "slot present?" projection at the
3024 /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3025 /// pattern-match is definitionally present, and its `:window`
3026 /// field carries the token-bucket refill period as a required-axis
3027 /// scalar).
3028 ///
3029 /// The `:politicas :rate-limit` `:window` axis carries the
3030 /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3031 /// — the typed slot's `Duration` accept-set (constrained to the
3032 /// three canonical windows `{1s, 60s, 3600s}` the
3033 /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3034 /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3035 /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3036 /// per-cluster token-bucket-refill-period scalar (equivalently the
3037 /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3038 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3039 /// consumer that reads the token-bucket refill period keys off
3040 /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3041 /// canonical-window gate that keys off
3042 /// [`is_canonical_rate_limit_window`], the
3043 /// [`rate_limit_codec::render`] `Duration → unit` projection that
3044 /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3045 /// [`rate_limit_window_unit`] and non-canonical fallback via
3046 /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3047 /// reconciler materialization pass, the future per-`:contratos`-
3048 /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3049 /// roadmap acknowledges).
3050 ///
3051 /// Prior to this lift the `.window` field was accessed inline at
3052 /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3053 /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3054 /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3055 /// error-payload construction on refusal, and the two
3056 /// [`rate_limit_codec::render`] arms
3057 /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3058 /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3059 /// open-coded field-accesses that expressed no compile-time link
3060 /// back to the typed sub-struct axis. A future extension of the
3061 /// `:window` axis to a richer author surface — a per-`:contratos`-
3062 /// edge window override the operator pins through a future
3063 /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3064 /// acknowledges, a per-cluster window-default overlay the M4 CR
3065 /// materializer resolves per-CR, a promotion of the plain
3066 /// `Duration` refill period to a richer
3067 /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3068 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3069 /// axis comes into scope, an addition of a `"d"` day suffix once
3070 /// Envoy's `rate_limit_action` grows daily-bucket support — would
3071 /// have had to be threaded through every open-coded copy in
3072 /// lockstep or the validate gate, the codec's render path, and
3073 /// the future M4 emit path would silently disagree on which
3074 /// refill period a given [`RateLimit`] resolves to (an author's
3075 /// `:rate-limit "100/s"` would satisfy validate while the render
3076 /// / emit paths silently read a drifted other value, or vice
3077 /// versa: a validated typed slot would land at the emit boundary
3078 /// as a limiter whose refill period is structurally so long that
3079 /// no realistic per-edge traffic shape stays inside the token
3080 /// budget). Lifting the resolution to a typed method on the
3081 /// substrate primitive means every downstream consumer of the
3082 /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3083 /// reaches for exactly one typed dispatch — the resolver's
3084 /// accept-set migrates as a unit on any future axis addition.
3085 ///
3086 /// Second sub-struct scalar accessor on the `RateLimit` axis —
3087 /// sibling in shape to the just-landed [`RateLimit::rate`]
3088 /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
3089 /// required-axis, extended onto the per-sub-struct
3090 /// required-`Duration` axis; closes the last unlifted
3091 /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
3092 /// per-sub-struct accessor coverage is now complete across both
3093 /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
3094 /// the substrate primitive, thin projections at each consumer"
3095 /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
3096 /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
3097 /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
3098 /// (7f0fd43), [`WitContract::world_ref`] (0804823),
3099 /// [`Membro::nome`] (4a32abf),
3100 /// [`Membro::versao_requirement`] (a40b0e3),
3101 /// [`Entrada::destination`] (6db982c) accessors carry on their
3102 /// respective per-mesh-slot-atom scalar-value axes. Named
3103 /// `window()` to match the storage field's name; the accessor's
3104 /// identity maps onto the canonical MESH-COMPOSITION §III.2
3105 /// vocabulary the slot's docstring already carries.
3106 #[must_use]
3107 pub const fn window(&self) -> Duration {
3108 self.window
3109 }
3110
3111 /// Recognize this rate-limit's `:window` as a canonical
3112 /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
3113 /// exactly matches one of the three closed-set arm-Durations
3114 /// (`1s` / `60s` / `3600s`), `None` when the window carries a
3115 /// non-canonical magnitude the codec's round-trip would break on
3116 /// (sub-second residue, or a second-magnitude outside the set
3117 /// [`RateLimitUnit::ALL`] enumerates).
3118 ///
3119 /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
3120 /// returns `Some` here — the validate gate's
3121 /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
3122 /// rejects every window this accessor returns `None` on. Downstream
3123 /// consumers past validate (the codec's [`rate_limit_codec::render`]
3124 /// path, the future M4 per-Aplicacao Envoy config reconciler's
3125 /// materialization pass, the future per-`:contratos`-edge rate-limit-
3126 /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3127 /// acknowledges) that read the typed unit off a validated slot can
3128 /// pattern-match on the returned `Some` without re-checking
3129 /// canonicality at the consumer layer — the typed enum surface is
3130 /// the load-bearing carrier of the canonicality invariant.
3131 ///
3132 /// Preferred over the free [`is_canonical_rate_limit_window`]
3133 /// module-private helper at any call site that has the typed
3134 /// [`RateLimit`] in hand (the codec's `render` arm at
3135 /// [`rate_limit_codec::render`], the validate gate's canonical-form
3136 /// arm in [`AplicacaoSpec::validate_politicas`], any future
3137 /// per-`:contratos` edge-override overlay resolver): those consumers
3138 /// reach for the typed enum without going through the
3139 /// `.window()` scalar-projection layer, and get the enum value
3140 /// directly (which the codec's render arm can then format via
3141 /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
3142 /// "typed sub-struct scalar accessor, one dispatch on the substrate
3143 /// primitive" discipline the sibling [`RateLimit::rate`] and
3144 /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
3145 /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
3146 /// projection axis (the third scalar accessor on the [`RateLimit`]
3147 /// axis, first typed-enum-return projection).
3148 ///
3149 /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
3150 /// the canonical [`RateLimitUnit`] arm now carries the same
3151 /// `const`-eval-surface posture the sibling `pub const fn`
3152 /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
3153 /// this typed sub-struct already carry, composing through the
3154 /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
3155 /// reverse-resolver in `const` context. Any downstream substrate-
3156 /// side `const`-context consumer of the typed unit (a module-scope
3157 /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
3158 /// invariant pin on a typed fixture, a future M4 admission-webhook
3159 /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
3160 /// resolver over a typed [`RateLimit`], any future `const fn`
3161 /// per-`:contratos`-edge rate-limit-override overlay resolver over
3162 /// the substrate primitive) now reaches the same typed dispatch on
3163 /// the substrate primitive at const-eval time as at runtime.
3164 ///
3165 /// Pinned load-bearing at the substrate-primitive level by
3166 /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
3167 /// eval-surface pin via `const fn` wrapper).
3168 #[must_use]
3169 pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
3170 RateLimitUnit::from_window(self.window)
3171 }
3172}
3173
3174/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
3175/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
3176/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
3177///
3178/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
3179/// the `:politicas :rate-limit` unit surface reads from
3180/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
3181/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
3182/// [`is_canonical_rate_limit_window`] predicate the
3183/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
3184/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
3185/// projection) now lives inside this typed enum's `match self` arms — a
3186/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
3187/// `rate_limit_action` grows daily-bucket support) is one new variant
3188/// plus the exhaustiveness arms on the four methods, so every consumer
3189/// picks it up by compile-time construction rather than a runtime
3190/// table-scan miss.
3191///
3192/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
3193/// scanned via `find_map` at every projection call — an untyped runtime
3194/// walk that carried no compile-time link between the parse arm's
3195/// accepted suffixes, the render arm's emitted suffixes, and the
3196/// validate gate's accepted windows. A future rate-limit-unit addition
3197/// that landed one row without threading through the other consumers
3198/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3199/// silently split the accepted-set across the three consumers — the
3200/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3201/// for a 24h window that parse can't round-trip, the validate gate
3202/// misses one canonical window. Lifting the pairs onto a typed
3203/// closed-set enum with exhaustive `match` arms makes any such
3204/// half-landed extension a caixa-core build error (the compiler enforces
3205/// arm coverage on every method), not a silent per-consumer drift
3206/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3207/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3208/// [`crate::supervisor::RestartStrategy`],
3209/// [`crate::supervisor::RestartPolicy`],
3210/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3211/// closed-set typed enums carry on their respective closed-set axes —
3212/// extended onto the seventh closed-set typed-enum discriminator axis
3213/// on the caixa typed surface (the `:politicas :rate-limit :window`
3214/// canonical-unit axis).
3215#[derive(
3216 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3217)]
3218pub enum RateLimitUnit {
3219 /// 1-second window — canonical author-surface suffix `"s"`
3220 /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3221 /// with a 1s magnitude.
3222 Second,
3223 /// 1-minute window — canonical author-surface suffix `"m"`
3224 /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3225 /// with a 60s magnitude.
3226 Minute,
3227 /// 1-hour window — canonical author-surface suffix `"h"`
3228 /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3229 /// with a 3600s magnitude.
3230 Hour,
3231}
3232
3233impl RateLimitUnit {
3234 /// Exhaustive iteration surface for every consumer that reads the
3235 /// full canonical-unit set (the byte-parity witness against the
3236 /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3237 /// webhook's accepted-suffix listing in its rejection body, any
3238 /// future round-trip fuzz harness). A future variant addition to
3239 /// [`RateLimitUnit`] extends this slice as a single edit and every
3240 /// consumer picks up the new entry by construction — the compiler-
3241 /// checked exhaustiveness on the sibling method `match` arms is the
3242 /// build-time guarantee that no arm forgets to grow.
3243 pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3244
3245 /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3246 /// string every `<n>/<unit>` rate-limit shape carries after its
3247 /// `/` separator. The single source of truth the codec's parse and
3248 /// render arms both dispatch on: the parse arm matches an incoming
3249 /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3250 /// output; the render arm emits the entry's `as_suffix` verbatim
3251 /// after the rate magnitude.
3252 #[must_use]
3253 pub const fn as_suffix(self) -> &'static str {
3254 match self {
3255 Self::Second => "s",
3256 Self::Minute => "m",
3257 Self::Hour => "h",
3258 }
3259 }
3260
3261 /// Canonical `Duration` for this unit — the token-bucket refill
3262 /// period the [`RateLimit::window`] axis carries when the surrounding
3263 /// slot's `:rate-limit` author surface named this unit.
3264 #[must_use]
3265 pub const fn window(self) -> Duration {
3266 Duration::from_secs(match self {
3267 Self::Second => 1,
3268 Self::Minute => 60,
3269 Self::Hour => 3_600,
3270 })
3271 }
3272
3273 /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3274 /// `None` when `suffix` is outside the closed-set arm-string set
3275 /// [`Self::as_suffix`] emits. The single `str → Self` projection
3276 /// [`rate_limit_codec::parse`] consumes.
3277 #[must_use]
3278 pub fn from_suffix(suffix: &str) -> Option<Self> {
3279 Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3280 }
3281
3282 /// Recognize a canonical rate-limit `Duration` as one of the three
3283 /// arms, or `None` when `window` carries sub-second residue or a
3284 /// second-magnitude outside the closed-set arm-window set
3285 /// [`Self::window`] emits. The single `Duration → Self` projection
3286 /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3287 /// both consume.
3288 ///
3289 /// `pub const fn` — the reverse `Duration → Self` projection now
3290 /// carries the same `const`-eval-surface posture the sibling
3291 /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
3292 /// projection accessors on this closed-set typed enum already
3293 /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
3294 /// typed-`RateLimit`-projection sibling composes through in `const`
3295 /// context. Routes byte-for-byte through the peer `pub const fn`
3296 /// [`Self::window`] canonical-`Duration` projection so any future
3297 /// arm-magnitude edit on the sibling accessor reaches this reverse
3298 /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
3299 /// per-arm probes each dispatch through one `pub const fn` on the
3300 /// substrate primitive rather than a hand-authored per-arm second-
3301 /// magnitude literal that would silently drift on any future
3302 /// [`Self::window`] arm-magnitude edit.
3303 ///
3304 /// Prior to the `const` lift the body dispatched through
3305 /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
3306 /// iterator-driven linear scan whose iterator methods
3307 /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
3308 /// `PartialEq` dispatch each carry non-`const` bounds on stable
3309 /// Rust 1.94, so any downstream substrate-side `const`-context
3310 /// consumer of the reverse resolver (a module-scope
3311 /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
3312 /// invariant pin on a typed fixture, a future M4
3313 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
3314 /// webhook `const fn` per-`:politicas` canonical-window floor over a
3315 /// typed [`RateLimit`] scalar, any future `const fn`
3316 /// per-`:contratos`-edge rate-limit-override overlay resolver over
3317 /// the substrate primitive that wants to fan on the canonical unit
3318 /// at compile time) surfaced as a downstream E0015 far from the
3319 /// resolver's own declaration. The `pub const fn` posture closes
3320 /// the drift structurally at caixa-core build time.
3321 ///
3322 /// Pinned load-bearing at the substrate-primitive level by
3323 /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
3324 /// eval-surface pin via `const fn` wrapper) and
3325 /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
3326 /// (composition-witness pin against the peer `Self::window` scalar
3327 /// dispatch).
3328 #[must_use]
3329 pub const fn from_window(window: Duration) -> Option<Self> {
3330 if window.subsec_nanos() != 0 {
3331 return None;
3332 }
3333 // Route through the peer `pub const fn` [`Self::window`]
3334 // canonical-`Duration` projection so any future arm-magnitude
3335 // edit on the sibling accessor reaches this reverse resolver by
3336 // construction — the per-arm `secs` comparison keys off
3337 // `Duration::as_secs` (`pub const fn`), not a hand-authored
3338 // per-arm second-magnitude literal that would silently drift.
3339 let secs = window.as_secs();
3340 if secs == Self::Second.window().as_secs() {
3341 Some(Self::Second)
3342 } else if secs == Self::Minute.window().as_secs() {
3343 Some(Self::Minute)
3344 } else if secs == Self::Hour.window().as_secs() {
3345 Some(Self::Hour)
3346 } else {
3347 None
3348 }
3349 }
3350
3351 /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3352 /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3353 /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3354 /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3355 /// consumes.
3356 ///
3357 /// The peer `Duration → &'static str` axis folded onto the substrate
3358 /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3359 /// production consumers ([`rate_limit_codec::render`] and
3360 /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3361 /// migrated (61421a6): the free helper's `Duration → &str` projection
3362 /// is now the two-step composition
3363 /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3364 /// reads through the typed accessor. This lift closes the peer
3365 /// `&str → Duration` axis by folding the vestigial module-private
3366 /// `rate_limit_window_from_unit` delegate onto this associated method
3367 /// — the codec's parse arm and every future wire-side consumer of the
3368 /// `&str → Duration` projection (a future admission-webhook that
3369 /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3370 /// before it's promoted to a validated typed slot, a future
3371 /// `feira lint` shape-probe that reads the author-surface bytes
3372 /// verbatim) now reach for exactly one typed dispatch on the
3373 /// substrate primitive.
3374 ///
3375 /// Same "closed-set typed-enum discriminator with canonical
3376 /// projections per axis" discipline the sibling [`Self::as_suffix`]
3377 /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3378 /// methods carry — this associated method closes the fifth (and last
3379 /// unlifted) projection axis on the arm-table, so the closed-set enum
3380 /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3381 /// consumer of the `:politicas :rate-limit :window` axis reaches
3382 /// through. A future rate-limit-unit addition (a `"d"` day suffix
3383 /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3384 /// `"ms"` sub-second window once high-throughput per-edge policies
3385 /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3386 /// variant plus one arm per method — the compiler enforces
3387 /// exhaustiveness on every consumer's `match self` arms and picks
3388 /// the new unit up by construction across all five projections.
3389 #[must_use]
3390 pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3391 Self::from_suffix(suffix).map(Self::window)
3392 }
3393}
3394
3395/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3396/// every consumer that formats a canonical rate-limit unit as user-
3397/// facing text (future M4 admission-webhook rejection bodies naming
3398/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3399/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3400/// codec's parse arm accepts and the render arm emits. Same
3401/// as_str-through-Display convergence discipline the sibling
3402/// [`PlacementStrategy`], [`crate::CaixaKind`],
3403/// [`crate::supervisor::RestartStrategy`], and
3404/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3405impl std::fmt::Display for RateLimitUnit {
3406 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3407 f.write_str(self.as_suffix())
3408 }
3409}
3410
3411/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3412/// validated [`MeshPolicy::timeout`] past
3413/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3414/// (inclusive on both ends, integer-millisecond magnitudes by the
3415/// canonical-form gate immediately preceding).
3416///
3417/// The typed field is `Option<Duration>` (the zero-floor arm
3418/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3419/// `Duration::ZERO`, and the canonical-form arm
3420/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3421/// sub-millisecond residue), so a programmatic struct literal
3422/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3423/// 24h) and the equivalent author-surface form
3424/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3425/// integer-hour magnitude) both round-trip cleanly through serde — a
3426/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3427/// above the documented production-playbook band (Envoy default `15s`,
3428/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3429/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3430/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3431/// at `~3600s`) silently degenerates the mesh-policy contract: the
3432/// per-call deadline is structurally so long that no realistic
3433/// synchronous-`:contratos` traversal can reach it, so the typed slot
3434/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3435/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3436/// blocking" degenerates to a nominal-only contract on the
3437/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3438/// the sibling `:politicas :retries` axis and the
3439/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3440/// `:politicas :circuit-breaker :max-failures` axis — all three close
3441/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3442/// footgun the prior zero-floor-and-canonical-form-only checks left
3443/// open.
3444///
3445/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3446/// shared duration codec emits (`"<n>h"` for any integer-hour
3447/// magnitude) — every value in the canonical authoring form's
3448/// `<integer><unit>` grammar at or below this cap renders to a clean
3449/// canonical string. The cap sits an order of magnitude above every
3450/// documented production-playbook recommendation band (Envoy default
3451/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3452/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3453/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3454/// below the clearly-pathological "effectively no timeout" floor
3455/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3456/// want for a long-running synchronous workflow, but a hard wall above
3457/// which the mesh-level deadline is structurally a non-deadline.
3458/// Lifted as a typed `pub const` so the bound has exactly one source
3459/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3460/// materializer's admission webhook and the caixa-mesh-side
3461/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3462/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3463/// other typed upper bound in this crate carries
3464/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3465/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3466/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3467/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3468pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3469
3470/// Upper-bound ceiling on the `:politicas :retries` axis — every
3471/// validated [`MeshPolicy::retries`] past
3472/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3473///
3474/// The typed slot is `Option<u32>` (`None` = no retries on transient
3475/// failure; `Some(0)` already rejected by the
3476/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3477/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3478/// .. }`) and the equivalent author-surface form
3479/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3480/// serde / the codec — a structurally unbounded `u32` ceiling. The
3481/// runtime substrate that consumes the value (Envoy's
3482/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3483/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3484/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3485/// admission cap is 10) translates a four-billion-retry policy into a
3486/// thundering-herd amplification vector on transient failure — the
3487/// caller's one request fans out to `retries` server-side calls per
3488/// edge per traversal, multiplying load by `(retries+1)^depth` across
3489/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3490/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3491/// invariant on the retry axis; both belong at the typed-slot layer.
3492///
3493/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3494/// upstream mesh-policy schema that documents one) and sits above the
3495/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3496/// every documented production playbook): a value the author can
3497/// plausibly want, but a hard wall above which the policy is
3498/// structurally a footgun. Lifted as a typed `pub const` so the bound
3499/// has exactly one source of truth — a future axis reaching for the
3500/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3501/// materializer's admission webhook, the caixa-mesh-side
3502/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3503/// one place. Same shape every other typed upper bound in this crate
3504/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3505/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3506/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3507/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3508pub const POLICY_RETRIES_MAX: u32 = 10;
3509
3510/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3511/// axis — every validated [`CircuitBreaker::max_failures`] past
3512/// [`AplicacaoSpec::validate_politicas`] lies in
3513/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3514///
3515/// The typed field is `u32` (the zero-floor arm
3516/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3517/// `0` — a breaker that trips on the first call), so a programmatic
3518/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3519/// and the equivalent author-surface form
3520/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3521/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3522/// `max_failures` value far above the documented production-playbook
3523/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3524/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3525/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3526/// typical 5–50) silently disables the breaker's protection role:
3527/// the threshold is structurally so high that no realistic
3528/// failures-per-`:window` traffic shape can reach it, so the breaker
3529/// never trips and the typed slot becomes a no-op carried on every
3530/// emitted Envoy / Cilium L7 overlay. Pairs with the
3531/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3532/// axis — both close the "structurally unbounded `u32` ceiling on a
3533/// typed policy axis" footgun the prior zero-floor-only checks left
3534/// open.
3535///
3536/// The `1000` ceiling sits an order of magnitude above every
3537/// documented upstream production-playbook recommendation band (the
3538/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3539/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3540/// the clearly-pathological "effectively no protection"
3541/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3542/// plausibly want at hyperscale, but a hard wall above which the
3543/// policy is structurally a no-op. Lifted as a typed `pub const` so
3544/// the bound has exactly one source of truth — the future M4
3545/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3546/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3547/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3548/// one place. Same shape every other typed upper bound in this crate
3549/// carries ([`POLICY_RETRIES_MAX`],
3550/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3551/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3552/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3553pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3554
3555/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3556/// every validated [`CircuitBreaker::window`] past
3557/// [`AplicacaoSpec::validate_politicas`] lies in
3558/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3559/// integer-millisecond magnitudes by the canonical-form gate
3560/// immediately preceding).
3561///
3562/// The typed field is `Duration` (the zero-floor arm
3563/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3564/// `Duration::ZERO`, and the canonical-form arm
3565/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3566/// sub-millisecond residue), so a programmatic struct literal
3567/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3568/// and the equivalent author-surface form
3569/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3570/// integer-hour magnitude) both round-trip cleanly through serde — a
3571/// structurally unbounded `Duration` ceiling. A `:window` value far
3572/// above the documented production-playbook band (Hystrix
3573/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3574/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3575/// Istio `outlierDetection.interval` default `10s`, Envoy
3576/// `outlier_detection.interval` default `10s`, AWS App Mesh
3577/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3578/// breaker's role: a rolling-window failure counter whose window is
3579/// hours long is operationally a lifetime counter, the breaker's
3580/// "recent failures" memory is structurally so long that transient
3581/// failures are never forgotten, and the typed slot becomes a no-op
3582/// trigger that trips once and stays tripped for the lifetime of the
3583/// component carried on every emitted Envoy / Cilium L7 overlay.
3584///
3585/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3586/// shared duration codec emits (`"<n>h"` for any integer-hour
3587/// magnitude) — every value in the canonical authoring form's
3588/// `<integer><unit>` grammar at or below this cap renders to a clean
3589/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3590/// cap on the first typed-`Duration` `:politicas` axis: the two
3591/// duration-typed `:politicas` axes now share a single uniform top
3592/// edge so the next typed-slot wiring (the future caixa-mesh
3593/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3594/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3595/// admission webhook) reaches for either field knowing the value is
3596/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3597/// sits two orders of magnitude above every documented upstream
3598/// production-playbook recommendation band (Hystrix / resilience4j /
3599/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3600/// and below the clearly-pathological "rolling window degenerates to
3601/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3602/// author can plausibly want for a very-low-traffic long-tail
3603/// failure-detection window, but a hard wall above which the breaker's
3604/// rolling-window contract is structurally a lifetime-counter contract.
3605/// Lifted as a typed `pub const` so the bound has exactly one source
3606/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3607/// materializer's admission webhook and the caixa-mesh-side
3608/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3609/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3610/// other typed upper bound in this crate carries
3611/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3612/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3613/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3614/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3615/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3616pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3617
3618/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3619/// every validated [`RateLimit::rate`] past
3620/// [`AplicacaoSpec::validate_politicas`] lies in
3621/// `1..=POLICY_RATE_LIMIT_MAX`.
3622///
3623/// The typed field is `u32` (the zero-floor arm
3624/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3625/// zero-rate limit denies every request, the canonical "I forgot
3626/// that 0 means deny-everything" footgun), so a programmatic struct
3627/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3628/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3629/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3630/// round-trip cleanly through serde — a structurally unbounded `u32`
3631/// ceiling. The runtime substrate consuming the value (Envoy's
3632/// `local_rate_limit.token_bucket.max_tokens`, the future
3633/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3634/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3635/// rate-limit into a no-op rate-limiter: the bucket capacity is
3636/// structurally so high no realistic per-edge traffic shape can
3637/// drain it, the limiter never trips, and the typed slot becomes a
3638/// "rate-limit declared, no enforcement" footgun — the canonical
3639/// declared-but-inert shape every other `:politicas` cap arm
3640/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3641/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3642///
3643/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3644/// above every documented upstream production-playbook recommendation
3645/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3646/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3647/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3648/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3649/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3650/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3651/// `u32::MAX`): a value the author can plausibly want at hyperscale
3652/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3653/// /h-window arm), but a hard wall above which the policy is
3654/// structurally a no-op carried verbatim on every emitted Envoy /
3655/// Cilium L7 overlay. The cap brackets all three canonical windows
3656/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3657/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3658/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3659/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3660/// has exactly one source of truth — the future M4
3661/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3662/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3663/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3664/// one place. Same shape every other typed upper bound in this crate
3665/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3666/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3667/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3668/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3669/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3670/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3671pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3672
3673// `:entrada :host` total-length and per-label cap axes route through
3674// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3675// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3676// pair of aplicacao-private aliases the previous `validate_entrada_host`
3677// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3678// = 63`) were structurally the same K8s Gateway API v1 Hostname
3679// admission-schema bounds — the total-length cap on the OpenAPI
3680// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3681// same regex — that the peer axes at the caixa-core::render level pin,
3682// so hoisting both readers onto the shared lifted constants closes the
3683// third-occurrence duplication threshold structurally: the M4
3684// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3685// label validator, the future per-`Certificate` SAN emitter, and every
3686// other per-Gateway-API-Hostname landing site reach the same one place
3687// as the `:entrada :host` gate does — no per-axis alias drift surface
3688// between them, by construction.
3689
3690/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3691/// extractor expression — the upper bound `validate_placement_shard_key`
3692/// enforces on every well-shaped shard-key past validate. The realistic
3693/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3694/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3695/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3696/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3697/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3698/// in `:shard-key`" footgun at validate time rather than at the future
3699/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3700const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3701
3702/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3703/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3704/// that maps the shared parser-shaped reason into the
3705/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3706/// is self-locating (the offending `caixa:` is named verbatim) and
3707/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3708/// fix it in one edit. Same diagnostic shape as
3709/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3710/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3711fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3712 // Empty is already gated by `MembroCaixaEmpty` at the call site;
3713 // re-checking here keeps the predicate usable from any future
3714 // call site (the M4 CR materializer) without an empty-check
3715 // footgun. The shared
3716 // [`crate::render::require_valid_dns_1123_label`] helper brackets
3717 // the empty-first + shape cascade every peer name axis
3718 // (`:placement :clusters`, `:placement :affinity`, `:contratos
3719 // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3720 // `:upgrade-from :module`) routes through, so drift between the
3721 // eight axes' accepted DNS-1123-label sets is structurally
3722 // impossible.
3723 crate::render::require_valid_dns_1123_label(
3724 caixa,
3725 || AplicacaoError::MembroCaixaEmpty,
3726 |reason| AplicacaoError::MembroCaixaInvalid {
3727 caixa: caixa.to_string(),
3728 reason,
3729 },
3730 )
3731}
3732
3733/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3734/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3735/// that maps the shared parser-shaped reason into the
3736/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3737///
3738/// Cluster names land in DNS-1123-label territory across every consumer:
3739/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3740/// the `lareira-fleet-programs` aggregator applies to scope programs to
3741/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3742/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3743/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3744/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3745/// side schema enforces the DNS-1123 label rule on admission; a
3746/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3747/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3748/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3749/// only gate and the failure surfaces as a no-match at filter time —
3750/// the workload doesn't land in the named cluster, with no diagnostic
3751/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3752/// build time mirrors the `:membros :caixa` value-shape trajectory
3753/// (3f9d7a0) on the peer name axis.
3754///
3755/// The diagnostic carries the offending `cluster:` verbatim plus a
3756/// parser-shaped `reason:` naming the specific violation, so the
3757/// author can grep their caixa.lisp for `:clusters` and fix it in
3758/// one edit. Same diagnostic shape as
3759/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3760fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3761 // Empty is already gated by `PlacementClusterEmpty` at the call
3762 // site; re-checking here keeps the predicate usable from any
3763 // future call site (the M4 CR materializer's per-cluster validator)
3764 // without an empty-check footgun. Routes through the shared
3765 // [`crate::render::require_valid_dns_1123_label`] gate the peer
3766 // name axes each land on.
3767 crate::render::require_valid_dns_1123_label(
3768 cluster,
3769 || AplicacaoError::PlacementClusterEmpty,
3770 |reason| AplicacaoError::PlacementClusterInvalid {
3771 cluster: cluster.to_string(),
3772 reason,
3773 },
3774 )
3775}
3776
3777/// Reject `:placement :affinity` hints whose shape can never legitimately
3778/// land in any downstream selector or label-keyed routing axis. Thin
3779/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3780/// shared parser-shaped reason into the
3781/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3782/// diagnostic is self-locating (the offending `:affinity` is named
3783/// verbatim) and the author can grep their caixa.lisp for
3784/// `:affinity "<hint>"` and fix it in one edit.
3785///
3786/// The `:affinity` slot carries a placement-engine hint — canonical
3787/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3788/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3789/// compression overlay and the future M4 placement-engine's per-hint
3790/// routing axis. Each downstream consumer (caixa-mesh's
3791/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3792/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3793/// `spec.placement.affinity` admission rule, the future M4 per-hint
3794/// node-affinity / pod-affinity rule generator keying off the same
3795/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3796/// selector) requires the value to be a DNS-1123 label — K8s label
3797/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3798/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3799/// admission rule the apiserver enforces.
3800///
3801/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3802/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3803/// Python-module-name leak), `:affinity "data.locality"` (the
3804/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3805/// `:affinity "data-locality-"` (boundary-hyphen violation),
3806/// `:affinity "data locality"` (paste-from-doc whitespace),
3807/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3808/// 64-byte over-cap slug silently passed the empty-only check and the
3809/// failure surfaced as a no-match at the M3 Adaptive compression
3810/// overlay's filter time (`placement.affinity` carried a malformed
3811/// value, no node matched, the workload landed on the default
3812/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3813/// the empty-:affinity / empty-shard-key / zero-:politicas /
3814/// empty-:contratos-target gates already close on every other
3815/// declare-but-no-opinion axis. Lifting the rejection to a build-time
3816/// gate closes the fifth typed slot on the Aplicacao surface to land
3817/// on the canonical DNS-1123 label floor (after the four Servico-name
3818/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
3819/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
3820/// b0e8748).
3821///
3822/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
3823/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
3824/// validated values are guaranteed-accepted by the apiserver without
3825/// re-validation at any downstream renderer or admission layer.
3826fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
3827 // Empty is gated separately at the call site for a self-locating
3828 // diagnostic; re-checking here keeps the predicate usable from any
3829 // future call site (the M4 CR materializer's per-affinity
3830 // validator) without an empty-check footgun. Routes through the
3831 // shared [`crate::render::require_valid_dns_1123_label`] gate the
3832 // peer name axes each land on.
3833 crate::render::require_valid_dns_1123_label(
3834 affinity,
3835 || AplicacaoError::PlacementAffinityEmpty,
3836 |reason| AplicacaoError::PlacementAffinityInvalid {
3837 affinity: affinity.to_string(),
3838 reason,
3839 },
3840 )
3841}
3842
3843/// Reject `:placement :shard-key` extractor expressions whose shape can
3844/// never legitimately drive the future M4 Akka-style cluster-sharding
3845/// reconciler's hash-extractor pass. Maps the per-byte / length checks
3846/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
3847/// diagnostic is self-locating (the offending `:shard-key` value is
3848/// named verbatim alongside the parser-shaped reason) and the author can
3849/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
3850/// edit.
3851///
3852/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
3853/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
3854/// expression naming the message property to hash on. The realistic
3855/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
3856/// property name; `$tenantId` — Akka entity-id placeholder;
3857/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
3858/// `${tenant}` — interpolation-style template) all sit in the printable
3859/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
3860/// multi-line blob landing in `:shard-key`, an embedded space from a
3861/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
3862/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
3863/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
3864/// check and the failure surfaces at the future M4 reconciler's hash
3865/// pass as a runtime extractor-evaluation error far from the source
3866/// `caixa.lisp`, with no field naming which member's `:shard-key`
3867/// carried the offending value.
3868///
3869/// The contract — the printable ASCII single-token intersection-floor
3870/// every Akka-style entity-id extractor implementation admits:
3871///
3872/// - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
3873/// peer DNS-1123-label-shaped `:placement :affinity` /
3874/// `:placement :clusters` identifier axes; realistic shard-keys sit
3875/// well under 32 bytes, the cap surfaces paste-from-doc multi-line
3876/// blob footguns at validate time;
3877/// - every byte in the printable ASCII range `0x21..=0x7E` —
3878/// rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
3879/// `"$tenantId\n"` from paste-from-aligned-doc /
3880/// paste-from-shell-heredoc), control characters (`\x00..\x1F`,
3881/// `\x7F` — the canonical "embedded null from a copy-paste-binary
3882/// footgun"), and non-ASCII bytes (`"$tenàntId"` —
3883/// un-Punycode-encoded IDN that round-trips inconsistently across
3884/// NFC/NFD normalization).
3885///
3886/// The accepted set is broader than the DNS-1123 label floor the peer
3887/// `:placement :clusters` / `:placement :affinity` axes use because the
3888/// `:shard-key` value is not a K8s `metadata.name` / label-selector
3889/// landing site; it's an extractor expression the future Akka-style
3890/// reconciler reads as a property reference. The realistic forms
3891/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
3892/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
3893/// but every Akka-style entity-id extractor parses. The
3894/// printable-ASCII-token floor accepts every shape any such extractor
3895/// would accept while rejecting the cross-implementation footguns
3896/// (whitespace breaks token boundaries; non-ASCII round-trips
3897/// inconsistently across YAML emitters and NFC/NFD normalization;
3898/// control characters silently corrupt the next read).
3899///
3900/// Until this gate landed `validate_placement` only refused the
3901/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
3902/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
3903/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
3904/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
3905/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
3906/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
3907/// control character from paste-from-binary, the 64-byte over-cap
3908/// paste-from-doc multi-line slug) silently passed validate. The future
3909/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
3910/// would then surface the malformed value either as a runtime
3911/// extractor-evaluation error (whitespace breaks the extractor's token
3912/// boundary, no match) or as a silently-different shard assignment
3913/// across YAML emitters (non-ASCII normalizes differently between the
3914/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
3915/// parser, the same entity ID maps to two distinct shards on a
3916/// re-render). Lifting the shape gate to caixa-build time makes the
3917/// extractor-floor invariant a structural property of every validated
3918/// `Placement`: every `Sharded` placement past `validate_placement` has
3919/// a `:shard-key` the future M4 reconciler can hash without
3920/// re-validating at the runtime layer.
3921///
3922/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
3923/// [`AplicacaoError::ContratoSubjectInvalid`] /
3924/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
3925/// on the peer `:contratos` payload axes — each lifts the
3926/// runtime-side parser's intersection-floor to a caixa-build-time gate,
3927/// closing the canonical "this passed validate but the runtime parser
3928/// rejected it" surprise.
3929fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
3930 // Empty is gated separately at the call site via the more
3931 // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
3932 // re-checking here keeps the predicate usable from any future call
3933 // site (the M4 CR materializer's per-shard-key validator) without
3934 // an empty-check footgun.
3935 if key.is_empty() {
3936 return Err(AplicacaoError::ShardedKeyEmpty);
3937 }
3938 if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
3939 return Err(AplicacaoError::ShardKeyInvalid {
3940 shard_key: key.to_string(),
3941 reason: format!(
3942 "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
3943 (got {} bytes; realistic Akka-style entity-id extractor expressions \
3944 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
3945 well under 32 bytes, this length suggests a paste-from-doc \
3946 multi-line blob landed in `:shard-key` instead of a single-token \
3947 extractor expression)",
3948 key.len()
3949 ),
3950 });
3951 }
3952 for &b in key.as_bytes() {
3953 if (0x21..=0x7E).contains(&b) {
3954 continue;
3955 }
3956 let reason = if b == b' ' {
3957 "contains a space (Akka-style entity-id extractor expressions are \
3958 single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
3959 whitespace breaks the extractor's token boundary at the runtime layer, \
3960 and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
3961 a multi-token blob in one `:shard-key` slot)"
3962 .to_string()
3963 } else if b == b'\t' {
3964 "contains a tab character (paste-from-aligned-doc footgun; the \
3965 Akka-style entity-id extractor reads `:shard-key` as a single-token \
3966 reference, embedded whitespace breaks the token boundary at the \
3967 runtime hash-extractor pass)"
3968 .to_string()
3969 } else if b == b'\n' || b == b'\r' {
3970 format!(
3971 "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
3972 paste-from-multiline-doc footgun; the Akka-style entity-id \
3973 extractor reads `:shard-key` as a single-token reference, embedded \
3974 newlines either truncate the value at the YAML emitter layer or \
3975 break the token boundary at the runtime hash-extractor pass)"
3976 )
3977 } else if b < 0x20 || b == 0x7F {
3978 format!(
3979 "contains control character 0x{b:02x} (the canonical \
3980 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
3981 control characters silently corrupt round-trip serialization \
3982 across YAML emitters and break the runtime hash-extractor's \
3983 single-token parser)"
3984 )
3985 } else {
3986 format!(
3987 "contains non-ASCII byte 0x{b:02x} (the canonical \
3988 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
3989 inconsistently across NFC/NFD normalization on APFS / ext4 / \
3990 across YAML emitter implementations — the same entity ID can \
3991 silently map to two distinct shards on a re-render. Use a \
3992 printable-ASCII extractor expression like `tenantId`, \
3993 `$tenantId`, or `metadata.tenantId`)"
3994 )
3995 };
3996 return Err(AplicacaoError::ShardKeyInvalid {
3997 shard_key: key.to_string(),
3998 reason,
3999 });
4000 }
4001 Ok(())
4002}
4003
4004/// Reject `:contratos :de` / `:contratos :para` values whose shape
4005/// can never legitimately match a validated `:membros :caixa`. Thin
4006/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4007/// shared parser-shaped reason into the
4008/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4009/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4010/// the offending value verbatim) and the author can grep their
4011/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4012/// one edit.
4013///
4014/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4015/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4016/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4017/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4018/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4019/// un-Punycode-encoded IDN) silently passed the per-axis check and
4020/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4021/// membership lookup — diagnostic-framed as "this caixa is not in
4022/// `:membros`" when the root cause is "this `:de` value is not a
4023/// well-shaped Servico-name identifier and could never legitimately
4024/// match any validated member". Because every `:membros :caixa` is
4025/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4026/// `names` HashSet structurally never contains an empty / malformed
4027/// string, so the membership lookup arm misframes every empty /
4028/// malformed input. Lifting the shape arm ahead of the lookup
4029/// preserves the legitimate `ContratoMemberMissing` arm (a
4030/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4031/// reference) while routing every structurally-impossible-to-match
4032/// input through the narrower self-locating shape diagnostic.
4033///
4034/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4035/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4036/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4037/// to land on the canonical [`crate::render::is_dns_1123_label`]
4038/// floor. The `slot: &'static str` field carries the kebab-case
4039/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4040/// per-callback-slot diagnostic shape and the
4041/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4042/// (85f102c) cross-list-tag pattern.
4043fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4044 // Routes through the shared
4045 // [`crate::render::require_valid_dns_1123_label`] gate the peer
4046 // name axes each land on. The `slot: &'static str` field flows
4047 // through both error variants so the diagnostic names which
4048 // per-edge axis (`:de` vs `:para`) the offending value came from.
4049 crate::render::require_valid_dns_1123_label(
4050 caixa,
4051 || AplicacaoError::ContratoCaixaEmpty { slot },
4052 |reason| AplicacaoError::ContratoCaixaInvalid {
4053 slot,
4054 caixa: caixa.to_string(),
4055 reason,
4056 },
4057 )
4058}
4059
4060/// Reject `:entrada :para` values whose shape can never legitimately
4061/// match a validated `:membros :caixa`. Thin wrapper around
4062/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4063/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4064/// variant, so the diagnostic is self-locating (the offending
4065/// `:entrada :para` value is named verbatim) and the author can grep
4066/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4067///
4068/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4069/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4070/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4071/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4072/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4073/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4074/// silently passed the per-axis check and surfaced as
4075/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4076/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4077/// root cause is "this `:entrada :para` value is not a well-shaped
4078/// Servico-name identifier and could never legitimately match any
4079/// validated member". Because every `:membros :caixa` is shape-
4080/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4081/// `HashSet` structurally never contains an empty / malformed string,
4082/// so the membership lookup arm misframes every empty / malformed
4083/// input. Lifting the shape arm ahead of the lookup preserves the
4084/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4085/// simply isn't in `:membros` — a phantom reference) while routing
4086/// every structurally-impossible-to-match input through the narrower
4087/// self-locating shape diagnostic.
4088///
4089/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4090/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4091/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4092/// fourth and last Aplicacao-level Servico-name reference axis to
4093/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4094/// No `slot: &'static str` field because there is only one axis
4095/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4096/// the simpler shape mirrors [`validate_membro_caixa`] and
4097/// [`validate_placement_cluster`].
4098fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4099 // Empty is gated separately at the call site for a self-locating
4100 // diagnostic; re-checking here keeps the predicate usable from any
4101 // future call site (the M4 CR materializer's per-`:entrada`
4102 // validator) without an empty-check footgun. Routes through the
4103 // shared [`crate::render::require_valid_dns_1123_label`] gate the
4104 // peer name axes each land on.
4105 crate::render::require_valid_dns_1123_label(
4106 para,
4107 || AplicacaoError::EntradaParaEmpty,
4108 |reason| AplicacaoError::EntradaParaInvalid {
4109 para: para.to_string(),
4110 reason,
4111 },
4112 )
4113}
4114
4115/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
4116/// would refuse at admission time. The contract — exactly the regex
4117/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
4118/// and `HTTPRoute.spec.hostnames[]`,
4119/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
4120/// (max length 253; per-label max length 63):
4121///
4122/// - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
4123/// uppercase, no underscore, no Unicode/IDN — IDN must be
4124/// pre-encoded as Punycode `xn--…` by the author);
4125/// - exactly one optional leading wildcard label (`*.`); a wildcard
4126/// in any non-leading label position is rejected;
4127/// - each `.`-separated label is 1..=63 bytes, with non-hyphen
4128/// alphanumeric at both boundaries (no `-foo`, no `foo-`);
4129/// - total length 1..=253 bytes;
4130/// - no IPv4 literal (Gateway API forbids IP literals);
4131/// - no scheme (`https://`, `http://`), no port (`:8080`), no
4132/// whitespace, no path (`/`).
4133///
4134/// Lifted as a typed gate (rather than an inline cascade in
4135/// `validate()`) so the contract lives in one place — every future
4136/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4137/// materializer's host validator, the future per-`:entrada` SAN
4138/// emission for cert-manager Certificates, the multi-`:entrada`
4139/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
4140/// for the same predicate, not its own. Same compounding shape as
4141/// `is_canonical_rate_limit_window` (808017c) and
4142/// [`WitTarget::label`] (previously the free `contrato_target_label`
4143/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
4144/// per-variant label match is compiler-checked-exhaustive).
4145///
4146/// The diagnostic carries the offending `host:` verbatim plus a
4147/// parser-shaped `reason:` naming the specific violation, so the
4148/// author can grep their caixa.lisp for `:host "<host>"` and fix it
4149/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
4150/// (9888b13).
4151fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
4152 // Empty is already gated by `EmptyEntradaHost` at the call site;
4153 // re-checking here keeps the predicate usable from any future
4154 // call site (M4 CR materializer) without an empty-check footgun.
4155 if host.is_empty() {
4156 return Err(AplicacaoError::EmptyEntradaHost);
4157 }
4158 if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
4159 return Err(AplicacaoError::EntradaHostInvalid {
4160 host: host.to_string(),
4161 reason: format!(
4162 "exceeds Gateway API v1 Hostname max length of {cap} bytes \
4163 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
4164 host.len(),
4165 cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
4166 ),
4167 });
4168 }
4169 if host.contains("://") {
4170 return Err(AplicacaoError::EntradaHostInvalid {
4171 host: host.to_string(),
4172 reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
4173 Gateway API takes the bare hostname)"
4174 .to_string(),
4175 });
4176 }
4177 if host.contains('/') {
4178 return Err(AplicacaoError::EntradaHostInvalid {
4179 host: host.to_string(),
4180 reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
4181 matching is in `:entrada :paths`)"
4182 .to_string(),
4183 });
4184 }
4185 // After the `://` scheme-prefix and `/` path arms have ruled out the
4186 // two `:`-bearing shapes the Gateway API actively rejects with
4187 // location-shaped diagnostics, any remaining `:` in the host body is
4188 // either the canonical "I put the port in the `:host` slot"
4189 // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
4190 // slot lives one axis away on the same `:entrada` block) or an
4191 // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
4192 // Hostname forbids identically to the IPv4-literal arm below. Both
4193 // shapes silently fell through the `://` and `/` arms before this
4194 // lift and surfaced as a deep `label "<rest>:<port>" contains
4195 // invalid character ':'` diagnostic from the per-byte loop near the
4196 // bottom of this predicate, which named the offending byte but not
4197 // the canonical authoring fix — for the port case the author has to
4198 // know the `:entrada` block carries a separate `:port u16` slot
4199 // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
4200 // move the value over; for the IPv6 case the author has to know
4201 // Gateway API v1 forbids IP literals across the board. The contract
4202 // doc-comment above already promises "no port (`:8080`)" verbatim
4203 // in the rejected-shape enumeration but the predicate's
4204 // implementation refused the `:` only as a side-effect of the
4205 // per-label `[a-z0-9-]` character-class loop; this arm brings the
4206 // implementation in line with the documented contract by surfacing
4207 // the canonical fix at the top-level shape gate, peer with how the
4208 // `://` arm names the scheme prefix and the `/` arm names the
4209 // `:entrada :paths` axis. Same compounding trajectory the recent
4210 // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
4211 // — the typed slot's rejected set matches the apiserver's rejected
4212 // set, structurally, with a self-locating diagnostic at the
4213 // offending axis instead of a deep parser-shape leak.
4214 if host.contains(':') {
4215 return Err(AplicacaoError::EntradaHostInvalid {
4216 host: host.to_string(),
4217 reason: "must not contain `:` (the port belongs in the `:entrada :port` \
4218 slot — a separate `u16` axis on the same `:entrada` block, \
4219 defaulting to 8080 — not in the host body; drop the `:<port>` \
4220 suffix and author the bare hostname. If you intended an IPv6 \
4221 literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
4222 Hostname forbids IP literals identically to the IPv4-literal \
4223 arm — use a DNS name)"
4224 .to_string(),
4225 });
4226 }
4227 // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
4228 // predicate — the same single source of truth every peer
4229 // ASCII-whitespace scan in caixa-core flows through: the four
4230 // typed-magnitude codec sites (`limits::parse_byte_size` backing
4231 // `:limits :memory`, `limits::parse_duration` backing `:limits
4232 // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
4233 // `aplicacao::rate_limit_codec::parse` backing `:politicas
4234 // :rate-limit`) and the shared duration codec
4235 // (`supervisor::duration_codec::parse`) backing `:supervisor
4236 // :restart-window` / `:politicas :timeout` / `:politicas
4237 // :circuit-breaker :window`. This landing closes the last string-typed
4238 // slot in caixa-core still calling `.bytes().any(|b|
4239 // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
4240 // across every typed slot now shares one predicate, so a future
4241 // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
4242 // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
4243 // deliberately excluded from the peer non-ASCII predicate) can
4244 // extend at this shared site in one edit rather than seven
4245 // independent scans diverging over time. Naming the offending byte
4246 // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
4247 // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
4248 // the offending byte verbatim" discipline every peer codec site
4249 // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4250 // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4251 if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4252 return Err(AplicacaoError::EntradaHostInvalid {
4253 host: host.to_string(),
4254 reason: format!(
4255 "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4256 Hostname is a single-token DNS name — leading, trailing, \
4257 or embedded whitespace breaks the K8s apiserver's Hostname \
4258 regex at admission time; the paste-from-aligned-doc / \
4259 paste-from-shell-history / paste-from-CSV footgun silently \
4260 lands a multi-token blob in `:entrada :host`. Strip every \
4261 whitespace byte and author the bare hostname — space \
4262 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4263 refuse identically)"
4264 ),
4265 });
4266 }
4267 // Peer of the ASCII-whitespace scan above: route the non-ASCII
4268 // subset of Unicode `White_Space` through the shared
4269 // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4270 // single source of truth every peer non-ASCII-whitespace scan in
4271 // caixa-core flows through: `limits::parse_byte_size` (`:limits
4272 // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4273 // `limits::parse_millicores` (`:limits :cpu`),
4274 // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4275 // and `supervisor::duration_codec::parse` (`:supervisor
4276 // :restart-window` / `:politicas :timeout` / `:politicas
4277 // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4278 // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4279 // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4280 // paste-from-web-doc), or an EM-SPACE-split host
4281 // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4282 // survived this predicate's ASCII byte-scan (none of the UTF-8
4283 // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4284 // `u8::is_ascii_whitespace`), then landed on the per-label
4285 // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4286 // predicate with the generic `label "…" must start and end with an
4287 // alphanumeric` diagnostic — a "far from source at build-time"
4288 // leak that names the label-shape violation but not the
4289 // paste-from-typography origin the author actually needs to fix.
4290 // Peer with the four codec sites the 1b75b38 landing pinned: the
4291 // typed slot's diagnostic axis names the offending codepoint
4292 // (`U+XXXX`) verbatim rather than laundering the value through a
4293 // downstream label-shape arm, so the author can grep their
4294 // caixa.lisp for the invisible codepoint at the surfaced position
4295 // rather than eyeball a multi-byte host for embedded NBSP / LINE
4296 // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4297 // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4298 // drift between any two typed-slot sites' non-ASCII-whitespace
4299 // rejection set becomes a single-edit fix at the shared predicate
4300 // rather than N independent inline scans diverging over time, and
4301 // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4302 // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4303 // `char::is_whitespace`" class the peer non-ASCII predicate's
4304 // doc-comment names as the follow-up trajectory) extends at the
4305 // shared predicate in one edit rather than seven.
4306 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4307 return Err(AplicacaoError::EntradaHostInvalid {
4308 host: host.to_string(),
4309 reason: format!(
4310 "contains non-ASCII Unicode whitespace character {ch:?} \
4311 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4312 single-token DNS name limited to `[a-z0-9-]` labels; \
4313 the paste-from-typography footgun silently lands an \
4314 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4315 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4316 `U+3000`, and every other member of the Unicode \
4317 `White_Space` property outside the ASCII byte range) \
4318 in `:entrada :host`, which the K8s apiserver's \
4319 Hostname regex refuses at admission time far from the \
4320 caixa.lisp source line. Strip every non-ASCII \
4321 whitespace character and author the bare hostname \
4322 with only ASCII bytes (write \"checkout.quero.cloud\" \
4323 verbatim)",
4324 codepoint = ch as u32,
4325 ),
4326 });
4327 }
4328
4329 // Strip the optional single leading wildcard label *before* the
4330 // trailing-dot check so the bare `"*."` form surfaces the more
4331 // self-locating "wildcard without domain" diagnostic instead of
4332 // the generic "trailing dot" one.
4333 let (had_wildcard, rest) = match host.strip_prefix("*.") {
4334 Some(r) => (true, r),
4335 None => (false, host),
4336 };
4337 if had_wildcard && rest.is_empty() {
4338 return Err(AplicacaoError::EntradaHostInvalid {
4339 host: host.to_string(),
4340 reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4341 });
4342 }
4343 if rest.contains('*') {
4344 return Err(AplicacaoError::EntradaHostInvalid {
4345 host: host.to_string(),
4346 reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4347 no inner or trailing `*` labels"
4348 .to_string(),
4349 });
4350 }
4351 if rest.ends_with('.') {
4352 return Err(AplicacaoError::EntradaHostInvalid {
4353 host: host.to_string(),
4354 reason: "must not have a trailing `.` (Gateway API hostnames are not \
4355 fully-qualified with a root dot; the apiserver regex rejects \
4356 trailing dots)"
4357 .to_string(),
4358 });
4359 }
4360
4361 // Reject pure IPv4 literals: four dot-separated labels, every
4362 // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4363 // literals as Hostnames.
4364 let labels: Vec<&str> = rest.split('.').collect();
4365 if labels.len() == 4
4366 && labels
4367 .iter()
4368 .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4369 {
4370 return Err(AplicacaoError::EntradaHostInvalid {
4371 host: host.to_string(),
4372 reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4373 literals; use a DNS name)"
4374 .to_string(),
4375 });
4376 }
4377
4378 // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4379 // hyphen, with non-hyphen at both boundaries.
4380 for label in &labels {
4381 if label.is_empty() {
4382 return Err(AplicacaoError::EntradaHostInvalid {
4383 host: host.to_string(),
4384 reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4385 });
4386 }
4387 if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4388 return Err(AplicacaoError::EntradaHostInvalid {
4389 host: host.to_string(),
4390 reason: format!(
4391 "label {label:?} exceeds DNS-1123 label max length of \
4392 {cap} bytes (got {} bytes)",
4393 label.len(),
4394 cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4395 ),
4396 });
4397 }
4398 let bytes = label.as_bytes();
4399 if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4400 return Err(AplicacaoError::EntradaHostInvalid {
4401 host: host.to_string(),
4402 reason: format!(
4403 "label {label:?} must start and end with an alphanumeric \
4404 (no leading or trailing `-`)"
4405 ),
4406 });
4407 }
4408 for &b in bytes {
4409 let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4410 if !valid {
4411 let msg = if b.is_ascii_uppercase() {
4412 format!(
4413 "label {label:?} contains uppercase character {ch:?} \
4414 (Gateway API hostnames are lowercase-only; use {lower:?})",
4415 ch = b as char,
4416 lower = label.to_ascii_lowercase()
4417 )
4418 } else if b == b'_' {
4419 format!(
4420 "label {label:?} contains `_` (Gateway API hostnames \
4421 allow only `[a-z0-9-]`; use `-` instead)"
4422 )
4423 } else {
4424 format!(
4425 "label {label:?} contains invalid character {ch:?} \
4426 (Gateway API hostnames allow only `[a-z0-9-]`)",
4427 ch = b as char
4428 )
4429 };
4430 return Err(AplicacaoError::EntradaHostInvalid {
4431 host: host.to_string(),
4432 reason: msg,
4433 });
4434 }
4435 }
4436 }
4437 Ok(())
4438}
4439
4440/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4441/// would refuse at admission time. Thin wrapper around
4442/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4443/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4444/// variant, preserving the more self-locating
4445/// [`AplicacaoError::EntradaPathEmpty`] /
4446/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4447/// path fails those narrower invariants first.
4448///
4449/// The contract is the canonical HTTP-path grammar — `1..=
4450/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4451/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4452/// whitespace/control/non-ASCII bytes — shared with the
4453/// `:contratos :endpoint` axis through the lifted predicate so drift
4454/// between either landing site and the K8s apiserver-side
4455/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4456/// the predicate, not a per-renderer "this passed validate but failed
4457/// admission" surprise. The diagnostic carries the offending `path:`
4458/// verbatim plus a parser-shaped `reason:` naming the specific
4459/// violation, so the author can grep their caixa.lisp for `:paths`
4460/// and fix it in one edit. Same diagnostic shape as
4461/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4462/// axis.
4463fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4464 // Empty and missing-leading-`/` are already gated at the call
4465 // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4466 // checking here keeps the per-axis narrower diagnostics in force
4467 // when the predicate is reached directly (and `is_gateway_api_http_path`
4468 // itself defends against `bytes[0]`-style indexing on empty
4469 // input).
4470 if path.is_empty() {
4471 return Err(AplicacaoError::EntradaPathEmpty);
4472 }
4473 if !path.starts_with('/') {
4474 return Err(AplicacaoError::EntradaPathNotAbsolute {
4475 path: path.to_string(),
4476 });
4477 }
4478 crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4479 AplicacaoError::EntradaPathInvalid {
4480 path: path.to_string(),
4481 reason,
4482 }
4483 })
4484}
4485
4486mod rate_limit_codec {
4487 // `Duration` is no longer named here — the codec routes through
4488 // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4489 // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4490 // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4491 // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4492 // closed-set enum's arm-table rather than through vestigial free-helper
4493 // delegates.
4494 use super::{RateLimit, RateLimitUnit};
4495 use serde::{Deserialize, Deserializer, Serializer};
4496
4497 pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4498 match v {
4499 Some(rl) => s.serialize_str(&render(*rl)),
4500 None => s.serialize_none(),
4501 }
4502 }
4503
4504 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4505 let opt: Option<String> = Option::deserialize(d)?;
4506 match opt {
4507 None => Ok(None),
4508 Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4509 }
4510 }
4511
4512 fn parse(s: &str) -> Result<RateLimit, String> {
4513 // Whitespace-rejection arm — peer with the leading-`+`
4514 // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4515 // same canonical-form render-determinism axis. Until this gate
4516 // landed the parser silently tolerated leading / trailing /
4517 // internal whitespace via the top-level `s.trim()` and the
4518 // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4519 // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4520 // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4521 // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4522 // serde silently round-tripped to `"100/s"` on the next emit
4523 // (a *different* canonical string) — breaking the THEORY.md
4524 // Part V render-determinism contract on the same
4525 // canonical-form-drift axis the leading-`+` arm below (the
4526 // 4eeae98 predecessor) and the leading-zero arm below (the
4527 // 4f46830 predecessor) already close.
4528 //
4529 // The canonical author shape is `<integer>/<s|m|h>` with no
4530 // whitespace bytes anywhere — every string [`render`] emits
4531 // carries none, so the parser's accepted set must match for
4532 // serialize / deserialize to round-trip losslessly. This gate
4533 // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4534 // `unit.trim()` calls below strict no-ops on the accepted set
4535 // (every byte-position match they would perform is now already
4536 // trimmed away by the accepted set itself), while the arm
4537 // surfaces every rejected whitespace-carrying shape with a
4538 // self-locating diagnostic naming the offending byte and the
4539 // canonical form the author intended, peer with every prior
4540 // canonical-form-drift arm on this codec.
4541 //
4542 // Routed through the lifted
4543 // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4544 // same source of truth the four peer typed-magnitude codec
4545 // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4546 // `limits::parse_millicores`, `supervisor::duration_codec`)
4547 // share. `u8::is_ascii_whitespace()` at the predicate covers
4548 // the five WhatWG-conformant ASCII whitespace bytes (space,
4549 // tab, LF, FF, CR); the "single lifted predicate" discipline
4550 // the peer non-ASCII arm below carries on the strictly-
4551 // complementary Unicode `White_Space` class extends here to
4552 // the ASCII byte set as well.
4553 if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4554 return Err(format!(
4555 "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4556 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4557 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4558 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4559 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4560 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4561 on first serialize — breaking the THEORY.md Part V render-determinism \
4562 contract every typed slot carries. Strip every whitespace byte (write \
4563 `\"100/s\"` verbatim)"
4564 ));
4565 }
4566 // Non-ASCII Unicode `White_Space` arm — the strictly-
4567 // complementary class the ASCII arm above cannot see.
4568 // `str::trim` at the top of every peer codec uses
4569 // `char::is_whitespace` (Unicode `White_Space`, strictly
4570 // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4571 // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4572 // survives the byte-scan (its UTF-8 bytes are not in
4573 // `is_ascii_whitespace`), gets silently stripped by the
4574 // top-level `s.trim()` below, and the value round-trips
4575 // through `render` to a *different* canonical form
4576 // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4577 // render-determinism contract every typed slot carries.
4578 // Closed here (`:politicas :rate-limit`) and at the three
4579 // peer codec sites (`limits::parse_byte_size`,
4580 // `limits::parse_duration`, `supervisor::duration_codec`)
4581 // through the shared
4582 // [`crate::render::find_non_ascii_whitespace_char`] predicate
4583 // — the "single lifted predicate across all four codec sites
4584 // in one follow-up run" the 24a8ad4 commit body's `Forward
4585 // compounding` bullet named as the next compounding step.
4586 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4587 return Err(format!(
4588 "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4589 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4590 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4591 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4592 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4593 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4594 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4595 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4596 silently strips it at parse entry, and the value round-trips through \
4597 `render` to a *different* canonical form (`\"100/s\"`) on first \
4598 serialize — breaking the THEORY.md Part V render-determinism contract \
4599 every typed slot carries. Strip every non-ASCII whitespace character \
4600 (write `\"100/s\"` verbatim with only ASCII bytes)",
4601 cp = ch as u32
4602 ));
4603 }
4604 let s = s.trim();
4605 let (rate_str, unit) = s
4606 .split_once('/')
4607 .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4608 let rate_trim = rate_str.trim();
4609 // The canonical authoring form for `:politicas :rate-limit` is
4610 // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4611 // non-negative integer with no decimal point and no leading
4612 // sign, so the parser's accepted set must match for
4613 // serialize/deserialize to round-trip without canonical-form
4614 // drift. Until this gate landed the parser accepted any
4615 // `u32::from_str`-shaped magnitude — and current Rust
4616 // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4617 // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4618 // serde silently round-tripped to `"100/s"` on the next emit
4619 // (a *different* canonical string) — breaking the THEORY.md
4620 // Part V render-determinism contract on the fifth typed-codec
4621 // surface in caixa-core (peer with the four duration codecs the
4622 // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4623 // already covered: `supervisor::duration_codec` backing three
4624 // typed-duration slots, `limits::parse_duration` backing
4625 // `:limits :wall-clock`, `limits::parse_byte_size` backing
4626 // `:limits :memory`). The fractional / decimal-shaped sibling
4627 // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4628 // existing rejection arm, but the diagnostic is value-laundered
4629 // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4630 // doesn't name the canonical-form remediation or the round-trip
4631 // drift the next emit would produce); this gate lifts the
4632 // fractional arm onto the same canonical-form diagnostic the
4633 // peer codecs carry.
4634 //
4635 // Strict canonical form: every byte of the magnitude is an
4636 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4637 // inputs the gate distinguishes "non-canonical-but-numeric"
4638 // (parses as f64 or i64 — surfaced with a self-locating
4639 // diagnostic naming the canonical authoring form and the
4640 // round-trip drift the rejected shape would produce on first
4641 // serialize) from "garbage" (parses as neither — surfaced with
4642 // the existing narrower `"not a u32"` wording so its
4643 // diagnostic shape remains stable for the parser-shape footgun
4644 // case).
4645 //
4646 // Routed through the lifted
4647 // [`crate::render::is_digit_only_magnitude`] predicate — the
4648 // same source of truth the four peer typed-magnitude codec
4649 // sites share.
4650 let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4651 if !digit_only {
4652 let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4653 if numeric {
4654 return Err(format!(
4655 "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4656 canonical authoring form for `:politicas :rate-limit` is \
4657 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4658 with no decimal point and no leading `+` / `-` sign. A fractional / \
4659 signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4660 through `render` to a *different* canonical form (`\"1/s\"`, \
4661 `\"100/s\"`, parser-reject) on first serialize — breaking the \
4662 THEORY.md Part V render-determinism contract every typed slot \
4663 carries. Pick an integer rate that fits the desired window \
4664 (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4665 ));
4666 }
4667 return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4668 }
4669 // Leading-zero arm — peer with the prior `"+100/s"` arm above
4670 // (4eeae98's predecessor) on the same canonical-form
4671 // render-determinism axis. The digit-only gate accepts
4672 // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4673 // them losslessly (= 100, 0, 7), but `render` emits the
4674 // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4675 // a *different* canonical string on the next emit, breaking
4676 // the THEORY.md Part V render-determinism contract the same
4677 // way `"+100/s"` did before the leading-`+` arm landed. The
4678 // single-byte magnitude `"0"` itself round-trips losslessly
4679 // through `render` (`render(0)` emits `"0/s"`) — the
4680 // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4681 // what refuses rate-zero authoring, so `"0/s"` stays in the
4682 // accepted set at this codec layer and the diagnostic
4683 // partitioning between canonical-form drift (this arm) and
4684 // semantic-zero (the downstream gate) remains stable.
4685 // Peer with the future leading-zero arms on the three peer
4686 // typed-magnitude codecs the trajectory acknowledges:
4687 // `supervisor::duration_codec`, `limits::parse_duration`,
4688 // `limits::parse_byte_size` — each carries the same
4689 // canonical-form-drift class today; this gate lands the
4690 // discipline on the fourth typed-magnitude codec in
4691 // caixa-core first because the peer `"+100/s"` arm above is
4692 // the closest predecessor on the trajectory.
4693 //
4694 // Routed through the lifted
4695 // [`crate::render::is_leading_zero_padded_magnitude`]
4696 // predicate — the same source of truth the four peer
4697 // typed-magnitude codec sites share.
4698 if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4699 return Err(format!(
4700 "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4701 canonical authoring form for `:politicas :rate-limit` is \
4702 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4703 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4704 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4705 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4706 first serialize — breaking the THEORY.md Part V render-determinism \
4707 contract every typed slot carries. Strip the leading zeros (write \
4708 `\"100/s\"` instead of `\"0100/s\"`)"
4709 ));
4710 }
4711 // The digit-only gate guarantees every byte is `[0-9]`, and
4712 // the leading-zero arm above guarantees the magnitude is
4713 // either the single byte `"0"` or starts with `[1-9]`, so
4714 // the only way `u32::from_str` can fail here is overflow
4715 // (the magnitude exceeds `u32::MAX`). Surface that with an
4716 // overflow-shaped wording so the diagnostic names the
4717 // offending magnitude verbatim rather than collapsing onto
4718 // the non-canonical arm. Same shape
4719 // `supervisor::duration_codec` (1c55a2a) carries on the peer
4720 // duration-codec axis.
4721 let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4722 format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4723 })?;
4724 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4725 // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4726 // arm reads the `&str → Duration` projection through the
4727 // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4728 // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4729 // with [`super::RateLimitUnit::window`]) rather than the vestigial
4730 // module-private `rate_limit_window_from_unit` free helper the
4731 // predecessor 61421a6 left as the last unlifted delegate on this
4732 // axis. One typed dispatch on the substrate primitive instead of
4733 // one runtime call through the free-helper delegate; the sole
4734 // production consumer of the `&str → Duration` axis (this parse
4735 // arm) now reaches for exactly one typed method on the closed-set
4736 // enum, sibling to the codec's render arm's
4737 // [`super::RateLimit::canonical_unit`] dispatch on the paired
4738 // `Duration → RateLimitUnit` axis and to the validate gate's
4739 // [`super::RateLimit::canonical_unit`] shape-probe on the
4740 // canonical-window axis. A future rate-limit-unit addition (a
4741 // `"d"` day suffix once Envoy's `rate_limit_action` grows
4742 // daily-bucket support, a `"ms"` sub-second window once
4743 // high-throughput per-edge policies come into scope per
4744 // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4745 // on the closed-set enum, and the compiler enforces exhaustiveness
4746 // on every consumer's `match self` arms — this parse arm's
4747 // accepted-suffix set, the render arm's emitted-suffix set, the
4748 // validate gate's canonical-window set, and every future
4749 // per-`:contratos`-edge rate-limit-override overlay all pick it up
4750 // by construction.
4751 let unit = unit.trim();
4752 let window = RateLimitUnit::window_from_suffix(unit)
4753 .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4754 Ok(RateLimit { rate, window })
4755 }
4756
4757 fn render(rl: RateLimit) -> String {
4758 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4759 // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4760 // this render arm reads the `Duration → RateLimitUnit` projection
4761 // through the substrate primitive [`super::RateLimit::canonical_unit`]
4762 // (returns `None` on every non-canonical window — the sub-second /
4763 // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4764 // formats the returned typed enum through its
4765 // [`std::fmt::Display`] impl (which routes through
4766 // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4767 // the substrate primitive instead of one runtime `find_map`
4768 // walk through the free-helper delegate chain
4769 // [`super::rate_limit_window_unit`] (the vestigial free helper's
4770 // sole production consumer was this arm; every other consumer of
4771 // the `Duration → unit` axis — the validate gate below and the
4772 // future M4 per-Aplicacao Envoy config reconciler — now reads
4773 // the same typed method).
4774 //
4775 // A future rate-limit-unit addition (a `"d"` day suffix once
4776 // Envoy's `rate_limit_action` grows daily-bucket support) is
4777 // one variant + one arm per method on the closed-set enum, and
4778 // the compiler enforces exhaustiveness on every consumer's
4779 // `match self` arms — the codec's `parse` accepted-suffix set,
4780 // this render arm's emitted-suffix set, the validate gate's
4781 // canonical-window set, and every future per-`:contratos`-edge
4782 // rate-limit-override overlay all pick it up by construction.
4783 if let Some(unit) = rl.canonical_unit() {
4784 format!("{}/{unit}", rl.rate())
4785 } else {
4786 // Defensive fallback for non-canonical windows. Note:
4787 // [`AplicacaoSpec::validate_politicas`] rejects any
4788 // non-canonical `:rate-limit :window` via
4789 // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4790 // a validated `RateLimit` never reaches this branch. The
4791 // emitted `<n>/<k>s` form is *not* round-trippable through
4792 // [`parse`] (which accepts only the closed-set
4793 // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4794 // explicit count) — the validate gate is what makes the
4795 // round-trip a structural property; this branch exists only
4796 // so a programmatic non-validated serialize doesn't panic.
4797 format!("{}/{}s", rl.rate(), rl.window().as_secs())
4798 }
4799 }
4800}
4801
4802// ── placement strategy ───────────────────────────────────────────────
4803
4804/// How the Aplicacao distributes across clusters. Three options:
4805///
4806/// - `SingleNode` — one cluster runs the app at a time; takeover on
4807/// death (Erlang/OTP distributed-app semantics).
4808/// - `Replicated` — every named cluster runs an instance (active-active).
4809/// - `Sharded` — entities distribute by hash key across clusters
4810/// (Akka cluster sharding).
4811#[derive(
4812 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4813)]
4814pub enum PlacementStrategy {
4815 SingleNode,
4816 Replicated,
4817 Sharded,
4818}
4819
4820/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
4821/// distribution-strategy default for the `:placement :estrategia` axis —
4822/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
4823/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
4824/// so every substrate-side consumer that resolves "what
4825/// [`PlacementStrategy`] variant does an author-omitted `:placement
4826/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
4827/// primitive [`PlacementStrategy`].
4828///
4829/// The `:placement :estrategia` default axis has three production
4830/// consumers on the substrate side today: the [`Default for
4831/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
4832/// impl's struct-literal `estrategia` field, and the serde-side
4833/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
4834/// author-omitted `:placement :estrategia` scalar through the [`Default
4835/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
4836/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
4837/// impl and implicit `PlacementStrategy::default()` routes at the sibling
4838/// consumers, with no compile-time link back to the paired
4839/// [`crate::manifest::Caixa::aplicacao_view`] fold's
4840/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
4841/// production consumer that resolves an author-omitted `:placement` slot
4842/// (entirely omitted, not just the `:estrategia` scalar within a declared
4843/// `:placement` block) through [`Placement::default`] which then routes
4844/// through this same discriminator. A future coherent rebrand of the
4845/// `:placement :estrategia` default (a widening to `Sharded` once the
4846/// substrate discovers hash-keyed distribution as the more common
4847/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
4848/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
4849/// names, a per-cluster overlay the operator pins through a future
4850/// `:placement-overrides` slot) would have had to migrate a lifted
4851/// discriminator on one path and open-coded discriminators on the peers
4852/// in lockstep or the four consumers would silently drift out of
4853/// pairing. Lifting the resolution rule to a typed `pub const` on the
4854/// substrate primitive means the M3-mesh-canonical `:placement
4855/// :estrategia` default migrates as one unit on any future axis change.
4856///
4857/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
4858/// §II.2's active-active-across-every-named-cluster arm — the closest
4859/// canonical M3 production reference the substrate carries, matching the
4860/// caixa-mesh default axis every M3 renderer already keys off (a
4861/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
4862/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
4863/// under the substrate's fleet-programs aggregator without an explicit
4864/// `:placement :estrategia` override). The two alternatives the closed
4865/// [`PlacementStrategy::ALL`] accept-set carries
4866/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
4867/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
4868/// Akka-style hash-keyed distribution across clusters,
4869/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
4870/// postures an author declares explicitly, never a posture an omitted
4871/// slot should silently assume.
4872///
4873/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
4874/// exactly one source of truth on the `:placement :estrategia` axis, on
4875/// the same substrate-primitive lift discipline the sibling M2
4876/// per-supervisor default set carries
4877/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
4878/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
4879/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
4880/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
4881/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
4882/// ([`crate::render::DEFAULT_NAMESPACE`],
4883/// [`crate::render::DEFAULT_LIBRARY_NAME`],
4884/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
4885/// the M3 mesh-primitive-defining slot family to converge onto the
4886/// substrate-primitive-lift discipline the M2 supervisor-slot family
4887/// already carries end-to-end.
4888pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
4889
4890impl Default for PlacementStrategy {
4891 fn default() -> Self {
4892 // Route the [`Default for PlacementStrategy`] impl through the
4893 // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
4894 // `pub const` rather than a raw `Self::Replicated` arm — one
4895 // source of truth for the M3-mesh-canonical active-active-
4896 // across-every-named-cluster `:placement :estrategia` default
4897 // (MESH-COMPOSITION §II.2), on the same substrate-primitive
4898 // lift discipline the sibling M2 per-supervisor default set
4899 // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
4900 // paired halves) carries end-to-end. Pinned by
4901 // `placement_strategy_default_routes_through_lifted_default`.
4902 PLACEMENT_ESTRATEGIA_DEFAULT
4903 }
4904}
4905
4906impl PlacementStrategy {
4907 /// Exhaustive iteration surface for every consumer that reads the
4908 /// full closed-set (the future M4 admission-webhook's accepted-
4909 /// strategy listing in its rejection body, a future `feira app
4910 /// placement --list` CLI-side surfacing of the accepted arm-set,
4911 /// any future round-trip fuzz harness). A future variant addition
4912 /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
4913 /// names as a trajectory item) extends this slice as a single edit
4914 /// and every consumer picks up the new entry by construction — the
4915 /// compiler-checked exhaustiveness on the sibling method `match`
4916 /// arms is the build-time guarantee that no arm forgets to grow.
4917 /// Same shape as the sibling closed-set typed enums'
4918 /// [`RateLimitUnit::ALL`] (6bce03d) and
4919 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
4920 /// surfaces — the third closed-set typed enum on the caixa surface
4921 /// to converge onto the same discipline.
4922 pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
4923
4924 /// Canonical camelCase-schema discriminator scalar this variant
4925 /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
4926 /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
4927 /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4928 /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
4929 /// every substrate consumer that dispatches on the strategy (the
4930 /// `lareira-fleet-programs` aggregator, the future `app-operator`
4931 /// reconciler, the M3 Adaptive compression pass) reads the same
4932 /// byte-string the `Serialize` derive emits — the pin test in
4933 /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
4934 /// asserts the two paths agree.
4935 #[must_use]
4936 pub const fn as_str(self) -> &'static str {
4937 match self {
4938 Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
4939 Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
4940 Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
4941 }
4942 }
4943
4944 /// Substrate-canonical reverse projection on the `:placement
4945 /// :estrategia` closed-set axis — parses the camelCase-schema
4946 /// discriminator scalar back to the typed variant, or `None` when
4947 /// `s` is outside the closed-set arm-string set [`Self::as_str`]
4948 /// emits. Dispatches on the same lifted
4949 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4950 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4951 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
4952 /// [`Self::as_str`] emitter walks, so the parse and emit halves of
4953 /// the round-trip migrate through one caixa-core edit on any future
4954 /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
4955 /// §II.5 hint names as a trajectory item lands one variant + one
4956 /// arm per method and the compiler enforces exhaustiveness on every
4957 /// consumer's `match self` arms).
4958 ///
4959 /// Prior to this lift the substrate carried only the forward
4960 /// `Self → &str` projection (the [`Self::as_str`] emitter, the
4961 /// [`std::fmt::Display`] impl routed through it, the `Serialize`
4962 /// derive that emits the same byte-string under
4963 /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
4964 /// consumer that wanted to parse a wire-form strategy scalar had to
4965 /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
4966 /// => …, "Sharded" => …, _ => … }` cascade that expressed no
4967 /// compile-time link back to the typed variant's canonical lifted
4968 /// constant. A future variant rename or a per-arm serde-attribute
4969 /// drift would silently split the wire byte-string one non-serde
4970 /// consumer parsed from the one the emitter wrote, with the
4971 /// failure surfacing at parse time far from the rebrand commit.
4972 ///
4973 /// Same closed-set-reverse-projection discipline the sibling
4974 /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
4975 /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
4976 /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
4977 /// defining `:placement :estrategia` closed-set axis, the third
4978 /// substrate-side closed-set typed enum to converge on the two-way
4979 /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
4980 /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
4981 /// and side-step the [`std::str::FromStr`]-collision clippy
4982 /// (`clippy::should_implement_trait`) the plain `from_str` name
4983 /// carries; a future explicit [`std::str::FromStr`] impl can layer
4984 /// on top by delegating to this canonical arm-dispatch method.
4985 ///
4986 /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
4987 /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
4988 /// picks the diagnostic form appropriate for its use site — a
4989 /// future `feira app placement --set` CLI-side arg-parse that wants
4990 /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
4991 /// Sharded)"` diagnostic builds one on top by iterating
4992 /// [`Self::ALL`], while the future M4 admission-webhook's rejection
4993 /// path folds `None` onto its per-CR structured refusal body.
4994 #[must_use]
4995 pub fn from_wire(s: &str) -> Option<Self> {
4996 match s {
4997 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
4998 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
4999 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5000 _ => None,
5001 }
5002 }
5003
5004 /// Substrate-canonical per-arm predicate naming the cross-slot
5005 /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5006 /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5007 /// consumes the paired [`Placement::shard_key`] axis (and therefore
5008 /// requires — and is the only strategy that permits — a non-empty
5009 /// `:shard-key` on the paired slot). Today the accept-set is the
5010 /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5011 /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5012 /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5013 /// distributed-app takeover — §II.1) and `Replicated` (active-active
5014 /// across every named cluster) have no hash-keyed routing axis to
5015 /// consume the slot and refuse a declared-but-inert `:shard-key`
5016 /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5017 ///
5018 /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5019 /// satisfies `placement.shard_key().is_some() ==
5020 /// placement.estrategia().requires_shard_key()` by construction — the
5021 /// cross-slot partition the pin
5022 /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5023 /// locks load-bearing, so every downstream consumer that reaches for
5024 /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5025 /// CR materializer's per-CR shard-key resolver, the future
5026 /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5027 /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5028 /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5029 /// shard-key requirement probe, a future author-facing tatara-lisp
5030 /// linter that flags `(:placement (:estrategia Replicated :shard-key
5031 /// "tenantId"))` shapes before `feira lint` reaches
5032 /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5033 /// the substrate primitive — the predicate names *the cross-slot
5034 /// invariant*, not the arm identity.
5035 ///
5036 /// Prior to this lift the "does this strategy consume `:shard-key`"
5037 /// classification lived under the `gen_platform::IsVariant`-derived
5038 /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5039 /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5040 /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5041 /// } else { None }` cascade, the
5042 /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5043 /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5044 /// "tenantId".to_string())` cascade, and the
5045 /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5046 /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5047 /// cascade). Each site conflated two semantically distinct questions:
5048 /// "is the variant `Sharded`?" (arm-identity, what
5049 /// [`Self::is_sharded`] answers) and "does the variant consume
5050 /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5051 /// The two questions land on the same three-way answer under today's
5052 /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5053 /// future arm addition that consumed `:shard-key` under a different
5054 /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5055 /// §II.5 roadmap-hint names that hash-partitions across the cluster
5056 /// pool by client-IP hash rather than an author-declared extractor
5057 /// expression, a hypothetical `WeightedShard` variant that carries a
5058 /// shard-key + per-cluster weight table under a promoted M5
5059 /// adaptive-placement engine) or an addition that did *not* consume
5060 /// `:shard-key` on a semantically Sharded-shaped arm would silently
5061 /// split the two questions. Any consumer that read
5062 /// `.is_sharded().then(…)` for the shard-key requirement gate would
5063 /// silently misclassify the new arm as non-consuming — a fixture
5064 /// builder would omit `:shard-key` where the new arm required one and
5065 /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5066 /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5067 /// commit, a future M4 CR materializer would fall through the
5068 /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5069 /// silently emit an empty extractor at the Akka reconciler layer.
5070 ///
5071 /// Lifting the classification as a substrate-primitive method on the
5072 /// closed-set typed enum names the cross-slot invariant on the
5073 /// primitive that owns the partition: every future arm addition
5074 /// declares its `:shard-key` consumption in one place (this predicate's
5075 /// `match self` arm-set), and every downstream consumer that reaches
5076 /// for the paired shape reads through one typed dispatch. Same
5077 /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5078 /// per-arm predicate on the pre-projection WIT-shape axis and the
5079 /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5080 /// paired predicate on the post-projection typed-view axis — a
5081 /// per-arm semantic-classification predicate paired with the
5082 /// arm-identity predicate the derive already emits, closing the drift
5083 /// footgun on the cross-slot invariant axis.
5084 ///
5085 /// Method-named `requires_shard_key` (not `has_shard_key`, not
5086 /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5087 /// invariant reads as "this strategy *requires* the paired
5088 /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5089 /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5090 /// merely omit it. The `has_*` framing would read as an accessor
5091 /// (returning the presence of an already-carried value) rather than a
5092 /// requirement (naming the invariant the paired slot must satisfy).
5093 /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5094 /// shape as the sibling [`WitContract::is_capability`] /
5095 /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5096 /// arm-family, so every consumer reaches for `.requires_shard_key()`
5097 /// as a drop-in replacement for the `.is_sharded()` conflated read
5098 /// without a return-shape migration.
5099 #[must_use]
5100 pub const fn requires_shard_key(self) -> bool {
5101 match self {
5102 Self::Sharded => true,
5103 Self::SingleNode | Self::Replicated => false,
5104 }
5105 }
5106}
5107
5108// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5109// cross-slot-invariant per-arm predicate: the module-scope const-eval
5110// assertions below trip at caixa-core build time (not test time) if a
5111// future edit rewires the predicate's arm-set away from the singleton
5112// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5113// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5114// runtime pin covers the same truth-table with a more descriptive
5115// diagnostic on failure; these const-eval items add a build-time failure
5116// surface strictly stronger than the runtime pin (a downstream renderer's
5117// `const`-context reader that composed against a rebound predicate would
5118// still surface here before the test suite even ran) and side-step the
5119// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5120// would otherwise accumulate on the caixa-core module baseline.
5121const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5122const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5123const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5124
5125/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5126/// the pretty-printed byte-string every consumer that formats the strategy
5127/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5128/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5129/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5130/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5131/// admission-webhook rejection body) reaches for the same lifted
5132/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5133/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5134/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5135/// `Serialize` derive already emits under
5136/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5137/// [`PlacementStrategy::as_str`] helper already returns.
5138///
5139/// Until this lift landed the sibling OTP-shape typed enums —
5140/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5141/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5142/// so [`std::fmt::Display`] routes through the same discriminant string
5143/// the wire format emits) — carried a stable [`std::fmt::Display`]
5144/// surface but [`PlacementStrategy`] did not; every consumer reaching
5145/// for a strategy byte-string past the wire format had to pick between
5146/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5147/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5148/// derive), any two of which a future variant rename or
5149/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5150/// desynchronize — with the failure surfacing as a downstream renderer /
5151/// operator's per-strategy dispatch reading one spelling while the wire
5152/// format emitted another, far from the source rebrand commit and with
5153/// no field naming the drift. Routing `Display` through
5154/// [`PlacementStrategy::as_str`] makes the three paths
5155/// (`Debug` for structural inspection, `Display` for user-facing text,
5156/// `Serialize` for the wire format) converge on the same lifted
5157/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5158/// the diagnostic byte-string, and the pretty-printed byte-string move
5159/// as a single unit through one canonical declaration each, by
5160/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5161/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5162/// closes the third path.
5163///
5164/// Pin tests
5165/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
5166/// and
5167/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
5168/// assert the three paths agree byte-for-byte on every variant, so a
5169/// future variant rename or per-arm serde attribute drift is a build
5170/// error visible at caixa-core test time, not a silent per-consumer
5171/// dispatch miss at apply / reconcile time.
5172impl std::fmt::Display for PlacementStrategy {
5173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5174 f.write_str(self.as_str())
5175 }
5176}
5177
5178/// Where the Aplicacao runs.
5179#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5180#[serde(rename_all = "camelCase")]
5181pub struct Placement {
5182 /// Distribution strategy.
5183 #[serde(default)]
5184 pub estrategia: PlacementStrategy,
5185
5186 /// Named clusters that host this Aplicacao. Required for
5187 /// `Replicated` and `SingleNode`; for `Sharded` declares the
5188 /// shard pool.
5189 #[serde(default)]
5190 pub clusters: Vec<String>,
5191
5192 /// Optional hint to the placement engine: `"data-locality"`,
5193 /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
5194 #[serde(default, skip_serializing_if = "Option::is_none")]
5195 pub affinity: Option<String>,
5196
5197 /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
5198 #[serde(default, skip_serializing_if = "Option::is_none")]
5199 pub shard_key: Option<String>,
5200}
5201
5202impl Placement {
5203 /// Substrate-canonical per-`:placement` Akka-cluster-sharding
5204 /// `:shard-key` extractor-expression scalar accessor every consumer
5205 /// of the Aplicacao's hash-keyed distribution routing keys off —
5206 /// returns the author-declared `:placement :shard-key` byte-string
5207 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
5208 /// own `Option<String>` storage; `None` when the slot is absent
5209 /// (the canonical shape under `:estrategia Replicated` /
5210 /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
5211 /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
5212 /// partition — `validate` refuses any `Placement` past this call
5213 /// that lands `Some` on a non-`Sharded` strategy or `None` on
5214 /// `Sharded`).
5215 ///
5216 /// The `:placement :shard-key` slot carries the Akka-style
5217 /// cluster-sharding entity-id extractor expression
5218 /// (MESH-COMPOSITION §II.4) — validated by
5219 /// [`validate_placement_shard_key`] to be a non-empty printable-
5220 /// ASCII single-token reference (`tenantId`, `$tenantId`,
5221 /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
5222 /// future M4 Akka-style cluster-sharding reconciler hashes without
5223 /// re-validating at the runtime layer), and every downstream
5224 /// consumer that reads the key keys off this scalar (the
5225 /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
5226 /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5227 /// declared-but-inert refusal diagnostic, the caixa-mesh
5228 /// per-Aplicacao `placement.shardKey` emit path the substrate
5229 /// operator's per-entity hash-routing reader consumes, the future
5230 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5231 /// per-shard-key resolver).
5232 ///
5233 /// Prior to this lift the `.shard_key` field was accessed inline at
5234 /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
5235 /// `Sharded` arm's `match &self.placement.shard_key { None => …,
5236 /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
5237 /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
5238 /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
5239 /// — two open-coded field-accesses that expressed no compile-time
5240 /// link back to the typed slot. A future extension of the
5241 /// `:placement :shard-key` axis to a richer author surface — a
5242 /// per-cluster override the operator pins through a future
5243 /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
5244 /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
5245 /// alias table the M4 CR materializer resolves per-CR, a
5246 /// per-Aplicacao dynamic `:shard-key` derivation the future
5247 /// adaptive placement engine computes from `:affinity` weights —
5248 /// would have had to be threaded through both open-coded copies in
5249 /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
5250 /// arm refusal would silently disagree on which extractor
5251 /// expression a given Placement resolves to. Lifting the resolution
5252 /// rule to a typed method on the substrate primitive means every
5253 /// downstream consumer of the Aplicacao's per-`:placement`
5254 /// hash-key surface reaches for exactly one typed dispatch — the
5255 /// resolver's accept-set migrates as a unit on any future axis
5256 /// addition.
5257 ///
5258 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
5259 /// [`WitContract::destination`] / [`WitContract::world_ref`]
5260 /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
5261 /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
5262 /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
5263 /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
5264 /// typed dispatch on the substrate primitive, thin projections at
5265 /// each consumer" discipline extended onto the per-`:placement`
5266 /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
5267 /// First `Option<&str>`-return accessor on the M3 mesh-slot family
5268 /// — opens the "optional per-slot scalar" projection pattern the
5269 /// sibling per-`:placement` `:affinity`, per-`:politicas`
5270 /// `:rate-limit` future lifts fold on. Named `shard_key()` to
5271 /// match the storage field's name; the accessor's identity name
5272 /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
5273 /// slot's docstring already carries.
5274 #[must_use]
5275 pub fn shard_key(&self) -> Option<&str> {
5276 self.shard_key.as_deref()
5277 }
5278
5279 /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
5280 /// compression-hint scalar accessor every weighting-consumer of the
5281 /// Aplicacao's per-hint routing surface keys off — returns the
5282 /// author-declared `:placement :affinity` byte-string verbatim as
5283 /// an `Option<&str>`, borrowed from the typed slot's own
5284 /// `Option<String>` storage; `None` when the slot is absent (the
5285 /// canonical shape of an Aplicacao that leaves the compression
5286 /// weighting up to the placement engine's cluster-default arm — no
5287 /// author-authored `data-locality` / `low-latency` / etc. hint
5288 /// biases the routing).
5289 ///
5290 /// The `:placement :affinity` slot carries the M3 Adaptive-
5291 /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
5292 /// by [`validate_placement_affinity`] to be a DNS-1123 label
5293 /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
5294 /// K8s-conformant label-selector shape every apiserver-side pod-
5295 /// affinity / node-affinity materializer already gates on
5296 /// admission), and every downstream consumer that reads the hint
5297 /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
5298 /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
5299 /// `placement.affinity` overlay emit path the substrate operator's
5300 /// per-hint weighting-consumer reads, the future M4
5301 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
5302 /// pod-affinity / node-affinity selector resolver).
5303 ///
5304 /// Prior to this lift the `.affinity` field was accessed inline at
5305 /// the sole caixa-core site — the
5306 /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
5307 /// `if let Some(a) = &self.placement.affinity { …
5308 /// validate_placement_affinity(a)? … }` cascade — one open-coded
5309 /// field-access that expressed no compile-time link back to the
5310 /// typed slot. A future extension of the `:placement :affinity`
5311 /// axis to a richer author surface — a per-cluster override the
5312 /// operator pins through a future `:placement :affinity-overrides`
5313 /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
5314 /// tenant hint alias table the M4 CR materializer resolves per-CR,
5315 /// a per-Aplicacao dynamic `:affinity` derivation the future
5316 /// adaptive placement engine computes from `:clusters` topology —
5317 /// would have had to be threaded through the open-coded copy in
5318 /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
5319 /// materializer reader that landed on the axis, or the per-hint
5320 /// value-shape gate and its downstream weighting consumers would
5321 /// silently disagree on which hint a given Placement resolves to.
5322 /// Lifting the resolution rule to a typed method on the substrate
5323 /// primitive means every downstream consumer of the Aplicacao's
5324 /// per-`:placement` compression-hint surface reaches for exactly
5325 /// one typed dispatch — the resolver's accept-set migrates as a
5326 /// unit on any future axis addition.
5327 ///
5328 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
5329 /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5330 /// optional-scalar axis — same "one typed dispatch on the substrate
5331 /// primitive, thin projections at each consumer" discipline extended
5332 /// onto the per-`:placement` M3-Adaptive-compression-hint
5333 /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5334 /// return accessor on the M3 mesh-slot family; closes the last
5335 /// un-lifted per-`:placement` `Option<String>` axis. Named
5336 /// `affinity()` to match the storage field's name; the accessor's
5337 /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5338 /// vocabulary the slot's docstring already carries.
5339 #[must_use]
5340 pub fn affinity(&self) -> Option<&str> {
5341 self.affinity.as_deref()
5342 }
5343
5344 /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5345 /// strategy scalar accessor every consumer that dispatches on the
5346 /// Aplicacao's per-cluster distribution shape keys off — returns the
5347 /// author-declared `:placement :estrategia` variant verbatim as a
5348 /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5349 /// `PlacementStrategy` storage.
5350 ///
5351 /// The `:placement :estrategia` slot carries the closed-set
5352 /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5353 /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5354 /// `Replicated` — active-active across every named cluster; `Sharded`
5355 /// — Akka-style hash-keyed entity distribution across the cluster pool
5356 /// per §II.4) that every downstream consumer of the Aplicacao's
5357 /// per-cluster fan-out shape keys off. Validated by
5358 /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5359 /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5360 /// matches!(estrategia, Sharded)` — the cross-slot partition the
5361 /// [`Placement::shard_key`] accessor's docstring pins), and every
5362 /// downstream consumer that reads the strategy keys off this scalar
5363 /// (the [`AplicacaoSpec::validate_placement`]
5364 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5365 /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5366 /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5367 /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5368 /// declared-but-inert refusal's
5369 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5370 /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5371 /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5372 /// emit path the substrate operator's per-strategy fan-out reader
5373 /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5374 /// materializer's per-strategy admission-webhook resolver).
5375 ///
5376 /// Prior to this lift the `.estrategia` field was accessed inline at
5377 /// four sites — the [`AplicacaoSpec::validate_placement`]
5378 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5379 /// `estrategia: self.placement.estrategia`, the same method's
5380 /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5381 /// partition dispatch, the non-`Sharded`-arm
5382 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5383 /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5384 /// per-Aplicacao strategy print line at
5385 /// `println!("… {} …", spec.placement.estrategia, …)`
5386 /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5387 /// expressed no compile-time link back to the typed slot. A future
5388 /// extension of the `:placement :estrategia` axis to a richer author
5389 /// surface (a per-cluster override the operator pins through a future
5390 /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5391 /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5392 /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5393 /// derivation the future adaptive placement engine computes from
5394 /// `:affinity` + `:clusters` topology) would have had to be threaded
5395 /// through every open-coded copy in lockstep — one consumer reading
5396 /// the raw variant while a peer read the operator-resolved variant
5397 /// would silently split the `PlacementWithoutClusters` /
5398 /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5399 /// partition-dispatch input, a two-consumer split at the validator
5400 /// far from the source `caixa.lisp` with no field naming the
5401 /// strategy-drift root cause. Lifting the resolution rule to a typed
5402 /// method on the substrate primitive means every downstream consumer
5403 /// of the Aplicacao's per-`:placement` distribution-strategy surface
5404 /// reaches for exactly one typed dispatch — the resolver's accept-set
5405 /// migrates as a unit on any future axis addition.
5406 ///
5407 /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5408 /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5409 /// same "one typed dispatch on the substrate primitive, thin
5410 /// projections at each consumer" discipline extended onto the
5411 /// per-`:placement` distribution-strategy `Copy`-composite-enum
5412 /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5413 /// family; first `Copy`-return accessor on the M3 mesh-slot
5414 /// `Placement` type — companion to the sibling per-`:placement`
5415 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5416 /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5417 /// optional-scalar axes, closing the last unlifted per-`:placement`
5418 /// scalar-value axis (the closed-set `PlacementStrategy`
5419 /// distribution-strategy discriminator) so every downstream
5420 /// per-`:placement` reader now routes through a typed dispatch on
5421 /// the substrate primitive. Named `estrategia()` to match the storage
5422 /// field's name; the accessor's identity name maps onto the
5423 /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5424 /// already carries. Declared `pub const fn` (matching the peer M3
5425 /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5426 /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5427 /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5428 /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5429 /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5430 /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5431 /// [`RateLimit`] — every one a `pub const fn`) so every future
5432 /// substrate-side `const`-context consumer of the resolved
5433 /// distribution-strategy variant (a `const _: () = assert!(…)`
5434 /// module-scope invariant pin on a per-fixture typed [`Placement`],
5435 /// a future M4 admission-webhook `const fn` resolver over a typed
5436 /// [`Placement`], any `const fn` composer that fans on the strategy
5437 /// at compile time) reaches through the same typed dispatch on the
5438 /// substrate primitive at const-eval time as at runtime. Pinned by
5439 /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
5440 /// const-eval posture at module scope via `const _:() = …` items so
5441 /// any future accidental downgrade to non-`const` trips at caixa-core
5442 /// build time.
5443 #[must_use]
5444 pub const fn estrategia(&self) -> PlacementStrategy {
5445 self.estrategia
5446 }
5447
5448 /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5449 /// per-cluster distribution-target slice accessor every consumer that
5450 /// walks the Aplicacao's declared cluster-pool keys off — returns the
5451 /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5452 /// `&[String]` slice-view, borrowed from the typed slot's own
5453 /// `Vec<String>` storage (a zero-copy slice-view over the same
5454 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5455 /// through). Non-optional: the empty slice is the load-bearing
5456 /// pre-validation sentinel every downstream consumer of the paired
5457 /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5458 /// off — every strategy in the closed
5459 /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5460 /// requires a non-empty list (`SingleNode` / `Replicated` use the
5461 /// list as hosting / takeover candidates per Erlang/OTP distributed-
5462 /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5463 /// shard pool per Akka cluster-sharding convention, §II.4), so the
5464 /// `.is_empty()` probe is the shared pre-condition every
5465 /// [`AplicacaoSpec::validate_placement`] arm heads on.
5466 ///
5467 /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5468 /// 1123-label per-cluster distribution-target list — the same
5469 /// set-not-multiset shape the sibling `:membros :caixa` /
5470 /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5471 /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5472 /// pins the shape). Every downstream consumer that fans on the list
5473 /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5474 /// pre-flight `.is_empty()` probe that trips
5475 /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5476 /// per-cluster value-shape + duplicate-detection fan-out loop, the
5477 /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5478 /// that materializes the list verbatim onto every
5479 /// programs.yaml entry the substrate operator's per-cluster
5480 /// `placement.clusters | contains .Values.cluster` filter reads,
5481 /// the `feira app graph` per-Aplicacao cluster print line, the
5482 /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5483 /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5484 /// placement engine's cluster-topology reader).
5485 ///
5486 /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5487 /// inline at three production sites — the
5488 /// [`AplicacaoSpec::validate_placement`] pre-flight
5489 /// `self.placement.clusters.is_empty()` refusal probe, the same
5490 /// method's per-cluster validate loop's
5491 /// `for c in &self.placement.clusters` traversal head, and the
5492 /// `feira app graph` per-Aplicacao print line's
5493 /// `spec.placement.clusters` `{:?}` formatter argument
5494 /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5495 /// that expressed no compile-time link back to the typed slot. A
5496 /// future extension of the `:placement :clusters` axis to a richer
5497 /// author surface (a per-tenant cluster-pool overlay the operator
5498 /// pins through a future `:placement :clusters-overrides` slot the
5499 /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5500 /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5501 /// the future M5 adaptive-placement engine computes from
5502 /// `:affinity` weights + live cluster-topology probes, a promotion
5503 /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5504 /// partition once the substrate operator's cluster-membership
5505 /// reconciler comes into typed scope) would have had to be threaded
5506 /// through all three open-coded copies in lockstep or one consumer
5507 /// would silently disagree with the peers on which cluster-pool a
5508 /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5509 /// reading the raw slot while the peer per-cluster validate loop
5510 /// read an operator-resolved slot would silently split the paired
5511 /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5512 /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5513 /// input from the pre-flight input, a three-consumer split at the
5514 /// validator and formatter far from the source `caixa.lisp` with
5515 /// no field naming the cluster-pool-drift root cause. Lifting the
5516 /// resolution rule to a typed method on the substrate primitive
5517 /// means every downstream consumer of the Aplicacao's
5518 /// per-`:placement` cluster-pool surface reaches for exactly one
5519 /// typed dispatch — the resolver's accept-set migrates as a unit
5520 /// on any future axis addition.
5521 ///
5522 /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5523 /// slot — sibling to the seed M2
5524 /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5525 /// slice-return accessor on the peer per-`:supervisor` static-
5526 /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5527 /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5528 /// primitive, thin projections at each consumer" discipline. The
5529 /// three peer `Vec`-carry axes still unlifted at the time of this
5530 /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5531 /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5532 /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5533 /// [`crate::UpgradeFromEntry::instructions`]
5534 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5535 /// — inherit this accessor's discipline as future compounding runs
5536 /// migrate their consumers onto the shared slice-return shape.
5537 /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5538 /// type, sibling to the two `Option<&str>`-return
5539 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5540 /// (74ec2d3) accessors and the `Copy`-return
5541 /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5542 /// unlifted per-`:placement` field axis (the `Vec<String>`
5543 /// distribution-target-list carrier) so every downstream
5544 /// per-`:placement` reader now routes through a typed dispatch on
5545 /// the substrate primitive. Named `clusters()` to match the storage
5546 /// field's name verbatim and the tatara-lisp author-surface term
5547 /// (`:clusters`) the field's own docstring already carries; the
5548 /// accessor's identity maps onto the canonical MESH-COMPOSITION
5549 /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5550 /// for. Returns `&[String]` (not `&Vec<String>`) because every
5551 /// downstream consumer of the cluster list treats it as a read-only
5552 /// sequence — the slice-view is the narrowest borrow that supports
5553 /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5554 /// `.len()`) without leaking the backing `Vec`'s
5555 /// grow/push/reserve surface that no consumer of the typed view
5556 /// reaches for (the storage-side `Vec` remains reachable through
5557 /// the `pub clusters` field for the mutation-carrying serde
5558 /// round-trip and per-test fixture-mutation paths).
5559 #[must_use]
5560 pub fn clusters(&self) -> &[String] {
5561 self.clusters.as_slice()
5562 }
5563}
5564
5565impl Default for Placement {
5566 fn default() -> Self {
5567 Self {
5568 // Route the struct-literal `estrategia` default arm through
5569 // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
5570 // typed `pub const` rather than the transitively-derived
5571 // [`PlacementStrategy::default`] route — one source of truth
5572 // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
5573 // active-active-across-every-named-cluster arm
5574 // (MESH-COMPOSITION §II.2) that both this struct-literal
5575 // altitude and the sibling [`Default for PlacementStrategy`]
5576 // impl already key off through the same substrate primitive.
5577 // Pinned by
5578 // `placement_default_estrategia_routes_through_lifted_default`.
5579 estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
5580 clusters: Vec::new(),
5581 affinity: None,
5582 shard_key: None,
5583 }
5584 }
5585}
5586
5587// ── external entry point ─────────────────────────────────────────────
5588
5589/// External entry point — what an outside caller sees. Renders to a
5590/// Gateway / Ingress + a route to the named member Servico.
5591#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5592#[serde(rename_all = "camelCase")]
5593pub struct Entrada {
5594 /// Public hostname (e.g. `"checkout.quero.cloud"`).
5595 pub host: String,
5596
5597 /// Member Servico the gateway routes to. Must be in `:membros`.
5598 pub para: String,
5599
5600 /// Optional path filter — if set, only matching paths route to
5601 /// this Aplicacao (the rest fall through to other route rules).
5602 #[serde(default)]
5603 pub paths: Vec<String>,
5604
5605 /// Default port on the destination Servico (the trigger.service.port).
5606 #[serde(default = "default_port")]
5607 pub port: u16,
5608}
5609
5610impl Entrada {
5611 /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5612 /// every HTTPRoute-aware renderer keys off — returns the author-
5613 /// declared `:entrada :paths` list verbatim when non-empty, and the
5614 /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5615 /// all fallback otherwise (so an Aplicacao author who declares an
5616 /// external `:entrada` block but no per-path rule surface still
5617 /// gets a route whose sole `HTTPPathMatch` matches every incoming
5618 /// request under the paired
5619 /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5620 ///
5621 /// Prior to this lift the "if `:entrada :paths` is empty use the
5622 /// substrate catch-all; else return each declared path verbatim"
5623 /// cascade lived inline at
5624 /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5625 /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5626 /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5627 /// substrate ships today, with no typed method on the substrate
5628 /// primitive that named the rule. A future path-resolution axis
5629 /// addition — a per-cluster `:entrada :default-path` override the
5630 /// operator pins through a future `:placement`-scoped slot, an
5631 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5632 /// admission-webhook floor that materializes the catch-all before
5633 /// the CR lands, a future per-`:entrada :paths` overlay from a
5634 /// per-cluster policy the future `feira app deploy` pipeline
5635 /// consumes — would have to be threaded through every renderer's
5636 /// inline copy of the cascade in lockstep or one consumer would
5637 /// silently disagree with the peers on which path list a given
5638 /// `:entrada` block resolves to. Lifting the rule to a typed
5639 /// method on the substrate primitive means every downstream
5640 /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5641 /// per-cluster overlay resolver, every future per-Aplicacao
5642 /// snapshot renderer) reaches for exactly one typed dispatch —
5643 /// the resolver's accept-set moves as a unit on any future axis
5644 /// addition.
5645 ///
5646 /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5647 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5648 /// per-`:entrada` scalar-value axes — extends the "one typed
5649 /// dispatch on the substrate primitive, thin projections at each
5650 /// consumer" discipline onto the per-`:entrada` path-list
5651 /// resolution axis every HTTPRoute-aware renderer consumes. Same
5652 /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5653 /// sibling `:politicas` primitive — one typed method on the
5654 /// substrate primitive that names the cascade every renderer
5655 /// otherwise re-inlines.
5656 #[must_use]
5657 pub fn resolved_paths(&self) -> Vec<&str> {
5658 // Route the internal cascade-head + per-entry projection reads
5659 // through the lifted [`Self::paths`] slice accessor rather than
5660 // the raw `self.paths` field access — the substrate-primitive
5661 // per-`:entrada` path-list resolver's two internal reads now
5662 // key off the canonical raw-slot surface every downstream
5663 // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5664 // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5665 // entrada summary line's `{:?}` Debug print) routes through, so
5666 // any future rebrand on the typed slot's raw-slot reader lands
5667 // at exactly one place. Same two-consumer coherence discipline
5668 // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5669 // the peer M3 mesh-slot `Vec<String>`-carry axis.
5670 if self.paths().is_empty() {
5671 vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5672 } else {
5673 self.paths().iter().map(String::as_str).collect()
5674 }
5675 }
5676
5677 /// Substrate-canonical per-`:entrada` DNS-hostname singular
5678 /// accessor every Gateway-API `Listener.hostname` reader keys off
5679 /// — returns the author-declared `:entrada :host` byte-string
5680 /// verbatim as a `&str`, borrowed from the typed slot's own
5681 /// [`String`] storage.
5682 ///
5683 /// Named the "singular" half of the DNS-hostname resolver pair on
5684 /// the substrate primitive: the parent-Gateway per-listener
5685 /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
5686 /// (`Listener.hostname: Option<PreciseHostname>` — at most one
5687 /// hostname per listener), and this accessor is the typed dispatch
5688 /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
5689 /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
5690 /// the per-HTTPRoute `spec.hostnames[]` list axis the same
5691 /// per-Aplicacao ingress-hostname surface projects onto.
5692 ///
5693 /// Prior to this lift the `entrada.host.clone()` byte-string was
5694 /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
5695 /// per-listener singular `hostname:` axis
5696 /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
5697 /// per-HTTPRoute plural `spec.hostnames[]` axis
5698 /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
5699 /// consumers read the same `entrada.host` field but the two-site
5700 /// duplication expressed no compile-time contract that the singular
5701 /// Gateway-listener filter and the plural `HTTPRoute` filter list
5702 /// stay in lockstep on future extensions of the `:entrada` slot to
5703 /// a multi-hostname author surface (an `:entrada :alt-hosts` list
5704 /// overlay, a per-cluster SNI fan-out the operator pins through a
5705 /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
5706 /// Aplicacao` CR materializer's per-listener virtual-host filter
5707 /// admission-webhook overlay). Any such extension would have to be
5708 /// threaded through every renderer's inline copy of the resolution
5709 /// in lockstep or the Gateway listener's `hostname:` filter would
5710 /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
5711 /// — a Gateway-API-conformance divergence whose apply-time symptom
5712 /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
5713 /// `NoMatchingParent` — the API server rejects the route because
5714 /// its `hostnames[]` filter doesn't intersect the parent listener's
5715 /// `hostname` filter) is far from the source `caixa.lisp` and never
5716 /// surfaces in the emitted YAML. Lifting the singular and plural
5717 /// resolvers to typed methods on the substrate primitive means
5718 /// every consumer of the Aplicacao's ingress-hostname surface
5719 /// reaches for exactly one typed dispatch, and the pair-invariant
5720 /// `hostnames() == vec![hostname()]` pinned by the sibling
5721 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
5722 /// keeps the two axes in lockstep by construction.
5723 ///
5724 /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
5725 /// (1449891) path-list resolver on the per-HTTPRoute per-rule
5726 /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
5727 /// the substrate primitive, thin projections at each consumer"
5728 /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5729 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5730 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5731 /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
5732 /// `:entrada` scalar-value + list-value axes.
5733 #[must_use]
5734 pub fn hostname(&self) -> &str {
5735 self.host.as_str()
5736 }
5737
5738 /// Substrate-canonical per-`:entrada` DNS-hostname plural
5739 /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
5740 /// keys off — returns the singleton `[hostname()]` list under
5741 /// today's single-hostname-per-Aplicacao author surface, and the
5742 /// authoritative multi-hostname list under a future
5743 /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
5744 ///
5745 /// Plural half of the DNS-hostname resolver pair — see the
5746 /// companion [`Entrada::hostname`] docstring for the two-consumer
5747 /// lift + pair-invariant discipline (`hostnames() ==
5748 /// vec![hostname()]`, pinned load-bearing by the sibling
5749 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
5750 /// test).
5751 ///
5752 /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
5753 /// per-`:entrada` plural-list resolver on the per-HTTPRoute
5754 /// per-rule path-list axis — same `Vec<&str>` shape, same
5755 /// substrate-primitive-owns-the-resolver discipline extended to
5756 /// the per-HTTPRoute virtual-host filter-list axis.
5757 #[must_use]
5758 pub fn hostnames(&self) -> Vec<&str> {
5759 vec![self.hostname()]
5760 }
5761
5762 /// Substrate-canonical per-`:entrada` destination-Servico scalar
5763 /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
5764 /// the author-declared `:entrada :para` byte-string verbatim as a
5765 /// `&str`, borrowed from the typed slot's own [`String`] storage.
5766 ///
5767 /// The `:entrada :para` slot names the single member Servico the
5768 /// external Gateway routes to (validated by
5769 /// [`AplicacaoSpec::validate`] to be a
5770 /// [`Membro::caixa`] the Aplicacao declares — a stray
5771 /// `:para` that doesn't name a member is
5772 /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
5773 /// backend-attachment miss at cluster-apply time). Under today's
5774 /// single-destination author surface `:entrada :para` is the ingress
5775 /// apex Servico's canonical identity; under a hypothetical
5776 /// future multi-backend author surface (a `:entrada
5777 /// :split :backends` weighted-fan-out overlay for canary /
5778 /// blue-green traffic-split rollouts, per-path override for
5779 /// path-based per-Servico routing beyond the single-apex model,
5780 /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5781 /// per-CR admission-webhook that promotes the scalar to a
5782 /// weighted list) this accessor is the substrate primitive's typed
5783 /// dispatch every downstream `HTTPRoute`-aware consumer routes
5784 /// through, so the resolution shape migrates as a unit on one
5785 /// caixa-core edit rather than a coordinated rewrite across every
5786 /// renderer's inline field-access.
5787 ///
5788 /// Prior to this lift the `entrada.para` byte-string was accessed
5789 /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
5790 /// `metadata.name` composer's per-destination discriminator arg
5791 /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
5792 /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
5793 /// per-HTTPRoute per-rule `backendRefs[0].name` axis
5794 /// (`entrada.para.clone()`,
5795 /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
5796 /// consumers read the same `entrada.para` field but the two-site
5797 /// duplication expressed no compile-time contract that the HTTPRoute
5798 /// name-discriminator and the per-rule backend name stay in
5799 /// lockstep on future extensions of the `:entrada` slot to a
5800 /// multi-destination author surface. Any such extension would have
5801 /// to be threaded through every renderer's inline copy of the
5802 /// destination projection in lockstep or the HTTPRoute
5803 /// `metadata.name` would silently reference a different destination
5804 /// than its own `backendRefs[]` — an operator-side
5805 /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
5806 /// grep-by-name lookup would land on a route whose `backendRefs[]`
5807 /// silently point at a peer Servico, dropping every external
5808 /// `:entrada` flow at the gateway with the destination-drift root
5809 /// cause invisible in the emitted YAML.
5810 ///
5811 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
5812 /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
5813 /// the per-listener singular / per-HTTPRoute plural filter axes and
5814 /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
5815 /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
5816 /// typed dispatch on the substrate primitive, thin projections at
5817 /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5818 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5819 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5820 /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
5821 /// sibling per-`:entrada` scalar-value + list-value axes — this
5822 /// accessor closes the last unlifted per-`:entrada` scalar axis
5823 /// (the destination-Servico byte-string) so every downstream
5824 /// per-`:entrada` reader now routes through a typed dispatch on
5825 /// the substrate primitive.
5826 #[must_use]
5827 pub fn destination(&self) -> &str {
5828 self.para.as_str()
5829 }
5830
5831 /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
5832 /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
5833 /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
5834 /// reader keys off — returns the author-declared `:entrada :port`
5835 /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
5836 /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
5837 /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
5838 /// [`AplicacaoError::EntradaPortZero`], not a silent
5839 /// admission-webhook rejection at cluster-apply time).
5840 ///
5841 /// The `:entrada :port` slot carries the destination Servico's
5842 /// canonical in-cluster L4 listener port (`trigger.service.port` on
5843 /// the `pleme-computeunit` library chart), and every downstream
5844 /// consumer that reads the port keys off this scalar (the
5845 /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
5846 /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
5847 /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
5848 /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5849 /// CR materializer's per-Aplicacao gateway port resolver).
5850 ///
5851 /// Prior to this lift the `.port` field was accessed inline at two
5852 /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
5853 /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
5854 /// the [`AplicacaoSpec::port_for_destination`] resolver's
5855 /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
5856 /// open-coded field-accesses that expressed no compile-time link
5857 /// back to the typed slot. A future extension of the `:entrada :port`
5858 /// axis to a richer author surface — a per-cluster override the
5859 /// operator pins through a future `:placement :default-port` slot the
5860 /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
5861 /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
5862 /// heterogeneous listener ports, an M4
5863 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5864 /// admission-webhook floor that promotes the scalar to a
5865 /// per-destination map — would have had to be threaded through both
5866 /// open-coded copies in lockstep or the structural-floor validator
5867 /// and the [`AplicacaoSpec::port_for_destination`] resolver would
5868 /// silently disagree on which port a given [`Entrada`] resolves to.
5869 /// Lifting the resolution rule to a typed method on the substrate
5870 /// primitive means every downstream consumer of the Aplicacao's
5871 /// per-`:entrada` L4-port surface reaches for exactly one typed
5872 /// dispatch — the resolver's accept-set migrates as a unit on any
5873 /// future axis addition.
5874 ///
5875 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
5876 /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
5877 /// accessors on the per-`:entrada` scalar-value axis — same "one
5878 /// typed dispatch on the substrate primitive, thin projections at
5879 /// each consumer" discipline extended onto the per-`:entrada`
5880 /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
5881 /// the M3 mesh-slot `Entrada` type — closes the last unlifted
5882 /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
5883 /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
5884 /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
5885 /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
5886 /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
5887 /// storage field's name; the accessor's identity name maps onto the
5888 /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
5889 /// already carries. Declared `pub const fn` (matching the peer M3
5890 /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5891 /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5892 /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5893 /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5894 /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5895 /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5896 /// [`RateLimit`], and the sibling per-`:placement`
5897 /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
5898 /// enum scalar axis — every one a `pub const fn`) so every future
5899 /// substrate-side `const`-context consumer of the resolved
5900 /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
5901 /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
5902 /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
5903 /// admission-webhook `const fn` per-CR gateway-port floor over a
5904 /// typed [`Entrada`], any `const fn` composer that fans on the port
5905 /// at compile time) reaches through the same typed dispatch on the
5906 /// substrate primitive at const-eval time as at runtime. Pinned by
5907 /// [`entrada_port_accessor_is_const_fn`] which witnesses the
5908 /// const-eval posture at module scope via `const _:() = …` items so
5909 /// any future accidental downgrade to non-`const` trips at caixa-core
5910 /// build time.
5911 #[must_use]
5912 pub const fn port(&self) -> u16 {
5913 self.port
5914 }
5915
5916 /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
5917 /// slice accessor every HTTPRoute-aware renderer keys off when it
5918 /// wants the raw author-declared path-list (not the fallback-
5919 /// applied projection [`Self::resolved_paths`] returns) — returns
5920 /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
5921 /// borrowed from the typed slot's own [`Vec<String>`] storage.
5922 ///
5923 /// Named the "raw slot" half of the per-`:entrada` path-list resolver
5924 /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
5925 /// (1449891) closes the fallback-applying arm every per-Aplicacao
5926 /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
5927 /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
5928 /// catch-all; non-empty slot → per-entry verbatim projection); this
5929 /// accessor closes the raw-slot arm every consumer that must see the
5930 /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
5931 /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
5932 /// not `Err(EntradaPathEmpty)`, so it cannot route through the
5933 /// fallback-applying sibling; the `feira app graph` per-Aplicacao
5934 /// external-gateway summary line's `{:?}` Debug print — which must
5935 /// name the author's declaration, not the substrate's fallback, so
5936 /// an author reading their graph output can grep their caixa.lisp
5937 /// for the exact list they authored) routes through.
5938 ///
5939 /// Prior to this lift the `.paths` field was accessed inline at four
5940 /// production sites: the two internal reads in [`Self::resolved_paths`]
5941 /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
5942 /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
5943 /// value-shape gate's `for p in &e.paths` traversal head, and the
5944 /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
5945 /// Debug print — four open-coded field-accesses that expressed no
5946 /// compile-time link back to the typed slot. A future extension of
5947 /// the `:entrada :paths` axis to a richer author surface — a
5948 /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
5949 /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
5950 /// spec supports through `matches[].method`), a per-path per-header
5951 /// filter overlay (`matches[].headers[]`), a per-cluster override
5952 /// the operator pins through a future `:placement :path-overlay`
5953 /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5954 /// per-CR admission-webhook that normalized the list at admission
5955 /// time — would have had to be threaded through every open-coded
5956 /// copy in lockstep or the validator's per-entry gate would silently
5957 /// disagree with the renderer's per-entry emit on which list a given
5958 /// `:entrada` block resolves to. Lifting the resolution to a typed
5959 /// method on the substrate primitive means every downstream consumer
5960 /// of the Aplicacao's per-`:entrada` path-list surface reaches for
5961 /// exactly one typed dispatch — the resolver's accept-set migrates
5962 /// as a unit on any future axis addition.
5963 ///
5964 /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
5965 /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
5966 /// carry axis — same "one typed dispatch on the substrate primitive,
5967 /// thin projections at each consumer" discipline extended onto the
5968 /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
5969 /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
5970 /// carrier) so every downstream per-`:entrada` reader now routes
5971 /// through a typed dispatch on the substrate primitive. Returns
5972 /// `&[String]` (not `&Vec<String>`) because every downstream consumer
5973 /// treats the list as a read-only sequence — the slice-view is the
5974 /// narrowest borrow that supports every present + roadmapped consumer
5975 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
5976 /// `Vec`'s grow/push/reserve surface that no consumer of the typed
5977 /// view reaches for (the storage-side `Vec` remains reachable through
5978 /// the `pub paths` field for the mutation-carrying serde round-trip
5979 /// and per-test fixture-mutation paths).
5980 #[must_use]
5981 pub fn paths(&self) -> &[String] {
5982 self.paths.as_slice()
5983 }
5984}
5985
5986/// Canonical default L4 port every typed Servico exposes on its
5987/// in-cluster K8s Service (the `trigger.service.port` axis the
5988/// `pleme-computeunit` library chart emits, the `:entrada :port` author
5989/// surface defaults to when the author omits the slot, and the
5990/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
5991/// `:entrada` block matches the per-`:contratos` destination Servico).
5992/// The single source of truth all three typed-port consumers reach for:
5993///
5994/// - [`Entrada::port`]'s serde default (via the
5995/// [`default_port`] helper this constant feeds); the author surface
5996/// `(:entrada (:host … :para …))` without an explicit `:port` slot
5997/// reads back as a typed [`Entrada`] carrying this exact value;
5998/// - the
5999/// [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6000/// emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6001/// fallback, fired when the typed `:entrada` block doesn't name
6002/// the per-`:contratos` destination Servico — the typed
6003/// `:contratos` graph carries no per-destination port axis (the
6004/// destination port is the destination Servico's
6005/// `lareira-<nome>` chart's `trigger.service.port`, which the
6006/// Aplicacao-level renderer has no visibility into without a
6007/// resolver round-trip), so the renderer falls back to the
6008/// substrate's canonical Servico-port assumption — by
6009/// construction the same value the destination's own
6010/// `pleme-computeunit` chart emits, the same value the
6011/// destination's own typed `:entrada :port` slot defaults to;
6012/// - every future per-Servico renderer the absorption-roadmap
6013/// acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6014/// CR materializer's per-edge port resolver, the future
6015/// per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6016/// emitter's per-route bucket key, the future caixa-otel
6017/// collector-pipeline emitter's per-Servico scrape port).
6018///
6019/// Until this lift landed the value `8080` lived at two production-code
6020/// call-sites: the [`default_port`] helper at
6021/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6022/// and the `.unwrap_or(8080)` literal at
6023/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6024/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6025/// resolver). A future Servico-port rebrand — the substrate moving the
6026/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6027/// gateway grows direct `:80` listeners, to `8443` once the substrate
6028/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6029/// override the operator pins through a future
6030/// `:placement :default-port` slot — without a coordinated edit on
6031/// both sides would silently emit Servicos listening on one port and
6032/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6033/// The CNP's apply-time symptom (the policy is admitted but every L4
6034/// flow on the destination Servico's actual port silently drops because
6035/// it doesn't match the whitelisted port) is far from the rebrand
6036/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6037/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6038/// a shared constant closes the drift footgun structurally — both
6039/// consumers read from the same `u16`, so any rebrand reaches both
6040/// sites by construction.
6041///
6042/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6043/// per-renderer canonical-K8s-axis constant — the namespace string
6044/// and the canonical Servico port both lived as duplicated literals
6045/// across caixa-core / caixa-mesh / caixa-flux before their respective
6046/// lifts. Same "the typed constant lives in one place" discipline the
6047/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6048/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6049/// shared-string axes.
6050///
6051/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6052pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6053
6054/// Structural floor for the typed `:entrada :port` axis — every
6055/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6056/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6057///
6058/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6059/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6060/// interprets as "let the kernel pick a free port at bind time", not a
6061/// well-defined destination the substrate's per-`:entrada` Gateway API
6062/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6063/// carrying `port: 0` degenerates to a nominal-only routing target: the
6064/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6065/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6066/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6067/// at build time rather than at `kubectl apply` time), and the
6068/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6069/// (caixa-mesh/src/lib.rs:2657 through
6070/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6071/// [`Entrada::port`] typed value — silently emits a policy whose
6072/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6073/// actual listener, dropping every L4 flow at the eBPF data plane far
6074/// from the source caixa.lisp with no field naming the port-zero-drift
6075/// root cause.
6076///
6077/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6078/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6079/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6080/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6081/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6082/// well below `u32::MAX` and therefore need explicit typed caps).
6083///
6084/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6085/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6086/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6087/// `:port` inherits through the serde default hook; this constant names
6088/// the accept-set floor every declared port must satisfy. The pair is
6089/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6090/// substrate's default must satisfy its own accept-set floor by
6091/// construction) — a future rebrand that accidentally moved
6092/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6093/// negative-cast typo, a per-cluster override the operator pins through
6094/// a future `:placement :default-port` slot that lands out-of-range)
6095/// would silently invalidate the serde-default emission at every
6096/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6097/// invariant pin
6098/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6099/// closes the drift footgun at caixa-core build time.
6100///
6101/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6102/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6103/// has exactly one source of truth — the future M4
6104/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6105/// gateway resolver, the future per-Servico
6106/// `computeunit.trigger.service.port` renderer's per-CR port-value
6107/// validator, and every downstream test-fixture navigator asserting
6108/// the accept-set floor all read from one place. Same shape every
6109/// other typed bracket-floor / bracket-ceiling in this crate carries
6110/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6111/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6112/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6113/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6114/// [`POLICY_RATE_LIMIT_MAX`]).
6115pub const SERVICO_PORT_MIN: u16 = 1;
6116
6117const fn default_port() -> u16 {
6118 DEFAULT_SERVICO_PORT
6119}
6120
6121// ── the typed view ───────────────────────────────────────────────────
6122
6123/// Typed composition view of the flat Aplicacao slots on
6124/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6125/// validation + downstream renderer consumption.
6126#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6127#[serde(rename_all = "camelCase")]
6128pub struct AplicacaoSpec {
6129 pub membros: Vec<Membro>,
6130 pub contratos: Vec<WitContract>,
6131 pub politicas: MeshPolicy,
6132 pub placement: Placement,
6133 pub entrada: Option<Entrada>,
6134}
6135
6136impl AplicacaoSpec {
6137 /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6138 /// per-Aplicacao member-list slice-return accessor every
6139 /// per-Aplicacao member-list reader keys off — returns the author-
6140 /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6141 /// over the same backing buffer the raw `self.membros.as_slice()`
6142 /// field access borrows from.
6143 ///
6144 /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6145 /// member list — the load-bearing identity of the application graph
6146 /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6147 /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6148 /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6149 /// accessor) with a `:versao` semver-requirement string (through
6150 /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6151 /// and every downstream consumer that fans on the member-set keys
6152 /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6153 /// membership-lookup `HashSet<&str>` seed's collect input, the
6154 /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6155 /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6156 /// per-member DNS-1123 / semver-requirement / duplicate-detection
6157 /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
6158 /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
6159 /// programs.yaml per-`:membros` fan-out emitter's per-entry
6160 /// mapping-composition loop, the `feira app graph` per-Aplicacao
6161 /// member-count print line and per-member tree traversal,
6162 /// every future wasm-operator (M4) per-Aplicacao CR materializer's
6163 /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
6164 /// placement engine's per-member weight-topology reader).
6165 ///
6166 /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
6167 /// inline at six production sites — the [`AplicacaoSpec::validate`]
6168 /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
6169 /// [`AplicacaoSpec::validate_membros`]'s pre-flight
6170 /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
6171 /// probe, the same method's per-member `for m in &self.membros`
6172 /// validate-loop traversal head, the
6173 /// [`AplicacaoSpec::detect_sync_cycles`]'s
6174 /// `for m in &self.membros` adjacency-list seed, the
6175 /// [`caixa_mesh::programs_for_aplicacao`] emitter's
6176 /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
6177 /// paired with the peer `for m in &spec.membros` per-entry fan-out
6178 /// loop, and the `feira app graph` per-Aplicacao print line's
6179 /// `spec.membros.len()` count formatter argument paired with the
6180 /// peer `for m in &spec.membros` per-member tree traversal — six
6181 /// open-coded field-accesses that expressed no compile-time link
6182 /// back to the typed slot. A future extension of the `:membros`
6183 /// axis to a richer author surface (a per-cluster member-set
6184 /// overlay the operator pins through a future
6185 /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
6186 /// roadmap acknowledges, a per-tenant member-alias table the M4
6187 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
6188 /// CR at admission time, a per-Aplicacao dynamic member-set
6189 /// derivation the future adaptive-placement engine computes from
6190 /// weighted membership topology, a promotion of the plain
6191 /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
6192 /// Orleans-style virtual-actor dynamic-membership comes into typed
6193 /// scope) would have had to be threaded through all six open-coded
6194 /// copies in lockstep or one consumer would silently disagree with
6195 /// the peers on which member-set a given Aplicacao resolves to —
6196 /// the `HashSet<&str>` name-set seed reading the raw slot while
6197 /// the peer `.is_empty()` refusal probe read an operator-resolved
6198 /// slot would silently split the `:contratos` membership-lookup
6199 /// input from the pre-flight-refusal input, a six-consumer split
6200 /// at the validator + programs.yaml emitter + graph printer far
6201 /// from the source `caixa.lisp` with no field naming the member-
6202 /// set-drift root cause. Lifting the resolution rule to a typed
6203 /// method on the substrate primitive means every downstream
6204 /// consumer of the Aplicacao's per-`:membros` member-list surface
6205 /// reaches for exactly one typed dispatch — the resolver's accept-
6206 /// set migrates as a unit on any future axis addition.
6207 ///
6208 /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
6209 /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6210 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6211 /// static-child-list `Vec`-carry axis, and to the M3
6212 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6213 /// on the peer per-`:placement` distribution-target-list `Vec`-
6214 /// carry axis. Same "one typed dispatch on the substrate primitive,
6215 /// thin projections at each consumer" discipline. The two peer
6216 /// `Vec`-carry axes still unlifted at the time of this lift —
6217 /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
6218 /// WIT-typed edge list) and
6219 /// [`crate::UpgradeFromEntry::instructions`]
6220 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6221 /// — inherit this accessor's discipline as future compounding runs
6222 /// migrate their consumers onto the shared slice-return shape.
6223 /// First `&[T]`-return accessor on the top-level M3 mesh-slot
6224 /// `AplicacaoSpec` type itself, extending the discipline beyond
6225 /// the inner per-slot types ([`crate::Placement`],
6226 /// [`crate::SupervisorSpec`]) onto the outermost typed composition
6227 /// view every renderer consumes. Named `membros()` to match the
6228 /// storage field's name verbatim and the tatara-lisp author-
6229 /// surface term (`:membros`) the field's own docstring already
6230 /// carries; the accessor's identity maps onto the canonical
6231 /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
6232 /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
6233 /// every downstream consumer of the member list treats it as a
6234 /// read-only sequence — the slice-view is the narrowest borrow
6235 /// that supports every present + roadmapped consumer
6236 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6237 /// backing `Vec`'s grow/push/reserve surface that no consumer of
6238 /// the typed view reaches for (the storage-side `Vec` remains
6239 /// reachable through the `pub membros` field for the mutation-
6240 /// carrying serde round-trip and per-test fixture-mutation paths).
6241 #[must_use]
6242 pub fn membros(&self) -> &[Membro] {
6243 self.membros.as_slice()
6244 }
6245
6246 /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
6247 /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
6248 /// accessor every per-Aplicacao contract-list reader keys off —
6249 /// returns the author-declared `:contratos` list verbatim as a
6250 /// `&[WitContract]` slice-view over the same backing buffer the raw
6251 /// `self.contratos.as_slice()` field access borrows from.
6252 ///
6253 /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
6254 /// WIT-typed edge list — the load-bearing set of directed edges
6255 /// on the application graph whose nodes are the `:membros` entries
6256 /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
6257 /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
6258 /// six-tuple is the edge identity every downstream duplicate gate
6259 /// keys off). Every per-`:contratos` entry pairs a `:de` source-
6260 /// Servico caller name + a `:para` destination-Servico callee name
6261 /// (through the lifted [`WitContract::source`] +
6262 /// [`WitContract::destination`] (7f0fd43) accessor pair on the
6263 /// caller/callee-Servico axis) with a `:wit` world-reference
6264 /// (through the lifted [`WitContract::world_ref`] (0804823)
6265 /// accessor) and the target-shape-appropriate payload-carrier
6266 /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
6267 /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
6268 /// (ed22b66) accessor on the per-target-shape payload-carrier
6269 /// axis). Every downstream consumer that fans on the edge-set
6270 /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
6271 /// name-set / self-edge / target-shape / dedup fan-out loop, the
6272 /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
6273 /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
6274 /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
6275 /// grouping loop, the `feira app graph` per-Aplicacao contract-
6276 /// count print line and per-contract tree traversal, every future
6277 /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
6278 /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
6279 /// mesh-policy overlay resolver's per-contract typed-edge weight
6280 /// reader).
6281 ///
6282 /// Prior to this lift the `.contratos` `Vec<WitContract>` was
6283 /// accessed inline at four production sites — the
6284 /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
6285 /// per-edge validate-loop traversal head (which drives every
6286 /// per-edge name-set membership lookup, self-edge check,
6287 /// target-shape dispatch, and dedup `HashSet` insert), the
6288 /// [`AplicacaoSpec::detect_sync_cycles`]'s
6289 /// `for c in &self.contratos` adjacency-list seed head (which
6290 /// drives every per-edge sync-vs-pub-sub partition and per-edge
6291 /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
6292 /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
6293 /// `BTreeMap` grouping loop head (which drives every per-CNP
6294 /// fan-out emit), and the `feira app graph` per-Aplicacao print
6295 /// line's `spec.contratos.len()` count formatter argument paired
6296 /// with the peer `for c in &spec.contratos` per-contract tree
6297 /// traversal — four open-coded field-accesses that expressed no
6298 /// compile-time link back to the typed slot. A future extension
6299 /// of the `:contratos` axis to a richer author surface (a
6300 /// per-cluster contract overlay the operator pins through a
6301 /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
6302 /// federation roadmap acknowledges, a per-tenant edge-policy
6303 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6304 /// materializer resolves per-CR at admission time, a per-edge
6305 /// weight scalar the future adaptive-placement engine reads to
6306 /// bias sync-subgraph routing, a promotion of the plain
6307 /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
6308 /// once virtual-actor-style dynamic-edge composition comes into
6309 /// typed scope) would have had to be threaded through all four
6310 /// open-coded copies in lockstep or one consumer would silently
6311 /// disagree with the peers on which edge-set a given Aplicacao
6312 /// resolves to — the validator's per-edge dedup `HashSet` seed
6313 /// reading the raw slot while the peer sync-cycle adjacency-list
6314 /// seed read an operator-resolved slot would silently split the
6315 /// build-time edge-set gate from the runtime deadlock-detection
6316 /// gate, a four-consumer split at the validator, the cycle
6317 /// detector, the CNP emitter, and the graph printer far from
6318 /// the source `caixa.lisp` with no field naming the edge-set-
6319 /// drift root cause. Lifting the resolution rule to a typed method on the
6320 /// substrate primitive means every downstream consumer of the
6321 /// Aplicacao's per-`:contratos` edge-list surface reaches for
6322 /// exactly one typed dispatch — the resolver's accept-set
6323 /// migrates as a unit on any future axis addition.
6324 ///
6325 /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
6326 /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6327 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6328 /// static-child-list `Vec`-carry axis, to the M3
6329 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6330 /// on the peer per-`:placement` distribution-target-list `Vec`-
6331 /// carry axis, and to the immediately-adjacent sibling M3
6332 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
6333 /// the peer per-`:membros` node-list `Vec`-carry axis — the
6334 /// per-`:contratos` edge-list accessor is the natural pair of
6335 /// the per-`:membros` node-list accessor (graph edges over graph
6336 /// nodes; every graph-shaped consumer reads both). Same "one
6337 /// typed dispatch on the substrate primitive, thin projections
6338 /// at each consumer" discipline. The last remaining `Vec`-carry
6339 /// axis still unlifted at the time of this lift —
6340 /// [`crate::UpgradeFromEntry::instructions`]
6341 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
6342 /// list) — inherits this accessor's discipline as future
6343 /// compounding runs migrate its consumers onto the shared slice-
6344 /// return shape. Second `&[T]`-return accessor on the top-level
6345 /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
6346 /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
6347 /// `:contratos` are the two `Vec` fields on the outer typed
6348 /// composition view — `:politicas`, `:placement`, `:entrada` are
6349 /// scalar/option-shaped and already route through their per-slot
6350 /// accessor families). Named `contratos()` to match the storage
6351 /// field's name verbatim and the tatara-lisp author-surface term
6352 /// (`:contratos`) the field's own docstring already carries; the
6353 /// accessor's identity maps onto the canonical MESH-COMPOSITION
6354 /// §III.1 vocabulary the slot's docstring already reaches for.
6355 /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
6356 /// every downstream consumer of the contract list treats it as a
6357 /// read-only sequence — the slice-view is the narrowest borrow
6358 /// that supports every present + roadmapped consumer
6359 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6360 /// backing `Vec`'s grow/push/reserve surface that no consumer of
6361 /// the typed view reaches for (the storage-side `Vec` remains
6362 /// reachable through the `pub contratos` field for the mutation-
6363 /// carrying serde round-trip and per-test fixture-mutation paths).
6364 #[must_use]
6365 pub fn contratos(&self) -> &[WitContract] {
6366 self.contratos.as_slice()
6367 }
6368
6369 /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
6370 /// per-Aplicacao mesh-policy composite-reference accessor every
6371 /// per-Aplicacao policy-block reader keys off — returns the author-
6372 /// declared `:politicas` composite verbatim as a `&MeshPolicy`
6373 /// reference over the same backing storage the raw `&self.politicas`
6374 /// field access borrows from.
6375 ///
6376 /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
6377 /// mesh-policy composite — the load-bearing container of every
6378 /// mesh-level operational-policy axis every downstream mesh-artifact
6379 /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6380 /// mesh-policy overlay is the single typed surface a
6381 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6382 /// from). Every per-`:politicas` axis threads through a lifted
6383 /// per-slot accessor on the [`MeshPolicy`] type: the
6384 /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6385 /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6386 /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6387 /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6388 /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6389 /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6390 /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6391 /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6392 /// accessor. Every downstream consumer that reaches for a policy
6393 /// axis first passes through this outer accessor onto the composite
6394 /// and then dispatches onto the per-axis accessor — the two-level
6395 /// dispatch means every per-`:politicas` reader now routes through
6396 /// a typed dispatch on the substrate primitive at both altitudes.
6397 ///
6398 /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6399 /// accessed inline at four production sites — the
6400 /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6401 /// &self.politicas;` traversal seed (which drives every per-axis
6402 /// zero-floor + upper-cap + canonical-form bracket dispatch through
6403 /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6404 /// `p.rate_limit()` on the axis-level lifted accessors), the
6405 /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6406 /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6407 /// chain (which drives every per-`(:de, :para)` CNP
6408 /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6409 /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6410 /// timeout + retry overlay emitter's paired
6411 /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6412 /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6413 /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6414 /// open-coded outer-field accesses that expressed no compile-time
6415 /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6416 /// future extension of the `:politicas` outer axis to a richer
6417 /// author surface (a per-cluster policy overlay the operator pins
6418 /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6419 /// §V federation roadmap acknowledges, a per-tenant policy-alias
6420 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6421 /// resolves per-CR at admission time, a per-Aplicacao dynamic
6422 /// policy-composite derivation the future adaptive-placement engine
6423 /// computes from a per-cluster load-topology reader, a promotion of
6424 /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6425 /// partition once virtual-actor-style dynamic-mesh-policy
6426 /// composition comes into typed scope) would have had to be threaded
6427 /// through all four open-coded copies in lockstep or one consumer
6428 /// would silently disagree with the peers on which mesh-policy
6429 /// composite a given Aplicacao resolves to — the validator's
6430 /// per-axis bracket-dispatch seed reading the raw slot while the
6431 /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6432 /// would silently split the build-time policy-shape gate from the
6433 /// runtime CNP-emission gate, a four-consumer split at the
6434 /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6435 /// the source `caixa.lisp` with no field naming the policy-drift
6436 /// root cause. Lifting the resolution rule to a typed method on the
6437 /// substrate primitive means every downstream consumer of the
6438 /// Aplicacao's per-`:politicas` mesh-policy composite surface
6439 /// reaches for exactly one typed dispatch — the resolver's accept-
6440 /// set migrates as a unit on any future axis addition.
6441 ///
6442 /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6443 /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6444 /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6445 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6446 /// close the two `Vec`-carry axes on the outer typed composition
6447 /// view; the outer `:politicas` composite-reference axis is the
6448 /// natural pair to the paired outer `Vec`-carry accessors on the
6449 /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6450 /// emitter reads all four axes as one unit (graph nodes + graph
6451 /// edges + mesh policy + placement pool). Peer to the same
6452 /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6453 /// slot: every M2 `SupervisorSpec`-scoped composite reader
6454 /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6455 /// `restart_window`, `children`) already routes through the M2
6456 /// `SupervisorSpec` accessor family — this lift extends the same
6457 /// "one typed dispatch on the substrate primitive at the outer
6458 /// composition altitude" discipline to the M3 mesh-slot
6459 /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6460 /// remaining peer outer-composite axes still unlifted at the time
6461 /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6462 /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6463 /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6464 /// inherit this accessor's discipline as future compounding runs
6465 /// migrate their consumers onto the shared reference-return shape.
6466 /// Named `politicas()` to match the storage field's name verbatim
6467 /// and the tatara-lisp author-surface term (`:politicas`) the
6468 /// field's own docstring already carries; the accessor's identity
6469 /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6470 /// slot's docstring already reaches for. Returns `&MeshPolicy`
6471 /// (not the owning composite by copy or clone) because every
6472 /// downstream consumer of the mesh-policy composite treats it as a
6473 /// read-only per-axis dispatch source — the reference-view is the
6474 /// narrowest borrow that supports every present + roadmapped
6475 /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6476 /// emptiness probe) without cloning the composite through every
6477 /// consumer's fast path.
6478 #[must_use]
6479 pub fn politicas(&self) -> &MeshPolicy {
6480 &self.politicas
6481 }
6482
6483 /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6484 /// per-Aplicacao distribution-composite composite-reference accessor
6485 /// every per-Aplicacao placement-block reader keys off — returns the
6486 /// author-declared `:placement` composite verbatim as a `&Placement`
6487 /// reference over the same backing storage the raw `&self.placement`
6488 /// field access borrows from.
6489 ///
6490 /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6491 /// distribution composite — the load-bearing container of every
6492 /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6493 /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6494 /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6495 /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6496 /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6497 /// `:affinity` hint). Every per-`:placement` axis threads through a
6498 /// lifted per-slot accessor on the [`Placement`] type: the
6499 /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6500 /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6501 /// per-cluster distribution-target slice-return accessor, the
6502 /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6503 /// optional-scalar accessor, and the [`Placement::shard_key`]
6504 /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6505 /// downstream consumer that reaches for a placement axis first passes
6506 /// through this outer accessor onto the composite and then dispatches
6507 /// onto the per-axis accessor — the two-level dispatch means every
6508 /// per-`:placement` reader now routes through a typed dispatch on the
6509 /// substrate primitive at both altitudes.
6510 ///
6511 /// Prior to this lift the `.placement` `Placement` composite was
6512 /// accessed inline at three production sites — the
6513 /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6514 /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6515 /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6516 /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6517 /// cluster `.clusters()` validate-loop traversal head, the per-
6518 /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6519 /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6520 /// paired with the shape-gate cascade's `.shard_key()` /
6521 /// `.estrategia()` diagnostic-carry pair), the
6522 /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6523 /// per-entry placement-block emitter's outer
6524 /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6525 /// seed (which fans onto every per-cluster `programs[]` entry as a
6526 /// self-describing distribution overlay the aggregator filters by),
6527 /// and the `feira app graph` per-Aplicacao print line's paired
6528 /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6529 /// then-inner-accessor chains (which drive the human-readable
6530 /// distribution summary of the typed Aplicacao view) — three open-
6531 /// coded outer-field accesses that expressed no compile-time link
6532 /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6533 /// extension of the `:placement` outer axis to a richer author surface
6534 /// (a per-cluster placement overlay the operator pins through a
6535 /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6536 /// federation roadmap acknowledges, a per-tenant placement-alias
6537 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6538 /// resolves per-CR at admission time, a per-Aplicacao dynamic
6539 /// placement-composite derivation the future M5 adaptive-placement
6540 /// engine computes from a per-cluster load-topology reader, a
6541 /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6542 /// partition once Orleans-style virtual-actor dynamic-placement comes
6543 /// into typed scope) would have had to be threaded through all three
6544 /// open-coded copies in lockstep or one consumer would silently
6545 /// disagree with the peers on which placement composite a given
6546 /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6547 /// seed reading the raw slot while the peer
6548 /// `programs_for_aplicacao` emitter read an operator-resolved slot
6549 /// would silently split the build-time distribution-shape gate from
6550 /// the runtime programs.yaml distribution-annotation gate, a three-
6551 /// consumer split at the validator, the programs.yaml emitter, and
6552 /// the `feira app graph` printer far from the source `caixa.lisp`
6553 /// with no field naming the placement-drift root cause. Lifting the
6554 /// resolution rule to a typed method on the substrate primitive
6555 /// means every downstream consumer of the Aplicacao's per-
6556 /// `:placement` distribution composite surface reaches for exactly
6557 /// one typed dispatch — the resolver's accept-set migrates as a unit
6558 /// on any future axis addition.
6559 ///
6560 /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6561 /// `AplicacaoSpec` type itself — sibling to the seed
6562 /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6563 /// composite-reference accessor on the peer per-`:politicas` outer-
6564 /// composite axis, and to the paired slice-return accessors
6565 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6566 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6567 /// the two `Vec`-carry axes on the outer typed composition view; the
6568 /// outer `:placement` composite-reference axis is the natural pair
6569 /// to the peer `:politicas` composite-reference axis on the two
6570 /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6571 /// how-to-run policy overlay, `:placement` carries the where-to-run
6572 /// distribution composite — every whole-Aplicacao mesh-artifact
6573 /// emitter reads both as one unit). Same "one typed dispatch on the
6574 /// substrate primitive, thin projections at each consumer"
6575 /// discipline the peer per-`:politicas` composite-reference axis
6576 /// already routes through. The one remaining outer-composite axis
6577 /// still unlifted at the time of this lift —
6578 /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6579 /// external-gateway composite) — inherits this accessor's discipline
6580 /// as the next compounding run migrates its consumers onto the shared
6581 /// reference-return shape, closing the outer-composite altitude on
6582 /// every M3 mesh-slot axis. Named `placement()` to match the storage
6583 /// field's name verbatim and the tatara-lisp author-surface term
6584 /// (`:placement`) the field's own docstring already carries; the
6585 /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6586 /// vocabulary the slot's docstring already reaches for. Returns
6587 /// `&Placement` (not the owning composite by copy or clone) because
6588 /// every downstream consumer of the placement composite treats it as
6589 /// a read-only per-axis dispatch source — the reference-view is the
6590 /// narrowest borrow that supports every present + roadmapped consumer
6591 /// (per-axis accessor dispatch, serde composite-serialization) without
6592 /// cloning the composite through every consumer's fast path.
6593 #[must_use]
6594 pub fn placement(&self) -> &Placement {
6595 &self.placement
6596 }
6597
6598 /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6599 /// per-Aplicacao external-gateway composite optional-composite-
6600 /// reference accessor every per-Aplicacao gateway-block reader
6601 /// keys off — returns the author-declared `:entrada` composite
6602 /// verbatim as an `Option<&Entrada>` reference over the same
6603 /// backing storage the raw `self.entrada.as_ref()` field access
6604 /// borrows from, with `None` naming the internal-only mesh shape
6605 /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6606 /// gateway_routes emitter treats as "emit nothing" and the peer
6607 /// `feira app graph` printer treats as "internal-only mesh").
6608 ///
6609 /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6610 /// external-gateway composite — the load-bearing container of
6611 /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6612 /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6613 /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6614 /// hostname axis, §III.4 for the `:para` destination-Servico
6615 /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6616 /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6617 /// axis threads through a lifted per-slot accessor on the
6618 /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6619 /// Gateway-API `Listener.hostname` scalar accessor, the paired
6620 /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6621 /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6622 /// backendRefs destination-Servico scalar accessor, the
6623 /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6624 /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6625 /// scalar accessor. Every downstream consumer that reaches for
6626 /// an entrada axis first passes through this outer accessor onto
6627 /// the composite and then dispatches onto the per-axis accessor
6628 /// — the two-level dispatch means every per-`:entrada` reader
6629 /// now routes through a typed dispatch on the substrate primitive
6630 /// at both altitudes.
6631 ///
6632 /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6633 /// was accessed inline at four production sites — the
6634 /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6635 /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6636 /// (which drives every per-axis refusal on the composite: the
6637 /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6638 /// `EntradaMemberMissing` membership lookup against the
6639 /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6640 /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6641 /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6642 /// per-path shape gate on each entry of `e.paths`), the
6643 /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6644 /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6645 /// composite-projection seed (which drives the destination-
6646 /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6647 /// backendRefs port emitter fans on), the
6648 /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6649 /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6650 /// early-return seed (which drives the "no `:entrada` ⇒ no
6651 /// external artifacts" partition on the whole-Aplicacao Gateway-
6652 /// API emitter's fan-out), and the `feira app graph` per-
6653 /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6654 /// external-gateway summary emitter (which drives the human-
6655 /// readable `entrada: host → para (paths=…, port=…)` /
6656 /// `entrada: (internal-only mesh)` partition on the typed
6657 /// Aplicacao view) — four open-coded outer-field accesses that
6658 /// expressed no compile-time link back to the typed slot at the
6659 /// [`AplicacaoSpec`] altitude. A future extension of the
6660 /// `:entrada` outer axis to a richer author surface (a
6661 /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6662 /// at admission time so an Aplicacao can expose a public-web +
6663 /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6664 /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6665 /// operator can pin a per-cluster hostname override without
6666 /// re-authoring the `caixa.lisp`, a promotion of the plain
6667 /// `Option<Entrada>` to a richer `{single, multi}` partition once
6668 /// the multi-`:entrada` roadmap lands) would have had to be
6669 /// threaded through all four open-coded copies in lockstep or one
6670 /// consumer would silently disagree with the peers on which
6671 /// entrada composite a given Aplicacao resolves to — the
6672 /// validator's per-axis bracket-dispatch seed reading the raw
6673 /// slot while the peer `gateway_routes` emitter read an
6674 /// operator-resolved slot would silently split the build-time
6675 /// gateway-shape gate from the runtime Gateway + HTTPRoute
6676 /// emission gate, a four-consumer split at the validator, the
6677 /// `port_for_destination` L4-port resolver, the `gateway_routes`
6678 /// emitter, and the `feira app graph` printer far from the
6679 /// source `caixa.lisp` with no field naming the entrada-drift
6680 /// root cause. Lifting the resolution rule to a typed method on
6681 /// the substrate primitive means every downstream consumer of
6682 /// the Aplicacao's per-`:entrada` external-gateway composite
6683 /// surface reaches for exactly one typed dispatch — the
6684 /// resolver's accept-set migrates as a unit on any future axis
6685 /// addition.
6686 ///
6687 /// Third and final `&Composite`-return accessor on the top-level
6688 /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
6689 /// unlifted outer-composite axis on the outer typed composition
6690 /// view, sibling to the seed [`AplicacaoSpec::politicas`]
6691 /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
6692 /// accessor on the per-`:politicas` outer-composite axis and to
6693 /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
6694 /// distribution-composite composite-reference accessor on the
6695 /// per-`:placement` outer-composite axis; extends the outer-
6696 /// composite reference-return discipline the two peers already
6697 /// route through onto the last unlifted per-`AplicacaoSpec`
6698 /// outer-composite axis. The `:entrada` outer-composite axis is
6699 /// the natural pair to the two peer outer-composite axes on the
6700 /// three operationally-symmetric M3 mesh-slot outer composites
6701 /// (`:politicas` carries the how-to-run policy overlay,
6702 /// `:placement` carries the where-to-run distribution composite,
6703 /// `:entrada` carries the who-can-reach-it external-gateway
6704 /// composite — every whole-Aplicacao mesh-artifact emitter reads
6705 /// all three as one unit). Same "one typed dispatch on the
6706 /// substrate primitive, thin projections at each consumer"
6707 /// discipline the peer outer-composite axes already route through.
6708 /// Named `entrada()` to match the storage field's name verbatim
6709 /// and the tatara-lisp author-surface term (`:entrada`) the
6710 /// field's own docstring already carries; the accessor's
6711 /// identity maps onto the canonical MESH-COMPOSITION §III.4
6712 /// vocabulary the slot's docstring already reaches for. Returns
6713 /// `Option<&Entrada>` (not the owning composite by copy or
6714 /// clone) because every downstream consumer of the entrada
6715 /// composite treats it as a read-only per-axis dispatch source
6716 /// — the reference-view is the narrowest borrow that supports
6717 /// every present + roadmapped consumer (per-axis accessor
6718 /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
6719 /// port-fallback projection, early-return partition on the
6720 /// `None` arm) without cloning the composite through every
6721 /// consumer's fast path. The `Option` half of the return-type
6722 /// preserves the load-bearing "author-omitted `:entrada` ⇒
6723 /// internal-only mesh" partition (not a default composite the
6724 /// downstream must reject on emptiness) — the accessor projects
6725 /// the raw `Option<Entrada>` slot's presence bit through the
6726 /// reference-return unchanged.
6727 #[must_use]
6728 pub fn entrada(&self) -> Option<&Entrada> {
6729 self.entrada.as_ref()
6730 }
6731
6732 /// Validate the typed shape:
6733 /// - `:membros` is non-empty; every entry has a non-empty `:caixa`
6734 /// and a non-empty `:versao`; no two entries share the same
6735 /// `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
6736 /// not a multiset)
6737 /// - every `:contratos` :de + :para must be in `:membros`
6738 /// - no `:contratos` edge is a self-edge (`:de == :para`) — a
6739 /// contract is an inter-Servico edge, so a Servico contracting
6740 /// with itself is a build error under every WIT shape
6741 /// (MESH-COMPOSITION §III.1)
6742 /// - no two `:contratos` entries agree on
6743 /// `(de, para, wit, endpoint, subject, slot)` — the typed-graph
6744 /// edges are a set, not a multiset (peer of the `:membros` /
6745 /// `:placement :clusters` / `:entrada :paths` duplicate gates)
6746 /// - `:entrada :para` must be in `:membros`
6747 /// - `:placement Sharded` must declare `:shard-key` (non-empty);
6748 /// `:placement Replicated`/`SingleNode` must NOT declare
6749 /// `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
6750 /// consumes it (MESH-COMPOSITION §II.4), and the typed partition
6751 /// between strategy and shard-key is symmetric: every validated
6752 /// `Placement` has `shard_key.is_some()` iff `estrategia ==
6753 /// Sharded`
6754 /// - every `:placement` strategy must declare ≥1 `:clusters` entry —
6755 /// `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
6756 /// the shard pool (MESH-COMPOSITION §III.1)
6757 /// - every `:clusters` entry is non-empty and unique
6758 /// - `:placement :affinity`, when set, is non-empty
6759 /// - the synchronous-`:contratos` subgraph is acyclic
6760 /// (MESH-COMPOSITION §III.3)
6761 /// - every declared `:politicas` value is operationally meaningful
6762 /// (zero timeout, zero retries, zero breaker thresholds, zero rate
6763 /// limit are all build errors — MESH-COMPOSITION §V CSE invariants;
6764 /// omit the field instead to express "no policy on this axis")
6765 pub fn validate(&self) -> Result<(), AplicacaoError> {
6766 self.validate_membros()?;
6767 let names: std::collections::HashSet<&str> =
6768 self.membros().iter().map(Membro::nome).collect();
6769
6770 // Identity key for the typed-edge duplicate gate below: every
6771 // field that distinguishes one contract from another. Two
6772 // entries that agree on all six are *the same edge declared
6773 // twice*, the typed-graph analogue of duplicate `:membros` /
6774 // `:placement :clusters` / `:entrada :paths` entries (which
6775 // are already build errors at this layer). Rejecting it at the
6776 // validate gate closes a renderer-side footgun: caixa-mesh's
6777 // `cilium_network_policies` keys each emitted policy by
6778 // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
6779 // (de, para) and identical payload would land as two K8s
6780 // objects with colliding `metadata.name`, rejected at apply
6781 // time far from the source caixa.lisp.
6782 let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
6783 std::collections::HashSet::new();
6784 for c in self.contratos() {
6785 // Per-axis value-shape gate on every `:contratos` name
6786 // reference, before any graph-membership lookup. Empty +
6787 // DNS-1123-malformed `:de`/`:para` values silently fell
6788 // through to `ContratoMemberMissing` at the lookup arm
6789 // because every `:membros :caixa` is shape-validated
6790 // (3f9d7a0), so the `names` set structurally cannot contain
6791 // an empty / malformed string and the membership-lookup
6792 // diagnostic always misframed the root cause as
6793 // "this caixa is not in `:membros`". The shape gate runs
6794 // ahead of the lookup so structurally-impossible-to-match
6795 // inputs route through the narrower self-locating
6796 // diagnostic, preserving the legitimate "well-shaped
6797 // phantom reference" arm. `:de` runs before `:para` per
6798 // the canonical edge-direction order the existing
6799 // membership lookup, self-edge check, target dispatch,
6800 // and diagnostic strings already use.
6801 // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
6802 // + the paired [`AplicacaoError::ContratoMemberMissing`]
6803 // diagnostic's `caixa:` carrier through the lifted
6804 // [`WitContract::source`] / [`WitContract::destination`]
6805 // scalar accessors rather than the raw `&c.de` / `&c.para`
6806 // `&String`-borrow arg site + the raw `c.de.clone()` /
6807 // `c.para.clone()` field-access `String`-carry sites — the
6808 // last unlifted per-`:contratos` raw-field-access sites in
6809 // the M3 mesh-slot validator's per-edge per-arm shape-gate
6810 // arg + phantom-name diagnostic wrap-envelope emit surface.
6811 // `c.source()` is byte-identical to `&c.de` (pinned by the
6812 // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
6813 // + `wit_contract_source_borrows_from_de_storage` accessor
6814 // tests) and `c.destination()` is byte-identical to `&c.para`
6815 // (pinned by the sibling
6816 // `wit_contract_destination_returns_para_byte_equal_across_permutations`
6817 // + `wit_contract_destination_borrows_from_para_storage`
6818 // accessor tests) — so a future rebrand of either underlying
6819 // storage flows through the accessor's one body without a
6820 // coordinated per-consumer rewrite across the M3 mesh
6821 // validator's per-edge shape-gate + phantom-name refusal
6822 // arms. Peer of the sibling per-`:contratos` self-loop
6823 // arm's `.source().to_string()` / `.world_ref().to_string()`
6824 // `String`-carry sites the earlier convergence lifted onto
6825 // the same accessor pair.
6826 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
6827 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
6828 if !names.contains(c.source()) {
6829 return Err(AplicacaoError::ContratoMemberMissing {
6830 caixa: c.source().to_string(),
6831 });
6832 }
6833 if !names.contains(c.destination()) {
6834 return Err(AplicacaoError::ContratoMemberMissing {
6835 caixa: c.destination().to_string(),
6836 });
6837 }
6838 // A `:contratos` entry is an *inter*-Servico contract
6839 // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
6840 // typed edge between two distinct graph nodes. An edge whose
6841 // `:de` equals its `:para` is a Servico contracting with
6842 // itself — a degenerate edge under every WIT shape. The
6843 // synchronous shapes were caught only incidentally, and with
6844 // a misleading diagnostic: `detect_sync_cycles` reported
6845 // `cart → cart` as a `ContratoCycle` whose path is
6846 // `["cart", "cart"]` — framing a self-edge as a multi-node
6847 // deadlock. The pub-sub shape slipped through entirely
6848 // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
6849 // `nats:pub-sub` edge from a member to itself silently
6850 // validated, then rendered a `CiliumNetworkPolicy` whose
6851 // endpointSelector and fromEndpoints both name the same
6852 // program — a self-allow rule that is a no-op, since
6853 // intra-pod traffic never traverses the mesh). A self-edge's
6854 // runtime meaning is an in-process call, which doesn't go
6855 // through the mesh at all, so no `:contratos` edge can carry
6856 // it. Firing the gate before the `:wit`/`target()` shape
6857 // checks means the structural "this edge can't exist" error
6858 // precedes the narrower payload-shape diagnostics, and shape-
6859 // agnostically covers all four `WitTarget` arms (HTTP / Store
6860 // / Capability / PubSub) at one point — closing the pub-sub
6861 // hole and replacing the misleading cycle diagnostic in one
6862 // gate. Peer of the duplicate-`:contratos` / duplicate-
6863 // `:membros` set gates: both reject a structurally
6864 // ill-formed graph at the typed surface, before the renderer
6865 // emits a K8s object that fails or no-ops far from the source
6866 // caixa.lisp.
6867 // Route the per-`:contratos` structural self-edge probe
6868 // through the lifted [`WitContract::is_self_loop`] typed
6869 // predicate rather than the raw `c.de == c.para` field-
6870 // equality check — the one production consumer of the per-
6871 // `:contratos` caller-equals-callee endpoint-equality axis
6872 // now keys off exactly one typed dispatch on the substrate
6873 // primitive, so any future rebrand of the axis (an M4-typed-
6874 // caller enum whose identity comparison rule the predicate
6875 // could route through, a per-cluster caller/callee-alias
6876 // table the M4 CR materializer resolves per-CR before the
6877 // equality probe) migrates as a single caixa-core edit
6878 // rather than a coordinated rewrite of the gate + every
6879 // downstream self-edge consumer. Peer of the sibling
6880 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
6881 // [`WitContract::is_store`] shape-predicate routing on the
6882 // `:wit` world-ref axis, extended onto the per-edge
6883 // endpoint-equality axis.
6884 //
6885 // Route the paired [`AplicacaoError::ContratoSelfLoop`]
6886 // diagnostic's `caixa:` / `wit:` carriers through the
6887 // lifted [`WitContract::source`] / [`WitContract::world_ref`]
6888 // scalar accessors rather than the raw `c.de.clone()` /
6889 // `c.wit.clone()` field-access `String`-carry sites — the
6890 // last unlifted per-`:contratos` raw-field-access
6891 // `.clone()` sites in the M3 mesh-slot validator's self-
6892 // edge refusal arm. `.source().to_string()` is byte-
6893 // identical to `.de.clone()` (pinned by the sibling
6894 // `source_returns_de_byte_equal_across_permutations` accessor
6895 // test), and `.world_ref().to_string()` is byte-identical
6896 // to `.wit.clone()` (pinned by the sibling
6897 // `world_ref_returns_wit_byte_equal_across_permutations`
6898 // accessor test) — so a future rebrand of either underlying
6899 // storage flows through the accessor's one body without a
6900 // coordinated per-consumer rewrite across the M3 mesh
6901 // validator.
6902 if c.is_self_loop() {
6903 return Err(AplicacaoError::ContratoSelfLoop {
6904 caixa: c.source().to_string(),
6905 wit: c.world_ref().to_string(),
6906 });
6907 }
6908 if c.world_ref().is_empty() {
6909 let (de, para) = c.edge_pair();
6910 return Err(AplicacaoError::EmptyWit { de, para });
6911 }
6912 // Shape ↔ target consistency — surfaces "HTTP wit without
6913 // :endpoint", "NATS wit with :endpoint set", etc. as named
6914 // build errors instead of silent renderer drops. Threaded
6915 // through the duplicate-edge diagnostic below (via
6916 // [`WitTarget::label`]) so the "which typed target arm did
6917 // the duplicate carry" question is answered by the typed
6918 // enum's variant discriminator, not by re-probing the raw
6919 // `Option<String>` payload fields.
6920 let target_view = c.target()?;
6921 // Contract identity: (de, para, wit, endpoint, subject, slot).
6922 // Two contracts that match on all six are the same typed edge
6923 // declared twice — author error, not a legitimate variant of
6924 // "same caller-callee pair, different payload" (e.g.
6925 // cart→catalog at /products vs /search), which keeps distinct
6926 // identity keys via the differing endpoint payloads.
6927 //
6928 // Route the six-axis dedup key through the lifted
6929 // [`WitContract::identity`] composite-projection accessor
6930 // rather than the inline six-tuple builder — the two
6931 // substrate primitives on the per-`:contratos` identity axis
6932 // (the [`ContratoIdentity`] type alias's six axes, this
6933 // dedup-key's six tuple arms) now migrate as a unit on any
6934 // future axis addition. Peer of the sibling per-`:contratos`
6935 // composite-projection [`WitContract::edge_pair`] /
6936 // [`WitContract::edge_triple`] accessors on the
6937 // caller-callee / caller-callee-wit prefix axes; extends
6938 // the discipline onto the full-identity axis that carries
6939 // the three payload-shape arms too.
6940 let key = c.identity();
6941 crate::render::insert_first_seen(&mut seen_contracts, key, || {
6942 // Route the per-`:contratos` duplicate-gate diagnostic's
6943 // `(de, para, wit)` triple through the lifted
6944 // [`WitContract::edge_triple`] typed accessor rather
6945 // than pairing `edge_pair()` for the `(de, para)` prefix
6946 // with a raw `c.wit.clone()` for the `wit:` tail — the
6947 // paired-with-raw-field-access shape was the last
6948 // per-`:contratos` diagnostic constructor bypassing the
6949 // substrate-primitive composite projection, sibling to
6950 // the eight [`AplicacaoError::Contrato*`] triple-
6951 // carrying constructors [`WitContract::target`]'s edge
6952 // closure feeds through the same accessor.
6953 let (de, para, wit) = c.edge_triple();
6954 AplicacaoError::ContratoDuplicate {
6955 de,
6956 para,
6957 wit,
6958 target: target_view.label(),
6959 }
6960 })?;
6961 }
6962
6963 // Cycles in the synchronous-edge subgraph are build errors
6964 // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
6965 // are "acyclic by construction" because the publisher fires
6966 // and forgets, so no caller blocks on a downstream that loops
6967 // back to it.
6968 self.detect_sync_cycles()?;
6969
6970 if let Some(e) = self.entrada() {
6971 // Route the per-`:entrada` composite-reference read
6972 // through the lifted [`AplicacaoSpec::entrada`] accessor
6973 // rather than the raw `&self.entrada` field access — the
6974 // shape-and-membership gate's traversal head is now the
6975 // canonical read-side surface every per-Aplicacao entrada
6976 // consumer routes through, closing the fourth of four
6977 // open-coded outer-field accesses on the per-`:entrada`
6978 // outer-composite axis.
6979 //
6980 // Shape gate on `:entrada :para` runs ahead of the
6981 // membership lookup. Every `:membros :caixa` past
6982 // `validate_membro_caixa` is a valid DNS-1123 label
6983 // (3f9d7a0), so the `names` set structurally cannot
6984 // contain an empty / malformed string and the membership-
6985 // lookup diagnostic always misframed the root cause as
6986 // "this caixa is not in `:membros`". The shape gate
6987 // routes structurally-impossible-to-match inputs through
6988 // the narrower self-locating diagnostic, preserving the
6989 // legitimate "well-shaped phantom reference" arm — the
6990 // same trajectory the peer `:membros :caixa` (3f9d7a0),
6991 // `:placement :clusters` (6c8c00b), and `:contratos :de`
6992 // / `:para` (8d5af6b) axes already follow. This closes
6993 // the fourth and last Aplicacao-level Servico-name
6994 // reference axis on the canonical DNS-1123 floor.
6995 // Route the per-`:entrada :para` byte-string reads through
6996 // the lifted [`Entrada::destination`] accessor rather than
6997 // the raw `e.para` field access — the three
6998 // per-`AplicacaoSpec::validate` `:entrada :para` consumers
6999 // (shape-gate `validate_entrada_para` arg, membership
7000 // lookup, `EntradaMemberMissing` diagnostic carry) now key
7001 // off exactly one typed dispatch on the substrate
7002 // primitive, closing the last unlifted per-`:entrada :para`
7003 // raw-field-access axis on the M3 mesh-slot validator.
7004 // The `.destination().to_string()` at the diagnostic site
7005 // is byte-identical to `.para.clone()` — pinned by the
7006 // sibling `destination_returns_entrada_para_byte_equal` +
7007 // `destination_borrows_from_entrada_para_storage` accessor
7008 // tests — so a future rebrand of the underlying `:para`
7009 // storage (a lift from `String` to a typed
7010 // `ServicoName(String)` newtype, a per-Aplicacao interning
7011 // arena the M4 CR materializer authors, a
7012 // `smol_str::SmolStr` inline-buffer swap) flows through
7013 // the accessor's one body without a coordinated
7014 // per-consumer rewrite across the M3 mesh validator.
7015 validate_entrada_para(e.destination())?;
7016 if !names.contains(e.destination()) {
7017 return Err(AplicacaoError::EntradaMemberMissing {
7018 para: e.destination().to_string(),
7019 });
7020 }
7021 // Route the per-`:entrada :host` byte-string reads through
7022 // the lifted [`Entrada::hostname`] accessor rather than
7023 // the raw `e.host` field access — the emptiness gate and
7024 // the shape-gate `validate_entrada_host` arg now key off
7025 // exactly one typed dispatch on the substrate primitive,
7026 // closing the last unlifted per-`:entrada :host` raw-
7027 // field-access axis on the M3 mesh-slot validator. Peer
7028 // of the sibling per-`:entrada :para` convergence above
7029 // and pinned by the existing
7030 // `hostname_returns_entrada_host_byte_equal` +
7031 // `hostnames_returns_singleton_of_hostname_accessor`
7032 // accessor tests, so any future
7033 // Gateway-API-shaped host renormalization (a wildcard-
7034 // label lift, a trailing-`.` FQDN substitution, an IDNA
7035 // Punycode round-trip the SNI fan-out overlay authors)
7036 // flows through the accessor's one body without a
7037 // coordinated per-consumer rewrite across the M3 mesh
7038 // validator.
7039 if e.hostname().is_empty() {
7040 return Err(AplicacaoError::EmptyEntradaHost);
7041 }
7042 // The `:host` lands verbatim as a K8s Gateway API v1
7043 // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7044 // both apiserver-validated against the same restrictive
7045 // pattern: lowercase RFC 1123 DNS subdomain, optional
7046 // single leading wildcard label (`*.`), max length 253,
7047 // per-label max length 63, no IP literals, no scheme,
7048 // no port. Until this gate landed `validate()` only
7049 // refused the empty string (`EmptyEntradaHost`); a
7050 // structurally invalid hostname (`"https://example.com"`,
7051 // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
7052 // `"_underscored.example.com"`, `"FOO.example.com"`,
7053 // `"checkout.quero.cloud."`) silently passed validate
7054 // and the apiserver `field is invalid` error surfaced at
7055 // `kubectl apply` time, far from the source caixa.lisp.
7056 // Lifting the gate to caixa-build time mirrors the
7057 // `:entrada :paths` value-shape trajectory (eb3456d) and
7058 // closes the last unstructured `:entrada` axis.
7059 validate_entrada_host(e.hostname())?;
7060 // Structural-floor gate on `:entrada :port`: every
7061 // validated `Entrada::port` past this gate lies in
7062 // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
7063 // type-inferred ceiling closes the top edge, so no companion
7064 // upper-cap arm is needed here — unlike the peer capped-
7065 // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
7066 // `require_positive_bounded_u32` bracket covers both edges).
7067 // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
7068 // accept-set-floor const rather than the prior inline
7069 // `if e.port == 0` byte-check so a future rebrand of the
7070 // accept-set floor (a hypothetical unprivileged-only
7071 // migration lifting the floor to `1024`, a per-cluster
7072 // scoping the operator pins through a future
7073 // `:placement :port-floor` slot as the M4 typed-slot
7074 // trajectory adds it, the future
7075 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7076 // per-Aplicacao gateway resolver reaching for the same
7077 // floor) is a one-line edit on the canonical
7078 // [`SERVICO_PORT_MIN`] declaration, not a coordinated
7079 // rewrite across the emit site + the pin test + every
7080 // future per-target renderer the substrate adds.
7081 if e.port() < SERVICO_PORT_MIN {
7082 return Err(AplicacaoError::EntradaPortZero);
7083 }
7084 // Each `:entrada :paths` entry becomes a K8s Gateway API
7085 // HTTPRoute `matches[].path.value`. The Gateway API rejects
7086 // values that don't start with `/` for `type: PathPrefix`,
7087 // and an empty value is meaningless. Surface those as build
7088 // errors (MESH-COMPOSITION §III.3) rather than apply-time
7089 // failures. Empty `:paths` itself is fine — caixa-mesh
7090 // falls back to a single `/` catch-all.
7091 let mut seen = std::collections::HashSet::new();
7092 // Route the per-entry value-shape gate's traversal head
7093 // through the lifted [`Entrada::paths`] slice accessor
7094 // rather than the raw `&e.paths` field access — the
7095 // per-Aplicacao `:entrada :paths` validate loop now keys
7096 // off the canonical raw-slot surface every downstream
7097 // per-`:entrada` path-list consumer (the sibling
7098 // [`Entrada::resolved_paths`] fallback-applying resolver
7099 // internal reads, `feira app graph`'s per-Aplicacao entrada
7100 // summary line's `{:?}` Debug print) routes through, so any
7101 // future rebrand on the typed slot's raw-slot reader lands
7102 // at exactly one place. Same convergence discipline as the
7103 // sibling [`Placement::clusters`] (a6e18d7) reader-site
7104 // convergences on the peer M3 mesh-slot `Vec<String>`-carry
7105 // axis.
7106 for p in e.paths() {
7107 if p.is_empty() {
7108 return Err(AplicacaoError::EntradaPathEmpty);
7109 }
7110 if !p.starts_with('/') {
7111 return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
7112 }
7113 // Per-entry value-shape gate: the path lands verbatim
7114 // as a K8s Gateway API HTTPRoute `matches[].path.value`
7115 // (caixa-mesh/src/lib.rs:498), apiserver-validated
7116 // against `maxLength: 1024` + the Gateway API webhook's
7117 // path-grammar rules (no `//`, no `/./`, no `/../`, no
7118 // query/fragment separators, no whitespace, no control
7119 // characters, no non-ASCII bytes). Until this gate
7120 // landed `validate` only refused the empty string and
7121 // missing-leading-slash (eb3456d); a structurally
7122 // invalid path (`"/api?q=1"`, `"/api#frag"`,
7123 // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
7124 // 1025-byte URL-shaped slug) silently passed validate
7125 // and the failure surfaced at `kubectl apply` time as
7126 // a Gateway API webhook rejection, far from the source
7127 // caixa.lisp, with no field naming the offending
7128 // `:paths` entry. Lifting the gate to caixa-build time
7129 // mirrors the `:entrada :host` value-shape trajectory
7130 // (c7d05ec) on the sibling axis — every author surface
7131 // that emits a Gateway API field now matches the
7132 // apiserver's accepted set at validate time.
7133 validate_entrada_path(p)?;
7134 crate::render::insert_first_seen(&mut seen, p.as_str(), || {
7135 AplicacaoError::EntradaPathDuplicate { path: p.clone() }
7136 })?;
7137 }
7138 }
7139
7140 self.validate_placement()?;
7141
7142 self.validate_politicas()?;
7143
7144 Ok(())
7145 }
7146
7147 /// Reject `:membros` values that are operationally meaningless. The
7148 /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
7149 /// every entry names a Servico that participates in the Aplicacao,
7150 /// and the rendered programs.yaml fan-out emits one entry per
7151 /// `:membros`. Three authoring footguns are closed here:
7152 ///
7153 /// - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
7154 /// a `programs:` entry whose `name:` is the empty string, which
7155 /// downstream `lareira-fleet-programs` rejects at template time
7156 /// with a non-localized error;
7157 /// - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
7158 /// an empty semver constraint, so the failure surfaces far from
7159 /// the source caixa.lisp;
7160 /// - duplicate `:caixa` names — two entries with the same name
7161 /// produce duplicate programs.yaml entries (one silently
7162 /// overwrites the other in the cluster's HelmRelease values), and
7163 /// contract membership lookups against `:contratos` collapse the
7164 /// two onto one node, masking authoring mistakes.
7165 ///
7166 /// Same value-shape discipline as `:placement :clusters` (where empty
7167 /// + duplicate cluster names are rejected) and `:entrada :paths`
7168 /// (where empty + duplicate path entries are rejected). Lifting these
7169 /// invariants to the typed surface mirrors the MESH-COMPOSITION
7170 /// §III.3 promise that the `:membros` set — the load-bearing identity
7171 /// of the application graph — is well-formed by construction.
7172 fn validate_membros(&self) -> Result<(), AplicacaoError> {
7173 if self.membros().is_empty() {
7174 return Err(AplicacaoError::NoMembros);
7175 }
7176 let mut seen = std::collections::HashSet::new();
7177 for m in self.membros() {
7178 // Route the `MembroCaixaEmpty` refusal-arm's per-member
7179 // empty-`:caixa` shape-gate through the typed
7180 // [`Membro::nome`] accessor rather than the raw `.caixa`
7181 // field access — the last un-lifted `.caixa` production-
7182 // code read site on the per-`:membros` member-caixa `:nome`
7183 // axis, sibling to the six caixa-core validator read sites
7184 // (member-set collector, per-member value-shape gate,
7185 // duplicate dedup key, cycle-detector adjacency-map seed,
7186 // self-loop gate) the 4a32abf lift already routed through
7187 // the accessor and the peer 54bf2f3 caixa-mesh emit-side
7188 // per-`programs[]` entry-`name:` `String`-carry converge.
7189 // Prior to this converge the `MembroCaixaEmpty` refusal
7190 // arm was the solitary consumer bypassing the typed
7191 // dispatch — the same-loop iteration's very next call
7192 // `validate_membro_caixa(m.nome())` already routed through
7193 // the accessor, so an author landing an empty-`:caixa`
7194 // entry hit the accessor on the shape-gate line but
7195 // bypassed it on the emptiness line one line above. A
7196 // future extension of the `:membros :caixa` axis to a
7197 // richer author surface (a per-cluster alias table pinned
7198 // through a future `:placement`-scoped slot, a namespace-
7199 // qualified rewrite the M4 CR materializer applies per-CR,
7200 // a per-member overlay from the future `:membros
7201 // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
7202 // that lands on the accessor would silently disagree
7203 // between the emptiness gate and every peer consumer —
7204 // an author-declared `:caixa "checkout"` value the
7205 // accessor rewrote to `""` under a future alias arm would
7206 // pass the raw `.is_empty()` gate here while the peer
7207 // `validate_membro_caixa(m.nome())` call one line below
7208 // (and every downstream emit-side consumer routing through
7209 // the accessor) tripped on the empty-value shape far from
7210 // this diagnostic. Pinned by the drift-detection test
7211 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
7212 // below.
7213 if m.nome().is_empty() {
7214 return Err(AplicacaoError::MembroCaixaEmpty);
7215 }
7216 // Every emitted cluster artifact's `metadata.name` derives
7217 // from a `:membros :caixa` value verbatim — the rendered
7218 // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
7219 // the [`crate::LABEL_PROGRAM`] label value on every CNP
7220 // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
7221 // 272), the composed `CiliumNetworkPolicy` `metadata.name`
7222 // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
7223 // `metadata.name` when the member is the `:entrada :para`
7224 // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
7225 // schema enforces the DNS-1123 label rule on admission;
7226 // a structurally invalid member name (`"Cart"`, `"my_cart"`,
7227 // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
7228 // mistaken-identity slug) silently passes the prior empty-/
7229 // duplicate-only gate and the failure surfaces at `kubectl
7230 // apply` time as a `metadata.name: Invalid value` rejection,
7231 // far from the source caixa.lisp, with no field naming the
7232 // offending `:membros` entry. Lifting the gate to caixa-build
7233 // time mirrors the `:entrada :host` value-shape trajectory
7234 // (c7d05ec) on the peer axis — every author surface that
7235 // emits a K8s name now matches the apiserver's accepted set
7236 // at validate time.
7237 validate_membro_caixa(m.nome())?;
7238 // The author surface for `:versao` is the same Cargo-shaped
7239 // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
7240 // `"*"`) every `:deps` entry carries — and the lacre pipeline
7241 // resolves both axes through the same
7242 // [`crate::version::parse_requirement`] entry-point. The
7243 // shared [`crate::render::require_valid_versao_requirement`]
7244 // helper brackets the empty-first + parse cascade both peer
7245 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
7246 // [`crate::SupervisorSpec::validate`] on `:children :versao`)
7247 // route through, so drift between the three axes' accepted
7248 // requirement sets is structurally impossible and the parse-
7249 // side no-op the empty-first arm closes (semver's empty
7250 // parse yields an implicit `*`) lives in exactly one
7251 // predicate.
7252 crate::render::require_valid_versao_requirement(
7253 m.versao_requirement(),
7254 || AplicacaoError::MembroVersaoEmpty {
7255 caixa: m.nome().to_string(),
7256 },
7257 |reason| AplicacaoError::MembroVersaoInvalid {
7258 caixa: m.nome().to_string(),
7259 versao: m.versao_requirement().to_string(),
7260 reason,
7261 },
7262 )?;
7263 crate::render::insert_first_seen(&mut seen, m.nome(), || {
7264 AplicacaoError::MembroDuplicate {
7265 caixa: m.nome().to_string(),
7266 }
7267 })?;
7268 }
7269 Ok(())
7270 }
7271
7272 /// Reject `:placement` values that are operationally meaningless or
7273 /// internally contradictory. Each strategy variant has the same
7274 /// invariants on `:clusters` (non-empty list, non-empty unique
7275 /// entries) — the §III.1 author surface is uniform on this axis,
7276 /// even though the *meaning* of the list differs by strategy
7277 /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
7278 /// shard pool).
7279 ///
7280 /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
7281 /// are the same authoring footgun closed for `:politicas` zero
7282 /// values and `:entrada` empty paths: the field is *declared* but
7283 /// carries no meaning, so downstream renderers either skip it
7284 /// silently (cluster-fanout drops the empty entry, no diagnostic)
7285 /// or apply it literally and fail at admission time. Lifting both
7286 /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
7287 /// violation is a build error" promise.
7288 ///
7289 /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
7290 /// is required exactly when `:estrategia Sharded` (hash-keyed
7291 /// distribution, Akka cluster-sharding convention, §II.4) and
7292 /// refused on `:estrategia Replicated`/`SingleNode` (where no
7293 /// hash-keyed routing axis consumes it). The partition closes the
7294 /// "I think I configured sharding" footgun where an author writes
7295 /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
7296 /// the typed slot's value silently vanishes at the renderer layer
7297 /// — every validated `Placement` past this call satisfies
7298 /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
7299 fn validate_placement(&self) -> Result<(), AplicacaoError> {
7300 // Every strategy needs at least one named cluster: `Replicated`
7301 // and `SingleNode` use the list as hosting/takeover candidates
7302 // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
7303 // §II.1), while `Sharded` uses it as the shard pool
7304 // (Akka cluster-sharding convention — §II.4). An empty list is
7305 // meaningless under any of the three.
7306 //
7307 // Route the paired pre-flight `.is_empty()` refusal probe and
7308 // the per-cluster validate loop's traversal head through the
7309 // lifted [`Placement::clusters`] slice-return accessor rather
7310 // than the raw `self.placement.clusters` field access — the
7311 // two production consumers of the per-`:placement` cluster-
7312 // pool `Vec`-carry now key off exactly one typed dispatch on
7313 // the substrate primitive, so any future rebrand on the axis
7314 // (a per-tenant cluster-pool overlay the operator pins through
7315 // a future `:placement :clusters-overrides` slot, a per-
7316 // Aplicacao dynamic cluster-pool derivation the future M5
7317 // adaptive-placement engine computes from `:affinity` weights)
7318 // migrates as a single caixa-core edit rather than a
7319 // coordinated rewrite of the paired arms — sibling of the
7320 // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
7321 // arm migration on the per-`:supervisor` static-child-list
7322 // `Vec`-carry axis.
7323 //
7324 // Route the per-`:placement` outer-composite reference read
7325 // through the lifted [`AplicacaoSpec::placement`] outer accessor
7326 // rather than the raw `&self.placement` field access — the
7327 // per-axis bracket-dispatch fan-out below (`p.clusters()`,
7328 // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
7329 // axis-level lifted accessor family) now routes through the
7330 // substrate-primitive typed dispatch at the outer composition
7331 // altitude, the same shape the peer caixa-mesh
7332 // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
7333 // and the sibling `feira app graph` per-Aplicacao print line
7334 // now key off after this accessor lift.
7335 let p = self.placement();
7336 if p.clusters().is_empty() {
7337 return Err(AplicacaoError::PlacementWithoutClusters {
7338 estrategia: p.estrategia(),
7339 });
7340 }
7341 let mut seen = std::collections::HashSet::new();
7342 for c in p.clusters() {
7343 // Per-entry value-shape gate: the cluster name lands in
7344 // every K8s context / `lareira-fleet-programs` aggregator
7345 // filter / future M4 CR materializer's per-cluster axis
7346 // a validated `:clusters` entry passes through, each
7347 // enforcing the DNS-1123 label rule on admission. Same
7348 // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
7349 // on the peer name axis — both axes' validated values
7350 // are guaranteed-accepted by the apiserver without
7351 // re-validation at any downstream renderer or admission
7352 // layer.
7353 validate_placement_cluster(c)?;
7354 crate::render::insert_first_seen(&mut seen, c.as_str(), || {
7355 AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
7356 })?;
7357 }
7358 // Route the per-`:placement :affinity` per-hint value-shape
7359 // gate through the typed [`Placement::affinity`] accessor rather
7360 // than the raw `&self.placement.affinity` field access — the
7361 // sole open-coded field-access site on the per-`:placement`
7362 // M3-Adaptive-compression-hint axis the accessor lift now owns.
7363 // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
7364 // the accessor's `Option<&str>` return type;
7365 // [`validate_placement_affinity`]'s `&str` parameter accepts
7366 // the narrower borrow without a re-allocation, so the routing
7367 // change is byte-for-byte in the pass arm and remains
7368 // byte-for-byte in every failure diagnostic
7369 // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
7370 // String` field is populated inside
7371 // [`validate_placement_affinity`] via the peer `.to_string()`
7372 // path on the same borrowed slice). Peer of the sibling
7373 // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
7374 // routing through [`Placement::shard_key`] at the caixa-core
7375 // site above — extends the "read `:placement` optional-scalars
7376 // through the typed accessor" discipline to the second
7377 // `Option<String>`-shape slot on the M3 mesh-slot family.
7378 //
7379 // Per-hint value-shape gate: the `:affinity` value lands
7380 // verbatim in the M3 Adaptive compression overlay
7381 // (caixa-mesh's `placement.affinity` emission) and every
7382 // future M4 placement-engine routing axis keying off the
7383 // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7384 // selector — each enforces the DNS-1123 label rule on
7385 // admission. Same typed-shape trajectory as `:placement
7386 // :clusters` (6c8c00b) on the sibling slot and the four
7387 // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7388 // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7389 // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7390 // on the Aplicacao surface to land on the canonical
7391 // [`crate::render::is_dns_1123_label`] floor.
7392 if let Some(a) = p.affinity() {
7393 validate_placement_affinity(a)?;
7394 }
7395 match p.estrategia() {
7396 // Route the `Sharded`-arm shape-gate cascade through the
7397 // typed [`Placement::shard_key`] accessor rather than the
7398 // raw `&self.placement.shard_key` field access — one of the
7399 // two open-coded field-access sites on the per-`:placement`
7400 // Akka-cluster-sharding-key axis the accessor lift now
7401 // owns. The `Some(k)`-bound `k` narrows from `&String` to
7402 // `&str` under the accessor's `Option<&str>` return type;
7403 // `str::is_empty` and [`validate_placement_shard_key`]'s
7404 // `&str` parameter both accept the narrower borrow without
7405 // a re-allocation.
7406 PlacementStrategy::Sharded => match p.shard_key() {
7407 None => return Err(AplicacaoError::ShardedWithoutKey),
7408 Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7409 // Per-axis value-shape gate on the Akka-cluster-sharding
7410 // `:shard-key` extractor expression. The shape gate runs
7411 // after the more self-locating `ShardedKeyEmpty` arm so
7412 // a `:shard-key ""` surfaces the narrower empty
7413 // diagnostic first; every non-empty `:shard-key` past
7414 // this call is guaranteed to be a printable-ASCII
7415 // single-token reference the future M4 Akka-style
7416 // cluster-sharding reconciler can hash without
7417 // re-validating at the runtime layer. Mirrors the
7418 // payload-axis shape gates on the peer `:contratos`
7419 // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7420 // 63e18a0 / c4213a4) — each lifts the runtime parser's
7421 // intersection-floor to a caixa-build-time gate.
7422 Some(k) => validate_placement_shard_key(k)?,
7423 },
7424 // `:shard-key` is the Akka-cluster-sharding axis
7425 // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7426 // across the cluster pool. `Replicated` (active-active across
7427 // every named cluster) and `SingleNode` (Erlang/OTP
7428 // distributed-app takeover/failover, §II.1) have no hash-keyed
7429 // routing axis to consume the slot; downstream renderers
7430 // (caixa-mesh's `placement.shardKey` overlay at
7431 // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7432 // sharding reconciler) ignore `:shard-key` outside the
7433 // `Sharded` arm by construction. Until this gate landed an
7434 // author who wrote `:placement (:estrategia Replicated
7435 // :shard-key "tenantId")` (an off-by-one strategy typo, a
7436 // copy-paste from a Sharded sibling caixa, the "I think I
7437 // configured sharding" footgun) silently passed validate and
7438 // the typed slot's value vanished at the renderer layer with
7439 // no diagnostic — the canonical "declared-but-inert" footgun
7440 // the empty-:affinity / empty-shard-key / zero-:politicas /
7441 // empty-:contratos-target gates already close on every other
7442 // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7443 // Lifting the rejection to a build-time gate closes the
7444 // Sharded ↔ non-Sharded partition over the typed
7445 // `:placement` slot: every validated `Placement` past this
7446 // call has `shard_key.is_some()` iff `estrategia ==
7447 // Sharded`, structurally — the future Akka reconciler can
7448 // reach for `placement.shard_key` knowing it's `Some` exactly
7449 // when the strategy consumes it, without re-deriving the
7450 // partition from inline strategy probes.
7451 PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7452 // Route the non-`Sharded`-arm declared-but-inert refusal
7453 // through the typed [`Placement::shard_key`] accessor —
7454 // the second of the two open-coded field-access sites the
7455 // accessor lift now owns. The `Some(k)`-bound `k` narrows
7456 // from `&String` to `&str`; the `AplicacaoError::
7457 // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7458 // materializes the owned `String` via `k.to_string()`
7459 // (peer to the sibling per-Membro `String`-carry sites
7460 // 4127bb6 routed through `m.nome().to_string()` /
7461 // `m.versao_requirement().to_string()`), so the whole
7462 // `Sharded` ↔ non-`Sharded` partition on the
7463 // `:shard-key` axis now flows through the same typed
7464 // dispatch as the sibling `Sharded`-arm shape gate.
7465 if let Some(k) = p.shard_key() {
7466 return Err(AplicacaoError::ShardKeyOnNonSharded {
7467 estrategia: p.estrategia(),
7468 shard_key: k.to_string(),
7469 });
7470 }
7471 }
7472 }
7473 Ok(())
7474 }
7475
7476 /// Reject `:politicas` values that are operationally meaningless.
7477 /// Each axis is optional — omitting it expresses "no policy on this
7478 /// axis". Carrying a *zero* value for a declared axis is the bug
7479 /// this function rejects: zero is either
7480 ///
7481 /// - re-interpreted as "infinite" by downstream proxies (Envoy's
7482 /// `RouteAction.timeout = 0s` disables the timeout entirely),
7483 /// directly contradicting MESH-COMPOSITION §V CSE invariant
7484 /// "every Aplicacao declares :politicas :timeout (no infinite
7485 /// blocking)", or
7486 /// - a renderer footgun (a 0-failure circuit breaker trips on the
7487 /// first call; a 0-rate rate-limit denies every request).
7488 ///
7489 /// Lifting these "0 means the opposite of what you think" idioms to
7490 /// the typed Aplicacao surface as build errors mirrors the §III.3
7491 /// promise that contract drift, capability leaks, and cycles are all
7492 /// build errors — not runtime surprises.
7493 fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7494 // Route the per-`:politicas` composite-reference read through
7495 // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7496 // than the raw `&self.politicas` field access — the per-axis
7497 // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7498 // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7499 // the substrate-primitive typed dispatch at the outer
7500 // composition altitude AND at every per-axis altitude, matching
7501 // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7502 // timeout/retry-overlay emitters that already key off the same
7503 // per-axis accessor family. The four-axis fan-out is now
7504 // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7505 // `p.retries` field-access sites (co-resident with the peer
7506 // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7507 // b0e741a / 21a6c3b already lifted) now route through
7508 // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7509 // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7510 // access axis on the M3 mesh-slot family.
7511 let p = self.politicas();
7512 if let Some(t) = p.timeout() {
7513 // Zero-floor + integer-millisecond canonical-form +
7514 // upper-cap bracket on the typed `:timeout` axis. See
7515 // [`crate::render::require_positive_canonical_bounded_duration`]
7516 // for the full three-arm ordering discipline (zero-floor
7517 // strictly precedes the canonical-form arm so
7518 // `Duration::ZERO` surfaces the self-locating
7519 // `PolicyTimeoutZero` diagnostic naming the omit-axis
7520 // remediation; canonical-form strictly precedes the cap
7521 // arm so a sub-millisecond above-cap `Duration` surfaces
7522 // the more fundamental round-trip-shape diagnostic first)
7523 // and the four peer typed-`Duration` sites that now share
7524 // this canonical bracket. Every validated value lies in
7525 // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7526 // granularity — the same top-and-bottom-edge discipline
7527 // [`POLICY_RETRIES_MAX`] and
7528 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7529 // capped-`u32` `:politicas` axes.
7530 crate::render::require_positive_canonical_bounded_duration(
7531 t,
7532 POLICY_TIMEOUT_MAX,
7533 || AplicacaoError::PolicyTimeoutZero,
7534 |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7535 |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7536 )?;
7537 }
7538 if let Some(r) = p.retries() {
7539 // Zero-floor + upper-cap bracket on the typed `:retries`
7540 // axis. See [`crate::render::require_positive_bounded_u32`]
7541 // for the ordering discipline (zero-floor arm strictly
7542 // precedes cap arm so `Some(0)` surfaces the self-locating
7543 // `PolicyRetriesZero` diagnostic with its omit-axis
7544 // remediation directly named, not the misleading
7545 // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7546 // this bracket landed the top edge ran all the way to
7547 // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7548 // Some(100_000), .. }` (or the equivalent author-surface
7549 // `(:retries 100000)` / `(:retries 4294967295)` typo
7550 // landing in the slot) silently passed validate. The
7551 // runtime substrate consuming the value (Envoy's
7552 // `retry_policy.num_retries`, the future
7553 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7554 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7555 // policy into a thundering-herd amplification vector —
7556 // the caller's one request fans out to `retries`
7557 // server-side calls per edge per traversal, multiplying
7558 // load by `(retries+1)^depth` across the
7559 // synchronous-`:contratos` subgraph at the precise moment
7560 // the substrate is already failing (transient failure is
7561 // the trigger), exactly the failure mode AWS App Mesh's
7562 // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7563 // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7564 // the sibling capped-`u32` `:politicas` axes
7565 // (`max_failures`, `rate_limit.rate`) and the peer capped-
7566 // `u32` axes in `:supervisor :max-restarts` +
7567 // `:limits :cpu`; all five now route through the same
7568 // canonical bracket helper.
7569 crate::render::require_positive_bounded_u32(
7570 r,
7571 POLICY_RETRIES_MAX,
7572 || AplicacaoError::PolicyRetriesZero,
7573 |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7574 )?;
7575 }
7576 if let Some(cb) = p.circuit_breaker() {
7577 // Zero-floor + upper-cap bracket on the typed
7578 // `:max-failures` axis. See
7579 // [`crate::render::require_positive_bounded_u32`] for the
7580 // ordering discipline (zero-floor arm strictly precedes
7581 // cap arm so `max_failures == 0` surfaces the
7582 // self-locating `PolicyBreakerZeroFailures` diagnostic
7583 // with its omit-axis remediation directly named, not the
7584 // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7585 // false` cap-arm miss). Until this bracket landed the top
7586 // edge ran all the way to `u32::MAX` and a struct-literal
7587 // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7588 // equivalent author-surface `(:max-failures 100000)` /
7589 // `(:max-failures 4294967295)` typo landing in the slot)
7590 // silently passed validate. The runtime substrate
7591 // consuming the value (Envoy's
7592 // `outlier_detection.consecutive_5xx`, the future
7593 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7594 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7595 // breaker policy into a no-op — the trip threshold is
7596 // structurally so high that no realistic
7597 // failures-per-`:window` traffic shape can reach it, the
7598 // breaker never trips, and every typed-slot consumer
7599 // emits an Envoy / Cilium L7 overlay carrying a
7600 // protection that is structurally never enforced. The
7601 // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7602 // peer with `retries` and `rate_limit.rate` on the same
7603 // helper.
7604 crate::render::require_positive_bounded_u32(
7605 cb.max_failures(),
7606 POLICY_BREAKER_MAX_FAILURES_MAX,
7607 || AplicacaoError::PolicyBreakerZeroFailures,
7608 |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7609 )?;
7610 // Zero-floor + integer-millisecond canonical-form +
7611 // upper-cap bracket on the typed `:window` axis. See
7612 // [`crate::render::require_positive_canonical_bounded_duration`]
7613 // for the full three-arm ordering discipline (peer to the
7614 // `:timeout` site immediately above); every validated
7615 // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7616 // (1ms..=1h), integer-millisecond granularity — the same
7617 // top-and-bottom-edge discipline
7618 // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7619 // duration-typed `:politicas :timeout` axis.
7620 crate::render::require_positive_canonical_bounded_duration(
7621 cb.window(),
7622 POLICY_BREAKER_WINDOW_MAX,
7623 || AplicacaoError::PolicyBreakerZeroWindow,
7624 |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7625 |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7626 )?;
7627 }
7628 if let Some(rl) = p.rate_limit() {
7629 // Zero-floor + upper-cap bracket on the typed
7630 // `:rate-limit` rate axis. See
7631 // [`crate::render::require_positive_bounded_u32`] for the
7632 // ordering discipline (zero-floor arm strictly precedes
7633 // cap arm so `rl.rate == 0` surfaces the self-locating
7634 // `PolicyRateLimitZero` diagnostic with its omit-axis
7635 // remediation directly named, not the misleading
7636 // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7637 // Until this bracket landed the top edge ran all the way
7638 // to `u32::MAX` and a struct-literal
7639 // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7640 // author-surface `(:rate-limit "4294967295/s")` /
7641 // `(:rate-limit "100000000/m")` typo landing in the slot)
7642 // silently passed validate. The runtime substrate
7643 // consuming the value (Envoy's
7644 // `local_rate_limit.token_bucket.max_tokens`, the future
7645 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7646 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7647 // rate-limit policy into a no-op limiter: the bucket
7648 // capacity is structurally so high that no realistic
7649 // per-edge traffic shape can drain it, the limiter never
7650 // trips, and every typed-slot consumer emits a "rate
7651 // declared" L7 overlay carrying enforcement that is
7652 // structurally never reached — the canonical
7653 // declared-but-inert footgun the sibling
7654 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7655 // the peer no-op-breaker shape. The bracket set is
7656 // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7657 // `max_failures` on the same helper. The rate bracket
7658 // strictly precedes the window-canonical gate so a
7659 // structurally absurd rate magnitude surfaces the more
7660 // fundamental amplification-shape diagnostic before the
7661 // narrower codec-round-trip-shape diagnostic on `:window`.
7662 crate::render::require_positive_bounded_u32(
7663 rl.rate(),
7664 POLICY_RATE_LIMIT_MAX,
7665 || AplicacaoError::PolicyRateLimitZero,
7666 |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7667 )?;
7668 // The `:rate-limit` author surface is the canonical
7669 // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7670 // accepts exactly the three-unit set (1s/60s/3600s) the
7671 // [`rate_limit_codec::render`] formatter emits the canonical
7672 // unit suffix for. A `RateLimit` whose `:window` is anything
7673 // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7674 // programmatically (struct literals in Rust + the typed
7675 // `Duration` field) but renders to a `<n>/<k>s` fragment
7676 // (the codec's fall-through) the parser then rejects on
7677 // round-trip — silently breaking the THEORY.md §V.2.7
7678 // render-determinism contract for any consumer that
7679 // serializes-then-deserializes the typed slot. Lifting the
7680 // canonical-window invariant to a build-time gate at
7681 // `validate_politicas` makes the codec's round-trip property
7682 // a structural property of the validated typed value:
7683 // every `RateLimit` past `AplicacaoSpec::validate` has a
7684 // window the codec round-trips losslessly, so the next
7685 // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
7686 // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
7687 // §III.2 #3) reaches for `rate_limit.window` knowing the
7688 // value is in the codec's accepted set without re-validating
7689 // at the renderer layer. Same trajectory as c4213a4 (typed
7690 // WitContract endpoint/subject/slot value-shape gates) and
7691 // the b0c8389 :behavior + :upgrade-from script-path lifts:
7692 // the typed slot's valid set matches its codec's accepted
7693 // set, structurally.
7694 // Route the canonical-window shape-gate through the substrate
7695 // primitive [`RateLimit::canonical_unit`] rather than the free
7696 // module-private [`is_canonical_rate_limit_window`] predicate:
7697 // both projections resolve `Duration → Option<RateLimitUnit>`
7698 // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
7699 // arm on the closed-set typed enum), but the accessor is the
7700 // typed method every downstream consumer of the validated slot
7701 // ([`rate_limit_codec::render`]'s canonical arm above, the
7702 // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7703 // per-`:politicas :rate-limit` admission webhook, the future
7704 // per-`:contratos`-edge rate-limit-override overlay
7705 // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
7706 // production consumers of the canonical-unit axis (the codec
7707 // render and this validate gate) now key off exactly one typed
7708 // dispatch on the substrate primitive, so any future extension
7709 // to `canonical_unit` (a per-cluster canonical-window overlay
7710 // the operator pins through a future `:contratos :rate-limit
7711 // -unit-overrides` slot, a per-tenant unit-alias table the M4
7712 // CR materializer resolves per-CR) reaches both consumers by
7713 // construction rather than a coordinated rewrite of every
7714 // free-helper call site.
7715 if rl.canonical_unit().is_none() {
7716 return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
7717 window: rl.window(),
7718 });
7719 }
7720 }
7721 Ok(())
7722 }
7723
7724 /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
7725 /// A synchronous edge is any contract whose typed [`WitTarget`] is
7726 /// `Http`, `Store`, or `Capability` — the caller blocks on the
7727 /// callee, so a cycle would deadlock at runtime. Pub-sub edges
7728 /// (`WitTarget::PubSub`) are skipped: an event publisher does not
7729 /// block on its subscribers, so they can never close a sync loop.
7730 ///
7731 /// Iterative DFS with three-coloring; the reported cycle is the
7732 /// path of caixa names traversed from the back-edge target around
7733 /// to itself, in declaration order. Adjacency lists and DFS roots
7734 /// are visited in `BTreeMap` key order so the diagnostic is
7735 /// deterministic across runs.
7736 fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
7737 use std::collections::{BTreeMap, BTreeSet};
7738
7739 #[derive(Clone, Copy, PartialEq, Eq)]
7740 enum Mark {
7741 White,
7742 Gray,
7743 Black,
7744 }
7745
7746 let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
7747 for m in self.membros() {
7748 adj.entry(m.nome()).or_default();
7749 }
7750 for c in self.contratos() {
7751 // target() was already called by validate(); re-running here
7752 // keeps detect_sync_cycles self-contained for callers that
7753 // reuse it (M4 per-edge policy resolver) without revalidating.
7754 //
7755 // The pub-sub-arm check routes through the lifted
7756 // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
7757 // arm-discriminator predicate rather than a raw `matches!(…,
7758 // WitTarget::PubSub { .. })` on the variant so a future
7759 // rebrand on the axis (an M4 per-edge WIT registry split of
7760 // [`WitTarget::PubSub`] into shape-specific peers, a
7761 // per-consumer rename that the accept-set already carries)
7762 // reaches this call site through the derive rather than a
7763 // scattered per-arm `matches!` rewrite — same
7764 // `IsVariant`-derived-arm-discriminator discipline the
7765 // peer closed-set typed enums ([`crate::CaixaKind`] via
7766 // f5bba80, [`PlacementStrategy`] via 766ec63,
7767 // [`crate::supervisor::RestartStrategy`] +
7768 // [`crate::supervisor::RestartPolicy`],
7769 // [`crate::upgrade::UpgradeInstruction`] via 915a934)
7770 // already route through on the substrate's other typed-enum
7771 // arm-discriminator axes.
7772 if c.target()?.is_pubsub() {
7773 continue;
7774 }
7775 adj.entry(c.source()).or_default().insert(c.destination());
7776 }
7777
7778 let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
7779 let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
7780
7781 // Stable DFS root order — BTreeMap iteration is sorted by key.
7782 let roots: Vec<&str> = adj.keys().copied().collect();
7783
7784 // Frame: (node, sorted-neighbours snapshot, next-edge index).
7785 for root in roots {
7786 if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
7787 continue;
7788 }
7789 let root_neighbors: Vec<&str> = adj
7790 .get(root)
7791 .map(|s| s.iter().copied().collect())
7792 .unwrap_or_default();
7793 let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
7794 color.insert(root, Mark::Gray);
7795
7796 loop {
7797 // Read+advance the top frame in one borrow scope so we
7798 // can later mutate the stack (push/pop) without holding
7799 // a borrow across.
7800 let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
7801 let node = top.0;
7802 if top.2 >= top.1.len() {
7803 (node, None)
7804 } else {
7805 let nxt = top.1[top.2];
7806 top.2 += 1;
7807 (node, Some(nxt))
7808 }
7809 });
7810 let Some((node, nxt_opt)) = step else { break };
7811 let Some(nxt) = nxt_opt else {
7812 color.insert(node, Mark::Black);
7813 stack.pop();
7814 continue;
7815 };
7816 let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
7817 match nxt_color {
7818 Mark::Gray => {
7819 // Reconstruct the cycle from `node` back through
7820 // the parent chain to `nxt`, then close.
7821 let mut cycle = Vec::new();
7822 let mut cur = node;
7823 cycle.push(cur.to_string());
7824 while cur != nxt {
7825 match parent.get(cur).copied() {
7826 Some(p) => {
7827 cur = p;
7828 cycle.push(cur.to_string());
7829 }
7830 None => break,
7831 }
7832 }
7833 cycle.reverse();
7834 cycle.push(nxt.to_string());
7835 return Err(AplicacaoError::ContratoCycle { cycle });
7836 }
7837 Mark::White => {
7838 parent.insert(nxt, node);
7839 color.insert(nxt, Mark::Gray);
7840 let nxt_neighbors: Vec<&str> = adj
7841 .get(nxt)
7842 .map(|s| s.iter().copied().collect())
7843 .unwrap_or_default();
7844 stack.push((nxt, nxt_neighbors, 0));
7845 }
7846 Mark::Black => {}
7847 }
7848 }
7849 }
7850 Ok(())
7851 }
7852
7853 /// Substrate-canonical destination-facing TCP port every emitted
7854 /// per-Aplicacao artifact must key `destination`-shaped port axes
7855 /// off. Returns the typed `:entrada :port` scalar when this
7856 /// Aplicacao's `:entrada` block names `destination` under its
7857 /// `:para` axis (the destination Servico *is* the ingress apex, so
7858 /// the substrate honors the author-declared listener port
7859 /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
7860 /// fallback otherwise (every non-apex destination — the internal
7861 /// mesh Servicos `:contratos` reach across, the future per-edge
7862 /// policy resolver's per-destination probe targets, the
7863 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
7864 /// L4 port resolver — reads the same substrate-canonical port floor
7865 /// by construction).
7866 ///
7867 /// Prior to this lift the "if :entrada matches this destination use
7868 /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
7869 /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
7870 /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
7871 /// prior to this lift), with no typed method on the substrate primitive
7872 /// that named the rule. A future per-destination port axis addition
7873 /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
7874 /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
7875 /// per-Servico listener ports land, a per-cluster override the operator
7876 /// pins through a future `:placement :default-port` slot — would have
7877 /// to be threaded through every renderer's inline cascade in lockstep
7878 /// or one consumer would silently disagree on which port a given
7879 /// destination Servico's ingress lands at. Lifting the rule to a
7880 /// typed method on the substrate primitive means the M4 CR
7881 /// materializer, the future per-edge policy resolver, and every
7882 /// downstream test-fixture navigator reach for exactly one typed
7883 /// dispatch — the resolver's accept-set moves as a unit on any
7884 /// future axis addition.
7885 ///
7886 /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
7887 /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
7888 /// the typed primitive, thin projections at each consumer"
7889 /// discipline lifts on the sibling `:contratos` payload / `:politicas
7890 /// :rate-limit` unit-suffix axes; extends the discipline onto the
7891 /// destination-facing port-resolution axis every per-Aplicacao
7892 /// L4-fallback renderer consumes.
7893 #[must_use]
7894 pub fn port_for_destination(&self, destination: &str) -> u16 {
7895 // Route the per-`:entrada` composite-reference read through
7896 // the lifted [`AplicacaoSpec::entrada`] accessor rather than
7897 // the raw `self.entrada.as_ref()` field access — the
7898 // per-destination L4-port fallback resolver's composite-
7899 // projection seed is now the canonical read-side surface
7900 // every per-Aplicacao entrada consumer routes through, peer
7901 // of the sibling `validate` per-`:entrada` shape-and-
7902 // membership gate migration on the same outer-composite
7903 // axis.
7904 // Route the per-`:entrada` apex-destination membership probe
7905 // through the lifted [`Entrada::destination`] accessor rather
7906 // than the raw `e.para == destination` field access — the last
7907 // un-lifted `.para` production-code read site on the per-
7908 // `:entrada` `:para` axis, sibling to the four caixa-core
7909 // consumer sites the peer 15ddd8c converge already routed
7910 // through the accessor (the three
7911 // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
7912 // membership gate sites: the `validate_entrada_para` DNS-1123
7913 // shape gate, the per-`:membros` membership lookup, and the
7914 // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
7915 // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
7916 // `entrada.para`-projection converge at
7917 // caixa-core/src/render.rs (the `gateway_api_http_route_name`
7918 // route-name projection site). Prior to this converge the
7919 // `port_for_destination` resolver was the solitary consumer
7920 // bypassing the typed dispatch on the `.para` axis — the two
7921 // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
7922 // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
7923 // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
7924 // reach through the same accessor family compose with this
7925 // resolver at the emit boundary via the apex-identity
7926 // invariant `spec.port_for_destination(entrada.destination())
7927 // == entrada.port` the sibling
7928 // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
7929 // pin pins across four permutations. A future extension of the
7930 // `:entrada :para` axis to a richer author surface (a per-
7931 // cluster alias overlay the operator pins through a future
7932 // `:placement`-scoped slot, a namespace-qualified rewrite the
7933 // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
7934 // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
7935 // §III.2 acknowledges) that lands on the accessor would silently
7936 // disagree between this resolver and the two `caixa-mesh` emit
7937 // sites — an author-declared `:para "cart"` value the accessor
7938 // rewrote to `"cart-v2"` under a future canary arm would leave
7939 // the resolver's membership arm falling through to
7940 // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
7941 // `.para`) while the peer emit-site consumers landed on the
7942 // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
7943 // silently disagreed on which destination port a given typed
7944 // `:entrada` resolves to at cluster-apply time. Pinned by the
7945 // drift-detection test
7946 // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
7947 // below.
7948 self.entrada()
7949 .filter(|e| e.destination() == destination)
7950 .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
7951 }
7952}
7953
7954/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
7955/// entry may name the Aplicacao's own `:nome`.
7956///
7957/// An Aplicacao that lists itself as a member is a degenerate self-edge in
7958/// the typed graph — the application graph is a DAG rooted at the Aplicacao
7959/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
7960/// Servicos that compose the app; an Aplicacao is never its own constituent),
7961/// and the lacre pipeline's closure-resolution would otherwise be handed a
7962/// node that is its own parent: a one-node cycle it either rejects far from
7963/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
7964/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
7965/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
7966/// label + lacre closure root), a member whose `:caixa` equals the
7967/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
7968/// peer.
7969///
7970/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
7971/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
7972/// gate `validate_upgrade_from_against_versao` and the supervision-tree
7973/// self-parent gate `crate::supervisor::validate_no_self_supervision`
7974/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
7975/// not a tree/mesh edge" discipline, here on the second typed-graph axis
7976/// (the Aplicacao :membros set; the supervision-tree :children list was the
7977/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
7978/// every validated Supervisor's children are distinct from its `:nome`,
7979/// every validated Aplicacao's membros are distinct from its `:nome`. The
7980/// transitive consequence is that `:entrada :para` and `:contratos`
7981/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
7982/// name the Aplicacao itself, without re-deriving the partition.
7983pub fn validate_no_self_membership(
7984 membros: &[Membro],
7985 parent_nome: &str,
7986) -> Result<(), AplicacaoError> {
7987 for m in membros {
7988 if m.nome() == parent_nome {
7989 return Err(AplicacaoError::MembroIsSelfAplicacao {
7990 caixa: parent_nome.to_string(),
7991 });
7992 }
7993 }
7994 Ok(())
7995}
7996
7997#[derive(Debug, Error, PartialEq, Eq)]
7998pub enum AplicacaoError {
7999 #[error("Aplicacao must declare at least one :membros entry")]
8000 NoMembros,
8001 #[error(
8002 ":membros entry has empty :caixa (every member must name a Servico; \
8003 omit the entry instead of carrying an empty name)"
8004 )]
8005 MembroCaixaEmpty,
8006 #[error(
8007 ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8008 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8009 name / label value the member name lands in; use a lowercase \
8010 alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8011 )]
8012 MembroCaixaInvalid { caixa: String, reason: String },
8013 #[error(
8014 ":membros entry {caixa:?} has empty :versao (every member must pin a \
8015 semver constraint that resolves through the lacre pipeline)"
8016 )]
8017 MembroVersaoEmpty { caixa: String },
8018 #[error(
8019 ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8020 requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8021 `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8022 carries; the lacre pipeline resolves both through the same parser)"
8023 )]
8024 MembroVersaoInvalid {
8025 caixa: String,
8026 versao: String,
8027 reason: String,
8028 },
8029 #[error(
8030 ":membros entry {caixa:?} appears more than once (the graph node set \
8031 is a set, not a multiset; duplicate members produce duplicate \
8032 programs.yaml entries and ambiguous :contratos membership lookups)"
8033 )]
8034 MembroDuplicate { caixa: String },
8035 #[error(
8036 "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8037 never its own constituent Servico (the application graph is a DAG rooted \
8038 at the Aplicacao; :membros names the *other* caixas that compose the \
8039 app, not the app itself). Since every :nome is a globally-unique \
8040 substrate identity, a member naming the Aplicacao's own :nome is a \
8041 one-node lacre-closure recursion, not a coincidentally-named peer; \
8042 drop the self-referential :membros entry or rename it to the actual \
8043 constituent caixa."
8044 )]
8045 MembroIsSelfAplicacao { caixa: String },
8046 #[error(
8047 "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8048 caixa declared in :membros; omit the contract or fill the {slot} field with a \
8049 member name)"
8050 )]
8051 ContratoCaixaEmpty { slot: &'static str },
8052 #[error(
8053 "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8054 :contratos {slot} value names a member of :membros, which is itself a \
8055 DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8056 object the member name lands in — Service, Pod, identity-based Cilium \
8057 selector; use a lowercase alphanumeric + hyphen identifier like \
8058 `\"checkout\"` or `\"cart-v2\"`)"
8059 )]
8060 ContratoCaixaInvalid {
8061 slot: &'static str,
8062 caixa: String,
8063 reason: String,
8064 },
8065 #[error("contrato references caixa {caixa:?} not declared in :membros")]
8066 ContratoMemberMissing { caixa: String },
8067 #[error(
8068 "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8069 entry is an inter-Servico contract whose :de and :para must name distinct \
8070 :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8071 the contract, or point :para at the member it actually calls)"
8072 )]
8073 ContratoSelfLoop { caixa: String, wit: String },
8074 #[error("contrato {de:?} → {para:?} has empty :wit")]
8075 EmptyWit { de: String, para: String },
8076 #[error(
8077 "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8078 {reason} (the substrate dispatches `:wit` values on the canonical \
8079 lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8080 `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8081 demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8082 kebab-case identifier per segment)"
8083 )]
8084 ContratoWitInvalid {
8085 de: String,
8086 para: String,
8087 wit: String,
8088 reason: String,
8089 },
8090 #[error(
8091 ":entrada :para is empty (every :entrada must route to a caixa declared in \
8092 :membros; fill the :para field with a member name)"
8093 )]
8094 EntradaParaEmpty,
8095 #[error(
8096 ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8097 :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8098 label per the K8s apiserver's `metadata.name` rule on every object the \
8099 member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8100 Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8101 `\"checkout\"` or `\"cart-v2\"`)"
8102 )]
8103 EntradaParaInvalid { para: String, reason: String },
8104 #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8105 EntradaMemberMissing { para: String },
8106 #[error(":entrada must declare a non-empty :host")]
8107 EmptyEntradaHost,
8108 #[error(
8109 ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8110 (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8111 `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8112 like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8113 )]
8114 EntradaHostInvalid { host: String, reason: String },
8115 #[error(":entrada :port must be in 1..=65535, got 0")]
8116 EntradaPortZero,
8117 #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8118 EntradaPathEmpty,
8119 #[error(
8120 ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8121 )]
8122 EntradaPathNotAbsolute { path: String },
8123 #[error(
8124 ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8125 value: {reason} (the K8s apiserver enforces the same shape on \
8126 `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8127 single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8128 requires percent-encoding `%XX` for non-ASCII and whitespace)"
8129 )]
8130 EntradaPathInvalid { path: String, reason: String },
8131 #[error(":entrada :paths entry {path:?} appears more than once")]
8132 EntradaPathDuplicate { path: String },
8133 #[error(
8134 ":placement {estrategia} requires at least one :clusters entry \
8135 (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8136 )]
8137 PlacementWithoutClusters { estrategia: PlacementStrategy },
8138 #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8139 PlacementClusterEmpty,
8140 #[error(
8141 ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8142 (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8143 in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8144 future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8145 — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8146 identifier like `\"rio\"` or `\"mar-east\"`)"
8147 )]
8148 PlacementClusterInvalid { cluster: String, reason: String },
8149 #[error(":placement :clusters entry {cluster:?} appears more than once")]
8150 PlacementClusterDuplicate { cluster: String },
8151 #[error(
8152 ":placement :affinity must be non-empty when set (omit :affinity to express \
8153 `no placement hint`)"
8154 )]
8155 PlacementAffinityEmpty,
8156 #[error(
8157 ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8158 (placement hints land verbatim in the M3 Adaptive compression overlay's \
8159 `placement.affinity` field and in every future M4 placement-engine routing \
8160 axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8161 selector — both enforce the DNS-1123 label rule on admission; use a \
8162 lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8163 `\"low-latency\"`, or `\"anti-affinity\"`)"
8164 )]
8165 PlacementAffinityInvalid { affinity: String, reason: String },
8166 #[error(":placement Sharded requires :shard-key")]
8167 ShardedWithoutKey,
8168 #[error(
8169 ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8170 hashes every entity onto the same shard, defeating sharding entirely)"
8171 )]
8172 ShardedKeyEmpty,
8173 #[error(
8174 ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8175 entity-id extractor expression: {reason} (the future M4 Akka-style \
8176 cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8177 as a single-token property reference and hashes the extracted entity ID \
8178 to compute shard placement; use a printable-ASCII extractor expression \
8179 like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8180 `\"${{tenant}}\"`)"
8181 )]
8182 ShardKeyInvalid { shard_key: String, reason: String },
8183 #[error(
8184 ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8185 Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8186 convention); :estrategia Replicated runs every cluster active-active and \
8187 :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8188 distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8189 to :estrategia Sharded if hash-keyed routing is the intent"
8190 )]
8191 ShardKeyOnNonSharded {
8192 estrategia: PlacementStrategy,
8193 shard_key: String,
8194 },
8195 #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8196 ContratoMissingTarget {
8197 de: String,
8198 para: String,
8199 wit: String,
8200 expected: &'static str,
8201 },
8202 #[error(
8203 "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8204 expected `:{expected}` only"
8205 )]
8206 ContratoWrongTarget {
8207 de: String,
8208 para: String,
8209 wit: String,
8210 expected: &'static str,
8211 },
8212 #[error(
8213 "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8214 like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8215 that matches no traffic and silently drops every request)"
8216 )]
8217 ContratoEndpointEmpty { de: String, para: String },
8218 #[error(
8219 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8220 (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8221 :entrada :paths)"
8222 )]
8223 ContratoEndpointNotAbsolute {
8224 de: String,
8225 para: String,
8226 endpoint: String,
8227 },
8228 #[error(
8229 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8230 Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8231 emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8232 caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8233 shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8234 like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8235 and whitespace)"
8236 )]
8237 ContratoEndpointInvalid {
8238 de: String,
8239 para: String,
8240 endpoint: String,
8241 reason: String,
8242 },
8243 #[error(
8244 "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8245 subject is a no-op subscribe; omit :subject only if the WIT world is not \
8246 pub-sub-shaped)"
8247 )]
8248 ContratoSubjectEmpty { de: String, para: String },
8249 #[error(
8250 "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8251 NATS subject: {reason} (the NATS server's subject parser enforces the \
8252 same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8253 single-token and `>` multi-token wildcards — at publish/subscribe time; \
8254 use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8255 `\"orders.*.completed\"` — a malformed subject silently drops every \
8256 message at runtime far from the source caixa.lisp)"
8257 )]
8258 ContratoSubjectInvalid {
8259 de: String,
8260 para: String,
8261 subject: String,
8262 reason: String,
8263 },
8264 #[error(
8265 "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8266 addresses the bucket root, defeating the per-key isolation the slot exists \
8267 for; omit :slot only if the WIT world is not store-shaped)"
8268 )]
8269 ContratoSlotEmpty { de: String, para: String },
8270 #[error(
8271 "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8272 WASI keyvalue store slot template: {reason} (the substrate enforces \
8273 the printable-ASCII intersection-floor every kv backend admits — \
8274 use a single-token path / template expression like `\"checkout/$orderId\"`, \
8275 `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8276 percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8277 slot either gets rejected on write by strict backends or silently \
8278 corrupts the next read on permissive ones, far from the source caixa.lisp)"
8279 )]
8280 ContratoSlotInvalid {
8281 de: String,
8282 para: String,
8283 slot: String,
8284 reason: String,
8285 },
8286 #[error(
8287 "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
8288 or an event-sourced indirection (MESH-COMPOSITION §III.3)",
8289 cycle.join(" → ")
8290 )]
8291 ContratoCycle { cycle: Vec<String> },
8292 #[error(
8293 ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
8294 than once (the typed graph edges are a set, not a multiset; duplicate \
8295 contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
8296 values that K8s admission rejects far from the source caixa.lisp)"
8297 )]
8298 ContratoDuplicate {
8299 de: String,
8300 para: String,
8301 wit: String,
8302 target: String,
8303 },
8304 #[error(
8305 ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
8306 contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
8307 express `no per-call deadline on this axis`"
8308 )]
8309 PolicyTimeoutZero,
8310 #[error(
8311 ":politicas :retries must be > 0 when set; omit :retries to express \
8312 `no retries on transient failure`"
8313 )]
8314 PolicyRetriesZero,
8315 #[error(
8316 ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
8317 (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
8318 retry policy into a thundering-herd amplification vector on transient \
8319 failure (one caller request fans out to `(retries+1)^depth` server-side \
8320 calls across the synchronous-:contratos subgraph), exactly the failure \
8321 mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
8322 Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
8323 or omit :retries to disable retries entirely"
8324 )]
8325 PolicyRetriesExceedsCap { retries: u32 },
8326 #[error(
8327 ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
8328 breaker trips on the first call); omit :circuit-breaker to disable it"
8329 )]
8330 PolicyBreakerZeroFailures,
8331 #[error(
8332 ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
8333 mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
8334 above this cap turns the typed breaker policy into a no-op: the trip \
8335 threshold is structurally so high that no realistic failures-per-:window \
8336 traffic shape can reach it, so the breaker never trips and every typed-slot \
8337 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
8338 Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
8339 structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
8340 Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
8341 omit :circuit-breaker to disable the breaker entirely"
8342 )]
8343 PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
8344 #[error(
8345 ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
8346 tracks no failures); omit :circuit-breaker to disable it"
8347 )]
8348 PolicyBreakerZeroWindow,
8349 #[error(
8350 ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
8351 request); omit :rate-limit to disable rate limiting"
8352 )]
8353 PolicyRateLimitZero,
8354 #[error(
8355 ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
8356 (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
8357 rate-limit policy into a no-op limiter: the token-bucket capacity is \
8358 structurally so high that no realistic per-edge traffic shape can drain it, \
8359 so the limiter never trips and every typed-slot consumer (the future \
8360 CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8361 local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
8362 that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
8363 Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
8364 Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
8365 Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
8366 to disable rate limiting entirely"
8367 )]
8368 PolicyRateLimitExceedsCap { rate: u32 },
8369 #[error(
8370 ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
8371 the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
8372 rate-limit codec round-trips losslessly; got {window:?} which renders to a \
8373 non-round-trippable form (omit :rate-limit to disable, or pick one of the \
8374 three canonical windows)"
8375 )]
8376 PolicyRateLimitWindowNotCanonical { window: Duration },
8377 #[error(
8378 ":politicas :timeout must be an integer number of milliseconds — the canonical \
8379 authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8380 duration codec round-trips losslessly; got {timeout:?} which carries a \
8381 sub-millisecond residue that either truncates to a different `Duration` on \
8382 re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8383 to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8384 zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8385 (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8386 )]
8387 PolicyTimeoutNotCanonical { timeout: Duration },
8388 #[error(
8389 ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8390 (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8391 per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8392 overlays carry a deadline so long no realistic synchronous-:contratos \
8393 traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8394 CSE invariant degenerates to enforcement only at the per-Servico \
8395 `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8396 `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8397 (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8398 ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8399 maxes out at the same `3600s` ceiling) or omit :timeout to express \
8400 `no per-call deadline on this axis` (the synchronous-call deadline then \
8401 relies entirely on the per-Servico `:limits :wall-clock` axis)"
8402 )]
8403 PolicyTimeoutExceedsCap { timeout: Duration },
8404 #[error(
8405 ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8406 the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8407 the shared duration codec round-trips losslessly; got {window:?} which carries a \
8408 sub-millisecond residue that either truncates to a different `Duration` on \
8409 re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8410 Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8411 )]
8412 PolicyBreakerWindowNotCanonical { window: Duration },
8413 #[error(
8414 ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8415 (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8416 rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8417 is structurally so long that transient failures are never forgotten, the breaker \
8418 trips once and stays tripped for the lifetime of the component, and every typed-slot \
8419 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8420 outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8421 Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8422 default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8423 the breaker entirely"
8424 )]
8425 PolicyBreakerWindowExceedsCap { window: Duration },
8426}
8427
8428#[cfg(test)]
8429mod tests {
8430 use super::*;
8431
8432 fn membro(name: &str, ver: &str) -> Membro {
8433 Membro {
8434 caixa: name.into(),
8435 versao: ver.into(),
8436 }
8437 }
8438
8439 fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8440 WitContract {
8441 de: de.into(),
8442 para: para.into(),
8443 wit: "wasi:http/proxy".into(),
8444 endpoint: Some(ep.into()),
8445 subject: None,
8446 slot: None,
8447 }
8448 }
8449
8450 fn three_member_spec() -> AplicacaoSpec {
8451 AplicacaoSpec {
8452 membros: vec![
8453 membro("catalog", "^0.1"),
8454 membro("cart", "^0.1"),
8455 membro("payment", "^0.2"),
8456 ],
8457 contratos: vec![
8458 contract_http("cart", "catalog", "/products/:id"),
8459 contract_http("cart", "payment", "/charge"),
8460 ],
8461 politicas: MeshPolicy {
8462 timeout: Some(Duration::from_secs(30)),
8463 retries: Some(3),
8464 mtls_required: Some(true),
8465 ..Default::default()
8466 },
8467 placement: Placement {
8468 estrategia: PlacementStrategy::Replicated,
8469 clusters: vec!["rio".into(), "mar".into()],
8470 affinity: Some("data-locality".into()),
8471 shard_key: None,
8472 },
8473 entrada: Some(Entrada {
8474 host: "checkout.quero.cloud".into(),
8475 para: "cart".into(),
8476 paths: vec!["/api/cart".into(), "/api/products".into()],
8477 port: 8080,
8478 }),
8479 }
8480 }
8481
8482 #[test]
8483 fn happy_path_validates() {
8484 three_member_spec().validate().unwrap();
8485 }
8486
8487 #[test]
8488 fn rejects_empty_membros() {
8489 let mut s = three_member_spec();
8490 s.membros = vec![];
8491 assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8492 }
8493
8494 #[test]
8495 fn rejects_empty_membro_caixa() {
8496 // A `:caixa ""` entry has no name to render into programs.yaml
8497 // and no caixa.lisp to resolve at lacre time.
8498 let mut s = three_member_spec();
8499 s.membros[1].caixa = String::new();
8500 assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8501 }
8502
8503 #[test]
8504 fn rejects_empty_membro_versao() {
8505 // A `:versao ""` entry can't pin a semver constraint, so the
8506 // lacre pipeline fails far from the source.
8507 let mut s = three_member_spec();
8508 s.membros[2].versao = String::new();
8509 let err = s.validate().unwrap_err();
8510 assert!(
8511 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8512 "got {err:?}"
8513 );
8514 }
8515
8516 #[test]
8517 fn rejects_duplicate_membro_caixa() {
8518 // Two `:membros` entries with the same `:caixa` collapse to one
8519 // node in the membership HashSet, which masks `:contratos`
8520 // membership errors and produces duplicate programs.yaml entries.
8521 let mut s = three_member_spec();
8522 s.membros.push(membro("cart", "^0.2"));
8523 let err = s.validate().unwrap_err();
8524 assert!(
8525 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8526 "got {err:?}"
8527 );
8528 }
8529
8530 #[test]
8531 fn rejects_invalid_membro_versao_requirement() {
8532 // The fail-before-pass-after pin: a non-empty but malformed
8533 // semver requirement (`"^bad-version"`) silently passed
8534 // `validate()` on every pre-gate codebase because the prior
8535 // shape only refused the empty string. The parse failure
8536 // surfaced far downstream at lacre-resolve time with a
8537 // `semver::Error` that didn't name which `:membros` entry
8538 // carried the typo. The new gate moves the check to caixa-build
8539 // time at the source caixa.lisp.
8540 let mut s = three_member_spec();
8541 s.membros[2].versao = "^bad-version".into();
8542 let err = s.validate().unwrap_err();
8543 assert!(
8544 matches!(
8545 err,
8546 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8547 if caixa == "payment" && versao == "^bad-version"
8548 ),
8549 "got {err:?}"
8550 );
8551 }
8552
8553 #[test]
8554 fn rejects_membro_versao_with_double_caret_typo() {
8555 // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8556 // Cargo-shaped requirement on first glance but fails the parser
8557 // because semver doesn't accept stacked operators. Pin this
8558 // adjacent-shape footgun explicitly so a future relaxation that
8559 // accepts "looks-canonical-but-isn't" forms surfaces here.
8560 let mut s = three_member_spec();
8561 s.membros[0].versao = "^^0.1".into();
8562 let err = s.validate().unwrap_err();
8563 assert!(
8564 matches!(
8565 err,
8566 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8567 if caixa == "catalog" && versao == "^^0.1"
8568 ),
8569 "got {err:?}"
8570 );
8571 }
8572
8573 #[test]
8574 fn rejects_membro_versao_with_v_prefixed_tag() {
8575 // `"v0.1"` is the canonical "git-tag-shape leaking into the
8576 // semver requirement slot" typo — an author copies the
8577 // publish-side git-tag string verbatim into `:versao`, but
8578 // Cargo's semver parser rejects the leading `v` (only digits +
8579 // canonical operators are valid in the major-version
8580 // position). The gate's diagnostic names which member entry
8581 // carried the v-prefix so the fix is one edit, not a grep
8582 // through every member's `:versao`. (Note: bare `x`-glob
8583 // shorthands like `^0.1.x` are *accepted* by the semver crate
8584 // as an `*` wildcard on the patch axis — they're a Cargo-side
8585 // valid shape, not a typo, so the gate intentionally lets them
8586 // through.)
8587 let mut s = three_member_spec();
8588 s.membros[1].versao = "v0.1".into();
8589 let err = s.validate().unwrap_err();
8590 assert!(
8591 matches!(
8592 err,
8593 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8594 if caixa == "cart" && versao == "v0.1"
8595 ),
8596 "got {err:?}"
8597 );
8598 }
8599
8600 #[test]
8601 fn accepts_canonical_membro_versao_forms() {
8602 // The four Cargo-shaped requirement forms `:deps :versao`
8603 // already accepts via `crate::parse_requirement` must pass the
8604 // membros gate without re-validating at the resolver layer.
8605 // Pin every leg so a future tightening of the canonical set
8606 // surfaces here as a test failure.
8607 for form in [
8608 "^0.1", // caret — minor-range pin (the most common shape)
8609 "~0.1.2", // tilde — patch-range pin
8610 "0.1.0", // exact — single-version pin
8611 "*", // wildcard — explicitly any-version (semver::VersionReq::STAR)
8612 ">=0.1, <2", // multi-range — comma-separated comparators
8613 ] {
8614 let mut s = three_member_spec();
8615 for m in &mut s.membros {
8616 m.versao = form.into();
8617 }
8618 s.validate()
8619 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8620 }
8621 }
8622
8623 #[test]
8624 fn membro_versao_empty_takes_precedence_over_invalid() {
8625 // Order pin: the existing `MembroVersaoEmpty` diagnostic
8626 // (which doesn't try to parse) fires before the new
8627 // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8628 // `:versao` keeps its narrower error message — `parse_requirement`
8629 // would also reject `""`, but the empty-string arm is the more
8630 // self-locating diagnostic for the author.
8631 let mut s = three_member_spec();
8632 s.membros[1].versao = String::new();
8633 let err = s.validate().unwrap_err();
8634 assert!(
8635 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8636 "got {err:?}"
8637 );
8638 }
8639
8640 #[test]
8641 fn membro_versao_invalid_fires_before_duplicate_check() {
8642 // Order pin: a malformed requirement on a non-duplicate entry
8643 // surfaces *its own* diagnostic (which names the offending
8644 // `:versao` string), even when a later entry would otherwise
8645 // collapse onto an earlier name. The per-entry shape gate runs
8646 // inline before the duplicate-key insert, parallel to
8647 // `membros_validation_runs_before_contratos_membership_check`
8648 // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8649 let mut s = three_member_spec();
8650 s.membros[0].versao = "^bad".into();
8651 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8652 let err = s.validate().unwrap_err();
8653 assert!(
8654 matches!(
8655 err,
8656 AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8657 ),
8658 "got {err:?}"
8659 );
8660 }
8661
8662 #[test]
8663 fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8664 // The diagnostic-shape pin: the error names the offending
8665 // `:versao` value verbatim so the author can grep their
8666 // caixa.lisp without re-running the build, and carries a
8667 // non-empty `reason` from `semver::VersionReq::parse` so the
8668 // parser's own wording flows through to the diagnostic.
8669 let mut s = three_member_spec();
8670 s.membros[2].versao = "not-a-req".into();
8671 let err = s.validate().unwrap_err();
8672 let AplicacaoError::MembroVersaoInvalid {
8673 caixa,
8674 versao,
8675 reason,
8676 } = err
8677 else {
8678 panic!("expected MembroVersaoInvalid, got other variant");
8679 };
8680 assert_eq!(caixa, "payment");
8681 assert_eq!(versao, "not-a-req");
8682 assert!(
8683 !reason.is_empty(),
8684 "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
8685 );
8686 }
8687
8688 #[test]
8689 fn membro_versao_invalid_runs_before_contratos_check() {
8690 // A malformed `:versao` on any member must surface its own
8691 // diagnostic (which names *which* member to fix) before any
8692 // `:contratos` membership lookup raises `ContratoMemberMissing`.
8693 // The `:contratos` gate runs after `validate_membros`, so this
8694 // is structurally guaranteed — pin it explicitly so a future
8695 // refactor that reorders the gates surfaces here.
8696 let mut s = three_member_spec();
8697 s.membros[1].versao = "^^0.1".into();
8698 // Add a contrato whose `:para` doesn't exist — would normally
8699 // raise ContratoMemberMissing at the membership lookup, but
8700 // the membros gate must fire first.
8701 s.contratos
8702 .push(contract_http("cart", "phantom", "/never-reached"));
8703 let err = s.validate().unwrap_err();
8704 assert!(
8705 matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
8706 "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
8707 );
8708 }
8709
8710 #[test]
8711 fn membros_validation_runs_before_contratos_membership_check() {
8712 // If `:membros` carries a duplicate, the membership-collapse
8713 // would silently accept a `:contratos :para "phantom"` so long
8714 // as some entry hashes to "phantom". Pinning order: the
8715 // duplicate-membros error fires first, regardless of whether
8716 // contratos reference real members.
8717 let mut s = three_member_spec();
8718 s.membros = vec![
8719 membro("cart", "^0.1"),
8720 membro("cart", "^0.2"),
8721 membro("catalog", "^0.1"),
8722 membro("payment", "^0.1"),
8723 ];
8724 let err = s.validate().unwrap_err();
8725 assert!(
8726 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8727 "got {err:?}"
8728 );
8729 }
8730
8731 #[test]
8732 fn distinct_membros_validate() {
8733 // Pin the happy-path: every `:membros` entry has a non-empty
8734 // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
8735 // The fixture already satisfies this; this test makes the
8736 // invariant explicit so a future refactor of the fixture can't
8737 // silently break the guarantee.
8738 three_member_spec().validate().unwrap();
8739 }
8740
8741 // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
8742
8743 #[test]
8744 fn rejects_membro_caixa_with_uppercase() {
8745 // The canonical "I copied the Servico's display name verbatim"
8746 // typo — caixa names are lowercase per K8s DNS-1123 label rule,
8747 // but author tools often round-trip a TitleCase or CamelCase
8748 // identifier from an ADR or a sketch. Pin the diagnostic names
8749 // the offending name and suggests the lower-cased fix in one
8750 // edit, mirroring the `rejects_entrada_host_with_uppercase`
8751 // gate's shape (c7d05ec).
8752 let mut s = three_member_spec();
8753 s.membros[1].caixa = "Cart".into();
8754 let err = s.validate().unwrap_err();
8755 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8756 panic!("expected MembroCaixaInvalid, got other variant");
8757 };
8758 assert_eq!(caixa, "Cart");
8759 assert!(
8760 reason.contains("uppercase"),
8761 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8762 );
8763 assert!(
8764 reason.contains("\"cart\""),
8765 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
8766 );
8767 }
8768
8769 #[test]
8770 fn rejects_membro_caixa_with_underscore() {
8771 // The canonical "I'm thinking of a Python module / Postgres
8772 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
8773 // label schema. K8s rejects `metadata.name: my_cart` at admission
8774 // time with an opaque `field is invalid` (no source-citing
8775 // diagnostic). The gate moves it to caixa-build time.
8776 let mut s = three_member_spec();
8777 s.membros[0].caixa = "my_cart".into();
8778 let err = s.validate().unwrap_err();
8779 assert!(
8780 matches!(
8781 err,
8782 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8783 if caixa == "my_cart" && reason.contains('_')
8784 ),
8785 "got {err:?}"
8786 );
8787 }
8788
8789 #[test]
8790 fn rejects_membro_caixa_with_dot() {
8791 // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
8792 // subdomain — even though K8s `metadata.name` itself accepts
8793 // dots (DNS-1123 subdomain rule), this string also lands as a
8794 // K8s Service name (DNS-1035 label — no dots) and as a label
8795 // value on identity-based Cilium selectors. The strictest floor
8796 // among the use sites wins. The "I want to namespace my member
8797 // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
8798 let mut s = three_member_spec();
8799 s.membros[2].caixa = "team.cart".into();
8800 let err = s.validate().unwrap_err();
8801 assert!(
8802 matches!(
8803 err,
8804 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8805 if caixa == "team.cart" && reason.contains('.')
8806 ),
8807 "got {err:?}"
8808 );
8809 }
8810
8811 #[test]
8812 fn rejects_membro_caixa_with_leading_hyphen() {
8813 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
8814 // with an alphanumeric. The K8s apiserver rejects `-cart`
8815 // outright; the renderer would emit a `metadata.name: "-cart"`
8816 // that fails admission far from the source caixa.lisp.
8817 let mut s = three_member_spec();
8818 s.membros[0].caixa = "-cart".into();
8819 let err = s.validate().unwrap_err();
8820 assert!(
8821 matches!(
8822 err,
8823 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8824 if caixa == "-cart" && reason.contains("start and end")
8825 ),
8826 "got {err:?}"
8827 );
8828 }
8829
8830 #[test]
8831 fn rejects_membro_caixa_with_trailing_hyphen() {
8832 // The symmetric arm of the boundary rule. Pin separately so
8833 // both ends of the label are covered against a future relaxation
8834 // that only checks one boundary.
8835 let mut s = three_member_spec();
8836 s.membros[1].caixa = "cart-".into();
8837 let err = s.validate().unwrap_err();
8838 assert!(
8839 matches!(
8840 err,
8841 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8842 if caixa == "cart-"
8843 ),
8844 "got {err:?}"
8845 );
8846 }
8847
8848 #[test]
8849 fn rejects_membro_caixa_with_unicode() {
8850 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8851 // (`xn--…`) by the author before it reaches K8s. The byte-by-
8852 // byte ASCII validity check rejects multi-byte UTF-8 sequences
8853 // by the first byte that fails the `[a-z0-9-]` predicate.
8854 let mut s = three_member_spec();
8855 s.membros[2].caixa = "café".into();
8856 let err = s.validate().unwrap_err();
8857 assert!(
8858 matches!(
8859 err,
8860 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8861 if caixa == "café"
8862 ),
8863 "got {err:?}"
8864 );
8865 }
8866
8867 #[test]
8868 fn rejects_membro_caixa_with_whitespace() {
8869 // Whitespace is the canonical "I pasted from a sketch / doc"
8870 // footgun. The apiserver rejects every `metadata.name` value
8871 // carrying whitespace; pin the gate fires at the right boundary.
8872 let mut s = three_member_spec();
8873 s.membros[0].caixa = "my cart".into();
8874 let err = s.validate().unwrap_err();
8875 assert!(
8876 matches!(
8877 err,
8878 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8879 if caixa == "my cart"
8880 ),
8881 "got {err:?}"
8882 );
8883 }
8884
8885 #[test]
8886 fn rejects_membro_caixa_too_long() {
8887 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
8888 // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
8889 // exactly. The gate's reason names both the cap and the actual
8890 // length so the author can shorten in one edit.
8891 let mut s = three_member_spec();
8892 let too_long = "a".repeat(64);
8893 s.membros[1].caixa = too_long.clone();
8894 let err = s.validate().unwrap_err();
8895 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8896 panic!("expected MembroCaixaInvalid");
8897 };
8898 assert_eq!(caixa, too_long);
8899 assert!(
8900 reason.contains("63") && reason.contains("64"),
8901 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
8902 );
8903 }
8904
8905 #[test]
8906 fn membro_caixa_max_length_validates() {
8907 // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
8908 // so a future tightening (e.g. dropping to 62) surfaces here as
8909 // a regression, mirroring `entrada_host_max_length_validates`
8910 // (c7d05ec).
8911 let mut s = three_member_spec();
8912 s.membros[2].caixa = "a".repeat(63);
8913 s.entrada.as_mut().unwrap().para = "a".repeat(63);
8914 // remove contratos referencing the renamed member; they'd
8915 // raise ContratoMemberMissing otherwise
8916 s.contratos
8917 .retain(|c| c.de != "payment" && c.para != "payment");
8918 s.validate().unwrap();
8919 }
8920
8921 #[test]
8922 fn accepts_canonical_membro_caixa_forms() {
8923 // The DNS-1123 label shapes a caixa author is realistically
8924 // going to write: single-word lowercase, hyphen-joined, ending
8925 // in a digit-suffixed version (`cart-v2`), starting with a
8926 // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
8927 // DNS-1035 which requires a letter at position 0), single-
8928 // character (`a` — boundary). Pin every leg so a future
8929 // tightening that bans (e.g.) digit-start identifiers surfaces
8930 // here.
8931 for form in [
8932 "checkout",
8933 "cart",
8934 "cart-v2",
8935 "a",
8936 "c0",
8937 "3rd-party-shim",
8938 "x-1-2-3-4",
8939 ] {
8940 let mut s = three_member_spec();
8941 // Renaming a member also requires updating downstream refs;
8942 // drop everything else and rebuild a minimal spec around
8943 // just the one renamed member.
8944 s.membros = vec![membro(form, "^0.1")];
8945 s.contratos = vec![];
8946 s.entrada = None;
8947 s.validate()
8948 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8949 }
8950 }
8951
8952 #[test]
8953 fn membro_caixa_empty_takes_precedence_over_invalid() {
8954 // Order pin: the existing `MembroCaixaEmpty` diagnostic
8955 // (which doesn't try to parse) fires before the new
8956 // `MembroCaixaInvalid` parse-side diagnostic, so an empty
8957 // `:caixa` keeps its narrower error message — the new gate
8958 // would also reject `""`, but the empty-string arm is the more
8959 // self-locating diagnostic for the author. Mirrors the
8960 // `entrada_host_empty_takes_precedence_over_invalid` pin
8961 // (c7d05ec).
8962 let mut s = three_member_spec();
8963 s.membros[1].caixa = String::new();
8964 let err = s.validate().unwrap_err();
8965 assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
8966 }
8967
8968 #[test]
8969 fn membro_caixa_invalid_fires_before_versao_check() {
8970 // Order pin: an invalid-shape `:caixa` surfaces *its own*
8971 // diagnostic (which names the offending caixa name), even when
8972 // the same entry's `:versao` is also empty/invalid. The shape
8973 // gate runs first because the diagnostic is more self-locating —
8974 // an empty/invalid `:versao` on an invalid-shape caixa name is
8975 // a downstream-fix-after-the-caixa-rename concern.
8976 let mut s = three_member_spec();
8977 s.membros[1].caixa = "Cart".into();
8978 s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
8979 let err = s.validate().unwrap_err();
8980 assert!(
8981 matches!(
8982 err,
8983 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
8984 ),
8985 "got {err:?}"
8986 );
8987 }
8988
8989 #[test]
8990 fn membro_caixa_invalid_fires_before_duplicate_check() {
8991 // Order pin: a malformed-shape `:caixa` on an earlier entry
8992 // surfaces *its own* diagnostic, even when a later entry would
8993 // otherwise collapse onto a duplicate name. The per-entry shape
8994 // gate runs inline before the duplicate-key insert, parallel
8995 // to `membro_versao_invalid_fires_before_duplicate_check`.
8996 let mut s = three_member_spec();
8997 s.membros[0].caixa = "Catalog".into();
8998 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8999 let err = s.validate().unwrap_err();
9000 assert!(
9001 matches!(
9002 err,
9003 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
9004 ),
9005 "got {err:?}"
9006 );
9007 }
9008
9009 #[test]
9010 fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
9011 // The diagnostic-shape pin: the error names the offending
9012 // `:caixa` value verbatim so the author can grep their
9013 // caixa.lisp without re-running the build, and carries a
9014 // non-empty `reason` naming the specific violation. Same
9015 // shape every typed-shape gate enshrines (c7d05ec's
9016 // `entrada_host_diagnostic_carries_offending_host`,
9017 // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
9018 let mut s = three_member_spec();
9019 s.membros[2].caixa = "BAD_NAME".into();
9020 let err = s.validate().unwrap_err();
9021 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9022 panic!("expected MembroCaixaInvalid");
9023 };
9024 assert_eq!(caixa, "BAD_NAME");
9025 assert!(
9026 !reason.is_empty(),
9027 "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
9028 );
9029 }
9030
9031 #[test]
9032 fn rejects_contrato_with_unknown_de() {
9033 let mut s = three_member_spec();
9034 s.contratos.push(contract_http("phantom", "catalog", "/x"));
9035 let err = s.validate().unwrap_err();
9036 assert!(
9037 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9038 );
9039 }
9040
9041 #[test]
9042 fn rejects_contrato_with_unknown_para() {
9043 let mut s = three_member_spec();
9044 s.contratos.push(contract_http("cart", "phantom", "/x"));
9045 let err = s.validate().unwrap_err();
9046 assert!(
9047 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9048 );
9049 }
9050
9051 #[test]
9052 fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
9053 // The read-path pin: the phantom-`:de` refusal arm's
9054 // `ContratoMemberMissing.caixa` carrier must be observed through
9055 // the lifted [`WitContract::source`] accessor, not the raw
9056 // `.de.clone()` field-access `String`-carry. Peer of the sibling
9057 // per-`:contratos` self-loop arm's `.source().to_string()` /
9058 // `.world_ref().to_string()` `String`-carry sites the earlier
9059 // convergence lifted onto the same accessor pair. A future
9060 // silent detour that reintroduced the raw `.de.clone()` at the
9061 // wrap envelope while the shape-gate and membership lookup
9062 // routed through the accessor would surface here as a byte-equal
9063 // miss between the fired diagnostic's `caixa:` field and the
9064 // offending edge's `.source()` — pinning the accessor as the
9065 // sole read path across the phantom-name refusal arm's arg +
9066 // wrap-envelope emit surface.
9067 let mut s = three_member_spec();
9068 let phantom = contract_http("phantom", "catalog", "/x");
9069 s.contratos.push(phantom.clone());
9070 let err = s.validate().unwrap_err();
9071 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9072 panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
9073 };
9074 assert_eq!(
9075 caixa,
9076 phantom.source(),
9077 "ContratoMemberMissing.caixa on the phantom-:de arm must \
9078 byte-equal WitContract::source — the wrap envelope must \
9079 route through the lifted accessor rather than the raw \
9080 .de.clone() field-access String-carry"
9081 );
9082 }
9083
9084 #[test]
9085 fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9086 // The symmetric read-path pin on the `:para` phantom-name
9087 // refusal arm — same shape as the sibling `:de` pin above but
9088 // on the callee-Servico axis. Pins the wrap envelope's
9089 // `caixa:` field is observed through the lifted
9090 // [`WitContract::destination`] accessor, not the raw
9091 // `.para.clone()` field-access `String`-carry.
9092 let mut s = three_member_spec();
9093 let phantom = contract_http("cart", "phantom", "/x");
9094 s.contratos.push(phantom.clone());
9095 let err = s.validate().unwrap_err();
9096 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9097 panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
9098 };
9099 assert_eq!(
9100 caixa,
9101 phantom.destination(),
9102 "ContratoMemberMissing.caixa on the phantom-:para arm must \
9103 byte-equal WitContract::destination — the wrap envelope \
9104 must route through the lifted accessor rather than the raw \
9105 .para.clone() field-access String-carry"
9106 );
9107 }
9108
9109 #[test]
9110 fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
9111 // The read-path pin on the `:de` DNS-1123-malformed shape-gate
9112 // refusal arm — the `validate_contrato_caixa` arg must be
9113 // observed through the lifted [`WitContract::source`] accessor,
9114 // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
9115 // value routes through the shared
9116 // [`crate::render::require_valid_dns_1123_label`] floor with the
9117 // accessor-projected value; the fired
9118 // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
9119 // the offending edge's `.source()`, pinning that the arg + the
9120 // downstream `caixa: caixa.to_string()` wrap route through the
9121 // same accessor's read path.
9122 let mut s = three_member_spec();
9123 let malformed = contract_http("BAD_NAME", "catalog", "/x");
9124 s.contratos.push(malformed.clone());
9125 let err = s.validate().unwrap_err();
9126 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9127 panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
9128 };
9129 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9130 assert_eq!(
9131 caixa,
9132 malformed.source(),
9133 "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
9134 byte-equal WitContract::source — the shape-gate arg + wrap \
9135 envelope must route through the lifted accessor rather \
9136 than the raw &c.de &String-borrow"
9137 );
9138 }
9139
9140 #[test]
9141 fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9142 // Symmetric arm to the sibling `:de` malformed-shape pin above,
9143 // on the `:para` axis. Pins the shape-gate arg + wrap envelope
9144 // route through the lifted [`WitContract::destination`]
9145 // accessor. `:para` runs after the `:de` shape gate in the
9146 // canonical edge-direction order, so the `:de` value must be
9147 // well-shaped for the `:para` gate to fire — the `cart` :de is
9148 // canonical.
9149 let mut s = three_member_spec();
9150 let malformed = contract_http("cart", "BAD_NAME", "/x");
9151 s.contratos.push(malformed.clone());
9152 let err = s.validate().unwrap_err();
9153 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9154 panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
9155 };
9156 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9157 assert_eq!(
9158 caixa,
9159 malformed.destination(),
9160 "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
9161 byte-equal WitContract::destination — the shape-gate arg + \
9162 wrap envelope must route through the lifted accessor \
9163 rather than the raw &c.para &String-borrow"
9164 );
9165 }
9166
9167 // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
9168
9169 #[test]
9170 fn rejects_contrato_de_empty() {
9171 // `:de ""` previously fell through to `ContratoMemberMissing`
9172 // (with `caixa: ""`) because the validated `:membros :caixa`
9173 // set never contains the empty string. The narrower
9174 // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
9175 // the offending slot.
9176 let mut s = three_member_spec();
9177 s.contratos.push(contract_http("", "catalog", "/x"));
9178 let err = s.validate().unwrap_err();
9179 assert_eq!(
9180 err,
9181 AplicacaoError::ContratoCaixaEmpty {
9182 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9183 },
9184 "got {err:?}"
9185 );
9186 }
9187
9188 #[test]
9189 fn rejects_contrato_para_empty() {
9190 // Symmetric arm to `:de ""` — `:para ""` previously fell
9191 // through to `ContratoMemberMissing { caixa: "" }`.
9192 let mut s = three_member_spec();
9193 s.contratos.push(contract_http("cart", "", "/x"));
9194 let err = s.validate().unwrap_err();
9195 assert_eq!(
9196 err,
9197 AplicacaoError::ContratoCaixaEmpty {
9198 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9199 },
9200 "got {err:?}"
9201 );
9202 }
9203
9204 #[test]
9205 fn rejects_contrato_de_with_uppercase() {
9206 // The canonical "I copied the Servico's TitleCase display
9207 // name from an ADR" typo. Until this gate landed `:de "Cart"`
9208 // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
9209 // as "this caixa isn't in `:membros`" when the root cause is
9210 // "this `:de` value's shape can never legitimately match a
9211 // validated member (DNS-1123 labels are lowercase)". The
9212 // narrower diagnostic names the offending slot, the value
9213 // verbatim, and the parser-shaped reason.
9214 let mut s = three_member_spec();
9215 s.contratos.push(contract_http("Cart", "catalog", "/x"));
9216 let err = s.validate().unwrap_err();
9217 let AplicacaoError::ContratoCaixaInvalid {
9218 slot,
9219 caixa,
9220 reason,
9221 } = err
9222 else {
9223 panic!("expected ContratoCaixaInvalid, got other variant");
9224 };
9225 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9226 assert_eq!(caixa, "Cart");
9227 assert!(
9228 reason.contains("uppercase"),
9229 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9230 );
9231 }
9232
9233 #[test]
9234 fn rejects_contrato_para_with_underscore() {
9235 // The canonical "I'm thinking of a Python module" leak —
9236 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9237 // Pin the `:para` axis surfaces the same diagnostic shape as
9238 // the `:de` axis on the underscore violation.
9239 let mut s = three_member_spec();
9240 s.contratos.push(contract_http("cart", "my_catalog", "/x"));
9241 let err = s.validate().unwrap_err();
9242 assert!(
9243 matches!(
9244 err,
9245 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9246 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
9247 ),
9248 "got {err:?}"
9249 );
9250 }
9251
9252 #[test]
9253 fn rejects_contrato_de_with_dot() {
9254 // A `:contratos :de` value is a single DNS-1123 *label*, not
9255 // a subdomain — mirroring the `:membros :caixa` floor. The
9256 // strictest floor among the use sites wins.
9257 let mut s = three_member_spec();
9258 s.contratos
9259 .push(contract_http("team.cart", "catalog", "/x"));
9260 let err = s.validate().unwrap_err();
9261 assert!(
9262 matches!(
9263 err,
9264 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9265 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
9266 ),
9267 "got {err:?}"
9268 );
9269 }
9270
9271 #[test]
9272 fn rejects_contrato_para_with_unicode() {
9273 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9274 // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
9275 // validity check rejects multi-byte UTF-8 by the first
9276 // non-`[a-z0-9-]` byte.
9277 let mut s = three_member_spec();
9278 s.contratos.push(contract_http("cart", "café", "/x"));
9279 let err = s.validate().unwrap_err();
9280 assert!(
9281 matches!(
9282 err,
9283 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9284 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
9285 ),
9286 "got {err:?}"
9287 );
9288 }
9289
9290 #[test]
9291 fn rejects_contrato_de_with_leading_hyphen() {
9292 // DNS-1123 boundary rule: labels must start and end with an
9293 // alphanumeric. K8s rejects `-cart` outright; the narrower
9294 // shape diagnostic now names the violation at caixa-build
9295 // time rather than the misframed membership-lookup arm.
9296 let mut s = three_member_spec();
9297 s.contratos.push(contract_http("-cart", "catalog", "/x"));
9298 let err = s.validate().unwrap_err();
9299 assert!(
9300 matches!(
9301 err,
9302 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9303 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
9304 ),
9305 "got {err:?}"
9306 );
9307 }
9308
9309 #[test]
9310 fn contrato_de_empty_takes_precedence_over_invalid() {
9311 // Order pin: the `ContratoCaixaEmpty` arm fires before the
9312 // `ContratoCaixaInvalid` parse-side arm — same empty-first
9313 // cascade `validate_membro_caixa` / `validate_placement_cluster`
9314 // / `validate_entrada_host` already establish on their peer
9315 // name axes. The empty string is a structurally distinct
9316 // authoring footgun (the author left the field blank, vs.
9317 // typed a malformed value), so it gets its own diagnostic.
9318 let mut s = three_member_spec();
9319 s.contratos.push(contract_http("", "catalog", "/x"));
9320 let err = s.validate().unwrap_err();
9321 assert_eq!(
9322 err,
9323 AplicacaoError::ContratoCaixaEmpty {
9324 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9325 }
9326 );
9327 }
9328
9329 #[test]
9330 fn contrato_de_shape_fires_before_para_shape() {
9331 // Per-axis order pin: within one `:contratos` entry, the `:de`
9332 // shape gate fires before the `:para` shape gate — same
9333 // edge-direction order the existing `ContratoMemberMissing` /
9334 // `ContratoSelfLoop` / target-dispatch checks use, so the
9335 // diagnostic for a contract with both `:de` and `:para`
9336 // malformed is stable. Authors fixing the surfaced `:de`
9337 // first will see `:para`'s diagnostic on re-run.
9338 let mut s = three_member_spec();
9339 s.contratos.push(contract_http("Cart", "Catalog", "/x"));
9340 let err = s.validate().unwrap_err();
9341 assert!(
9342 matches!(
9343 err,
9344 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9345 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9346 ),
9347 "got {err:?}"
9348 );
9349 }
9350
9351 #[test]
9352 fn contrato_shape_fires_before_membership_lookup() {
9353 // The load-bearing pin: an invalid-shape `:de` surfaces its
9354 // *own* diagnostic, not the misframed `ContratoMemberMissing`.
9355 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9356 // an invalid-shape `:de` could never legitimately match any
9357 // member — the prior `ContratoMemberMissing` diagnostic was
9358 // a structural impossibility framed as a graph-membership
9359 // failure. The shape gate now routes every such input through
9360 // the narrower self-locating diagnostic.
9361 let mut s = three_member_spec();
9362 s.contratos.push(contract_http("Cart", "catalog", "/x"));
9363 let err = s.validate().unwrap_err();
9364 assert!(
9365 matches!(
9366 err,
9367 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
9368 ),
9369 "got {err:?}"
9370 );
9371 // And the symmetric case: an invalid-shape `:para` surfaces
9372 // its own diagnostic too, even when `:de` is well-shaped.
9373 let mut s = three_member_spec();
9374 s.contratos.push(contract_http("cart", "Catalog", "/x"));
9375 let err = s.validate().unwrap_err();
9376 assert!(
9377 matches!(
9378 err,
9379 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9380 ),
9381 "got {err:?}"
9382 );
9383 }
9384
9385 #[test]
9386 fn contrato_shape_fires_before_self_edge_check() {
9387 // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9388 // bugs: the shape violation (uppercase) and the self-edge
9389 // violation. The narrower per-axis shape diagnostic surfaces
9390 // first because fixing the shape may reveal that the author
9391 // also meant to point `:para` at a different member — the
9392 // self-edge framing is only useful once both endpoints have
9393 // valid shape.
9394 let mut s = three_member_spec();
9395 s.contratos.push(contract_http("Cart", "Cart", "/x"));
9396 let err = s.validate().unwrap_err();
9397 assert!(
9398 matches!(
9399 err,
9400 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9401 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9402 ),
9403 "got {err:?}"
9404 );
9405 }
9406
9407 #[test]
9408 fn contrato_well_shaped_phantom_still_raises_member_missing() {
9409 // Strict-improvement pin: a well-shaped `:de` that simply
9410 // isn't in `:membros` (a phantom reference — author meant
9411 // to add the member but didn't, or renamed and missed an
9412 // update) still surfaces `ContratoMemberMissing`, unchanged.
9413 // The shape gate only intercepts inputs that could never
9414 // legitimately match a validated member; legitimately-shaped
9415 // phantom references remain on the graph-membership axis.
9416 let mut s = three_member_spec();
9417 s.contratos
9418 .push(contract_http("phantom-shim", "catalog", "/x"));
9419 let err = s.validate().unwrap_err();
9420 assert!(
9421 matches!(
9422 err,
9423 AplicacaoError::ContratoMemberMissing { ref caixa }
9424 if caixa == "phantom-shim"
9425 ),
9426 "got {err:?}"
9427 );
9428 }
9429
9430 #[test]
9431 fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9432 // The diagnostic-shape pin: the error names the offending
9433 // slot (`:de` or `:para`) verbatim and the offending value
9434 // verbatim plus a non-empty parser-shaped reason, so the
9435 // author can grep their caixa.lisp for `:de "<name>"` /
9436 // `:para "<name>"` and fix it in one edit. Same diagnostic
9437 // shape as `MembroCaixaInvalid` (3f9d7a0) and
9438 // `PlacementClusterInvalid` (6c8c00b).
9439 let mut s = three_member_spec();
9440 s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9441 let err = s.validate().unwrap_err();
9442 let AplicacaoError::ContratoCaixaInvalid {
9443 slot,
9444 caixa,
9445 reason,
9446 } = err
9447 else {
9448 panic!("expected ContratoCaixaInvalid, got {err:?}");
9449 };
9450 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9451 assert_eq!(caixa, "BAD_NAME");
9452 assert!(
9453 !reason.is_empty(),
9454 "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9455 );
9456 }
9457
9458 #[test]
9459 fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9460 // Scalar-value pin: the two author-facing kebab-case labels the
9461 // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9462 // admits on the `:contratos` per-entry endpoint-shape axis,
9463 // one arm per typed sub-slot. Mirrors the peer scalar-value
9464 // pin the sibling top-level M2 / M3 / Supervisor
9465 // author-facing-label consts carry
9466 // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9467 // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9468 // slot itself), so every altitude of the typed-slot algebra
9469 // shares the same "one canonical byte-string per arm"
9470 // discipline. A future rebrand (`:de` → `:from` matching the
9471 // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9472 // sibling, `:para` → `:to` matching the same, or
9473 // `:de`/`:para` → `:source`/`:target` matching the WIT
9474 // world's `import`/`export` half-vocabulary) lands as an
9475 // edit to exactly one const, and every consumer that reaches
9476 // for the label picks it up at build time rather than at
9477 // runtime as a downstream `ContratoCaixaEmpty` /
9478 // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9479 // diagnostic mismatch far from the rename's commit.
9480 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9481 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9482 }
9483
9484 #[test]
9485 fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9486 // Production-through-const pin: the two per-axis labels the
9487 // per-`:contratos` entry endpoint-shape gate at
9488 // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9489 // argument to [`validate_contrato_caixa`] route through the
9490 // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9491 // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9492 // future rebrand that reaches the const but not the gate (or
9493 // vice versa) surfaces here at build time rather than at
9494 // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9495 // `slot: <stale-kebab-case>` diagnostic far from the rename's
9496 // commit. Mirror of the peer
9497 // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9498 // pin (882f498) on the sibling M3 top-level slot axis.
9499 let mut s = three_member_spec();
9500 s.contratos.push(contract_http("", "catalog", "/x"));
9501 assert_eq!(
9502 s.validate().unwrap_err(),
9503 AplicacaoError::ContratoCaixaEmpty {
9504 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9505 }
9506 );
9507 let mut s = three_member_spec();
9508 s.contratos.push(contract_http("cart", "", "/x"));
9509 assert_eq!(
9510 s.validate().unwrap_err(),
9511 AplicacaoError::ContratoCaixaEmpty {
9512 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9513 }
9514 );
9515 }
9516
9517 #[test]
9518 fn accepts_canonical_contrato_caixa_forms() {
9519 // The DNS-1123 label shapes a caixa author is realistically
9520 // going to write on a `:contratos :de` / `:para`. Pin every
9521 // leg so a future tightening that bans (e.g.) digit-start
9522 // identifiers surfaces here, mirroring
9523 // `accepts_canonical_membro_caixa_forms` on the peer name
9524 // axis.
9525 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9526 let mut s = three_member_spec();
9527 s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9528 s.contratos = vec![contract_http("checkout", form, "/x")];
9529 s.entrada = None;
9530 s.validate().unwrap_or_else(|e| {
9531 panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9532 });
9533
9534 let mut s = three_member_spec();
9535 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9536 s.contratos = vec![contract_http(form, "catalog", "/x")];
9537 s.entrada = None;
9538 s.validate().unwrap_or_else(|e| {
9539 panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9540 });
9541 }
9542 }
9543
9544 #[test]
9545 fn rejects_empty_wit() {
9546 let mut s = three_member_spec();
9547 s.contratos.push(WitContract {
9548 de: "cart".into(),
9549 para: "catalog".into(),
9550 wit: "".into(),
9551 endpoint: None,
9552 subject: None,
9553 slot: None,
9554 });
9555 let err = s.validate().unwrap_err();
9556 assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9557 }
9558
9559 #[test]
9560 fn rejects_entrada_to_unknown_member() {
9561 let mut s = three_member_spec();
9562 s.entrada.as_mut().unwrap().para = "phantom".into();
9563 assert!(matches!(
9564 s.validate().unwrap_err(),
9565 AplicacaoError::EntradaMemberMissing { .. }
9566 ));
9567 }
9568
9569 // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9570
9571 #[test]
9572 fn rejects_entrada_para_empty() {
9573 // `:para ""` previously fell through to
9574 // `EntradaMemberMissing { para: "" }` because the validated
9575 // `:membros :caixa` set never contains the empty string. The
9576 // narrower `EntradaParaEmpty` diagnostic now names the
9577 // offending slot directly — same empty-first cascade
9578 // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9579 // `ContratoCaixaEmpty` establish on the peer name axes.
9580 let mut s = three_member_spec();
9581 s.entrada.as_mut().unwrap().para = String::new();
9582 let err = s.validate().unwrap_err();
9583 assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9584 }
9585
9586 #[test]
9587 fn rejects_entrada_para_with_uppercase() {
9588 // The canonical "I copied the Servico's TitleCase display
9589 // name from an ADR" typo. Until this gate landed `:para "Cart"`
9590 // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9591 // as "this caixa isn't in `:membros`" when the root cause is
9592 // "this `:para` value's shape can never legitimately match a
9593 // validated member (DNS-1123 labels are lowercase)". The
9594 // narrower diagnostic names the value verbatim plus the
9595 // parser-shaped reason.
9596 let mut s = three_member_spec();
9597 s.entrada.as_mut().unwrap().para = "Cart".into();
9598 let err = s.validate().unwrap_err();
9599 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9600 panic!("expected EntradaParaInvalid, got other variant");
9601 };
9602 assert_eq!(para, "Cart");
9603 assert!(
9604 reason.contains("uppercase"),
9605 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9606 );
9607 }
9608
9609 #[test]
9610 fn rejects_entrada_para_with_underscore() {
9611 // The canonical "I'm thinking of a Python module" leak —
9612 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9613 let mut s = three_member_spec();
9614 s.entrada.as_mut().unwrap().para = "my_cart".into();
9615 let err = s.validate().unwrap_err();
9616 assert!(
9617 matches!(
9618 err,
9619 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9620 if para == "my_cart" && reason.contains('_')
9621 ),
9622 "got {err:?}"
9623 );
9624 }
9625
9626 #[test]
9627 fn rejects_entrada_para_with_dot() {
9628 // An `:entrada :para` value is a single DNS-1123 *label*, not
9629 // a subdomain — mirroring the `:membros :caixa` floor. The
9630 // strictest floor among the use sites wins.
9631 let mut s = three_member_spec();
9632 s.entrada.as_mut().unwrap().para = "team.cart".into();
9633 let err = s.validate().unwrap_err();
9634 assert!(
9635 matches!(
9636 err,
9637 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9638 if para == "team.cart" && reason.contains('.')
9639 ),
9640 "got {err:?}"
9641 );
9642 }
9643
9644 #[test]
9645 fn rejects_entrada_para_with_unicode() {
9646 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9647 // (`xn--…`) before it reaches K8s.
9648 let mut s = three_member_spec();
9649 s.entrada.as_mut().unwrap().para = "café".into();
9650 let err = s.validate().unwrap_err();
9651 assert!(
9652 matches!(
9653 err,
9654 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9655 ),
9656 "got {err:?}"
9657 );
9658 }
9659
9660 #[test]
9661 fn rejects_entrada_para_with_leading_hyphen() {
9662 // DNS-1123 boundary rule: labels must start and end with an
9663 // alphanumeric. K8s rejects `-cart` outright.
9664 let mut s = three_member_spec();
9665 s.entrada.as_mut().unwrap().para = "-cart".into();
9666 let err = s.validate().unwrap_err();
9667 assert!(
9668 matches!(
9669 err,
9670 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9671 if para == "-cart" && reason.contains("start and end")
9672 ),
9673 "got {err:?}"
9674 );
9675 }
9676
9677 #[test]
9678 fn rejects_entrada_para_with_trailing_hyphen() {
9679 // Symmetric boundary arm.
9680 let mut s = three_member_spec();
9681 s.entrada.as_mut().unwrap().para = "cart-".into();
9682 let err = s.validate().unwrap_err();
9683 assert!(
9684 matches!(
9685 err,
9686 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9687 if para == "cart-" && reason.contains("start and end")
9688 ),
9689 "got {err:?}"
9690 );
9691 }
9692
9693 #[test]
9694 fn rejects_entrada_para_too_long() {
9695 // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
9696 // bytes per label. K8s rejects longer names at admission on
9697 // every `metadata.name` axis.
9698 let mut s = three_member_spec();
9699 s.entrada.as_mut().unwrap().para = "a".repeat(64);
9700 let err = s.validate().unwrap_err();
9701 assert!(
9702 matches!(
9703 err,
9704 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9705 if para.len() == 64 && reason.contains("max length")
9706 ),
9707 "got {err:?}"
9708 );
9709 }
9710
9711 #[test]
9712 fn entrada_para_empty_takes_precedence_over_invalid() {
9713 // Order pin: the `EntradaParaEmpty` arm fires before the
9714 // `EntradaParaInvalid` parse-side arm — same empty-first
9715 // cascade `validate_membro_caixa` / `validate_placement_cluster`
9716 // / `validate_contrato_caixa` already establish.
9717 let mut s = three_member_spec();
9718 s.entrada.as_mut().unwrap().para = String::new();
9719 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
9720 }
9721
9722 #[test]
9723 fn entrada_para_shape_fires_before_membership_lookup() {
9724 // The load-bearing pin: an invalid-shape `:para` surfaces its
9725 // *own* diagnostic, not the misframed `EntradaMemberMissing`.
9726 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9727 // an invalid-shape `:para` could never legitimately match any
9728 // member — the prior `EntradaMemberMissing` diagnostic framed
9729 // a structural impossibility as a graph-membership failure.
9730 let mut s = three_member_spec();
9731 s.entrada.as_mut().unwrap().para = "Cart".into();
9732 let err = s.validate().unwrap_err();
9733 assert!(
9734 matches!(
9735 err,
9736 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9737 ),
9738 "got {err:?}"
9739 );
9740 }
9741
9742 #[test]
9743 fn entrada_para_shape_fires_before_host_gate() {
9744 // Per-`:entrada` order pin: the `:para` shape gate fires
9745 // before the `:host` gate, mirroring the existing
9746 // `entrada_host_member_missing_takes_precedence_over_host_invalid`
9747 // ordering where the member-lookup arm preceded the host gate.
9748 // The shape gate slots ahead of that, so a malformed `:para`
9749 // surfaces its own diagnostic even when `:host` is also wrong.
9750 let mut s = three_member_spec();
9751 let e = s.entrada.as_mut().unwrap();
9752 e.para = "Cart".into();
9753 e.host = "BAD HOST".into();
9754 let err = s.validate().unwrap_err();
9755 assert!(
9756 matches!(
9757 err,
9758 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9759 ),
9760 "got {err:?}"
9761 );
9762 }
9763
9764 #[test]
9765 fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
9766 // Strict-improvement pin: a well-shaped `:para` that simply
9767 // isn't in `:membros` (a phantom reference — author meant to
9768 // add the member but didn't, or renamed and missed an
9769 // update) still surfaces `EntradaMemberMissing`, unchanged.
9770 // The shape gate only intercepts inputs that could never
9771 // legitimately match a validated member.
9772 let mut s = three_member_spec();
9773 s.entrada.as_mut().unwrap().para = "phantom-shim".into();
9774 let err = s.validate().unwrap_err();
9775 assert!(
9776 matches!(
9777 err,
9778 AplicacaoError::EntradaMemberMissing { ref para }
9779 if para == "phantom-shim"
9780 ),
9781 "got {err:?}"
9782 );
9783 }
9784
9785 #[test]
9786 fn entrada_para_invalid_diagnostic_carries_offending_para() {
9787 // The diagnostic-shape pin: the error names the offending
9788 // `:para` value verbatim plus a non-empty parser-shaped
9789 // reason, so the author can grep their caixa.lisp for
9790 // `:para "<name>"` and fix it in one edit. Same diagnostic
9791 // shape as `MembroCaixaInvalid` (3f9d7a0),
9792 // `PlacementClusterInvalid` (6c8c00b), and
9793 // `ContratoCaixaInvalid` (8d5af6b).
9794 let mut s = three_member_spec();
9795 s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
9796 let err = s.validate().unwrap_err();
9797 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9798 panic!("expected EntradaParaInvalid, got {err:?}");
9799 };
9800 assert_eq!(para, "BAD_NAME");
9801 assert!(
9802 !reason.is_empty(),
9803 "EntradaParaInvalid `reason` must carry a parser-shaped wording"
9804 );
9805 }
9806
9807 #[test]
9808 fn accepts_canonical_entrada_para_forms() {
9809 // Positive-control sweep covering the DNS-1123 label shapes a
9810 // caixa author is realistically going to write on `:entrada
9811 // :para`. Pin every leg so a future tightening that bans
9812 // (e.g.) digit-start identifiers surfaces here, mirroring
9813 // `accepts_canonical_membro_caixa_forms` and
9814 // `accepts_canonical_contrato_caixa_forms` on the peer name
9815 // axes.
9816 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9817 let mut s = three_member_spec();
9818 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9819 s.contratos = vec![contract_http(form, "catalog", "/x")];
9820 s.entrada = Some(Entrada {
9821 host: "checkout.quero.cloud".into(),
9822 para: form.into(),
9823 paths: vec!["/api".into()],
9824 port: 8080,
9825 });
9826 s.validate().unwrap_or_else(|e| {
9827 panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
9828 });
9829 }
9830 }
9831
9832 #[test]
9833 fn rejects_replicated_without_clusters() {
9834 let mut s = three_member_spec();
9835 s.placement.clusters = vec![];
9836 assert!(matches!(
9837 s.validate().unwrap_err(),
9838 AplicacaoError::PlacementWithoutClusters { .. }
9839 ));
9840 }
9841
9842 #[test]
9843 fn rejects_sharded_without_key() {
9844 let mut s = three_member_spec();
9845 s.placement.estrategia = PlacementStrategy::Sharded;
9846 s.placement.shard_key = None;
9847 s.placement.clusters = vec!["rio".into()];
9848 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
9849 }
9850
9851 #[test]
9852 fn sharded_with_key_validates() {
9853 let mut s = three_member_spec();
9854 s.placement.estrategia = PlacementStrategy::Sharded;
9855 s.placement.shard_key = Some("$tenantId".into());
9856 s.validate().unwrap();
9857 }
9858
9859 #[test]
9860 fn round_trip_via_json_preserves_shape() {
9861 let s = three_member_spec();
9862 let json = serde_json::to_string(&s.membros).unwrap();
9863 let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
9864 assert_eq!(back, s.membros);
9865
9866 let json = serde_json::to_string(&s.contratos).unwrap();
9867 let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
9868 assert_eq!(back, s.contratos);
9869
9870 let json = serde_json::to_string(&s.placement).unwrap();
9871 let back: Placement = serde_json::from_str(&json).unwrap();
9872 assert_eq!(back, s.placement);
9873
9874 let json = serde_json::to_string(&s.entrada).unwrap();
9875 let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
9876 assert_eq!(back, s.entrada);
9877 }
9878
9879 #[test]
9880 fn rate_limit_round_trip_seconds() {
9881 let policy = MeshPolicy {
9882 rate_limit: Some(RateLimit {
9883 rate: 100,
9884 window: Duration::from_secs(1),
9885 }),
9886 ..Default::default()
9887 };
9888 let json = serde_json::to_string(&policy).unwrap();
9889 assert!(json.contains("\"100/s\""));
9890 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9891 assert_eq!(back.rate_limit.unwrap().rate, 100);
9892 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
9893 }
9894
9895 #[test]
9896 fn rate_limit_round_trip_minutes() {
9897 let policy = MeshPolicy {
9898 rate_limit: Some(RateLimit {
9899 rate: 5000,
9900 window: Duration::from_secs(60),
9901 }),
9902 ..Default::default()
9903 };
9904 let json = serde_json::to_string(&policy).unwrap();
9905 assert!(json.contains("\"5000/m\""));
9906 }
9907
9908 #[test]
9909 fn circuit_breaker_round_trip() {
9910 let policy = MeshPolicy {
9911 circuit_breaker: Some(CircuitBreaker {
9912 max_failures: 5,
9913 window: Duration::from_secs(60),
9914 }),
9915 ..Default::default()
9916 };
9917 let json = serde_json::to_string(&policy).unwrap();
9918 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9919 assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
9920 assert_eq!(
9921 back.circuit_breaker.unwrap().window,
9922 Duration::from_secs(60)
9923 );
9924 }
9925
9926 #[test]
9927 fn rejects_http_contrato_without_endpoint() {
9928 let mut s = three_member_spec();
9929 s.contratos.push(WitContract {
9930 de: "cart".into(),
9931 para: "catalog".into(),
9932 wit: "wasi:http/proxy".into(),
9933 endpoint: None,
9934 subject: None,
9935 slot: None,
9936 });
9937 let err = s.validate().unwrap_err();
9938 assert!(matches!(
9939 err,
9940 AplicacaoError::ContratoMissingTarget {
9941 expected: WitTarget::HTTP_FIELD_NAME,
9942 ..
9943 }
9944 ));
9945 }
9946
9947 #[test]
9948 fn rejects_http_contrato_with_subject() {
9949 let mut s = three_member_spec();
9950 s.contratos.push(WitContract {
9951 de: "cart".into(),
9952 para: "catalog".into(),
9953 wit: "wasi:http/proxy".into(),
9954 endpoint: Some("/x".into()),
9955 subject: Some("not.allowed.here".into()),
9956 slot: None,
9957 });
9958 let err = s.validate().unwrap_err();
9959 assert!(matches!(
9960 err,
9961 AplicacaoError::ContratoWrongTarget {
9962 expected: WitTarget::HTTP_FIELD_NAME,
9963 ..
9964 }
9965 ));
9966 }
9967
9968 #[test]
9969 fn rejects_pubsub_contrato_without_subject() {
9970 let mut s = three_member_spec();
9971 s.contratos.push(WitContract {
9972 de: "cart".into(),
9973 para: "catalog".into(),
9974 wit: "nats:pub-sub".into(),
9975 endpoint: None,
9976 subject: None,
9977 slot: None,
9978 });
9979 let err = s.validate().unwrap_err();
9980 assert!(matches!(
9981 err,
9982 AplicacaoError::ContratoMissingTarget {
9983 expected: WitTarget::PUBSUB_FIELD_NAME,
9984 ..
9985 }
9986 ));
9987 }
9988
9989 #[test]
9990 fn rejects_pubsub_contrato_with_endpoint() {
9991 let mut s = three_member_spec();
9992 s.contratos.push(WitContract {
9993 de: "cart".into(),
9994 para: "catalog".into(),
9995 wit: "kafka:topic".into(),
9996 endpoint: Some("/wrong".into()),
9997 subject: Some("topic.x".into()),
9998 slot: None,
9999 });
10000 let err = s.validate().unwrap_err();
10001 assert!(matches!(
10002 err,
10003 AplicacaoError::ContratoWrongTarget {
10004 expected: WitTarget::PUBSUB_FIELD_NAME,
10005 ..
10006 }
10007 ));
10008 }
10009
10010 #[test]
10011 fn rejects_store_contrato_without_slot() {
10012 let mut s = three_member_spec();
10013 s.contratos.push(WitContract {
10014 de: "cart".into(),
10015 para: "catalog".into(),
10016 wit: "wasi:keyvalue/store".into(),
10017 endpoint: None,
10018 subject: None,
10019 slot: None,
10020 });
10021 let err = s.validate().unwrap_err();
10022 assert!(matches!(
10023 err,
10024 AplicacaoError::ContratoMissingTarget {
10025 expected: WitTarget::STORE_FIELD_NAME,
10026 ..
10027 }
10028 ));
10029 }
10030
10031 // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
10032
10033 #[test]
10034 fn rejects_http_contrato_with_empty_endpoint() {
10035 // `Some("")` for an HTTP endpoint passes the presence check
10036 // (target() previously returned WitTarget::Http { endpoint: "" })
10037 // but renders as a `path: ""` Cilium L7 rule that matches no
10038 // traffic. Same value-shape footgun closed for :entrada :paths
10039 // entries (eb3456d).
10040 let mut s = three_member_spec();
10041 s.contratos.push(WitContract {
10042 de: "cart".into(),
10043 para: "catalog".into(),
10044 wit: "wasi:http/proxy".into(),
10045 endpoint: Some(String::new()),
10046 subject: None,
10047 slot: None,
10048 });
10049 let err = s.validate().unwrap_err();
10050 assert!(
10051 matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
10052 if de == "cart" && para == "catalog"),
10053 "got {err:?}"
10054 );
10055 }
10056
10057 #[test]
10058 fn rejects_http_contrato_with_relative_endpoint() {
10059 // Cilium L7 :path + Gateway API PathPrefix both require a
10060 // leading `/`. Same shape required of :entrada :paths
10061 // (eb3456d). Lifted into target() so every consumer of the
10062 // typed WitTarget view inherits the guarantee.
10063 let mut s = three_member_spec();
10064 s.contratos.push(WitContract {
10065 de: "cart".into(),
10066 para: "catalog".into(),
10067 wit: "wasi:http/proxy".into(),
10068 endpoint: Some("products/:id".into()),
10069 subject: None,
10070 slot: None,
10071 });
10072 let err = s.validate().unwrap_err();
10073 assert!(
10074 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10075 if endpoint == "products/:id"),
10076 "got {err:?}"
10077 );
10078 }
10079
10080 #[test]
10081 fn rejects_pubsub_contrato_with_empty_subject() {
10082 // NATS / Kafka publish without a subject is a no-op subscribe;
10083 // never the author's intent. Same empty-string rejection as
10084 // :membros :caixa, :placement :clusters entries, :entrada
10085 // :paths entries — every value carried by every typed slot is
10086 // value-shape-checked at validate().
10087 let mut s = three_member_spec();
10088 s.contratos.push(WitContract {
10089 de: "cart".into(),
10090 para: "catalog".into(),
10091 wit: "nats:pub-sub".into(),
10092 endpoint: None,
10093 subject: Some(String::new()),
10094 slot: None,
10095 });
10096 let err = s.validate().unwrap_err();
10097 assert!(
10098 matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
10099 if de == "cart" && para == "catalog"),
10100 "got {err:?}"
10101 );
10102 }
10103
10104 #[test]
10105 fn rejects_store_contrato_with_empty_slot() {
10106 // An empty slot template addresses the bucket root, defeating
10107 // the per-key isolation the slot exists for — a footgun on
10108 // `wasi:keyvalue/store` whose closest analog is the empty
10109 // shard-key rejected on :placement Sharded (c7c7799).
10110 let mut s = three_member_spec();
10111 s.contratos.push(WitContract {
10112 de: "cart".into(),
10113 para: "catalog".into(),
10114 wit: "wasi:keyvalue/store".into(),
10115 endpoint: None,
10116 subject: None,
10117 slot: Some(String::new()),
10118 });
10119 let err = s.validate().unwrap_err();
10120 assert!(
10121 matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
10122 if de == "cart" && para == "catalog"),
10123 "got {err:?}"
10124 );
10125 }
10126
10127 #[test]
10128 fn http_contrato_root_endpoint_validates() {
10129 // Pin the boundary case: a single-`/` endpoint is the catch-all
10130 // form the Gateway HTTPRoute renderer falls back to when
10131 // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
10132 // must remain a valid contrato endpoint too.
10133 let mut s = three_member_spec();
10134 s.contratos.push(contract_http("cart", "catalog", "/"));
10135 s.validate().unwrap();
10136 }
10137
10138 // ── :contratos :endpoint value-shape gate ────────────────────────────
10139 //
10140 // Mirrors the `:entrada :paths` value-shape suite on the peer
10141 // HTTP-path axis. Until this gate landed `WitContract::target()`
10142 // only refused the empty string + the missing-leading-`/` form
10143 // (c4213a4); a structurally invalid endpoint passed validate and
10144 // landed verbatim as a Cilium L7 `path:` rule
10145 // (caixa-mesh/src/lib.rs:311) that either silently dropped all
10146 // traffic or was rejected at apply time by Cilium policy admission.
10147 // Every authoring footgun the K8s Gateway API webhook / Cilium
10148 // policy validator would catch on admission now becomes a caixa-
10149 // build-time `ContratoEndpointInvalid` with the offending
10150 // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
10151 // shape as `EntradaPathInvalid` on the sibling axis; same shared
10152 // predicate (`crate::render::is_gateway_api_http_path`) ensures
10153 // drift between the two axes' rule enforcement is a build error
10154 // at the predicate.
10155
10156 fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
10157 // Fresh spec per call so the would-be-duplicate edge
10158 // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
10159 // `three_member_spec`'s pre-existing
10160 // `(cart, catalog, …, /products/:id)` entry — only the
10161 // endpoint payload differs.
10162 let mut s = three_member_spec();
10163 s.contratos.push(contract_http("cart", "catalog", ep));
10164 s.validate().unwrap_err()
10165 }
10166
10167 #[test]
10168 fn rejects_http_contrato_endpoint_with_query() {
10169 // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
10170 // silently rendered as a Cilium L7 `path: "/charge?token=X"`
10171 // rule the L7 matcher would never satisfy.
10172 let err = contrato_endpoint_err("/charge?token=X");
10173 assert!(
10174 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10175 if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
10176 "got {err:?}"
10177 );
10178 }
10179
10180 #[test]
10181 fn rejects_http_contrato_endpoint_with_fragment() {
10182 let err = contrato_endpoint_err("/charge#frag");
10183 assert!(
10184 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10185 if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
10186 "got {err:?}"
10187 );
10188 }
10189
10190 #[test]
10191 fn rejects_http_contrato_endpoint_with_whitespace() {
10192 let err = contrato_endpoint_err("/foo bar");
10193 assert!(
10194 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10195 if endpoint == "/foo bar" && reason.contains("whitespace")),
10196 "got {err:?}"
10197 );
10198 }
10199
10200 #[test]
10201 fn rejects_http_contrato_endpoint_with_control_char() {
10202 let err = contrato_endpoint_err("/api/\x01bar");
10203 assert!(
10204 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10205 if endpoint == "/api/\x01bar" && reason.contains("control character")),
10206 "got {err:?}"
10207 );
10208 }
10209
10210 #[test]
10211 fn rejects_http_contrato_endpoint_with_non_ascii() {
10212 let err = contrato_endpoint_err("/api/café");
10213 assert!(
10214 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10215 if endpoint == "/api/café" && reason.contains("non-ASCII")),
10216 "got {err:?}"
10217 );
10218 }
10219
10220 #[test]
10221 fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
10222 let err = contrato_endpoint_err("/api//cart");
10223 assert!(
10224 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10225 if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
10226 "got {err:?}"
10227 );
10228 }
10229
10230 #[test]
10231 fn rejects_http_contrato_endpoint_with_dot_segment() {
10232 let err = contrato_endpoint_err("/api/./cart");
10233 assert!(
10234 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10235 if endpoint == "/api/./cart" && reason.contains("`.` segment")),
10236 "got {err:?}"
10237 );
10238 }
10239
10240 #[test]
10241 fn rejects_http_contrato_endpoint_with_parent_segment() {
10242 // Path-traversal in a contrato endpoint is the canonical
10243 // "L7 rule that the workload's HTTP server's path-resolution
10244 // logic interprets differently than the policy enforcer"
10245 // footgun. Rejected outright at validate time.
10246 let err = contrato_endpoint_err("/api/../etc");
10247 assert!(
10248 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10249 if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
10250 "got {err:?}"
10251 );
10252 }
10253
10254 #[test]
10255 fn rejects_http_contrato_endpoint_too_long() {
10256 // 1025-byte endpoint — one over the Gateway API
10257 // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
10258 // path matcher has no inherent length limit but the policy
10259 // CR itself rides through the K8s apiserver, which enforces
10260 // ConfigMap-shaped limits; sharing the Gateway API cap is the
10261 // conservative floor.
10262 let big = format!("/api/{}", "a".repeat(1020));
10263 assert_eq!(big.len(), 1025);
10264 let err = contrato_endpoint_err(&big);
10265 assert!(
10266 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10267 if endpoint == &big && reason.contains("max length of 1024")),
10268 "got {err:?}"
10269 );
10270 }
10271
10272 #[test]
10273 fn http_contrato_endpoint_max_length_validates() {
10274 // 1024-byte endpoint — exactly the cap. Boundary pin: drift
10275 // in the cap surfaces here and at
10276 // `rejects_http_contrato_endpoint_too_long` simultaneously,
10277 // mirroring `entrada_path_max_length_validates` on the peer
10278 // axis.
10279 let big = format!("/api/{}", "a".repeat(1019));
10280 assert_eq!(big.len(), 1024);
10281 let mut s = three_member_spec();
10282 s.contratos.push(contract_http("cart", "catalog", &big));
10283 s.validate().unwrap();
10284 }
10285
10286 #[test]
10287 fn http_contrato_endpoint_accepts_canonical_forms() {
10288 // Positive-set sweep: every canonical HTTP-path shape the
10289 // sibling `:entrada :paths` axis accepts (the bare-root `/`,
10290 // plain paths, hidden-file-style `.config` segments distinct
10291 // from the `.` segment, digit-bearing segments, the canonical
10292 // route-template `:param` form, trailing-slash form,
10293 // percent-encoded segments, the `/foo..bar` interior-`..`-
10294 // substring forms that are NOT `..` segments) must remain a
10295 // valid contrato endpoint too. Drift between this list and
10296 // the entrada path positive sweep surfaces at the shared
10297 // `is_gateway_api_http_path` substrate-side suite — one
10298 // source of truth. Uses a fresh `(payment, catalog)` edge so
10299 // none of the swept endpoints collide with the pre-existing
10300 // `(cart, catalog, /products/:id)` / `(cart, payment,
10301 // /charge)` entries in `three_member_spec`.
10302 for ep in [
10303 "/",
10304 "/charge",
10305 "/v1/charge",
10306 "/api/.config",
10307 "/products/:id",
10308 "/api/cart/",
10309 "/api/caf%C3%A9",
10310 "/foo..bar",
10311 "/...",
10312 ] {
10313 let mut s = three_member_spec();
10314 s.contratos.push(contract_http("payment", "catalog", ep));
10315 s.validate()
10316 .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
10317 }
10318 }
10319
10320 #[test]
10321 fn contrato_endpoint_empty_takes_precedence_over_invalid() {
10322 // Ordering pin: `ContratoEndpointEmpty` is the more self-
10323 // locating diagnostic on `""` and must lead — the value-
10324 // shape gate is only reached after the empty-check fires.
10325 // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
10326 // on the peer axis.
10327 let mut s = three_member_spec();
10328 s.contratos.push(WitContract {
10329 de: "cart".into(),
10330 para: "catalog".into(),
10331 wit: "wasi:http/proxy".into(),
10332 endpoint: Some(String::new()),
10333 subject: None,
10334 slot: None,
10335 });
10336 let err = s.validate().unwrap_err();
10337 assert!(
10338 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10339 "got {err:?}"
10340 );
10341 }
10342
10343 #[test]
10344 fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
10345 // Ordering pin: an endpoint without a leading `/` surfaces the
10346 // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
10347 // value-shape gate is only consulted on endpoints that already
10348 // satisfy the absolute-prefix invariant. Mirrors
10349 // `entrada_path_not_absolute_takes_precedence_over_invalid`.
10350 let err = contrato_endpoint_err("bad path");
10351 assert!(
10352 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10353 if endpoint == "bad path"),
10354 "got {err:?}"
10355 );
10356 }
10357
10358 #[test]
10359 fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
10360 // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
10361 // `:para` + a non-empty reason flow through verbatim so the
10362 // author can grep their caixa.lisp for the offending contrato
10363 // block and fix it in one edit. Same shape as
10364 // `entrada_path_diagnostic_carries_offending_path`.
10365 let err = contrato_endpoint_err("/api?q=1");
10366 match err {
10367 AplicacaoError::ContratoEndpointInvalid {
10368 de,
10369 para,
10370 endpoint,
10371 reason,
10372 } => {
10373 assert_eq!(de, "cart");
10374 assert_eq!(para, "catalog");
10375 assert_eq!(endpoint, "/api?q=1");
10376 assert!(!reason.is_empty(), "reason field must be non-empty");
10377 }
10378 other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
10379 }
10380 }
10381
10382 #[test]
10383 fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10384 // The compounding theorem: every &str inside a WitTarget
10385 // returned by target() is non-empty (and absolute, for Http).
10386 // Renderers downstream of typed_view() can rely on this
10387 // without re-checking — the type system carries the proof.
10388 let http = contract_http("cart", "catalog", "/x");
10389 match http.target().unwrap() {
10390 WitTarget::Http { endpoint } => {
10391 assert!(!endpoint.is_empty());
10392 assert!(endpoint.starts_with('/'));
10393 }
10394 other => panic!("expected Http, got {other:?}"),
10395 }
10396 let nats = WitContract {
10397 de: "a".into(),
10398 para: "b".into(),
10399 wit: "nats:pub-sub".into(),
10400 endpoint: None,
10401 subject: Some("topic.x".into()),
10402 slot: None,
10403 };
10404 match nats.target().unwrap() {
10405 WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10406 other => panic!("expected PubSub, got {other:?}"),
10407 }
10408 let kv = WitContract {
10409 de: "a".into(),
10410 para: "b".into(),
10411 wit: "wasi:keyvalue/store".into(),
10412 endpoint: None,
10413 subject: None,
10414 slot: Some("checkout/$orderId".into()),
10415 };
10416 match kv.target().unwrap() {
10417 WitTarget::Store { slot } => assert!(!slot.is_empty()),
10418 other => panic!("expected Store, got {other:?}"),
10419 }
10420 }
10421
10422 #[test]
10423 fn target_diagnostic_names_offending_endpoint_value() {
10424 // When the malformed endpoint string is non-trivial, the
10425 // diagnostic carries the actual value back to the author —
10426 // not a generic "endpoint malformed" error.
10427 let bad = WitContract {
10428 de: "src".into(),
10429 para: "dst".into(),
10430 wit: "wasi:http/proxy".into(),
10431 endpoint: Some("api/v1/charge".into()),
10432 subject: None,
10433 slot: None,
10434 };
10435 match bad.target().unwrap_err() {
10436 AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10437 assert_eq!(de, "src");
10438 assert_eq!(para, "dst");
10439 assert_eq!(endpoint, "api/v1/charge");
10440 }
10441 other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10442 }
10443 }
10444
10445 #[test]
10446 fn rejects_unknown_wit_with_target_set() {
10447 let mut s = three_member_spec();
10448 s.contratos.push(WitContract {
10449 de: "cart".into(),
10450 para: "catalog".into(),
10451 wit: "custom:exchange".into(),
10452 endpoint: Some("/leaked".into()),
10453 subject: None,
10454 slot: None,
10455 });
10456 let err = s.validate().unwrap_err();
10457 assert!(matches!(
10458 err,
10459 AplicacaoError::ContratoWrongTarget {
10460 expected: WitTarget::CAPABILITY_EXPECTED,
10461 ..
10462 }
10463 ));
10464 }
10465
10466 #[test]
10467 fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10468 // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10469 // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10470 // fourth arm of the same "which payload field name goes in the
10471 // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10472 // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10473 // consts cover on the peer HTTP / PubSub / Store arms
10474 // (`wit_target_field_name_pins_per_variant`). Until this lift
10475 // landed the byte-string sat twice — once inline in the
10476 // [`WitContract::target`] Capability-arm rejection at the
10477 // production dispatch, once in `rejects_unknown_wit_with_target_set`
10478 // pinning against the same literal — with no compile-time link
10479 // between them. Same "one canonical declaration, next to the
10480 // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10481 // lift established for the payload-less arm's human-readable
10482 // label axis; this test is the shape peer of
10483 // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10484 // pair (routes-through-const + scalar-value pin) on the
10485 // wrong-target diagnostic-scalar axis.
10486 //
10487 // Fail-before-pass-after was verified locally by mutating the
10488 // const declaration to `"capability"` — the scalar-value pin
10489 // below fires (`"capability" != "none"`) and the routes-through
10490 // assertion below still holds (production and const walk in
10491 // lockstep), which is the correct behavior: a rename on the
10492 // const drifts here first, not at a downstream consumer.
10493 assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10494
10495 let mut s = three_member_spec();
10496 s.contratos.push(WitContract {
10497 de: "cart".into(),
10498 para: "catalog".into(),
10499 wit: "custom:exchange".into(),
10500 endpoint: Some("/leaked".into()),
10501 subject: None,
10502 slot: None,
10503 });
10504 match s.validate().unwrap_err() {
10505 AplicacaoError::ContratoWrongTarget { expected, .. } => {
10506 assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10507 }
10508 other => panic!("expected ContratoWrongTarget, got {other:?}"),
10509 }
10510 }
10511
10512 #[test]
10513 fn unknown_wit_capability_only_validates() {
10514 let mut s = three_member_spec();
10515 s.contratos.push(WitContract {
10516 de: "cart".into(),
10517 para: "catalog".into(),
10518 // A WIT world we haven't yet shaped — accept it as a typed
10519 // capability edge so authors aren't blocked while the WIT
10520 // registry catches up. No payload field may be carried.
10521 wit: "custom:exchange".into(),
10522 endpoint: None,
10523 subject: None,
10524 slot: None,
10525 });
10526 s.validate().unwrap();
10527 let added = s.contratos.last().unwrap();
10528 assert_eq!(added.target().unwrap(), WitTarget::Capability);
10529 }
10530
10531 #[test]
10532 fn target_typed_view_round_trips_each_shape() {
10533 let http = contract_http("cart", "catalog", "/products/:id");
10534 assert_eq!(
10535 http.target().unwrap(),
10536 WitTarget::Http {
10537 endpoint: "/products/:id"
10538 }
10539 );
10540 let nats = WitContract {
10541 de: "a".into(),
10542 para: "b".into(),
10543 wit: "nats:pub-sub".into(),
10544 endpoint: None,
10545 subject: Some("topic.x".into()),
10546 slot: None,
10547 };
10548 assert_eq!(
10549 nats.target().unwrap(),
10550 WitTarget::PubSub { subject: "topic.x" }
10551 );
10552 let kv = WitContract {
10553 de: "a".into(),
10554 para: "b".into(),
10555 wit: "wasi:keyvalue/store".into(),
10556 endpoint: None,
10557 subject: None,
10558 slot: Some("checkout/$orderId".into()),
10559 };
10560 assert_eq!(
10561 kv.target().unwrap(),
10562 WitTarget::Store {
10563 slot: "checkout/$orderId"
10564 }
10565 );
10566 }
10567
10568 #[test]
10569 fn wit_contract_kind_predicates() {
10570 let http = contract_http("a", "b", "/x");
10571 assert!(http.is_http());
10572 assert!(!http.is_pubsub());
10573 assert!(!http.is_store());
10574 assert!(!http.is_capability());
10575
10576 let nats = WitContract {
10577 de: "a".into(),
10578 para: "b".into(),
10579 wit: "nats:pub-sub".into(),
10580 endpoint: None,
10581 subject: Some("topic.x".into()),
10582 slot: None,
10583 };
10584 assert!(nats.is_pubsub());
10585 assert!(!nats.is_http());
10586 assert!(!nats.is_capability());
10587
10588 let kv = WitContract {
10589 de: "a".into(),
10590 para: "b".into(),
10591 wit: "wasi:keyvalue/store".into(),
10592 endpoint: None,
10593 subject: None,
10594 slot: Some("checkout/$orderId".into()),
10595 };
10596 assert!(kv.is_store());
10597 assert!(!kv.is_http());
10598 assert!(!kv.is_capability());
10599
10600 // Fourth arm on the paired closed-set predicate family: the
10601 // payload-less capability edge that projects to the payload-
10602 // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10603 // Extends the 3-arm predicate sweep this test opened to cover
10604 // the closed 4-way partition [`WitContract::is_capability`]
10605 // closes on the pre-projection WIT-shape axis, matched with the
10606 // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10607 // 4-arm predicate set.
10608 let cap = WitContract {
10609 de: "a".into(),
10610 para: "b".into(),
10611 wit: "custom:capability-only".into(),
10612 endpoint: None,
10613 subject: None,
10614 slot: None,
10615 };
10616 assert!(cap.is_capability());
10617 assert!(!cap.is_http());
10618 assert!(!cap.is_pubsub());
10619 assert!(!cap.is_store());
10620 }
10621
10622 // ── :contratos :wit value-shape gate ─────────────────────────────────
10623 //
10624 // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10625 // dispatch-discriminator axis. Until this gate landed
10626 // `WitContract::target()` accepted any non-empty string and
10627 // silently demoted unrecognized shapes to a capability-only L4
10628 // edge — the canonical "I thought I had L7 HTTP routing, got
10629 // L4-only" footgun. Every authoring footgun the WIT registry's
10630 // own grammar rejects (uppercase, hyphen-for-colon typo,
10631 // whitespace, empty package, doubled `@`, …) now becomes a
10632 // caixa-build-time `ContratoWitInvalid` with the offending
10633 // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10634 // as `ContratoEndpointInvalid` on the sibling axis; same shared
10635 // predicate (`crate::render::is_wit_world_ref`) ensures drift
10636 // between any two axes' rule enforcement is a build error at the
10637 // predicate, not piecemeal across renderers.
10638
10639 fn contrato_wit_err(wit: &str) -> AplicacaoError {
10640 // Fresh spec per call so the new contract doesn't collide on
10641 // identity with `three_member_spec`'s pre-existing entries.
10642 // The new edge uses `(payment, catalog)` — a pair the fixture
10643 // doesn't already declare — with no payload field set, so the
10644 // wit-shape gate fires before any payload-shape arm.
10645 let mut s = three_member_spec();
10646 s.contratos.push(WitContract {
10647 de: "payment".into(),
10648 para: "catalog".into(),
10649 wit: wit.into(),
10650 endpoint: None,
10651 subject: None,
10652 slot: None,
10653 });
10654 s.validate().unwrap_err()
10655 }
10656
10657 #[test]
10658 fn rejects_wit_with_uppercase_namespace() {
10659 // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10660 // didn't match the lowercase `wasi:http/` prefix is_http() keys
10661 // off, so the dispatch fell through to the capability arm and
10662 // the contract silently rendered as an L4-only Cilium edge.
10663 // The new gate surfaces the uppercase typo at validate time
10664 // with the offending `:wit` named.
10665 let err = contrato_wit_err("WASI:http/proxy");
10666 assert!(
10667 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10668 if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10669 "got {err:?}"
10670 );
10671 }
10672
10673 #[test]
10674 fn rejects_wit_with_hyphen_for_colon_typo() {
10675 // The canonical "I forgot the `:` separator" typo — pre-gate
10676 // this passed as Capability silently, so the renderer emitted
10677 // an L4-only policy where the author expected L7 HTTP rules.
10678 let err = contrato_wit_err("wasi-http/proxy");
10679 assert!(
10680 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10681 if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
10682 "got {err:?}"
10683 );
10684 }
10685
10686 #[test]
10687 fn rejects_wit_with_multiple_colons() {
10688 // Doubled `:` — the namespace/package split has nowhere to
10689 // anchor, so the dispatch silently demotes to Capability.
10690 let err = contrato_wit_err("wasi:http:proxy");
10691 assert!(
10692 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10693 if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
10694 "got {err:?}"
10695 );
10696 }
10697
10698 #[test]
10699 fn rejects_wit_with_empty_package() {
10700 // `wasi:` — namespace alone with no package. Pre-gate this
10701 // failed neither the is_http nor is_pubsub nor is_store
10702 // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
10703 // a bare `wasi:`), so it silently demoted to Capability.
10704 let err = contrato_wit_err("wasi:");
10705 assert!(
10706 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10707 if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
10708 "got {err:?}"
10709 );
10710 }
10711
10712 #[test]
10713 fn rejects_wit_with_underscore() {
10714 // Underscore — WIT identifiers are kebab-case, same rule
10715 // DNS-1123 enforces on its peer axes. The diagnostic carries
10716 // the explicit "use `-` instead" remediation.
10717 let err = contrato_wit_err("wasi:http_proxy");
10718 assert!(
10719 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10720 if wit == "wasi:http_proxy" && reason.contains('_')),
10721 "got {err:?}"
10722 );
10723 }
10724
10725 #[test]
10726 fn rejects_wit_with_whitespace() {
10727 // Whitespace mid-token — the prefix check matches but the
10728 // package-and-onward parse silently demoted to Capability.
10729 let err = contrato_wit_err("wasi:http proxy");
10730 assert!(
10731 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10732 if wit == "wasi:http proxy" && reason.contains("whitespace")),
10733 "got {err:?}"
10734 );
10735 }
10736
10737 #[test]
10738 fn rejects_wit_with_non_ascii() {
10739 // Un-percent-encoded non-ASCII byte — the canonical "I copied
10740 // the package name from a doc with smart quotes / accented
10741 // characters" footgun.
10742 let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
10743 assert!(
10744 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10745 if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
10746 "got {err:?}"
10747 );
10748 }
10749
10750 #[test]
10751 fn rejects_wit_with_consecutive_hyphens() {
10752 // `pub--sub` — WIT identifiers join words with single hyphens.
10753 let err = contrato_wit_err("nats:pub--sub");
10754 assert!(
10755 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10756 if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
10757 "got {err:?}"
10758 );
10759 }
10760
10761 #[test]
10762 fn rejects_wit_with_trailing_at_no_version() {
10763 // `wasi:http/proxy@` — the version-suffix author started to
10764 // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
10765 // parser would reject this; surface it at validate time.
10766 let err = contrato_wit_err("wasi:http/proxy@");
10767 assert!(
10768 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10769 if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
10770 "got {err:?}"
10771 );
10772 }
10773
10774 #[test]
10775 fn rejects_wit_too_long() {
10776 // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
10777 // The legitimate-shape arms all pass (lowercase, single `:`,
10778 // kebab-case identifiers); only the cap arm fires. Surfaces
10779 // the paste-from-binary / accidental-multi-line-blob landing
10780 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10781 // on the peer axis.
10782 let big = format!("wasi:{}", "a".repeat(124));
10783 assert_eq!(big.len(), 129);
10784 let err = contrato_wit_err(&big);
10785 assert!(
10786 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10787 if wit == &big && reason.contains("max length of 128")),
10788 "got {err:?}"
10789 );
10790 }
10791
10792 #[test]
10793 fn wit_max_length_validates() {
10794 // 128-byte WIT reference — exactly the cap. Boundary pin:
10795 // drift in the cap surfaces here and at `rejects_wit_too_long`
10796 // simultaneously, mirroring
10797 // `http_contrato_endpoint_max_length_validates` on the peer
10798 // axis.
10799 let big = format!("wasi:{}", "a".repeat(123));
10800 assert_eq!(big.len(), 128);
10801 let mut s = three_member_spec();
10802 s.contratos.push(WitContract {
10803 de: "payment".into(),
10804 para: "catalog".into(),
10805 wit: big,
10806 endpoint: None,
10807 subject: None,
10808 slot: None,
10809 });
10810 s.validate().unwrap();
10811 }
10812
10813 #[test]
10814 fn wit_accepts_canonical_forms_at_aplicacao_layer() {
10815 // Positive-set sweep through the AplicacaoSpec::validate
10816 // surface (rather than the substrate-side predicate directly)
10817 // — pins every shape the existing test fixtures + the
10818 // checkout-aplicacao example carry, so the gate's accept-set
10819 // matches the substrate's emit-set. Drift between this list
10820 // and `render::tests::wit_world_ref_accepts_canonical_forms`
10821 // surfaces at the substrate layer's positive sweep — one
10822 // source of truth for the rule.
10823 for wit in [
10824 "wasi:http/proxy",
10825 "wasi:keyvalue/store",
10826 "nats:pub-sub",
10827 "kafka:topic",
10828 "custom:exchange",
10829 "pleme:cap/audit",
10830 "wasi:http/proxy@0.2.0",
10831 ] {
10832 // Payload field paired to the dispatched WIT shape so the
10833 // shape-↔-target arm doesn't fire instead of the wit-shape
10834 // arm we're exercising. Routes off the same
10835 // `wit_shape_is_http` / `wit_shape_is_pubsub` /
10836 // `wit_shape_is_store` free functions the production
10837 // `WitContract::is_http` / `is_pubsub` / `is_store`
10838 // methods delegate to (both consult the lifted
10839 // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
10840 // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
10841 // future prefix addition to the routing accept-set
10842 // reaches this test's payload-dispatch arm by
10843 // construction — no per-test-site drift can hide a
10844 // shape-→-target-slot mismatch that would silently
10845 // demote a canonical `:wit` value to the
10846 // `(None, None, None)` capability-only arm and let the
10847 // `AplicacaoSpec::validate` positive sweep pass on a
10848 // shape it should exercise as HTTP / pub-sub / store.
10849 let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
10850 (Some("/x".into()), None, None)
10851 } else if wit_shape_is_pubsub(wit) {
10852 (None, Some("topic.x".into()), None)
10853 } else if wit_shape_is_store(wit) {
10854 (None, None, Some("bucket/$key".into()))
10855 } else {
10856 (None, None, None)
10857 };
10858 let mut s = three_member_spec();
10859 s.contratos.push(WitContract {
10860 de: "payment".into(),
10861 para: "catalog".into(),
10862 wit: wit.into(),
10863 endpoint,
10864 subject,
10865 slot,
10866 });
10867 s.validate()
10868 .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
10869 }
10870 }
10871
10872 #[test]
10873 fn wit_shape_predicates_accept_canonical_prefix_set() {
10874 // Positive-set sweep pinning every prefix in
10875 // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
10876 // WIT_STORE_SHAPE_PREFIXES against the three free-function
10877 // dispatch predicates. The six prefixes are the load-bearing
10878 // routing keys the substrate's WIT-shape dispatch consults
10879 // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
10880 // key/value-store-slot admission); any drift between the
10881 // free-function accept-set and this list surfaces here
10882 // rather than at apply time as a silent
10883 // shape-→-capability-only demotion.
10884 assert!(wit_shape_is_http("wasi:http/proxy"));
10885 assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
10886 assert!(wit_shape_is_http("http:incoming"));
10887
10888 assert!(wit_shape_is_pubsub("nats:pub-sub"));
10889 assert!(wit_shape_is_pubsub("kafka:topic"));
10890
10891 assert!(wit_shape_is_store("wasi:keyvalue/store"));
10892 assert!(wit_shape_is_store("kv:cache/session"));
10893 }
10894
10895 #[test]
10896 fn wit_shape_predicates_reject_uncanonical_forms() {
10897 // Negative-set pin: the six canonical prefixes are
10898 // lowercase-only (mirrors the `is_wit_world_ref` substrate
10899 // predicate's lowercase invariant — see its docstring on the
10900 // "I thought I had L7 HTTP routing, got L4-only" footgun).
10901 // The empty string, an uppercase-prefixed form, a hyphen-
10902 // instead-of-colon typo, and a bare kebab identifier all miss
10903 // every shape arm — reachable-by-construction only via the
10904 // `is_wit_world_ref` gate that admission-checks the `:wit`
10905 // value first, but pinned here so any future
10906 // free-function change (e.g. a case-insensitive
10907 // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
10908 // this unit level.
10909 for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
10910 assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
10911 assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
10912 assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
10913 }
10914 }
10915
10916 #[test]
10917 fn wit_shape_predicates_partition_canonical_set() {
10918 // Every canonical prefix routes to exactly one shape arm —
10919 // the three prefix sets are pairwise disjoint. Pins the
10920 // routing property [`WitContract::target`] relies on: an
10921 // `is_http()` return of `true` guarantees `is_pubsub()` and
10922 // `is_store()` return `false`, so the shape-→-target-slot
10923 // dispatch (endpoint vs subject vs slot) is unambiguous.
10924 // Drift (e.g. a future `"kv:"` moved into the HTTP set
10925 // without removal from the store set) would silently route
10926 // one prefix to two arms and the first-matching-arm order
10927 // becomes load-bearing — this pin surfaces it as a build
10928 // error instead.
10929 for prefix in WIT_HTTP_SHAPE_PREFIXES {
10930 let sample = format!("{prefix}x");
10931 assert!(wit_shape_is_http(&sample));
10932 assert!(!wit_shape_is_pubsub(&sample));
10933 assert!(!wit_shape_is_store(&sample));
10934 }
10935 for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
10936 let sample = format!("{prefix}x");
10937 assert!(!wit_shape_is_http(&sample));
10938 assert!(wit_shape_is_pubsub(&sample));
10939 assert!(!wit_shape_is_store(&sample));
10940 }
10941 for prefix in WIT_STORE_SHAPE_PREFIXES {
10942 let sample = format!("{prefix}x");
10943 assert!(!wit_shape_is_http(&sample));
10944 assert!(!wit_shape_is_pubsub(&sample));
10945 assert!(wit_shape_is_store(&sample));
10946 }
10947 }
10948
10949 #[test]
10950 fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
10951 // Positive pin: [`wit_shape_matches`] is exactly the
10952 // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
10953 // parameterized on the accept-set. Two-prefix accept-set,
10954 // one-prefix accept-set, and empty accept-set (which must
10955 // reject everything, including the empty string — an empty
10956 // `any()` fold returns `false`) all pinned so a future
10957 // reimplementation that swaps `starts_with` for `contains`,
10958 // `==`, or a case-folded comparator surfaces at unit-test
10959 // time.
10960 let two = &["wasi:http/", "http:"];
10961 assert!(wit_shape_matches("wasi:http/proxy", two));
10962 assert!(wit_shape_matches("http:incoming", two));
10963 assert!(!wit_shape_matches("wasi:keyvalue/store", two));
10964
10965 let one = &["nats:"];
10966 assert!(wit_shape_matches("nats:pub-sub", one));
10967 assert!(!wit_shape_matches("kafka:topic", one));
10968
10969 // Empty accept-set matches nothing — the identity element
10970 // for the disjunctive `any()` fold across the prefix set.
10971 // Reachable via a future `wit_shape_is_<name>` const paired
10972 // to a still-empty prefix table on a nascent shape-arm draft.
10973 let empty: &[&str] = &[];
10974 assert!(!wit_shape_matches("wasi:http/proxy", empty));
10975 assert!(!wit_shape_matches("", empty));
10976
10977 // starts_with, not contains: a prefix embedded mid-string
10978 // never matches. Pins the routing invariant [`WitContract::target`]
10979 // relies on (an authored `:wit "custom:wasi:http/"` string
10980 // does not silently route through the HTTP arm just because
10981 // it happens to contain the canonical HTTP prefix).
10982 assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
10983 }
10984
10985 #[test]
10986 fn wit_shape_predicates_delegate_to_wit_shape_matches() {
10987 // Equivalence pin: each per-shape predicate is exactly
10988 // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
10989 // every canonical prefix + the empty string + one negative
10990 // sample against every peer so a future predicate that grew
10991 // its own inline `iter().any(starts_with)` (rather than
10992 // delegating through the lifted combinator) drifts loudly here
10993 // — the peer-const table's contents must agree with the
10994 // predicate's accept-set by construction.
10995 let samples = [
10996 String::new(),
10997 "wasi:http/proxy".to_string(),
10998 "http:incoming".to_string(),
10999 "nats:pub-sub".to_string(),
11000 "kafka:topic".to_string(),
11001 "wasi:keyvalue/store".to_string(),
11002 "kv:cache/session".to_string(),
11003 "custom-shape".to_string(),
11004 "WASI:HTTP/proxy".to_string(),
11005 ];
11006 for wit in &samples {
11007 assert_eq!(
11008 wit_shape_is_http(wit),
11009 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11010 "wit_shape_is_http drifted from combinator on {wit:?}",
11011 );
11012 assert_eq!(
11013 wit_shape_is_pubsub(wit),
11014 wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
11015 "wit_shape_is_pubsub drifted from combinator on {wit:?}",
11016 );
11017 assert_eq!(
11018 wit_shape_is_store(wit),
11019 wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
11020 "wit_shape_is_store drifted from combinator on {wit:?}",
11021 );
11022 }
11023 }
11024
11025 #[test]
11026 fn wit_contract_shape_methods_delegate_to_free_functions() {
11027 // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
11028 // `is_store` are `&self` conveniences on top of the free
11029 // functions — for every canonical prefix the method's return
11030 // matches its free-function peer. Sweeps the union of the
11031 // three prefix sets so a future method that grew its own
11032 // inline prefix logic (rather than delegating) drifts loudly
11033 // here on the first prefix the free function accepts and the
11034 // method doesn't.
11035 for shape_set in [
11036 WIT_HTTP_SHAPE_PREFIXES,
11037 WIT_PUBSUB_SHAPE_PREFIXES,
11038 WIT_STORE_SHAPE_PREFIXES,
11039 ] {
11040 for prefix in shape_set {
11041 let c = WitContract {
11042 de: "cart".into(),
11043 para: "catalog".into(),
11044 wit: format!("{prefix}x"),
11045 endpoint: None,
11046 subject: None,
11047 slot: None,
11048 };
11049 assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
11050 assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
11051 assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
11052 assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11053 }
11054 }
11055 // Capability-arm delegation sweep: two representative
11056 // Capability-shaped `:wit` values (a bare non-prefix-matching
11057 // WIT world, the deliberately-shaped empty string
11058 // [`WitContract::is_capability`]'s docstring calls out as
11059 // syntactically Capability). Extends the free-function
11060 // delegation pin onto the fourth arm so a future
11061 // [`WitContract::is_capability`] rewrite that grew an inline
11062 // prefix-set scan (rather than delegating through
11063 // [`wit_shape_is_capability`]) drifts loudly here on the first
11064 // Capability-shaped sample.
11065 for wit in ["custom:capability-only", ""] {
11066 let c = WitContract {
11067 de: "cart".into(),
11068 para: "catalog".into(),
11069 wit: wit.into(),
11070 endpoint: None,
11071 subject: None,
11072 slot: None,
11073 };
11074 assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11075 }
11076 }
11077
11078 #[test]
11079 fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
11080 // 4-way partition-witness pin on the raw `&str` axis: for every
11081 // canonical prefix in the three payload-arm accept-sets,
11082 // exactly one of the four [`wit_shape_is_http`] /
11083 // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11084 // [`wit_shape_is_capability`] free functions returns `true` and
11085 // the other three return `false` — the four-arm partition
11086 // witness that locks the free-function WIT-shape-classifier
11087 // family into a partition of the `:contratos :wit` axis
11088 // load-bearing. Peer of the sibling [`WitContract`]-surface
11089 // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
11090 // partition pin — extends the discipline onto the raw `&str`
11091 // axis so any future arm addition (a hypothetical
11092 // `wasi:sockets/*` transport-layer shape, an `oci:*`
11093 // capability-import carrier per the sibling
11094 // [`wit_shape_matches`] docstring's trajectory bullet) that
11095 // landed on one of the payload-arm free functions without
11096 // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
11097 // here as two arms returning `true` simultaneously at
11098 // caixa-core build time rather than a silent per-consumer
11099 // misclassification at renderer emit time.
11100 for shape_set in [
11101 WIT_HTTP_SHAPE_PREFIXES,
11102 WIT_PUBSUB_SHAPE_PREFIXES,
11103 WIT_STORE_SHAPE_PREFIXES,
11104 ] {
11105 for prefix in shape_set {
11106 let wit = format!("{prefix}x");
11107 let hits = [
11108 wit_shape_is_http(&wit),
11109 wit_shape_is_pubsub(&wit),
11110 wit_shape_is_store(&wit),
11111 wit_shape_is_capability(&wit),
11112 ]
11113 .iter()
11114 .filter(|&&b| b)
11115 .count();
11116 assert_eq!(
11117 hits,
11118 1,
11119 "raw-&str WIT-shape 4-way predicate partition must \
11120 admit exactly one arm per canonical prefix; got {hits} \
11121 hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
11122 is_capability={})",
11123 wit_shape_is_http(&wit),
11124 wit_shape_is_pubsub(&wit),
11125 wit_shape_is_store(&wit),
11126 wit_shape_is_capability(&wit),
11127 );
11128 }
11129 }
11130 // Capability-arm sweep on the raw `&str` axis: two
11131 // representative Capability-shaped `:wit` values (a bare non-
11132 // prefix-matching WIT world, the deliberately-shaped empty
11133 // string the pure classifier still admits per
11134 // [`wit_shape_is_capability`]'s docstring). Both must land on
11135 // the fourth arm exclusively so the partition witness holds
11136 // across the full 4-arm closure on the raw `&str` axis.
11137 for wit in ["custom:capability-only", ""] {
11138 let hits = [
11139 wit_shape_is_http(wit),
11140 wit_shape_is_pubsub(wit),
11141 wit_shape_is_store(wit),
11142 wit_shape_is_capability(wit),
11143 ]
11144 .iter()
11145 .filter(|&&b| b)
11146 .count();
11147 assert_eq!(
11148 hits, 1,
11149 "raw-&str WIT-shape 4-way predicate partition must \
11150 admit exactly one arm on Capability-shaped wit={wit:?}"
11151 );
11152 assert!(
11153 wit_shape_is_capability(wit),
11154 "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
11155 );
11156 }
11157 }
11158
11159 #[test]
11160 fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
11161 // Composition-witness pin: [`wit_shape_is_capability`] is the
11162 // exact-inverse disjunction of the sibling payload-arm free-
11163 // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
11164 // / [`wit_shape_is_store`]. A future reimplementation that
11165 // grew its own prefix-set scan (e.g. inlining a fourth
11166 // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
11167 // not own today) rather than delegating to the sibling trio
11168 // would drift loudly here — the composition contract binds the
11169 // fourth-arm free-function predicate to the exact-inverse of
11170 // the three payload-arm free-function predicates, so any
11171 // rebrand of any prefix-set const flows through
11172 // [`wit_shape_is_capability`] by construction without a
11173 // coordinated per-consumer rewrite. Peer of the sibling
11174 // [`WitContract`]-surface
11175 // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
11176 // composition pin — extends the discipline onto the raw
11177 // `&str` axis.
11178 let mut cases: Vec<String> = Vec::new();
11179 for shape_set in [
11180 WIT_HTTP_SHAPE_PREFIXES,
11181 WIT_PUBSUB_SHAPE_PREFIXES,
11182 WIT_STORE_SHAPE_PREFIXES,
11183 ] {
11184 for prefix in shape_set {
11185 cases.push(format!("{prefix}x"));
11186 }
11187 }
11188 cases.push("custom:capability-only".to_string());
11189 cases.push(String::new());
11190 for wit in cases {
11191 assert_eq!(
11192 wit_shape_is_capability(&wit),
11193 !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
11194 "wit_shape_is_capability must equal \
11195 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
11196 at wit={wit:?}"
11197 );
11198 }
11199 }
11200
11201 #[test]
11202 fn wit_contract_is_capability_partitions_the_wit_shape_space() {
11203 // 4-way partition-witness pin: for every canonical prefix in
11204 // the payload-arm accept-sets, exactly one of the four
11205 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11206 // [`WitContract::is_store`] / [`WitContract::is_capability`]
11207 // predicates returns `true` and the other three return `false`
11208 // — the four-arm partition witness that locks the substrate's
11209 // WIT-shape-space closure on the pre-projection axis load-
11210 // bearing. A future arm addition (a hypothetical fourth
11211 // payload-shape prefix set, a `wasi:sockets/*` transport-layer
11212 // shape) that landed on one of the payload-arm predicates
11213 // without shrinking [`WitContract::is_capability`]'s accept-set
11214 // would surface here as two arms returning `true` simultaneously
11215 // — a partition-witness break the pin catches at caixa-core
11216 // build time rather than a silent per-consumer misclassification
11217 // at renderer emit time. Peer of the sibling `WitTarget`-side
11218 // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
11219 // partition-witness pin on the post-projection payload-scalar
11220 // arm-set — extends the discipline onto the pre-projection
11221 // 4-arm shape-space.
11222 for shape_set in [
11223 WIT_HTTP_SHAPE_PREFIXES,
11224 WIT_PUBSUB_SHAPE_PREFIXES,
11225 WIT_STORE_SHAPE_PREFIXES,
11226 ] {
11227 for prefix in shape_set {
11228 let c = WitContract {
11229 de: "cart".into(),
11230 para: "catalog".into(),
11231 wit: format!("{prefix}x"),
11232 endpoint: None,
11233 subject: None,
11234 slot: None,
11235 };
11236 let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11237 .iter()
11238 .filter(|&&b| b)
11239 .count();
11240 assert_eq!(
11241 hits,
11242 1,
11243 "WitContract WIT-shape 4-way predicate partition must \
11244 admit exactly one arm per canonical prefix; got {hits} \
11245 hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
11246 is_capability={})",
11247 c.wit,
11248 c.is_http(),
11249 c.is_pubsub(),
11250 c.is_store(),
11251 c.is_capability(),
11252 );
11253 }
11254 }
11255 // Capability-arm sweep: two representative capability shapes
11256 // (a bare WIT world outside the three payload-arm prefix sets,
11257 // and the deliberately-shaped empty string that
11258 // [`crate::render::is_wit_world_ref`] rejects at
11259 // [`WitContract::target`] time but which the pure classifier
11260 // still admits — see the method docstring's "purely syntactic
11261 // classification" note). Both must land on the fourth arm
11262 // exclusively, so the partition witness holds across the full
11263 // 4-arm closure.
11264 for wit in ["custom:capability-only", ""] {
11265 let c = WitContract {
11266 de: "cart".into(),
11267 para: "catalog".into(),
11268 wit: wit.into(),
11269 endpoint: None,
11270 subject: None,
11271 slot: None,
11272 };
11273 let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11274 .iter()
11275 .filter(|&&b| b)
11276 .count();
11277 assert_eq!(
11278 hits, 1,
11279 "WitContract WIT-shape 4-way predicate partition must \
11280 admit exactly one arm on Capability-shaped wit={wit:?}"
11281 );
11282 assert!(
11283 c.is_capability(),
11284 "wit={wit:?} must project onto the Capability arm"
11285 );
11286 }
11287 }
11288
11289 #[test]
11290 fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
11291 // Composition-witness pin: [`WitContract::is_capability`] is the
11292 // exact-inverse disjunction of the sibling payload-arm predicate
11293 // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11294 // [`WitContract::is_store`]. A future reimplementation that
11295 // grew its own prefix-set scan (e.g. inlining a fourth
11296 // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
11297 // own today) rather than delegating to the sibling trio would
11298 // drift loudly here — the composition contract binds the
11299 // fourth-arm predicate to the exact-inverse of the three
11300 // payload-arm predicates, so any rebrand of any prefix-set const
11301 // flows through this method by construction without a
11302 // coordinated per-consumer rewrite. Sweeps the union of the
11303 // three payload-arm prefix sets plus two Capability-shaped
11304 // shapes (a bare non-prefix-matching WIT world, the deliberately-
11305 // empty string the pure classifier still admits per the method
11306 // docstring's "purely syntactic classification" note).
11307 let mut cases: Vec<String> = Vec::new();
11308 for shape_set in [
11309 WIT_HTTP_SHAPE_PREFIXES,
11310 WIT_PUBSUB_SHAPE_PREFIXES,
11311 WIT_STORE_SHAPE_PREFIXES,
11312 ] {
11313 for prefix in shape_set {
11314 cases.push(format!("{prefix}x"));
11315 }
11316 }
11317 cases.push("custom:capability-only".to_string());
11318 cases.push(String::new());
11319 for wit in cases {
11320 let c = WitContract {
11321 de: "cart".into(),
11322 para: "catalog".into(),
11323 wit: wit.clone(),
11324 endpoint: None,
11325 subject: None,
11326 slot: None,
11327 };
11328 assert_eq!(
11329 c.is_capability(),
11330 !c.is_http() && !c.is_pubsub() && !c.is_store(),
11331 "WitContract::is_capability must equal \
11332 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
11333 );
11334 }
11335 }
11336
11337 #[test]
11338 fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
11339 // Cross-projection-witness pin: whenever [`WitContract::target`]
11340 // succeeds, the pre-projection [`WitContract::is_capability`]
11341 // classification agrees with the post-projection
11342 // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
11343 // predicate — the 4-arm typed partition on the substrate's
11344 // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
11345 // partition on the pre-projection axis line up by construction.
11346 // A future divergence between the two axes (a peer
11347 // [`WitTarget`] variant addition that landed on the typed-view
11348 // surface without a peer prefix-set + [`WitContract`] predicate
11349 // extension, or vice versa) would surface here at caixa-core
11350 // build time rather than a silent per-consumer split at renderer
11351 // emit time. Peer of the sibling pre-/post-projection
11352 // agreement pins the payload-carrier trio
11353 // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11354 // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
11355 // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
11356 // post-projection — b11bb49 trio lift) already carry across the
11357 // three payload arms — this pin closes the pair on the fourth
11358 // payload-less arm.
11359 let http = WitContract {
11360 de: "cart".into(),
11361 para: "catalog".into(),
11362 wit: "wasi:http/proxy".into(),
11363 endpoint: Some("/x".into()),
11364 subject: None,
11365 slot: None,
11366 };
11367 assert!(!http.is_capability());
11368 assert!(!http.target().unwrap().is_capability());
11369
11370 let nats = WitContract {
11371 de: "cart".into(),
11372 para: "catalog".into(),
11373 wit: "nats:pub-sub".into(),
11374 endpoint: None,
11375 subject: Some("events.x".into()),
11376 slot: None,
11377 };
11378 assert!(!nats.is_capability());
11379 assert!(!nats.target().unwrap().is_capability());
11380
11381 let kv = WitContract {
11382 de: "cart".into(),
11383 para: "catalog".into(),
11384 wit: "wasi:keyvalue/store".into(),
11385 endpoint: None,
11386 subject: None,
11387 slot: Some("checkout/$orderId".into()),
11388 };
11389 assert!(!kv.is_capability());
11390 assert!(!kv.target().unwrap().is_capability());
11391
11392 let cap = WitContract {
11393 de: "cart".into(),
11394 para: "catalog".into(),
11395 wit: "custom:capability-only".into(),
11396 endpoint: None,
11397 subject: None,
11398 slot: None,
11399 };
11400 assert!(cap.is_capability());
11401 assert!(cap.target().unwrap().is_capability());
11402 }
11403
11404 #[test]
11405 fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
11406 // Load-bearing contract pin: on every canonical
11407 // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
11408 // [`WitContract::target_projected`] returns byte-equal to
11409 // [`WitContract::target`]`().unwrap()` — the post-validation
11410 // projection accessor is a thin panicking wrapper over the
11411 // pre-validation validator, no extra work in the projection
11412 // path. Any future divergence (a validator-side normalization
11413 // the projection doesn't route through, an accessor-side
11414 // caching layer the validator doesn't populate) would surface
11415 // here at caixa-core build time rather than a silent per-consumer
11416 // split at renderer emit time. Sweeps the closed 4-arm
11417 // [`WitTarget`] partition ([`WitTarget::Http`] /
11418 // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
11419 // [`WitTarget::Capability`]) so every arm carries a byte-equality
11420 // pin on the two-accessor pair.
11421 for (wit, endpoint, subject, slot) in [
11422 ("wasi:http/proxy", Some("/x"), None, None),
11423 ("nats:pub-sub", None, Some("events.x"), None),
11424 ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
11425 ("custom:capability-only", None, None, None),
11426 ] {
11427 let c = WitContract {
11428 de: "cart".into(),
11429 para: "catalog".into(),
11430 wit: wit.into(),
11431 endpoint: endpoint.map(str::to_string),
11432 subject: subject.map(str::to_string),
11433 slot: slot.map(str::to_string),
11434 };
11435 assert_eq!(
11436 c.target_projected(),
11437 c.target().unwrap(),
11438 "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
11439 );
11440 }
11441 }
11442
11443 #[test]
11444 #[should_panic(expected = "validated by typed_view")]
11445 fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
11446 // Panic-path pin: [`WitContract::target_projected`] threads the
11447 // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
11448 // through its expect-panic when called on a contract whose
11449 // (`:wit`, payload) shape has not been crossed by
11450 // [`AplicacaoSpec::validate`] — a contract with a structurally-
11451 // invalid `:wit` (hyphen-for-colon typo) that would surface
11452 // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
11453 // A future rebrand on the panic-message axis would land at one
11454 // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
11455 // and this pin's [`should_panic(expected = …)`] literal would
11456 // migrate alongside — the pin catches drift between the const
11457 // and the accessor's `expect(…)` call by construction.
11458 let c = WitContract {
11459 de: "cart".into(),
11460 para: "catalog".into(),
11461 // Hyphen-for-colon typo: `WitContract::target` returns
11462 // [`AplicacaoError::ContratoWitInvalid`] on this shape,
11463 // driving the [`WitContract::target_projected`] expect-panic.
11464 wit: "wasi-http/proxy".into(),
11465 endpoint: Some("/x".into()),
11466 subject: None,
11467 slot: None,
11468 };
11469 let _ = c.target_projected();
11470 }
11471
11472 #[test]
11473 fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
11474 // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
11475 // carries the exact byte-string the two prior open-coded
11476 // `.target().expect("validated by typed_view")` production
11477 // consumers threaded through inline before this lift converged
11478 // them onto [`WitContract::target_projected`] — the caixa-mesh
11479 // per-`(:de, :para)` CNP L7 introspection branch at
11480 // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
11481 // graph` per-`:contratos` payload-column printer at
11482 // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
11483 // byte-string load-bearing so a well-meaning const-side rebrand
11484 // that didn't carry a matched pin migration would surface here
11485 // at caixa-core build time rather than a silent per-consumer
11486 // panic-message drift at cluster-apply time. Peer of the
11487 // sibling [`WitTarget::CAPABILITY_LABEL`] /
11488 // [`WitTarget::CAPABILITY_EXPECTED`] /
11489 // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
11490 // the paired payload-less-arm scalar-const family.
11491 assert_eq!(
11492 WitContract::PROJECTED_INVARIANT_MSG,
11493 "validated by typed_view"
11494 );
11495 }
11496
11497 #[test]
11498 fn empty_wit_takes_precedence_over_invalid() {
11499 // Ordering pin: `EmptyWit` is the more self-locating
11500 // diagnostic on `""` and must lead — the value-shape gate is
11501 // only reached after the empty-check fires. Mirrors
11502 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11503 // the peer payload axis.
11504 let mut s = three_member_spec();
11505 s.contratos.push(WitContract {
11506 de: "payment".into(),
11507 para: "catalog".into(),
11508 wit: String::new(),
11509 endpoint: None,
11510 subject: None,
11511 slot: None,
11512 });
11513 let err = s.validate().unwrap_err();
11514 assert!(
11515 matches!(err, AplicacaoError::EmptyWit { .. }),
11516 "got {err:?}"
11517 );
11518 }
11519
11520 #[test]
11521 fn wit_invalid_fires_before_payload_shape_arm() {
11522 // Ordering pin: a malformed `:wit` surfaces *its own*
11523 // diagnostic (which names the offending wit verbatim) before
11524 // any payload-field check — a contrato whose wit is
11525 // structurally invalid AND carries a wrong target field
11526 // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
11527 // because the dispatch on the wit is what decides which
11528 // payload field is "right" in the first place. Without this
11529 // ordering, the author would see "wrong target field" for a
11530 // wit that hasn't even been parsed, which doesn't name the
11531 // root cause.
11532 let mut s = three_member_spec();
11533 s.contratos.push(WitContract {
11534 de: "payment".into(),
11535 para: "catalog".into(),
11536 // Hyphen-for-colon typo + endpoint set: pre-gate this
11537 // raised `ContratoWrongTarget { expected: "none" }` (the
11538 // Capability arm rejecting the endpoint), masking the
11539 // real authoring mistake (the wit isn't `wasi:http/proxy`).
11540 wit: "wasi-http/proxy".into(),
11541 endpoint: Some("/x".into()),
11542 subject: None,
11543 slot: None,
11544 });
11545 let err = s.validate().unwrap_err();
11546 assert!(
11547 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
11548 if wit == "wasi-http/proxy"),
11549 "got {err:?}"
11550 );
11551 }
11552
11553 #[test]
11554 fn wit_invalid_diagnostic_carries_offending_wit() {
11555 // Diagnostic-shape pin — the offending `:wit` + `:de` +
11556 // `:para` + a non-empty reason flow through verbatim so the
11557 // author can grep their caixa.lisp for the offending contrato
11558 // block and fix it in one edit. Same shape as
11559 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
11560 let err = contrato_wit_err("WASI:HTTP/proxy");
11561 match err {
11562 AplicacaoError::ContratoWitInvalid {
11563 de,
11564 para,
11565 wit,
11566 reason,
11567 } => {
11568 assert_eq!(de, "payment");
11569 assert_eq!(para, "catalog");
11570 assert_eq!(wit, "WASI:HTTP/proxy");
11571 assert!(!reason.is_empty(), "reason field must be non-empty");
11572 }
11573 other => panic!("expected ContratoWitInvalid, got {other:?}"),
11574 }
11575 }
11576
11577 // ── :contratos :subject value-shape gate ─────────────────────────────
11578 //
11579 // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
11580 // suites on the peer payload axes. Until this gate landed
11581 // `WitContract::target()` only refused the empty string; a
11582 // structurally invalid subject silently passed validate and the
11583 // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
11584 // Subject'` on publish / subscribe, or as a silent message drop,
11585 // far from the source caixa.lisp. Every authoring footgun the
11586 // NATS server's subject parser would catch on admission now
11587 // becomes a caixa-build-time `ContratoSubjectInvalid` with the
11588 // offending `:subject` + `:de` + `:para` named verbatim. Same
11589 // diagnostic shape as `ContratoEndpointInvalid` /
11590 // `ContratoWitInvalid` on the peer payload axes; same shared
11591 // predicate (`crate::render::is_nats_subject`) ensures drift
11592 // between any two axes' rule enforcement is a build error at the
11593 // predicate, not piecemeal across renderers.
11594
11595 fn contrato_subject_err(subject: &str) -> AplicacaoError {
11596 // Fresh spec per call so the new contract doesn't collide on
11597 // identity with `three_member_spec`'s pre-existing entries.
11598 // The new edge uses `(payment, catalog)` — a pair the fixture
11599 // doesn't already declare — with `:wit "nats:pub-sub"` and the
11600 // varying `:subject`, so the subject-shape gate fires cleanly
11601 // after the wit-shape gate (which `"nats:pub-sub"` passes).
11602 let mut s = three_member_spec();
11603 s.contratos.push(WitContract {
11604 de: "payment".into(),
11605 para: "catalog".into(),
11606 wit: "nats:pub-sub".into(),
11607 endpoint: None,
11608 subject: Some(subject.into()),
11609 slot: None,
11610 });
11611 s.validate().unwrap_err()
11612 }
11613
11614 #[test]
11615 fn rejects_pubsub_contrato_subject_with_whitespace() {
11616 // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
11617 // landed at the NATS server as a malformed subject the parser
11618 // rejects with `-ERR 'Invalid Subject'`. Now caught at the
11619 // source caixa.lisp.
11620 let err = contrato_subject_err("foo bar");
11621 assert!(
11622 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11623 if subject == "foo bar" && reason.contains("whitespace")),
11624 "got {err:?}"
11625 );
11626 }
11627
11628 #[test]
11629 fn rejects_pubsub_contrato_subject_with_control_char() {
11630 let err = contrato_subject_err("foo\x01bar");
11631 assert!(
11632 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11633 if subject == "foo\x01bar" && reason.contains("control character")),
11634 "got {err:?}"
11635 );
11636 }
11637
11638 #[test]
11639 fn rejects_pubsub_contrato_subject_with_non_ascii() {
11640 // Un-percent-encoded non-ASCII byte — the canonical "I copied
11641 // the subject from a doc with smart quotes / accented
11642 // characters" footgun.
11643 let err = contrato_subject_err("foo.caf\u{e9}");
11644 assert!(
11645 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11646 if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
11647 "got {err:?}"
11648 );
11649 }
11650
11651 #[test]
11652 fn rejects_pubsub_contrato_subject_with_leading_dot() {
11653 // Empty leading token — NATS rejects.
11654 let err = contrato_subject_err(".foo");
11655 assert!(
11656 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11657 if subject == ".foo" && reason.contains("must not start with `.`")),
11658 "got {err:?}"
11659 );
11660 }
11661
11662 #[test]
11663 fn rejects_pubsub_contrato_subject_with_trailing_dot() {
11664 // Empty trailing token — NATS rejects. The remediation
11665 // (use `>` instead) is in the reason string.
11666 let err = contrato_subject_err("foo.");
11667 assert!(
11668 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11669 if subject == "foo." && reason.contains("must not end with `.`")),
11670 "got {err:?}"
11671 );
11672 }
11673
11674 #[test]
11675 fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
11676 // The canonical "I forgot to fill in the middle segment"
11677 // typo — `"foo..bar"`. NATS rejects empty tokens.
11678 let err = contrato_subject_err("foo..bar");
11679 assert!(
11680 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11681 if subject == "foo..bar" && reason.contains("consecutive `.`")),
11682 "got {err:?}"
11683 );
11684 }
11685
11686 #[test]
11687 fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
11688 // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
11689 // as the final segment. Pre-gate this passed as a typed edge
11690 // and surfaced at runtime as a NATS subscribe rejection.
11691 let err = contrato_subject_err("foo.>.bar");
11692 assert!(
11693 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11694 if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
11695 "got {err:?}"
11696 );
11697 }
11698
11699 #[test]
11700 fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
11701 // `foo*.bar` — NATS wildcards are standalone tokens. The
11702 // remediation is in the reason string.
11703 let err = contrato_subject_err("foo*.bar");
11704 assert!(
11705 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11706 if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
11707 "got {err:?}"
11708 );
11709 }
11710
11711 #[test]
11712 fn rejects_pubsub_contrato_subject_with_invalid_char() {
11713 // `foo,bar` — comma is not a valid NATS subject character.
11714 // Pinned separately from the wildcard arms so the invalid-
11715 // character diagnostic is in force.
11716 let err = contrato_subject_err("foo,bar");
11717 assert!(
11718 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11719 if subject == "foo,bar" && reason.contains("invalid character")),
11720 "got {err:?}"
11721 );
11722 }
11723
11724 #[test]
11725 fn rejects_pubsub_contrato_subject_too_long() {
11726 // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
11727 // The legitimate-shape arms all pass (one all-`a` token, no
11728 // `.`, no wildcards); only the cap arm fires. Surfaces the
11729 // paste-from-binary / accidental-multi-line-blob landing
11730 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
11731 // on the peer axis.
11732 let big = "a".repeat(257);
11733 assert_eq!(big.len(), 257);
11734 let err = contrato_subject_err(&big);
11735 assert!(
11736 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11737 if subject == &big && reason.contains("max length of 256")),
11738 "got {err:?}"
11739 );
11740 }
11741
11742 #[test]
11743 fn pubsub_contrato_subject_max_length_validates() {
11744 // 256-byte subject — exactly the cap. Boundary pin: drift in
11745 // the cap surfaces here and at
11746 // `rejects_pubsub_contrato_subject_too_long` simultaneously,
11747 // mirroring `http_contrato_endpoint_max_length_validates` and
11748 // `wit_max_length_validates` on the peer axes.
11749 let big = "a".repeat(256);
11750 assert_eq!(big.len(), 256);
11751 let mut s = three_member_spec();
11752 s.contratos.push(WitContract {
11753 de: "payment".into(),
11754 para: "catalog".into(),
11755 wit: "nats:pub-sub".into(),
11756 endpoint: None,
11757 subject: Some(big),
11758 slot: None,
11759 });
11760 s.validate().unwrap();
11761 }
11762
11763 #[test]
11764 fn pubsub_contrato_subject_accepts_canonical_forms() {
11765 // Positive-set sweep: every canonical NATS subject shape the
11766 // substrate-side `is_nats_subject` predicate accepts (the
11767 // multi-dot `events.order.charged`, the snake_case / kebab-
11768 // case / mixed-case tokens, the digit-bearing tokens, the
11769 // single-token wildcard `*` at every segment position, and
11770 // the trailing `>` multi-token wildcard) must remain a valid
11771 // contrato subject too. Drift between this list and the
11772 // substrate-side `nats_subject_accepts_canonical_forms` sweep
11773 // surfaces at the shared predicate — one source of truth.
11774 // Uses a fresh `(payment, catalog)` edge so none of the swept
11775 // subjects collide with the pre-existing entries in
11776 // `three_member_spec`.
11777 for subject in [
11778 "checkout.events.charge.failed",
11779 "rio.events.order.charged",
11780 "orders",
11781 "orders.123",
11782 "snake_case.token",
11783 "kebab-case.token",
11784 "MixedCase.Token",
11785 "orders.*.charged",
11786 "*.events.*",
11787 "orders.>",
11788 ] {
11789 let mut s = three_member_spec();
11790 s.contratos.push(WitContract {
11791 de: "payment".into(),
11792 para: "catalog".into(),
11793 wit: "nats:pub-sub".into(),
11794 endpoint: None,
11795 subject: Some(subject.into()),
11796 slot: None,
11797 });
11798 s.validate()
11799 .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
11800 }
11801 }
11802
11803 #[test]
11804 fn contrato_subject_empty_takes_precedence_over_invalid() {
11805 // Ordering pin: `ContratoSubjectEmpty` is the more self-
11806 // locating diagnostic on `""` and must lead — the value-shape
11807 // gate is only reached after the empty-check fires. Mirrors
11808 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11809 // the peer payload axis.
11810 let mut s = three_member_spec();
11811 s.contratos.push(WitContract {
11812 de: "payment".into(),
11813 para: "catalog".into(),
11814 wit: "nats:pub-sub".into(),
11815 endpoint: None,
11816 subject: Some(String::new()),
11817 slot: None,
11818 });
11819 let err = s.validate().unwrap_err();
11820 assert!(
11821 matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
11822 "got {err:?}"
11823 );
11824 }
11825
11826 #[test]
11827 fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
11828 // Diagnostic-shape pin — the offending `:subject` + `:de` +
11829 // `:para` + a non-empty reason flow through verbatim so the
11830 // author can grep their caixa.lisp for the offending contrato
11831 // block and fix it in one edit. Same shape as
11832 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
11833 // and `wit_invalid_diagnostic_carries_offending_wit`.
11834 let err = contrato_subject_err("foo..bar");
11835 match err {
11836 AplicacaoError::ContratoSubjectInvalid {
11837 de,
11838 para,
11839 subject,
11840 reason,
11841 } => {
11842 assert_eq!(de, "payment");
11843 assert_eq!(para, "catalog");
11844 assert_eq!(subject, "foo..bar");
11845 assert!(!reason.is_empty(), "reason field must be non-empty");
11846 }
11847 other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
11848 }
11849 }
11850
11851 #[test]
11852 fn target_view_pubsub_subject_passes_through_to_typed_view() {
11853 // The compounding theorem on the pub-sub axis: every
11854 // `WitTarget::PubSub { subject }` returned by `target()` carries
11855 // a NATS-server-accepted subject. Renderers downstream of
11856 // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
11857 // NATS Stream/Consumer CR emitter, the future `feira app graph`
11858 // view's subject labeller) can rely on this without re-checking
11859 // — the type system carries the proof. Mirrors
11860 // `target_view_payload_is_guaranteed_nonempty_after_target_call`
11861 // on the peer axes.
11862 let nats = WitContract {
11863 de: "a".into(),
11864 para: "b".into(),
11865 wit: "nats:pub-sub".into(),
11866 endpoint: None,
11867 subject: Some("orders.events.*.charged".into()),
11868 slot: None,
11869 };
11870 match nats.target().unwrap() {
11871 WitTarget::PubSub { subject } => {
11872 assert_eq!(subject, "orders.events.*.charged");
11873 }
11874 other => panic!("expected PubSub, got {other:?}"),
11875 }
11876 }
11877
11878 // ── :contratos :slot value-shape gate ────────────────────────────────
11879 //
11880 // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
11881 // (63e18a0) value-shape suites on the peer payload axes. Until this
11882 // gate landed `WitContract::target()` only refused the empty string
11883 // for the Store arm; a structurally invalid slot (raw whitespace,
11884 // control character, non-ASCII byte, paste-from-binary multi-line
11885 // blob) silently passed validate and surfaced at runtime as a
11886 // per-backend kv write rejection or a silent next-read corruption,
11887 // far from the source caixa.lisp with no field naming which
11888 // `:contratos` edge carried the typo. Every authoring footgun the
11889 // kv backend intersection-floor would catch on write now becomes a
11890 // caixa-build-time `ContratoSlotInvalid` with the offending
11891 // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
11892 // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
11893 // peer payload axes; same shared predicate
11894 // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
11895 // any two axes' rule enforcement is a build error at the
11896 // predicate, not piecemeal across renderers. Closes the typed
11897 // payload-axis value-shape trajectory across all three legs of the
11898 // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
11899
11900 fn contrato_slot_err(slot: &str) -> AplicacaoError {
11901 // Fresh spec per call so the new contract doesn't collide on
11902 // identity with `three_member_spec`'s pre-existing entries
11903 // and doesn't close a synchronous cycle the cycle detector
11904 // would reject before the slot-shape gate fires. The new edge
11905 // uses `(payment, catalog)` — a pair the fixture doesn't
11906 // already declare in either direction (the fixture carries
11907 // `cart -> catalog` and `cart -> payment`, so `payment ->
11908 // catalog` doesn't form a cycle on the sync subgraph) — with
11909 // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
11910 // slot-shape gate fires cleanly after the wit-shape gate
11911 // (which `"wasi:keyvalue/store"` passes). Same edge pair the
11912 // peer `contrato_subject_err` helper uses (63e18a0).
11913 let mut s = three_member_spec();
11914 s.contratos.push(WitContract {
11915 de: "payment".into(),
11916 para: "catalog".into(),
11917 wit: "wasi:keyvalue/store".into(),
11918 endpoint: None,
11919 subject: None,
11920 slot: Some(slot.into()),
11921 });
11922 s.validate().unwrap_err()
11923 }
11924
11925 #[test]
11926 fn rejects_store_contrato_slot_with_whitespace() {
11927 // Fail-before-pass-after pin — pre-gate `"check out/$order"`
11928 // silently landed at the kv backend with whitespace whose
11929 // runtime behavior varies unpredictably across backends (etcd
11930 // accepts, Redis accepts then breaks on next CLI op, DynamoDB
11931 // rejects on write). Now caught at the source caixa.lisp.
11932 let err = contrato_slot_err("check out/$order");
11933 assert!(
11934 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11935 if slot == "check out/$order" && reason.contains("whitespace")),
11936 "got {err:?}"
11937 );
11938 }
11939
11940 #[test]
11941 fn rejects_store_contrato_slot_with_tab() {
11942 // Tab byte arm-pinned separately from the space arm so a
11943 // future relaxation that admits one but not the other surfaces
11944 // here.
11945 let err = contrato_slot_err("check\tout");
11946 assert!(
11947 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11948 if slot == "check\tout" && reason.contains("whitespace")),
11949 "got {err:?}"
11950 );
11951 }
11952
11953 #[test]
11954 fn rejects_store_contrato_slot_with_control_char() {
11955 // SOH (0x01) — distinct from the whitespace arm. Redis admits
11956 // and corrupts on RESP protocol framing; DynamoDB rejects on
11957 // write.
11958 let err = contrato_slot_err("checkout/\x01order");
11959 assert!(
11960 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11961 if slot == "checkout/\x01order" && reason.contains("control character")),
11962 "got {err:?}"
11963 );
11964 }
11965
11966 #[test]
11967 fn rejects_store_contrato_slot_with_newline() {
11968 // Embedded newline — the canonical "the paste-from-binary slug
11969 // spans multiple lines" footgun. Distinct from the whitespace
11970 // arm because `\n` is a control character (0x0A).
11971 let err = contrato_slot_err("checkout\norder");
11972 assert!(
11973 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11974 if slot == "checkout\norder" && reason.contains("control character")),
11975 "got {err:?}"
11976 );
11977 }
11978
11979 #[test]
11980 fn rejects_store_contrato_slot_with_non_ascii() {
11981 // Un-percent-encoded non-ASCII byte — the canonical "I copied
11982 // the slot from a doc with accented characters" footgun. Each
11983 // kv backend re-encodes non-ASCII differently (etcd preserves
11984 // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
11985 // rejects), so the typed slot's value set is the intersection-
11986 // floor every backend admits identically (printable ASCII).
11987 let err = contrato_slot_err("ch\u{e9}ckout/$order");
11988 assert!(
11989 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11990 if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
11991 "got {err:?}"
11992 );
11993 }
11994
11995 #[test]
11996 fn rejects_store_contrato_slot_too_long() {
11997 // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
11998 // legitimate-shape arms all pass (a single all-`a` token, no
11999 // separators); only the cap arm fires. Surfaces the paste-
12000 // from-binary / accidental-multi-line-blob landing footgun.
12001 // Mirrors `rejects_pubsub_contrato_subject_too_long` and
12002 // `rejects_http_contrato_endpoint_too_long` on the peer
12003 // payload axes.
12004 let big = "a".repeat(513);
12005 assert_eq!(big.len(), 513);
12006 let err = contrato_slot_err(&big);
12007 assert!(
12008 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12009 if slot == &big && reason.contains("max length of 512")),
12010 "got {err:?}"
12011 );
12012 }
12013
12014 #[test]
12015 fn store_contrato_slot_max_length_validates() {
12016 // 512-byte slot — exactly the cap. Boundary pin: drift in the
12017 // cap surfaces here and at `rejects_store_contrato_slot_too_long`
12018 // simultaneously, mirroring
12019 // `pubsub_contrato_subject_max_length_validates` and
12020 // `http_contrato_endpoint_max_length_validates` on the peer
12021 // payload axes.
12022 let big = "a".repeat(512);
12023 assert_eq!(big.len(), 512);
12024 let mut s = three_member_spec();
12025 s.contratos.push(WitContract {
12026 de: "payment".into(),
12027 para: "catalog".into(),
12028 wit: "wasi:keyvalue/store".into(),
12029 endpoint: None,
12030 subject: None,
12031 slot: Some(big),
12032 });
12033 s.validate().unwrap();
12034 }
12035
12036 #[test]
12037 fn store_contrato_slot_accepts_canonical_forms() {
12038 // Positive-set sweep: every canonical kv slot template the
12039 // substrate-side `is_wasi_keyvalue_slot` predicate accepts
12040 // (single-token identifiers, path-namespaced `$`-templates,
12041 // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
12042 // snake_case / kebab-case / MixedCase tokens, digit-bearing
12043 // tokens, percent-encoded fragments) must remain valid
12044 // contrato slots too. Drift between this list and the
12045 // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
12046 // surfaces at the shared predicate — one source of truth.
12047 // Uses a fresh `(payment, catalog)` edge so none of the swept
12048 // slots collide with the pre-existing entries in
12049 // `three_member_spec`.
12050 for slot in [
12051 "checkout",
12052 "checkout/$orderId",
12053 "users:{tenant}/{id}",
12054 "session.<sid>",
12055 "session.tokens.<sid>",
12056 "snake_case_key",
12057 "kebab-case-key",
12058 "MixedCase",
12059 "shard0",
12060 "v2/key",
12061 "users/caf%C3%A9",
12062 ] {
12063 let mut s = three_member_spec();
12064 s.contratos.push(WitContract {
12065 de: "payment".into(),
12066 para: "catalog".into(),
12067 wit: "wasi:keyvalue/store".into(),
12068 endpoint: None,
12069 subject: None,
12070 slot: Some(slot.into()),
12071 });
12072 s.validate()
12073 .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
12074 }
12075 }
12076
12077 #[test]
12078 fn contrato_slot_empty_takes_precedence_over_invalid() {
12079 // Ordering pin: `ContratoSlotEmpty` is the more self-locating
12080 // diagnostic on `""` and must lead — the value-shape gate is
12081 // only reached after the empty-check fires. Mirrors
12082 // `contrato_subject_empty_takes_precedence_over_invalid` and
12083 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12084 // the peer payload axes.
12085 let mut s = three_member_spec();
12086 s.contratos.push(WitContract {
12087 de: "payment".into(),
12088 para: "catalog".into(),
12089 wit: "wasi:keyvalue/store".into(),
12090 endpoint: None,
12091 subject: None,
12092 slot: Some(String::new()),
12093 });
12094 let err = s.validate().unwrap_err();
12095 assert!(
12096 matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
12097 "got {err:?}"
12098 );
12099 }
12100
12101 #[test]
12102 fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
12103 // Diagnostic-shape pin — the offending `:slot` + `:de` +
12104 // `:para` + a non-empty reason flow through verbatim so the
12105 // author can grep their caixa.lisp for the offending contrato
12106 // block and fix it in one edit. Same shape as
12107 // `contrato_subject_invalid_diagnostic_carries_offending_subject`
12108 // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12109 // on the peer payload axes.
12110 let err = contrato_slot_err("check out/$order");
12111 match err {
12112 AplicacaoError::ContratoSlotInvalid {
12113 de,
12114 para,
12115 slot,
12116 reason,
12117 } => {
12118 assert_eq!(de, "payment");
12119 assert_eq!(para, "catalog");
12120 assert_eq!(slot, "check out/$order");
12121 assert!(!reason.is_empty(), "reason field must be non-empty");
12122 }
12123 other => panic!("expected ContratoSlotInvalid, got {other:?}"),
12124 }
12125 }
12126
12127 #[test]
12128 fn target_view_store_slot_passes_through_to_typed_view() {
12129 // The compounding theorem on the store axis: every
12130 // `WitTarget::Store { slot }` returned by `target()` carries a
12131 // kv-backend-accepted slot template. Renderers downstream of
12132 // `typed_view()` (the future per-Servico `:capabilities
12133 // wasi:keyvalue/store` axis emitter, the future `feira app
12134 // graph` view's slot labeller, the future kv-provider CR
12135 // materializer) can rely on this without re-checking — the
12136 // type system carries the proof. Mirrors
12137 // `target_view_pubsub_subject_passes_through_to_typed_view` on
12138 // the peer payload axis.
12139 let store = WitContract {
12140 de: "a".into(),
12141 para: "b".into(),
12142 wit: "wasi:keyvalue/store".into(),
12143 endpoint: None,
12144 subject: None,
12145 slot: Some("checkout/$orderId".into()),
12146 };
12147 match store.target().unwrap() {
12148 WitTarget::Store { slot } => {
12149 assert_eq!(slot, "checkout/$orderId");
12150 }
12151 other => panic!("expected Store, got {other:?}"),
12152 }
12153 }
12154
12155 #[test]
12156 fn rejects_self_loop_in_synchronous_contratos() {
12157 // A synchronous self-edge (`cart → cart` over HTTP) is now
12158 // rejected by the dedicated `ContratoSelfLoop` gate — a precise
12159 // "this edge is degenerate" diagnostic — rather than incidentally
12160 // by the cycle detector framing it as a `["cart", "cart"]`
12161 // multi-node deadlock.
12162 let mut s = three_member_spec();
12163 s.contratos.push(contract_http("cart", "cart", "/loop"));
12164 let err = s.validate().unwrap_err();
12165 match err {
12166 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
12167 assert_eq!(caixa, "cart");
12168 assert_eq!(wit, "wasi:http/proxy");
12169 }
12170 other => panic!("expected ContratoSelfLoop, got {other:?}"),
12171 }
12172 }
12173
12174 #[test]
12175 fn rejects_self_loop_in_pubsub_contratos() {
12176 // The cycle detector excludes pub-sub edges (acyclic by
12177 // construction), so before the explicit gate a `nats:pub-sub`
12178 // self-edge silently validated and rendered a self-allow CNP.
12179 // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
12180 let mut s = three_member_spec();
12181 s.contratos.push(WitContract {
12182 de: "payment".into(),
12183 para: "payment".into(),
12184 wit: "nats:pub-sub".into(),
12185 endpoint: None,
12186 subject: Some("rio.events.payment".into()),
12187 slot: None,
12188 });
12189 let err = s.validate().unwrap_err();
12190 match err {
12191 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
12192 assert_eq!(caixa, "payment");
12193 assert_eq!(wit, "nats:pub-sub");
12194 }
12195 other => panic!("expected ContratoSelfLoop, got {other:?}"),
12196 }
12197 }
12198
12199 #[test]
12200 fn self_loop_fires_before_payload_shape_check() {
12201 // The structural "this edge can't exist" error precedes the
12202 // narrower payload-shape diagnostics: a self-edge carrying an
12203 // otherwise-malformed endpoint still reports ContratoSelfLoop,
12204 // not ContratoEndpointInvalid.
12205 let mut s = three_member_spec();
12206 s.contratos.push(WitContract {
12207 de: "cart".into(),
12208 para: "cart".into(),
12209 wit: "wasi:http/proxy".into(),
12210 endpoint: Some("not-absolute".into()),
12211 subject: None,
12212 slot: None,
12213 });
12214 match s.validate().unwrap_err() {
12215 AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
12216 other => panic!("expected ContratoSelfLoop, got {other:?}"),
12217 }
12218 }
12219
12220 #[test]
12221 fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
12222 // A self-edge naming a non-member reports the more fundamental
12223 // ContratoMemberMissing first (the member doesn't exist), so the
12224 // self-loop gate is reached only once both endpoints resolve.
12225 let mut s = three_member_spec();
12226 s.contratos.push(contract_http("ghost", "ghost", "/loop"));
12227 match s.validate().unwrap_err() {
12228 AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
12229 other => panic!("expected ContratoMemberMissing, got {other:?}"),
12230 }
12231 }
12232
12233 #[test]
12234 fn rejects_two_node_synchronous_cycle() {
12235 let mut s = three_member_spec();
12236 // existing edges: cart → catalog, cart → payment
12237 // adding catalog → cart closes a 2-cycle on the HTTP subgraph
12238 s.contratos
12239 .push(contract_http("catalog", "cart", "/refresh"));
12240 let err = s.validate().unwrap_err();
12241 match err {
12242 AplicacaoError::ContratoCycle { cycle } => {
12243 // Cycle traversal should mention both endpoints, with
12244 // the back-edge target appearing as both first and last
12245 // element to close the loop.
12246 assert!(cycle.len() >= 3);
12247 assert_eq!(cycle.first(), cycle.last());
12248 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
12249 assert!(body.contains("cart"));
12250 assert!(body.contains("catalog"));
12251 }
12252 other => panic!("expected ContratoCycle, got {other:?}"),
12253 }
12254 }
12255
12256 #[test]
12257 fn rejects_three_node_synchronous_cycle() {
12258 let mut s = three_member_spec();
12259 // Reset to a clean 3-cycle: catalog → cart → payment → catalog
12260 s.contratos = vec![
12261 contract_http("catalog", "cart", "/x"),
12262 contract_http("cart", "payment", "/y"),
12263 contract_http("payment", "catalog", "/z"),
12264 ];
12265 let err = s.validate().unwrap_err();
12266 match err {
12267 AplicacaoError::ContratoCycle { cycle } => {
12268 assert_eq!(cycle.first(), cycle.last());
12269 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
12270 assert_eq!(body.len(), 3);
12271 assert!(body.contains("cart"));
12272 assert!(body.contains("catalog"));
12273 assert!(body.contains("payment"));
12274 }
12275 other => panic!("expected ContratoCycle, got {other:?}"),
12276 }
12277 }
12278
12279 #[test]
12280 fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
12281 // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
12282 // "acyclic by construction" — so a cycle whose closing edge
12283 // is pub-sub should NOT raise ContratoCycle.
12284 let mut s = three_member_spec();
12285 s.contratos = vec![
12286 contract_http("catalog", "cart", "/x"),
12287 contract_http("cart", "payment", "/y"),
12288 // Closing edge is pub-sub — async; not a sync deadlock.
12289 WitContract {
12290 de: "payment".into(),
12291 para: "catalog".into(),
12292 wit: "nats:pub-sub".into(),
12293 endpoint: None,
12294 subject: Some("checkout.events.charge.completed".into()),
12295 slot: None,
12296 },
12297 ];
12298 s.validate().expect("pub-sub edge breaks the sync cycle");
12299 }
12300
12301 #[test]
12302 fn store_edge_counts_as_synchronous_for_cycle_detection() {
12303 // wasi:keyvalue/store is request/response; a cycle through one
12304 // *is* a sync deadlock, just like HTTP.
12305 let mut s = three_member_spec();
12306 s.contratos = vec![
12307 contract_http("catalog", "cart", "/x"),
12308 WitContract {
12309 de: "cart".into(),
12310 para: "catalog".into(),
12311 wit: "wasi:keyvalue/store".into(),
12312 endpoint: None,
12313 subject: None,
12314 slot: Some("session/$id".into()),
12315 },
12316 ];
12317 let err = s.validate().unwrap_err();
12318 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
12319 }
12320
12321 #[test]
12322 fn capability_edge_counts_as_synchronous_for_cycle_detection() {
12323 // Capability-only edges (unknown WIT shape, no payload) default
12324 // to synchronous — safer; authors with truly async capability
12325 // semantics can model them as pub-sub explicitly.
12326 let mut s = three_member_spec();
12327 s.contratos = vec![
12328 contract_http("catalog", "cart", "/x"),
12329 WitContract {
12330 de: "cart".into(),
12331 para: "catalog".into(),
12332 wit: "custom:exchange".into(),
12333 endpoint: None,
12334 subject: None,
12335 slot: None,
12336 },
12337 ];
12338 let err = s.validate().unwrap_err();
12339 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
12340 }
12341
12342 #[test]
12343 fn long_acyclic_chain_validates() {
12344 // A long sync chain (no back-edges) must validate even when
12345 // every node is reachable from the first.
12346 let mut s = three_member_spec();
12347 s.membros = vec![
12348 membro("a", "^0.1"),
12349 membro("b", "^0.1"),
12350 membro("c", "^0.1"),
12351 membro("d", "^0.1"),
12352 membro("e", "^0.1"),
12353 ];
12354 s.contratos = vec![
12355 contract_http("a", "b", "/1"),
12356 contract_http("b", "c", "/2"),
12357 contract_http("c", "d", "/3"),
12358 contract_http("d", "e", "/4"),
12359 ];
12360 s.entrada.as_mut().unwrap().para = "a".into();
12361 s.validate().unwrap();
12362 }
12363
12364 #[test]
12365 fn diamond_acyclic_validates() {
12366 // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
12367 let mut s = three_member_spec();
12368 s.membros = vec![
12369 membro("a", "^0.1"),
12370 membro("b", "^0.1"),
12371 membro("c", "^0.1"),
12372 membro("d", "^0.1"),
12373 ];
12374 s.contratos = vec![
12375 contract_http("a", "b", "/1"),
12376 contract_http("a", "c", "/2"),
12377 contract_http("b", "d", "/3"),
12378 contract_http("c", "d", "/4"),
12379 ];
12380 s.entrada.as_mut().unwrap().para = "a".into();
12381 s.validate().unwrap();
12382 }
12383
12384 // ── duplicate-`:contratos` build-error gate ──────────────────────────
12385
12386 #[test]
12387 fn rejects_duplicate_http_contrato() {
12388 // Fail-before-pass-after pin: the fixture's `cart → catalog`
12389 // HTTP edge appears once. Push an identical entry — same
12390 // (de, para, wit, endpoint) — and validate() must reject it.
12391 // Until this gate landed the typed surface accepted the
12392 // duplicate silently and caixa-mesh's `cilium_network_policies`
12393 // emitted two ``CiliumNetworkPolicy`` objects with identical
12394 // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
12395 // admission rejects on `kubectl apply` far from the source.
12396 let mut s = three_member_spec();
12397 s.contratos
12398 .push(contract_http("cart", "catalog", "/products/:id"));
12399 let err = s.validate().unwrap_err();
12400 assert!(
12401 matches!(
12402 err,
12403 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12404 if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
12405 ),
12406 "got {err:?}"
12407 );
12408 }
12409
12410 #[test]
12411 fn rejects_duplicate_pubsub_contrato() {
12412 // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
12413 // edges with identical (de, para, subject) are degenerate;
12414 // pin that the typed surface refuses both at validate time.
12415 let mut s = three_member_spec();
12416 let pubsub = WitContract {
12417 de: "payment".into(),
12418 para: "cart".into(),
12419 wit: "nats:pub-sub".into(),
12420 endpoint: None,
12421 subject: Some("checkout.events.charge.failed".into()),
12422 slot: None,
12423 };
12424 s.contratos.push(pubsub.clone());
12425 s.contratos.push(pubsub);
12426 let err = s.validate().unwrap_err();
12427 assert!(
12428 matches!(
12429 err,
12430 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12431 if de == "payment" && para == "cart" && wit == "nats:pub-sub"
12432 ),
12433 "got {err:?}"
12434 );
12435 }
12436
12437 #[test]
12438 fn rejects_duplicate_store_contrato() {
12439 // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
12440 // edges with identical (de, para, slot) collapse to one mesh-
12441 // policy edge; pin the build error.
12442 let mut s = three_member_spec();
12443 let store = WitContract {
12444 de: "cart".into(),
12445 para: "payment".into(),
12446 wit: "wasi:keyvalue/store".into(),
12447 endpoint: None,
12448 subject: None,
12449 slot: Some("checkout/$orderId".into()),
12450 };
12451 // Drop the conflicting HTTP `cart → payment` edge from the
12452 // fixture so the duplicate-store pair is the only one
12453 // distinguishable on this pair.
12454 s.contratos
12455 .retain(|c| !(c.de == "cart" && c.para == "payment"));
12456 s.contratos.push(store.clone());
12457 s.contratos.push(store);
12458 let err = s.validate().unwrap_err();
12459 assert!(
12460 matches!(
12461 err,
12462 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12463 if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
12464 ),
12465 "got {err:?}"
12466 );
12467 }
12468
12469 #[test]
12470 fn rejects_duplicate_capability_contrato() {
12471 // Same gate on the pure-capability axis (no payload selector).
12472 // Two contracts with identical (de, para, wit) and no
12473 // endpoint/subject/slot are duplicate edges; pin so a future
12474 // `target_label` change can't accidentally collapse the
12475 // capability arm into a None-shaped key that compares equal
12476 // to a populated one.
12477 let mut s = three_member_spec();
12478 let capability = WitContract {
12479 de: "cart".into(),
12480 para: "catalog".into(),
12481 wit: "pleme:cap/audit".into(),
12482 endpoint: None,
12483 subject: None,
12484 slot: None,
12485 };
12486 s.contratos.push(capability.clone());
12487 s.contratos.push(capability);
12488 let err = s.validate().unwrap_err();
12489 match err {
12490 AplicacaoError::ContratoDuplicate {
12491 de,
12492 para,
12493 wit,
12494 target,
12495 } => {
12496 assert_eq!(de, "cart");
12497 assert_eq!(para, "catalog");
12498 assert_eq!(wit, "pleme:cap/audit");
12499 assert!(
12500 target.contains("capability"),
12501 "capability-edge duplicate diagnostic must surface the \
12502 no-payload shape (got target = {target:?})"
12503 );
12504 }
12505 other => panic!("expected ContratoDuplicate, got {other:?}"),
12506 }
12507 }
12508
12509 #[test]
12510 fn accepts_distinct_http_paths_between_same_pair() {
12511 // Negative pin: two HTTP contracts cart → catalog at distinct
12512 // endpoints (`/products/:id` and `/search`) are *not*
12513 // duplicates — they're distinct typed edges differing on the
12514 // payload axis. The duplicate-gate must not over-match here,
12515 // since the cart-calls-catalog-on-multiple-paths shape is the
12516 // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
12517 // example: cart calls catalog at /products/:id, payment at
12518 // /charge — same shape extends to two paths on one para).
12519 let mut s = three_member_spec();
12520 s.contratos
12521 .push(contract_http("cart", "catalog", "/search"));
12522 s.validate()
12523 .expect("distinct endpoints between same (de, para) must validate");
12524 }
12525
12526 #[test]
12527 fn accepts_same_endpoint_on_different_pairs() {
12528 // Negative pin: the same `/charge` endpoint reused on two
12529 // different (de, para) pairs is two distinct edges, not a
12530 // duplicate. Pinning this shape so the gate's identity key
12531 // includes both `de` and `para` (not just `(wit, endpoint)`).
12532 let mut s = three_member_spec();
12533 s.contratos
12534 .push(contract_http("payment", "catalog", "/charge"));
12535 s.validate()
12536 .expect("same endpoint reused on distinct (de, para) must validate");
12537 }
12538
12539 #[test]
12540 fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
12541 // Pin the diagnostic shape: the duplicate-edge error names
12542 // *which* target field carried the conflict, so the author
12543 // doesn't have to re-grep the source caixa.lisp to find it.
12544 // Same self-locating diagnostic discipline as
12545 // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
12546 let mut s = three_member_spec();
12547 s.contratos
12548 .push(contract_http("cart", "catalog", "/products/:id"));
12549 let err = s.validate().unwrap_err();
12550 let msg = format!("{err}");
12551 assert!(
12552 msg.contains("\"/products/:id\""),
12553 "duplicate-contrato diagnostic must name the offending \
12554 :endpoint payload (got: {msg:?})"
12555 );
12556 assert!(
12557 msg.contains("cart") && msg.contains("catalog"),
12558 "diagnostic must name both endpoints of the duplicate edge \
12559 (got: {msg:?})"
12560 );
12561 }
12562
12563 #[test]
12564 fn duplicate_contrato_gate_runs_after_membership_check() {
12565 // Order pin: a duplicate contract whose `:de` is *also* not in
12566 // `:membros` surfaces the membership error first — the
12567 // missing-member diagnostic is more locating than the
12568 // duplicate-edge one (the author has to fix the membership
12569 // before the duplicate is meaningful). Same ordering
12570 // discipline as `membros_validation_runs_before_contratos_membership_check`.
12571 let mut s = three_member_spec();
12572 s.contratos.push(contract_http("phantom", "catalog", "/x"));
12573 s.contratos.push(contract_http("phantom", "catalog", "/x"));
12574 let err = s.validate().unwrap_err();
12575 assert!(
12576 matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
12577 "membership-missing must fire before duplicate-edge (got {err:?})"
12578 );
12579 }
12580
12581 #[test]
12582 fn duplicate_contrato_gate_runs_after_target_shape_check() {
12583 // Order pin: a contract with a malformed target (e.g. an HTTP
12584 // wit world with an empty :endpoint) surfaces the target-shape
12585 // error first, not the duplicate one. Even when two such
12586 // malformed entries are identical, the per-contract `target()`
12587 // check fires inside the loop *before* the duplicate-key
12588 // insert, so the diagnostic remains the most-locating one.
12589 let mut s = three_member_spec();
12590 let malformed = WitContract {
12591 de: "cart".into(),
12592 para: "catalog".into(),
12593 wit: "wasi:http/proxy".into(),
12594 endpoint: Some(String::new()),
12595 subject: None,
12596 slot: None,
12597 };
12598 s.contratos.push(malformed.clone());
12599 s.contratos.push(malformed);
12600 let err = s.validate().unwrap_err();
12601 assert!(
12602 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
12603 "endpoint-empty must fire before duplicate-edge (got {err:?})"
12604 );
12605 }
12606
12607 #[test]
12608 fn wit_target_label_pins_per_variant_format() {
12609 // Label format is the single source of truth every duplicate-
12610 // `:contratos` diagnostic + every future `feira app graph`
12611 // consumer routes through. Pin the shape per variant so a
12612 // future edit to `WitTarget::label` (e.g. a JSON emitter that
12613 // strips the leading `:`, or a rename from `endpoint` →
12614 // `path`) surfaces as a red-red test rather than as a silent
12615 // downstream diagnostic drift. Together with the exhaustive
12616 // `match` on `WitTarget` inside `label()`, adding a future
12617 // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
12618 // peer, per-edge WIT registry variants) is a compile error at
12619 // the label site — not a fall-through into the `Capability`
12620 // "no payload" default the prior raw-field-probe helper
12621 // silently landed on.
12622 assert_eq!(
12623 WitTarget::Http {
12624 endpoint: "/charge",
12625 }
12626 .label(),
12627 "\
12628:endpoint \"/charge\""
12629 );
12630 assert_eq!(
12631 WitTarget::PubSub {
12632 subject: "events.checkout.paid",
12633 }
12634 .label(),
12635 "\
12636:subject \"events.checkout.paid\""
12637 );
12638 assert_eq!(
12639 WitTarget::Store {
12640 slot: "checkout/$order",
12641 }
12642 .label(),
12643 "\
12644:slot \"checkout/$order\""
12645 );
12646 assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
12647 // Capability-arm label routes through the lifted
12648 // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
12649 // declaration per arm, next to the variant" discipline the
12650 // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
12651 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12652 // consts already carry extends to the payload-less arm; the
12653 // byte-string equality pin below plus this label-routes-
12654 // through-the-const pin make a future rebrand on either the
12655 // const declaration or the `label()` template a build error
12656 // here rather than a downstream consumer surprise.
12657 assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
12658 assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
12659 }
12660
12661 #[test]
12662 fn wit_target_display_routes_through_label_helper() {
12663 // Fail-before-pass-after pin on the fourth (and only remaining)
12664 // typed-shape-discriminator axis to converge onto the
12665 // three-path-convergence discipline the sibling M3
12666 // [`PlacementStrategy`] (0a2f653) and M2
12667 // [`crate::supervisor::RestartStrategy`] /
12668 // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
12669 // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
12670 // through [`WitTarget::label`], so every consumer reaching for
12671 // `format!("{v}")` on a typed payload target lands on the same
12672 // stable author-facing byte-string [`WitTarget::label`] returns
12673 // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
12674 // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
12675 // `:contratos` gate seeds via [`WitTarget::label`] at
12676 // aplicacao.rs:5491 already threads through.
12677 //
12678 // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
12679 // through to the `Debug` derive's structural output
12680 // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
12681 // rather than the [`WitTarget::label`] helper's stable byte-
12682 // string (`:endpoint "/charge"` — the author-facing `:contratos`
12683 // keyword form). Every future consumer that reaches for
12684 // `format!("{target}")` — the canonical shape every user-facing
12685 // pretty-print site on the sibling typed-enum axes
12686 // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
12687 // [`crate::supervisor::RestartPolicy`]) already uses — would
12688 // silently land under a different byte-string than the
12689 // [`WitTarget::label`] callers that the duplicate-`:contratos`
12690 // diagnostic already threads through, with the mismatch
12691 // surfacing as a downstream diagnostic / graph / audit line
12692 // reading one spelling while the substrate's own gate emitted
12693 // another.
12694 //
12695 // Pin the routing here so a future
12696 // `impl std::fmt::Display for WitTarget<'_>` reimplementation
12697 // that hand-rolls the per-arm formatting instead of delegating
12698 // to [`WitTarget::label`] fails at caixa-core build time.
12699 for variant in [
12700 WitTarget::Http {
12701 endpoint: "/charge",
12702 },
12703 WitTarget::PubSub {
12704 subject: "events.checkout.paid",
12705 },
12706 WitTarget::Store {
12707 slot: "checkout/$order",
12708 },
12709 WitTarget::Capability,
12710 ] {
12711 assert_eq!(
12712 variant.to_string(),
12713 variant.label(),
12714 "WitTarget::{variant:?} Display must route through \
12715 WitTarget::label (single source of truth: the lifted \
12716 payload_pair 4-arm dispatch the label helper already \
12717 threads through)"
12718 );
12719 }
12720 }
12721
12722 #[test]
12723 fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
12724 // Consumer-side pin on the three-path convergence:
12725 // [`std::fmt::Display`] agrees byte-for-byte with the
12726 // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
12727 // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
12728 // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
12729 // Pre-lift the two paths were structurally independent — the
12730 // substrate-side gate reached for `target_view.label()` while a
12731 // future downstream diagnostic / graph / audit line reaching
12732 // for `format!("{target}")` would silently land on the `Debug`
12733 // derive's structural output. Pin the two paths byte-for-byte
12734 // here so any future variant addition (M4 `Rest`/`Grpc` split
12735 // of [`WitTarget::Http`], `Queue`-shaped peer of
12736 // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
12737 // match error at [`WitTarget::payload_pair`] rather than a
12738 // silent per-consumer dispatch miss.
12739 for variant in [
12740 WitTarget::Http {
12741 endpoint: "/charge",
12742 },
12743 WitTarget::PubSub {
12744 subject: "events.checkout.paid",
12745 },
12746 WitTarget::Store {
12747 slot: "checkout/$order",
12748 },
12749 WitTarget::Capability,
12750 ] {
12751 assert_eq!(
12752 format!("{variant}"),
12753 variant.label(),
12754 "WitTarget::{variant:?} Display byte-string must match \
12755 the AplicacaoError::ContratoDuplicate `target:` carrier \
12756 the AplicacaoSpec::validate duplicate-`:contratos` gate \
12757 seeds via WitTarget::label — three-path convergence: \
12758 Display + label + payload_pair all resolve to the same \
12759 per-arm byte-string"
12760 );
12761 }
12762 }
12763
12764 #[test]
12765 fn wit_target_payload_pair_pins_per_variant() {
12766 // Pin the per-arm `(field-name, payload)` pair single-sourced
12767 // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
12768 // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
12769 // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
12770 // and [`WitTarget::field_name`] (returns the first component)
12771 // route through. Until this lift landed [`WitTarget::label`]
12772 // dispatched on the same three arms with a per-arm
12773 // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
12774 // paired [`WitTarget::HTTP_FIELD_NAME`] /
12775 // [`WitTarget::PUBSUB_FIELD_NAME`] /
12776 // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
12777 // canonical "same shape, written N times" duplication
12778 // THEORY.md §I.3.5 promotes to a build-time concern. A future
12779 // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
12780 // [`WitTarget::Http`], `Queue`-shaped peer of
12781 // [`WitTarget::Store`]) is one match-arm edit at
12782 // [`WitTarget::payload_pair`], visible here as a compile-time
12783 // exhaustiveness error on both this pin and the label-format
12784 // pin above.
12785 assert_eq!(
12786 WitTarget::Http {
12787 endpoint: "/charge"
12788 }
12789 .payload_pair(),
12790 Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
12791 );
12792 assert_eq!(
12793 WitTarget::PubSub {
12794 subject: "events.x",
12795 }
12796 .payload_pair(),
12797 Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
12798 );
12799 assert_eq!(
12800 WitTarget::Store {
12801 slot: "checkout/$order",
12802 }
12803 .payload_pair(),
12804 Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
12805 );
12806 assert_eq!(WitTarget::Capability.payload_pair(), None);
12807 }
12808
12809 #[test]
12810 fn wit_target_field_name_pins_per_variant() {
12811 // Pin the per-arm author-facing `:contratos` payload field
12812 // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
12813 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12814 // + returned by [`WitTarget::field_name`]. Every downstream
12815 // consumer (the [`WitContract::target`] gate's `expected:`
12816 // scalar, the [`WitTarget::label`] template's keyword prefix,
12817 // the `feira app graph` verb's `endpoint=…` prefix) routes
12818 // through the same three peer consts, so a rename on the
12819 // author-surface `(defcaixa … :contratos ((:de … :para …
12820 // :wit … :endpoint …)))` field lands in exactly one place.
12821 assert_eq!(
12822 WitTarget::Http {
12823 endpoint: "/charge"
12824 }
12825 .field_name(),
12826 Some(WitTarget::HTTP_FIELD_NAME),
12827 );
12828 assert_eq!(
12829 WitTarget::PubSub {
12830 subject: "events.x",
12831 }
12832 .field_name(),
12833 Some(WitTarget::PUBSUB_FIELD_NAME),
12834 );
12835 assert_eq!(
12836 WitTarget::Store {
12837 slot: "checkout/$order",
12838 }
12839 .field_name(),
12840 Some(WitTarget::STORE_FIELD_NAME),
12841 );
12842 // Capability arm carries no payload field — the diagnostic
12843 // never reports `expected: "capability"` because the gate's
12844 // Capability arm accepts no payload at all (it fires the
12845 // "expected: none" WrongTarget error instead), so the field-
12846 // name method returns None here rather than a placeholder.
12847 assert_eq!(WitTarget::Capability.field_name(), None);
12848
12849 // Peer const scalar values pinned so a rename on either side
12850 // (author-surface field name in the `(defcaixa …)` DSL, or
12851 // the diagnostic's `expected:` scalar) can't drift without
12852 // failing here first.
12853 assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
12854 assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
12855 assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
12856 }
12857
12858 #[test]
12859 fn wit_target_payload_pins_per_variant() {
12860 // Pin the per-arm payload scalar single-sourced onto the
12861 // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
12862 // [`WitTarget::payload`] — the peer per-half projection to
12863 // [`WitTarget::field_name`] on the paired sub-selector axis. The
12864 // three payload-carrying arms round-trip their author-declared
12865 // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
12866 // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
12867 // the payload-less [`WitTarget::Capability`] arm returns `None`.
12868 // Same shape as the sibling `wit_target_field_name_pins_per_variant`
12869 // (c6ec2af) pin on the Component-0 projection axis, extended
12870 // onto the Component-1 projection axis so both per-half readers
12871 // on the paired dispatch carry their own byte-shape pin.
12872 assert_eq!(
12873 WitTarget::Http {
12874 endpoint: "/charge",
12875 }
12876 .payload(),
12877 Some("/charge"),
12878 );
12879 assert_eq!(
12880 WitTarget::PubSub {
12881 subject: "events.x",
12882 }
12883 .payload(),
12884 Some("events.x"),
12885 );
12886 assert_eq!(
12887 WitTarget::Store {
12888 slot: "checkout/$order",
12889 }
12890 .payload(),
12891 Some("checkout/$order"),
12892 );
12893 assert_eq!(WitTarget::Capability.payload(), None);
12894 }
12895
12896 #[test]
12897 fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
12898 // Per-variant equivalence pin: for every arm of [`WitTarget`],
12899 // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
12900 // byte-for-byte. Guards the drift surface where a future refactor
12901 // that split one accessor off the shared match onto its own
12902 // dispatch — a well-meaning "inline the pair back into per-half
12903 // fields for one crate-internal caller who only wanted one half"
12904 // or a scratch `impl` shadowing the derived projection — would
12905 // silently desynchronize [`WitTarget::payload`] from the
12906 // authoritative [`WitTarget::payload_pair`] dispatch, and every
12907 // downstream consumer that thinks "the payload half of the pair"
12908 // would drift from the diagnostic / graph consumers reading the
12909 // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
12910 // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
12911 // per-half projection pin (`gitrefspec_ref_pair_projects_
12912 // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
12913 // FluxCD source-controller `spec.ref.<field>` axis — same "one
12914 // paired dispatch, both per-half projections agree byte-for-
12915 // byte" discipline extended onto the M3 `:contratos` payload-
12916 // arm surface.
12917 for variant in [
12918 WitTarget::Http {
12919 endpoint: "/charge",
12920 },
12921 WitTarget::PubSub {
12922 subject: "events.checkout.paid",
12923 },
12924 WitTarget::Store {
12925 slot: "checkout/$order",
12926 },
12927 WitTarget::Capability,
12928 ] {
12929 let via_projection = variant.payload();
12930 let via_pair = variant.payload_pair().map(|(_, p)| p);
12931 assert_eq!(
12932 via_projection, via_pair,
12933 "WitTarget::{variant:?} payload() must equal \
12934 payload_pair().map(|(_, p)| p) byte-for-byte — a \
12935 regression that splits the two per-half projections off \
12936 their shared match would silently desynchronize the \
12937 payload accessor from the paired dispatch every \
12938 diagnostic / graph consumer reads through",
12939 );
12940 }
12941 }
12942
12943 #[test]
12944 fn wit_target_http_endpoint_pins_per_variant() {
12945 // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
12946 // [`WitTarget::http_endpoint`] 2-arm dispatch — the
12947 // substrate-primitive per-arm post-projection accessor every
12948 // L7-HTTP-facing consumer routes through, sibling to the peer
12949 // WitContract pre-projection [`WitContract::endpoint`] (7020470)
12950 // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
12951 // arm round-trips its author-declared endpoint verbatim as
12952 // `Some("/charge")`; the three sibling arms
12953 // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
12954 // [`WitTarget::Capability`]) each return `None` because they
12955 // carry no HTTP endpoint by definition. Same fail-before-pass-
12956 // after per-variant discipline as the sibling
12957 // `wit_target_payload_pins_per_variant` (5d6dc92) /
12958 // `wit_target_field_name_pins_per_variant` (c6ec2af) /
12959 // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
12960 // the peer pan-arm / per-half projection axes — extended onto
12961 // the per-arm HTTP-shape post-projection axis so a future
12962 // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
12963 // [`WitTarget::Http`], a `Queue`-shaped peer of
12964 // [`WitTarget::Store`]) trips a compile-time exhaustiveness
12965 // error on the sibling [`WitTarget::http_endpoint`] match arms
12966 // whose payload the L7-HTTP-shape accept-set is meant to bound.
12967 assert_eq!(
12968 WitTarget::Http {
12969 endpoint: "/charge",
12970 }
12971 .http_endpoint(),
12972 Some("/charge"),
12973 );
12974 assert_eq!(
12975 WitTarget::PubSub {
12976 subject: "events.checkout.paid",
12977 }
12978 .http_endpoint(),
12979 None,
12980 );
12981 assert_eq!(
12982 WitTarget::Store {
12983 slot: "checkout/$order",
12984 }
12985 .http_endpoint(),
12986 None,
12987 );
12988 assert_eq!(WitTarget::Capability.http_endpoint(), None);
12989 }
12990
12991 #[test]
12992 fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
12993 // Per-variant coherence pin: for every arm of [`WitTarget`],
12994 // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
12995 // arm (both project the same author-declared request-path
12996 // scalar), and returns `None` on every sibling arm regardless of
12997 // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
12998 // Store carry their own payload the pan-arm accessor surfaces,
12999 // but that payload is not an HTTP endpoint — the per-arm
13000 // accessor must not leak it through the HTTP-shape channel).
13001 // Guards the drift surface where a future refactor that
13002 // conflated the per-arm HTTP projection with the pan-arm
13003 // [`WitTarget::payload`] projection — a well-meaning "one
13004 // accessor for the L7 branch, one for the graph" collapse that
13005 // routes both through the same 4-arm dispatch — would silently
13006 // widen the L7-HTTP-shape accept-set onto pub-sub / store
13007 // payloads at the caixa-mesh L7 emit branch, admitting a
13008 // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
13009 // rule with the operator-side apply-time symptom (Cilium's
13010 // eBPF data-plane rejects every ingress edge whose L7 filter
13011 // doesn't match the wire-format HTTP request line) far from
13012 // the source refactor. Sibling to the peer
13013 // `wit_target_payload_matches_payload_pair_second_component_
13014 // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
13015 // extended onto the per-arm HTTP specialization axis so both
13016 // the pan-arm and the per-arm projections carry their own
13017 // byte-shape coherence witness against the substrate's typed
13018 // arm-family accept-set.
13019 for variant in [
13020 WitTarget::Http {
13021 endpoint: "/charge",
13022 },
13023 WitTarget::PubSub {
13024 subject: "events.checkout.paid",
13025 },
13026 WitTarget::Store {
13027 slot: "checkout/$order",
13028 },
13029 WitTarget::Capability,
13030 ] {
13031 let per_arm = variant.http_endpoint();
13032 let pan_arm = variant.payload();
13033 if variant.is_http() {
13034 assert_eq!(
13035 per_arm, pan_arm,
13036 "WitTarget::{variant:?} http_endpoint() must equal \
13037 payload() on the Http arm — a per-arm-vs-pan-arm \
13038 split would silently drift the L7 emit branch's \
13039 path-scalar source from the graph verb's payload \
13040 scalar source",
13041 );
13042 } else {
13043 assert_eq!(
13044 per_arm, None,
13045 "WitTarget::{variant:?} http_endpoint() must return \
13046 None on non-Http arms — a leak that surfaced a \
13047 pub-sub :subject or a key/value :slot through the \
13048 HTTP-endpoint accessor would silently widen the \
13049 Cilium L7 HTTP `path:` rule accept-set onto \
13050 protocol shapes Cilium's eBPF data-plane can't \
13051 introspect",
13052 );
13053 }
13054 }
13055 }
13056
13057 #[test]
13058 fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
13059 // Per-variant coherence pin: for every arm of [`WitTarget`],
13060 // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
13061 // drift surface where a future extension of the
13062 // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
13063 // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
13064 // accessor to cover both peers) landed without a paired
13065 // extension of the [`gen_platform::IsVariant`]-derived
13066 // `is_http()` predicate's accept-set, or vice versa — a
13067 // regression that split the "which arms count as HTTP-shaped
13068 // for L7-path emission?" answer between two dispatch surfaces
13069 // the substrate ships. Sibling to the peer
13070 // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
13071 // on the paired dispatch axis — extended onto the per-arm
13072 // predicate-vs-accessor coherence axis so the gen-platform
13073 // IsVariant predicate and the substrate-lifted per-arm
13074 // accessor carry one shared answer to "is this the HTTP arm?".
13075 for variant in [
13076 WitTarget::Http {
13077 endpoint: "/charge",
13078 },
13079 WitTarget::PubSub {
13080 subject: "events.checkout.paid",
13081 },
13082 WitTarget::Store {
13083 slot: "checkout/$order",
13084 },
13085 WitTarget::Capability,
13086 ] {
13087 assert_eq!(
13088 variant.http_endpoint().is_some(),
13089 variant.is_http(),
13090 "WitTarget::{variant:?} http_endpoint().is_some() must \
13091 equal is_http() — a drift would split the L7 emit \
13092 branch's arm-set gate from the substrate-derived \
13093 shape-discrimination predicate on the same axis",
13094 );
13095 }
13096 }
13097
13098 #[test]
13099 fn wit_target_pubsub_subject_pins_per_variant() {
13100 // Fail-before-pass-after pin: the substrate-canonical per-arm
13101 // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
13102 // is the single dispatch every future pub-sub-facing consumer
13103 // routes through, sibling to the peer [`WitContract::subject`]
13104 // (63e18a0) pre-projection scalar accessor on the raw-field
13105 // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
13106 // post-projection per-arm accessor on the sibling HTTP-shape
13107 // axis. The [`WitTarget::PubSub`] arm round-trips its
13108 // author-declared subject verbatim as
13109 // `Some("events.checkout.paid")`; the three sibling arms each
13110 // return `None` because they carry no NATS-shaped subject by
13111 // definition. Same fail-before-pass-after per-variant discipline
13112 // as the sibling `wit_target_http_endpoint_pins_per_variant`
13113 // pin on the peer per-arm axis — extended onto the per-arm
13114 // pub-sub-shape post-projection axis so a future [`WitTarget`]
13115 // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
13116 // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
13117 // compile-time exhaustiveness error on the sibling
13118 // [`WitTarget::pubsub_subject`] match arms whose payload the
13119 // pub-sub-shape accept-set is meant to bound.
13120 assert_eq!(
13121 WitTarget::PubSub {
13122 subject: "events.checkout.paid",
13123 }
13124 .pubsub_subject(),
13125 Some("events.checkout.paid"),
13126 );
13127 assert_eq!(
13128 WitTarget::Http {
13129 endpoint: "/charge",
13130 }
13131 .pubsub_subject(),
13132 None,
13133 );
13134 assert_eq!(
13135 WitTarget::Store {
13136 slot: "checkout/$order",
13137 }
13138 .pubsub_subject(),
13139 None,
13140 );
13141 assert_eq!(WitTarget::Capability.pubsub_subject(), None);
13142 }
13143
13144 #[test]
13145 fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
13146 // Per-variant coherence pin: for every arm of [`WitTarget`],
13147 // `.pubsub_subject()` equals `.payload()` on the
13148 // [`WitTarget::PubSub`] arm (both project the same
13149 // author-declared subject scalar), and returns `None` on every
13150 // sibling arm regardless of whether [`WitTarget::payload`]
13151 // itself returns `Some` (Http / Store carry their own payload
13152 // the pan-arm accessor surfaces, but that payload is not a
13153 // pub-sub subject — the per-arm accessor must not leak it
13154 // through the pub-sub-shape channel). Sibling to the peer
13155 // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
13156 // coherence pin on the per-arm HTTP-shape axis — extended onto
13157 // the per-arm pub-sub specialization axis so both per-arm
13158 // projections carry their own byte-shape coherence witness
13159 // against the substrate's typed arm-family accept-set.
13160 for variant in [
13161 WitTarget::Http {
13162 endpoint: "/charge",
13163 },
13164 WitTarget::PubSub {
13165 subject: "events.checkout.paid",
13166 },
13167 WitTarget::Store {
13168 slot: "checkout/$order",
13169 },
13170 WitTarget::Capability,
13171 ] {
13172 let per_arm = variant.pubsub_subject();
13173 let pan_arm = variant.payload();
13174 if variant.is_pubsub() {
13175 assert_eq!(
13176 per_arm, pan_arm,
13177 "WitTarget::{variant:?} pubsub_subject() must equal \
13178 payload() on the PubSub arm — a per-arm-vs-pan-arm \
13179 split would silently drift the pub-sub-shape emit \
13180 branch's subject-scalar source from the graph verb's \
13181 payload scalar source",
13182 );
13183 } else {
13184 assert_eq!(
13185 per_arm, None,
13186 "WitTarget::{variant:?} pubsub_subject() must return \
13187 None on non-PubSub arms — a leak that surfaced an \
13188 HTTP :endpoint or a key/value :slot through the \
13189 pub-sub-subject accessor would silently widen the \
13190 downstream NATS-shape accept-set onto protocol \
13191 shapes NATS servers can't route",
13192 );
13193 }
13194 }
13195 }
13196
13197 #[test]
13198 fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
13199 // Per-variant coherence pin: for every arm of [`WitTarget`],
13200 // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
13201 // drift surface where a future extension of the
13202 // [`WitTarget::pubsub_subject`] accessor's accept-set landed
13203 // without a paired extension of the [`gen_platform::IsVariant`]-
13204 // derived `is_pubsub()` predicate's accept-set, or vice versa
13205 // — a regression that split the "which arms count as pub-sub-
13206 // shaped for subject emission?" answer between two dispatch
13207 // surfaces the substrate ships. Sibling to the peer
13208 // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13209 // pin on the per-arm HTTP-shape axis — extended onto the
13210 // per-arm pub-sub predicate-vs-accessor coherence axis so the
13211 // gen-platform IsVariant predicate and the substrate-lifted
13212 // per-arm accessor carry one shared answer to "is this the
13213 // PubSub arm?".
13214 for variant in [
13215 WitTarget::Http {
13216 endpoint: "/charge",
13217 },
13218 WitTarget::PubSub {
13219 subject: "events.checkout.paid",
13220 },
13221 WitTarget::Store {
13222 slot: "checkout/$order",
13223 },
13224 WitTarget::Capability,
13225 ] {
13226 assert_eq!(
13227 variant.pubsub_subject().is_some(),
13228 variant.is_pubsub(),
13229 "WitTarget::{variant:?} pubsub_subject().is_some() must \
13230 equal is_pubsub() — a drift would split the pub-sub \
13231 emit branch's arm-set gate from the substrate-derived \
13232 shape-discrimination predicate on the same axis",
13233 );
13234 }
13235 }
13236
13237 #[test]
13238 fn wit_target_store_slot_pins_per_variant() {
13239 // Fail-before-pass-after pin: the substrate-canonical per-arm
13240 // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
13241 // is the single dispatch every future store-facing consumer
13242 // routes through, sibling to the peer [`WitContract::slot`]
13243 // pre-projection scalar accessor on the raw-field axis and to
13244 // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
13245 // [`WitTarget::pubsub_subject`] post-projection per-arm
13246 // accessors on the sibling per-payload-arm axes. The
13247 // [`WitTarget::Store`] arm round-trips its author-declared
13248 // slot verbatim as `Some("checkout/$order")`; the three
13249 // sibling arms each return `None` because they carry no
13250 // WASI-key/value slot by definition. Same fail-before-pass-
13251 // after per-variant discipline as the sibling
13252 // `wit_target_http_endpoint_pins_per_variant` +
13253 // `wit_target_pubsub_subject_pins_per_variant` pins on the
13254 // peer per-arm axes — extended onto the per-arm store-shape
13255 // post-projection axis so a future [`WitTarget`] variant
13256 // addition trips a compile-time exhaustiveness error on the
13257 // sibling [`WitTarget::store_slot`] match arms whose payload
13258 // the store-shape accept-set is meant to bound.
13259 assert_eq!(
13260 WitTarget::Store {
13261 slot: "checkout/$order",
13262 }
13263 .store_slot(),
13264 Some("checkout/$order"),
13265 );
13266 assert_eq!(
13267 WitTarget::Http {
13268 endpoint: "/charge",
13269 }
13270 .store_slot(),
13271 None,
13272 );
13273 assert_eq!(
13274 WitTarget::PubSub {
13275 subject: "events.checkout.paid",
13276 }
13277 .store_slot(),
13278 None,
13279 );
13280 assert_eq!(WitTarget::Capability.store_slot(), None);
13281 }
13282
13283 #[test]
13284 fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
13285 // Per-variant coherence pin: for every arm of [`WitTarget`],
13286 // `.store_slot()` equals `.payload()` on the
13287 // [`WitTarget::Store`] arm (both project the same
13288 // author-declared slot scalar), and returns `None` on every
13289 // sibling arm regardless of whether [`WitTarget::payload`]
13290 // itself returns `Some`. Sibling to the peer
13291 // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
13292 // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
13293 // pins on the per-arm HTTP and PubSub axes — closes the
13294 // per-arm-vs-pan-arm byte-shape coherence trio across all
13295 // three payload arms.
13296 for variant in [
13297 WitTarget::Http {
13298 endpoint: "/charge",
13299 },
13300 WitTarget::PubSub {
13301 subject: "events.checkout.paid",
13302 },
13303 WitTarget::Store {
13304 slot: "checkout/$order",
13305 },
13306 WitTarget::Capability,
13307 ] {
13308 let per_arm = variant.store_slot();
13309 let pan_arm = variant.payload();
13310 if variant.is_store() {
13311 assert_eq!(
13312 per_arm, pan_arm,
13313 "WitTarget::{variant:?} store_slot() must equal \
13314 payload() on the Store arm — a per-arm-vs-pan-arm \
13315 split would silently drift the store-shape emit \
13316 branch's slot-scalar source from the graph verb's \
13317 payload scalar source",
13318 );
13319 } else {
13320 assert_eq!(
13321 per_arm, None,
13322 "WitTarget::{variant:?} store_slot() must return \
13323 None on non-Store arms — a leak that surfaced an \
13324 HTTP :endpoint or a NATS :subject through the \
13325 key/value-slot accessor would silently widen the \
13326 downstream WASI-key/value slot accept-set onto \
13327 protocol shapes the kv backends can't route",
13328 );
13329 }
13330 }
13331 }
13332
13333 #[test]
13334 fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
13335 // Per-variant coherence pin: for every arm of [`WitTarget`],
13336 // `.store_slot().is_some()` iff `.is_store()`. Guards the
13337 // drift surface where a future extension of the
13338 // [`WitTarget::store_slot`] accessor's accept-set landed
13339 // without a paired extension of the [`gen_platform::IsVariant`]-
13340 // derived `is_store()` predicate's accept-set. Sibling to the
13341 // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13342 // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
13343 // pins — closes the per-arm predicate-vs-accessor coherence
13344 // trio across all three payload arms so the gen-platform
13345 // IsVariant predicate and the substrate-lifted per-arm
13346 // accessor carry one shared answer to "is this the Store arm?".
13347 for variant in [
13348 WitTarget::Http {
13349 endpoint: "/charge",
13350 },
13351 WitTarget::PubSub {
13352 subject: "events.checkout.paid",
13353 },
13354 WitTarget::Store {
13355 slot: "checkout/$order",
13356 },
13357 WitTarget::Capability,
13358 ] {
13359 assert_eq!(
13360 variant.store_slot().is_some(),
13361 variant.is_store(),
13362 "WitTarget::{variant:?} store_slot().is_some() must \
13363 equal is_store() — a drift would split the store-shape \
13364 emit branch's arm-set gate from the substrate-derived \
13365 shape-discrimination predicate on the same axis",
13366 );
13367 }
13368 }
13369
13370 #[test]
13371 fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
13372 // Fail-before-pass-after cross-axis pin on the trio
13373 // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
13374 // payload-carrying arm of [`WitTarget`], exactly one per-arm
13375 // accessor returns `Some(payload)` and the two peers return
13376 // `None`; and on the payload-less [`WitTarget::Capability`]
13377 // arm, all three return `None`. Guards the drift surface where
13378 // a future extension of one per-arm accessor's accept-set (e.g.
13379 // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
13380 // that widened `http_endpoint` to cover both peers without
13381 // narrowing the peer `pubsub_subject` / `store_slot` accept-
13382 // sets to keep the partition mutually exclusive) landed without
13383 // threading through the peer per-arm accessors — the resulting
13384 // silent overlap would land the same edge's payload on two
13385 // downstream per-shape emit branches at once, or leak a
13386 // pub-sub subject through the store-slot channel, at renderer
13387 // emit time far from the substrate primitive's arm-widening
13388 // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
13389 // 3-way pin on the payload-field-name axis — extended onto the
13390 // per-arm-accessor payload-projection axis so the substrate-
13391 // owned partition invariant is load-bearing at every per-arm
13392 // consumer's read site.
13393 let payload_variants = [
13394 (
13395 WitTarget::Http {
13396 endpoint: "/charge",
13397 },
13398 "http",
13399 ),
13400 (
13401 WitTarget::PubSub {
13402 subject: "events.checkout.paid",
13403 },
13404 "pubsub",
13405 ),
13406 (
13407 WitTarget::Store {
13408 slot: "checkout/$order",
13409 },
13410 "store",
13411 ),
13412 ];
13413 for (variant, own_arm_label) in payload_variants {
13414 let own_arm_hit = match own_arm_label {
13415 "http" => variant.is_http(),
13416 "pubsub" => variant.is_pubsub(),
13417 "store" => variant.is_store(),
13418 other => panic!("unknown own-arm label {other:?}"),
13419 };
13420 let per_arm_results = [
13421 ("http_endpoint", variant.http_endpoint()),
13422 ("pubsub_subject", variant.pubsub_subject()),
13423 ("store_slot", variant.store_slot()),
13424 ];
13425 let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
13426 assert_eq!(
13427 some_count, 1,
13428 "WitTarget::{variant:?} must land exactly one per-arm \
13429 post-projection accessor's Some result — the trio \
13430 (http_endpoint, pubsub_subject, store_slot) must \
13431 partition the payload arm-set; got {per_arm_results:?}",
13432 );
13433 assert!(
13434 own_arm_hit,
13435 "WitTarget::{variant:?} own-arm gen-platform predicate \
13436 must return true on its own arm — a partition failure \
13437 upstream of this pin",
13438 );
13439 assert!(
13440 variant.payload().is_some(),
13441 "WitTarget::{variant:?} pan-arm payload() must return \
13442 Some on every payload-carrying arm the trio partitions",
13443 );
13444 }
13445 // The payload-less Capability arm must return None on every
13446 // per-arm accessor — the partition's terminal-fallback shape.
13447 let cap = WitTarget::Capability;
13448 assert_eq!(cap.http_endpoint(), None);
13449 assert_eq!(cap.pubsub_subject(), None);
13450 assert_eq!(cap.store_slot(), None);
13451 assert_eq!(
13452 cap.payload(),
13453 None,
13454 "WitTarget::Capability pan-arm payload() must return None — \
13455 the trio's payload-less-arm coherence witness",
13456 );
13457 }
13458
13459 #[test]
13460 fn wit_target_field_names_are_pairwise_distinct() {
13461 // Distinctness pin: if any two of the three payload-field-name
13462 // scalars ever collapse (e.g. an accidental `endpoint` copy-
13463 // paste over the `subject` const), the [`WitContract::target`]
13464 // gate's diagnostic would point authors at the wrong field —
13465 // an "expected `:endpoint`" error on a pub-sub edge would
13466 // silently misroute the fix. Same cross-axis-distinctness
13467 // discipline as the peer M3 `:placement :estrategia` variant-
13468 // discriminator scalar-value pins (cc8f749) applied to the
13469 // payload-field-name axis.
13470 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
13471 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
13472 assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
13473 }
13474
13475 #[test]
13476 fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
13477 // Fail-before-pass-after pin: the graph-verb payload column's
13478 // per-arm `{field}={payload}` byte-string is derived through the
13479 // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
13480 // payload-carrying arms, not through a hand-rolled per-arm match
13481 // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
13482 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13483 // inline. A future variant addition — the M4-and-later per-edge
13484 // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
13485 // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
13486 // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
13487 // and both [`WitTarget::label`] (duplicate-`:contratos`
13488 // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
13489 // payload column) pick up the new arm from the same dispatch.
13490 // Prior to this lift the graph verb open-coded the 4-arm match
13491 // in caixa-feira, so a variant addition would have to be threaded
13492 // through both projections in lockstep or the graph verb would
13493 // silently drop the new arm to `(capability-only)`.
13494 for variant in [
13495 WitTarget::Http {
13496 endpoint: "/charge",
13497 },
13498 WitTarget::PubSub {
13499 subject: "events.checkout.paid",
13500 },
13501 WitTarget::Store {
13502 slot: "checkout/$order",
13503 },
13504 ] {
13505 let (field, payload) = variant
13506 .payload_pair()
13507 .expect("payload arm must expose (field, payload)");
13508 assert_eq!(
13509 variant.graph_label(),
13510 format!("{field}={payload}"),
13511 "WitTarget::{variant:?} graph_label must route the \
13512 `{{field}}={{payload}}` template through payload_pair — \
13513 a regression to a hand-rolled per-arm match at the graph \
13514 verb would silently disagree with a future variant \
13515 addition landed only at payload_pair"
13516 );
13517 }
13518 }
13519
13520 #[test]
13521 fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
13522 // Fail-before-pass-after pin on the payload-less arm: the graph
13523 // verb's `(capability-only)` byte-string routes through the
13524 // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
13525 // [`WitTarget::Capability`] arm, not through an inline
13526 // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
13527 // per-`:contratos` payload column. Peer of the sibling
13528 // [`wit_target_label_pins_per_variant_format`] Capability-arm
13529 // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
13530 // extended here onto the third payload-less-arm consumer axis
13531 // (graph verb, sibling to the duplicate-`:contratos` diagnostic
13532 // axis and the wrong-target diagnostic axis).
13533 assert_eq!(
13534 WitTarget::Capability.graph_label(),
13535 WitTarget::CAPABILITY_GRAPH_LABEL,
13536 );
13537 assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
13538 }
13539
13540 #[test]
13541 fn wit_target_capability_graph_label_distinct_from_capability_label() {
13542 // Cross-consumer-axis distinctness pin: the graph-verb
13543 // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
13544 // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
13545 // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
13546 // payload)`) surface the payload-less arm on two distinct
13547 // consumer axes; a collapse (an accidental rebrand that lands
13548 // one spelling on both consts, a copy-paste that unifies them
13549 // "for consistency") would silently merge the two byte-strings
13550 // and lose the vocabulary distinction the graph verb's
13551 // compact-column form and the diagnostic's descriptive-clause
13552 // form each carry on purpose. Peer of the sibling 4-way
13553 // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
13554 // pin on the `ContratoWrongTarget::expected` scalar-value axis —
13555 // extended here onto the cross-consumer-axis distinctness of the
13556 // two payload-less-arm consts.
13557 assert_ne!(
13558 WitTarget::CAPABILITY_GRAPH_LABEL,
13559 WitTarget::CAPABILITY_LABEL,
13560 "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
13561 and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
13562 diagnostic) must remain distinct — a collapse would silently \
13563 merge two consumer axes onto one spelling"
13564 );
13565 }
13566
13567 #[test]
13568 fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
13569 // 4-way distinctness pin extending the sibling
13570 // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
13571 // (which covers only the HTTP / PubSub / Store payload arms)
13572 // onto the fourth scalar the shared
13573 // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
13574 // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
13575 // (`"none"`), the payload-less Capability-arm rejection scalar.
13576 //
13577 // All four [`WitTarget::HTTP_FIELD_NAME`] /
13578 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13579 // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
13580 // dispatch surface [`WitContract::target`] writes onto the
13581 // `ContratoWrongTarget::expected` field — the same `&'static
13582 // str` axis authors read as "this WIT world's shape admits
13583 // (only|not) `:<field>`". Pairwise-distinctness is the invariant
13584 // downstream consumers rely on: an `expected: "endpoint"`
13585 // diagnostic on a Capability-shaped edge tells the author to
13586 // add a `:endpoint "…"` slot to a WIT world that admits none,
13587 // silently misrouting the fix. Until this pin landed the three
13588 // payload-arm consts were distinctness-guarded by the sibling
13589 // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
13590 // scalar (d4f54f2) sat unguarded — a rebrand collision (the
13591 // author-facing vocabulary shift from `"none"` to `"endpoint"`
13592 // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
13593 // into per-shape peers) would have silently landed one
13594 // Capability-arm rejection on a payload-arm's `expected:` byte-
13595 // string and desynchronized the diagnostic from the author's
13596 // typed shape.
13597 //
13598 // Same 4-way pairwise-distinctness pin discipline as the peer
13599 // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
13600 // (cc8f749) applies on the sibling M3 closed-set typed-enum
13601 // scalar-value dispatch axis; extends the pin trajectory the
13602 // sibling `wit_target_field_names_are_pairwise_distinct`
13603 // 3-way pin opened to cover the last unguarded corner on the
13604 // `ContratoWrongTarget::expected` scalar-value axis.
13605 //
13606 // Fail-before-pass-after locally verified by mutating
13607 // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
13608 // — this pin fires as expected; restoring passes.
13609 let all = [
13610 WitTarget::HTTP_FIELD_NAME,
13611 WitTarget::PUBSUB_FIELD_NAME,
13612 WitTarget::STORE_FIELD_NAME,
13613 WitTarget::CAPABILITY_EXPECTED,
13614 ];
13615 for (i, a) in all.iter().enumerate() {
13616 for (j, b) in all.iter().enumerate() {
13617 if i != j {
13618 assert_ne!(
13619 a, b,
13620 "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
13621 STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
13622 pairwise distinct — got duplicate {a:?} at indices \
13623 {i} and {j}; all four scalars thread through the \
13624 shared `AplicacaoError::ContratoWrongTarget::expected` \
13625 &'static str axis, so a collapse silently misdirects \
13626 the diagnostic on which typed shape the WIT world admits",
13627 );
13628 }
13629 }
13630 }
13631 }
13632
13633 #[test]
13634 fn wit_target_is_variant_predicates_partition_the_arm_set() {
13635 // Fail-before-pass-after pin on the
13636 // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
13637 // each of the four variants exactly one of the generated
13638 // `is_http` / `is_pubsub` / `is_store` / `is_capability`
13639 // predicates returns `true` and the other three return
13640 // `false`. Prior to this derive the only production
13641 // arm-discriminator on [`WitTarget`] — the sync-cycle
13642 // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
13643 // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
13644 // the variant that expressed no compile-time link back to
13645 // the closed-set typed dispatch a future fifth
13646 // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
13647 // split of [`WitTarget::PubSub`] into shape-specific peers,
13648 // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
13649 // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
13650 // to thread through in lockstep or the DFS exclusion would
13651 // silently disagree with the peer diagnostic templates on
13652 // which arms carry sync-versus-async semantics. Peer of the
13653 // sibling [`crate::CaixaKind`] (f5bba80),
13654 // [`PlacementStrategy`] (766ec63),
13655 // [`crate::supervisor::RestartStrategy`],
13656 // [`crate::supervisor::RestartPolicy`], and
13657 // [`crate::upgrade::UpgradeInstruction`] (915a934)
13658 // `IsVariant` derives on the sibling closed-set typed-enum
13659 // discriminator axes — extends the same one-typed-dispatch-
13660 // per-variant discipline onto the last unlifted closed-set
13661 // typed-enum discriminator on the caixa surface (the M3
13662 // mesh-slot per-`:contratos` target-arm axis), closing the
13663 // arm-discriminator convergence trajectory across every
13664 // closed-set typed enum in caixa-core.
13665 let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
13666 (
13667 WitTarget::Http { endpoint: "/x" },
13668 [true, false, false, false],
13669 ),
13670 (
13671 WitTarget::PubSub {
13672 subject: "events.x",
13673 },
13674 [false, true, false, false],
13675 ),
13676 (
13677 WitTarget::Store { slot: "kv/x" },
13678 [false, false, true, false],
13679 ),
13680 (WitTarget::Capability, [false, false, false, true]),
13681 ];
13682 for (variant, expected) in rows {
13683 let observed = [
13684 variant.is_http(),
13685 variant.is_pubsub(),
13686 variant.is_store(),
13687 variant.is_capability(),
13688 ];
13689 assert_eq!(
13690 observed, expected,
13691 "WitTarget::{variant:?} is_* predicates must partition \
13692 the arm set (http, pubsub, store, capability); got {observed:?}"
13693 );
13694 }
13695 }
13696
13697 #[test]
13698 fn wit_target_is_variant_predicates_are_const_fn() {
13699 // The [`gen_platform::IsVariant`] derive emits `const fn`
13700 // predicates on the peer [`crate::CaixaKind`] +
13701 // [`crate::upgrade::UpgradeInstruction`] +
13702 // [`crate::supervisor::RestartStrategy`] +
13703 // [`crate::supervisor::RestartPolicy`] +
13704 // [`PlacementStrategy`] closed-set typed enums — pin the
13705 // same posture on [`WitTarget`] so a future accidental
13706 // downgrade to non-`const` (an added runtime helper reachable
13707 // only from a non-`const` context, a manual hand-rolled
13708 // `impl` that shadows the derive-generated method) trips at
13709 // caixa-core build time rather than surfacing as a downstream
13710 // `const`-context regression far from the derive declaration.
13711 //
13712 // Unlike the peer unit-variant enums (`CaixaKind` /
13713 // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
13714 // whose `const` constructors need no arguments, the three
13715 // payload-carrying [`WitTarget`] arms are const-constructed
13716 // through `&'static str` payloads — the same `'static`
13717 // lifetime the closed-set typed enum's four-arm partition
13718 // pin above already threads through.
13719 const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
13720 const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
13721 const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
13722 const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
13723 const IS_HTTP: bool = HTTP.is_http();
13724 const IS_PUBSUB: bool = PUBSUB.is_pubsub();
13725 const IS_STORE: bool = STORE.is_store();
13726 const IS_CAPABILITY: bool = CAPABILITY.is_capability();
13727 assert!(IS_HTTP);
13728 assert!(IS_PUBSUB);
13729 assert!(IS_STORE);
13730 assert!(IS_CAPABILITY);
13731 }
13732
13733 #[test]
13734 fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
13735 // Consumer-side pin on the sole production converge site:
13736 // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
13737 // edges from the synchronous-subgraph DFS via the lifted
13738 // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
13739 // predicate (rebound from the prior raw
13740 // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
13741 // variant). Byte-equivalent today (`is_pubsub` is the
13742 // derive-generated `matches!(self, Self::PubSub { .. })` by
13743 // construction, the `#[is_variant(name = "pubsub")]` override
13744 // aliasing the auto-derived `is_pub_sub` back to the sibling
13745 // [`WitContract::is_pubsub`] name); pin the behavior so a
13746 // future accidental drift (a rebind onto a peer arm
13747 // predicate, a manual hand-rolled `impl` that shadows the
13748 // derive-generated method with different semantics, a peer
13749 // arm rename that shifts which variant carries sync-versus-
13750 // async semantics) trips at caixa-core test time rather than
13751 // at some downstream operator's runtime dispatch far from the
13752 // rebind commit.
13753 //
13754 // The fixture constructs a two-Servico Aplicacao with one
13755 // pub-sub edge that would close a sync-cycle if the DFS did
13756 // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
13757 // pub-sub exclusion means the DFS sees only the `b → a` HTTP
13758 // edge, which is not a cycle. A regression in the converge
13759 // (a rebind that reads the pub-sub arm as sync) would report
13760 // `AplicacaoError::ContratoCycle`.
13761 let s = AplicacaoSpec {
13762 membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
13763 contratos: vec![
13764 // Pub-sub edge: DFS must skip via is_pubsub().
13765 WitContract {
13766 de: "a".into(),
13767 para: "b".into(),
13768 wit: "nats:pub-sub".into(),
13769 endpoint: None,
13770 subject: Some("events.x".into()),
13771 slot: None,
13772 },
13773 // HTTP edge: DFS must include.
13774 WitContract {
13775 de: "b".into(),
13776 para: "a".into(),
13777 wit: "wasi:http/proxy".into(),
13778 endpoint: Some("/x".into()),
13779 subject: None,
13780 slot: None,
13781 },
13782 ],
13783 politicas: MeshPolicy::default(),
13784 placement: Placement {
13785 estrategia: PlacementStrategy::Replicated,
13786 clusters: vec!["rio".into()],
13787 affinity: None,
13788 shard_key: None,
13789 },
13790 entrada: None,
13791 };
13792 s.validate()
13793 .expect("pub-sub edge must be excluded from sync-cycle DFS");
13794 }
13795
13796 #[test]
13797 fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
13798 // Consumer-side pin: the same three peer consts thread through
13799 // both the [`WitTarget::label`] template (leading-`:` keyword
13800 // prefix in the duplicate-`:contratos` diagnostic) and the
13801 // [`WitContract::target`] gate's [`AplicacaoError::
13802 // ContratoMissingTarget`] `expected:` scalar (the field the
13803 // author needs to add). Pin both routes at once so a future
13804 // refactor can't accidentally split them onto separate string
13805 // literals — the "one place, everywhere reaches for it"
13806 // invariant the peer const set carries.
13807 let http_label = WitTarget::Http { endpoint: "/x" }.label();
13808 assert!(
13809 http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
13810 "label must lead with :{} keyword (got {http_label:?})",
13811 WitTarget::HTTP_FIELD_NAME,
13812 );
13813
13814 let mut s = three_member_spec();
13815 s.contratos.push(WitContract {
13816 de: "cart".into(),
13817 para: "catalog".into(),
13818 wit: "kafka:topic".into(),
13819 endpoint: None,
13820 subject: None,
13821 slot: None,
13822 });
13823 match s.validate().unwrap_err() {
13824 AplicacaoError::ContratoMissingTarget { expected, .. } => {
13825 assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
13826 }
13827 other => panic!("expected ContratoMissingTarget, got {other:?}"),
13828 }
13829 }
13830
13831 #[test]
13832 fn duplicate_pubsub_diagnostic_names_offending_subject() {
13833 // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
13834 // on the pub-sub target axis: the duplicate-edge diagnostic
13835 // must name the `:subject` payload verbatim (not just the
13836 // `(de, para, wit)` triple). Prior to lifting the label onto
13837 // [`WitTarget::label`] the diagnostic derived the label from
13838 // raw [`WitContract`] `Option<String>` probes — a future
13839 // `WitTarget` variant addition (M4 per-edge WIT registry)
13840 // would silently fall through to the `Capability` "no
13841 // payload" default without a compiler warning. Pinning the
13842 // pub-sub arm's format closes the second of three
13843 // payload-carrying `WitTarget` arms this diagnostic threads
13844 // through.
13845 let mut s = three_member_spec();
13846 let pubsub = WitContract {
13847 de: "payment".into(),
13848 para: "cart".into(),
13849 wit: "nats:pub-sub".into(),
13850 endpoint: None,
13851 subject: Some("events.checkout.paid".into()),
13852 slot: None,
13853 };
13854 s.contratos.push(pubsub.clone());
13855 s.contratos.push(pubsub);
13856 let err = s.validate().unwrap_err();
13857 let msg = format!("{err}");
13858 assert!(
13859 msg.contains(":subject \"events.checkout.paid\""),
13860 "duplicate-pubsub diagnostic must name the offending \
13861 :subject payload (got: {msg:?})"
13862 );
13863 }
13864
13865 #[test]
13866 fn duplicate_store_diagnostic_names_offending_slot() {
13867 // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
13868 // key-value target axis: the diagnostic must name the `:slot`
13869 // payload verbatim. Third of three payload-carrying
13870 // `WitTarget` arms this diagnostic threads through, closing
13871 // the per-arm label pin trilogy (`Http` — 6841,
13872 // `PubSub` + `Store` — this test + peer above).
13873 let mut s = three_member_spec();
13874 let store = WitContract {
13875 de: "cart".into(),
13876 para: "payment".into(),
13877 wit: "wasi:keyvalue/store".into(),
13878 endpoint: None,
13879 subject: None,
13880 slot: Some("checkout/$orderId".into()),
13881 };
13882 s.contratos
13883 .retain(|c| !(c.de == "cart" && c.para == "payment"));
13884 s.contratos.push(store.clone());
13885 s.contratos.push(store);
13886 let err = s.validate().unwrap_err();
13887 let msg = format!("{err}");
13888 assert!(
13889 msg.contains(":slot \"checkout/$orderId\""),
13890 "duplicate-store diagnostic must name the offending :slot \
13891 payload (got: {msg:?})"
13892 );
13893 }
13894
13895 #[test]
13896 fn rejects_entrada_path_without_leading_slash() {
13897 let mut s = three_member_spec();
13898 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
13899 let err = s.validate().unwrap_err();
13900 assert!(
13901 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
13902 "got {err:?}"
13903 );
13904 }
13905
13906 #[test]
13907 fn rejects_empty_entrada_path() {
13908 let mut s = three_member_spec();
13909 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
13910 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
13911 }
13912
13913 #[test]
13914 fn rejects_duplicate_entrada_paths() {
13915 let mut s = three_member_spec();
13916 s.entrada.as_mut().unwrap().paths = vec![
13917 "/api/cart".into(),
13918 "/api/products".into(),
13919 "/api/cart".into(),
13920 ];
13921 let err = s.validate().unwrap_err();
13922 assert!(
13923 matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
13924 "got {err:?}"
13925 );
13926 }
13927
13928 #[test]
13929 fn rejects_zero_entrada_port() {
13930 let mut s = three_member_spec();
13931 s.entrada.as_mut().unwrap().port = 0;
13932 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
13933 }
13934
13935 // ── :entrada :paths value-shape gate ─────────────────────────────
13936 //
13937 // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
13938 // sibling `:paths` axis. Every authoring footgun the K8s Gateway
13939 // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
13940 // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
13941 // time now becomes a caixa-build-time `EntradaPathInvalid` with
13942 // the offending `:paths` entry named verbatim.
13943
13944 #[test]
13945 fn rejects_entrada_path_with_query() {
13946 // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
13947 // silently passed validate and the Gateway API webhook
13948 // rejected it at apply time with no source citation.
13949 let mut s = three_member_spec();
13950 s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
13951 let err = s.validate().unwrap_err();
13952 assert!(
13953 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13954 if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
13955 "got {err:?}"
13956 );
13957 }
13958
13959 #[test]
13960 fn rejects_entrada_path_with_fragment() {
13961 let mut s = three_member_spec();
13962 s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
13963 let err = s.validate().unwrap_err();
13964 assert!(
13965 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13966 if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
13967 "got {err:?}"
13968 );
13969 }
13970
13971 #[test]
13972 fn rejects_entrada_path_with_space() {
13973 let mut s = three_member_spec();
13974 s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
13975 let err = s.validate().unwrap_err();
13976 assert!(
13977 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13978 if path == "/api/my cart" && reason.contains("whitespace")),
13979 "got {err:?}"
13980 );
13981 }
13982
13983 #[test]
13984 fn rejects_entrada_path_with_tab() {
13985 let mut s = three_member_spec();
13986 s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
13987 let err = s.validate().unwrap_err();
13988 assert!(
13989 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13990 if path == "/api/\tcart" && reason.contains("whitespace")),
13991 "got {err:?}"
13992 );
13993 }
13994
13995 #[test]
13996 fn rejects_entrada_path_with_control_char() {
13997 // 0x01 (SOH) — a non-whitespace control char surfaces the
13998 // distinct "control character" reason arm, separate from
13999 // the whitespace arm. Pinned so a future refactor that
14000 // collapses the two arms can't accidentally drop the more
14001 // self-locating diagnostic.
14002 let mut s = three_member_spec();
14003 s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
14004 let err = s.validate().unwrap_err();
14005 assert!(
14006 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14007 if path == "/api/\x01cart" && reason.contains("control character")),
14008 "got {err:?}"
14009 );
14010 }
14011
14012 #[test]
14013 fn rejects_entrada_path_with_non_ascii() {
14014 // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
14015 // unreserved-set rule rejects. The Gateway API webhook
14016 // rejects literal non-ASCII bytes; percent-encoding is the
14017 // only way to author non-ASCII in a path.
14018 let mut s = three_member_spec();
14019 s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
14020 let err = s.validate().unwrap_err();
14021 assert!(
14022 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14023 if path == "/api/café" && reason.contains("non-ASCII")),
14024 "got {err:?}"
14025 );
14026 }
14027
14028 #[test]
14029 fn rejects_entrada_path_with_consecutive_slashes() {
14030 let mut s = three_member_spec();
14031 s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
14032 let err = s.validate().unwrap_err();
14033 assert!(
14034 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14035 if path == "/api//cart" && reason.contains("consecutive `/`")),
14036 "got {err:?}"
14037 );
14038 }
14039
14040 #[test]
14041 fn rejects_entrada_path_with_dot_segment() {
14042 let mut s = three_member_spec();
14043 s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
14044 let err = s.validate().unwrap_err();
14045 assert!(
14046 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14047 if path == "/api/./cart" && reason.contains("`.` segment")),
14048 "got {err:?}"
14049 );
14050 }
14051
14052 #[test]
14053 fn rejects_entrada_path_with_trailing_dot_segment() {
14054 // The bare `/.` and the trailing `/foo/.` are both rejected
14055 // by the Gateway API webhook; pinned separately so a future
14056 // narrowing that catches only the inner form surfaces here.
14057 let mut s = three_member_spec();
14058 s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
14059 let err = s.validate().unwrap_err();
14060 assert!(
14061 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14062 if path == "/api/." && reason.contains("`.` segment")),
14063 "got {err:?}"
14064 );
14065 }
14066
14067 #[test]
14068 fn rejects_entrada_path_with_parent_segment() {
14069 let mut s = three_member_spec();
14070 s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
14071 let err = s.validate().unwrap_err();
14072 assert!(
14073 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14074 if path == "/api/../etc" && reason.contains("`..` parent-segment")),
14075 "got {err:?}"
14076 );
14077 }
14078
14079 #[test]
14080 fn rejects_entrada_path_with_trailing_parent_segment() {
14081 // Trailing `/..` — symmetric arm of the parent-segment rule,
14082 // pinned separately so a future relaxation that only checks
14083 // the inner form (`/../`) surfaces here.
14084 let mut s = three_member_spec();
14085 s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
14086 let err = s.validate().unwrap_err();
14087 assert!(
14088 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14089 if path == "/api/.." && reason.contains("`..` parent-segment")),
14090 "got {err:?}"
14091 );
14092 }
14093
14094 #[test]
14095 fn rejects_entrada_path_too_long() {
14096 // 1025-byte path — one over the Gateway API HTTPPathMatch.value
14097 // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
14098 // ASCII-alphanumeric body so only the length rule fires.
14099 let mut s = three_member_spec();
14100 let big = format!("/api/{}", "a".repeat(1020));
14101 assert_eq!(big.len(), 1025);
14102 s.entrada.as_mut().unwrap().paths = vec![big.clone()];
14103 let err = s.validate().unwrap_err();
14104 assert!(
14105 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14106 if path == &big && reason.contains("max length of 1024")),
14107 "got {err:?}"
14108 );
14109 }
14110
14111 #[test]
14112 fn entrada_path_max_length_validates() {
14113 // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
14114 // maxLength cap. Boundary pin: drift in the cap surfaces here
14115 // and at `rejects_entrada_path_too_long` simultaneously.
14116 let mut s = three_member_spec();
14117 let big = format!("/api/{}", "a".repeat(1019));
14118 assert_eq!(big.len(), 1024);
14119 s.entrada.as_mut().unwrap().paths = vec![big];
14120 s.validate().unwrap();
14121 }
14122
14123 #[test]
14124 fn entrada_accepts_canonical_paths() {
14125 // Positive-control sweep — every form the Gateway API
14126 // apiserver accepts must round-trip through validate. Covers
14127 // the root catch-all, plain paths, dot-prefixed segments
14128 // (hidden-file-style, distinct from `.` and `..` segments
14129 // which are rejected), digit-bearing segments, the canonical
14130 // route-template `:param` form (`:` is RFC 3986 reserved-set
14131 // valid in paths), trailing-slash form, percent-encoded
14132 // segments, and an interior `..` *substring* (`/foo..bar` is
14133 // not the `..` segment and is allowed).
14134 for path in [
14135 "/",
14136 "/api/cart",
14137 "/healthz",
14138 "/api/.config",
14139 "/v1/products",
14140 "/products/:id",
14141 "/api/cart/",
14142 "/api/caf%C3%A9",
14143 "/foo..bar",
14144 "/...",
14145 ] {
14146 let mut s = three_member_spec();
14147 s.entrada.as_mut().unwrap().paths = vec![path.into()];
14148 s.validate()
14149 .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
14150 }
14151 }
14152
14153 #[test]
14154 fn entrada_path_empty_takes_precedence_over_invalid() {
14155 // Ordering pin: `EntradaPathEmpty` is the more self-locating
14156 // diagnostic on `""` and must lead — `validate_entrada_path`
14157 // is only reached after the empty-check fires at the call
14158 // site. (The predicate itself defends against direct
14159 // invocation by returning the same error on `""`.)
14160 let mut s = three_member_spec();
14161 s.entrada.as_mut().unwrap().paths = vec!["".into()];
14162 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14163 }
14164
14165 #[test]
14166 fn entrada_path_not_absolute_takes_precedence_over_invalid() {
14167 // Ordering pin: a path without a leading `/` surfaces the
14168 // narrower `EntradaPathNotAbsolute` diagnostic first; the
14169 // value-shape gate is only consulted on paths that already
14170 // satisfy the absolute-prefix invariant.
14171 let mut s = three_member_spec();
14172 // `bad path` would fire the whitespace rule under the
14173 // value-shape gate, but missing-leading-`/` is the more
14174 // self-locating diagnostic.
14175 s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
14176 let err = s.validate().unwrap_err();
14177 assert!(
14178 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
14179 "got {err:?}"
14180 );
14181 }
14182
14183 #[test]
14184 fn entrada_path_invalid_fires_before_duplicate_check() {
14185 // Ordering pin: a malformed path on the *first* entry of a
14186 // would-be duplicate pair fires the value-shape gate before
14187 // the duplicate gate, mirroring the
14188 // `placement_cluster_invalid_fires_before_duplicate_check`
14189 // (6cbb900) pattern on the peer axis.
14190 let mut s = three_member_spec();
14191 s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
14192 let err = s.validate().unwrap_err();
14193 assert!(
14194 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
14195 "got {err:?}"
14196 );
14197 }
14198
14199 #[test]
14200 fn entrada_path_diagnostic_carries_offending_path() {
14201 // Diagnostic-shape pin — the offending path + a non-empty
14202 // reason flow through verbatim so the author can grep their
14203 // caixa.lisp for `:paths` and fix it in one edit. Same shape
14204 // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
14205 let mut s = three_member_spec();
14206 s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
14207 let err = s.validate().unwrap_err();
14208 match err {
14209 AplicacaoError::EntradaPathInvalid { path, reason } => {
14210 assert_eq!(path, "/api?q=1");
14211 assert!(!reason.is_empty(), "reason field must be non-empty");
14212 }
14213 other => panic!("expected EntradaPathInvalid, got {other:?}"),
14214 }
14215 }
14216
14217 #[test]
14218 fn rejects_entrada_path_with_curly_brace_template_form() {
14219 // Per-axis pin on the shared `is_gateway_api_http_path`
14220 // reserved-byte arm: the canonical "I wrote an OpenAPI
14221 // path-template `{id}` instead of the Gateway API `:id` form"
14222 // footgun the K8s apiserver would otherwise catch at admission
14223 // time on every `HTTPRoute.spec.rules[].matches[].path.value`
14224 // landing site, far from the caixa.lisp. Surfaces as
14225 // `EntradaPathInvalid` carrying the offending path verbatim
14226 // plus the canonical `%7B`/`%7D` percent-encoding remediation
14227 // — the substrate-side `gateway_api_http_path_rejects_every_
14228 // reserved_printable_ascii_byte` predicate-level sweep pins the
14229 // full eleven-byte set; this per-axis pin confirms the
14230 // diagnostic flows through to the `EntradaPathInvalid` variant.
14231 let mut s = three_member_spec();
14232 s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
14233 let err = s.validate().unwrap_err();
14234 assert!(
14235 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14236 if path == "/api/cart/{id}"
14237 && reason.contains("reserved character")
14238 && reason.contains("'{'")
14239 && reason.contains("%7B")),
14240 "got {err:?}"
14241 );
14242 }
14243
14244 #[test]
14245 fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
14246 // Per-axis peer of `rejects_entrada_path_with_curly_brace_
14247 // template_form` on the sibling `:contratos :endpoint` axis.
14248 // Same shared `is_gateway_api_http_path` reserved-byte arm
14249 // fires through `ContratoEndpointInvalid`, with the offending
14250 // endpoint + `:de` + `:para` + reason flowing through verbatim.
14251 // Pins that the lifted predicate's tightening lands on both
14252 // caller axes simultaneously — one source of truth for the
14253 // Gateway API HTTPPathMatch.value accepted set.
14254 let err = contrato_endpoint_err("/api/cart/{id}");
14255 assert!(
14256 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14257 if endpoint == "/api/cart/{id}"
14258 && reason.contains("reserved character")
14259 && reason.contains("'{'")
14260 && reason.contains("%7B")),
14261 "got {err:?}"
14262 );
14263 }
14264
14265 // ── :entrada :host value-shape gate ──────────────────────────────
14266 //
14267 // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
14268 // the sibling `:host` axis. Every authoring footgun the K8s
14269 // Gateway API v1 apiserver would catch at admission time becomes
14270 // a caixa-build-time `EntradaHostInvalid` with the offending
14271 // `:host` named verbatim. Same diagnostic shape as
14272 // `MembroVersaoInvalid` (9888b13).
14273
14274 #[test]
14275 fn rejects_entrada_host_with_scheme() {
14276 // Fail-before-pass-after pin — pre-gate codebases silently
14277 // accepted `https://…` and the apiserver rejected it at apply
14278 // time with no source citation.
14279 let mut s = three_member_spec();
14280 s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
14281 let err = s.validate().unwrap_err();
14282 assert!(
14283 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14284 if host == "https://checkout.quero.cloud"),
14285 "got {err:?}"
14286 );
14287 }
14288
14289 #[test]
14290 fn rejects_entrada_host_with_port() {
14291 // The `:8080` port suffix is the canonical "I forgot the port
14292 // belongs in `:entrada :port`" footgun. The top-level `:` arm
14293 // (introduced after the per-label loop-only impl silently
14294 // surfaced a deep "label \"cloud:8080\" contains invalid
14295 // character ':'" leak) names the canonical fix verbatim — the
14296 // `:entrada :port` slot.
14297 let mut s = three_member_spec();
14298 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
14299 let err = s.validate().unwrap_err();
14300 assert!(
14301 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14302 if host == "checkout.quero.cloud:8080"
14303 && reason.contains(":entrada :port")),
14304 "got {err:?}"
14305 );
14306 }
14307
14308 #[test]
14309 fn rejects_entrada_host_with_trailing_colon() {
14310 // Trailing `:` (e.g. an in-progress `:host "example.com:"`
14311 // edit) — the per-label loop would land it as a deep
14312 // "label \"com:\" must start and end with an alphanumeric"
14313 // / "contains invalid character ':'" leak. The top-level
14314 // `:` arm pre-empts with the canonical `:port` slot
14315 // diagnostic.
14316 let mut s = three_member_spec();
14317 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
14318 let err = s.validate().unwrap_err();
14319 assert!(
14320 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14321 if host == "checkout.quero.cloud:"
14322 && reason.contains(":entrada :port")),
14323 "got {err:?}"
14324 );
14325 }
14326
14327 #[test]
14328 fn rejects_entrada_host_unbracketed_ipv6_literal() {
14329 // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
14330 // literals across the board (peer with `rejects_entrada_host_
14331 // ipv4_literal` above for the four-label-all-digit IPv4 arm).
14332 // Before this top-level `:` arm landed the per-label loop
14333 // surfaced a single-label byte-class diagnostic that named the
14334 // `:` byte but not the IP-literal prohibition. The top-level
14335 // `:` arm names both the `:port` slot and the IP-literal
14336 // prohibition verbatim, so an author whose `:host "2001:..."`
14337 // value lands here gets a self-locating fix either way.
14338 let mut s = three_member_spec();
14339 s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
14340 let err = s.validate().unwrap_err();
14341 assert!(
14342 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14343 if host == "2001:db8::1"
14344 && reason.contains("IPv6")),
14345 "got {err:?}"
14346 );
14347 }
14348
14349 #[test]
14350 fn rejects_entrada_host_wildcard_with_port() {
14351 // Wildcard host with port suffix — the `*.` strip and the
14352 // per-label loop on `["foo", "quero", "cloud:8080"]` would
14353 // surface the deep byte-class leak. The top-level `:` arm sits
14354 // upstream of the `*.` strip, so it names the canonical `:port`
14355 // fix verbatim regardless of whether the host is wildcard-led.
14356 let mut s = three_member_spec();
14357 s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
14358 let err = s.validate().unwrap_err();
14359 assert!(
14360 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14361 if host == "*.quero.cloud:8080"
14362 && reason.contains(":entrada :port")),
14363 "got {err:?}"
14364 );
14365 }
14366
14367 #[test]
14368 fn rejects_entrada_host_with_path() {
14369 let mut s = three_member_spec();
14370 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
14371 let err = s.validate().unwrap_err();
14372 assert!(
14373 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14374 if host == "checkout.quero.cloud/api"),
14375 "got {err:?}"
14376 );
14377 }
14378
14379 #[test]
14380 fn rejects_entrada_host_with_uppercase() {
14381 // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
14382 // rejected, not silently lower-cased.
14383 let mut s = three_member_spec();
14384 s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
14385 let err = s.validate().unwrap_err();
14386 assert!(
14387 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14388 if reason.contains("uppercase")),
14389 "got {err:?}"
14390 );
14391 }
14392
14393 #[test]
14394 fn rejects_entrada_host_with_underscore() {
14395 // RFC 1123 allows `[a-z0-9-]` only; underscore is the
14396 // canonical "I'm thinking of HTTP cookies / SRV records" leak.
14397 let mut s = three_member_spec();
14398 s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
14399 let err = s.validate().unwrap_err();
14400 assert!(
14401 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14402 if reason.contains('_')),
14403 "got {err:?}"
14404 );
14405 }
14406
14407 #[test]
14408 fn rejects_entrada_host_ipv4_literal() {
14409 // Gateway API v1 explicitly forbids IP literals as Hostnames.
14410 let mut s = three_member_spec();
14411 s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
14412 let err = s.validate().unwrap_err();
14413 assert!(
14414 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14415 if reason.contains("IPv4")),
14416 "got {err:?}"
14417 );
14418 }
14419
14420 #[test]
14421 fn rejects_entrada_host_with_trailing_dot() {
14422 // The Gateway API regex anchors at end-of-string with no
14423 // trailing `.` allowance — the FQDN root-dot form is rejected.
14424 let mut s = three_member_spec();
14425 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
14426 let err = s.validate().unwrap_err();
14427 assert!(
14428 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14429 if host == "checkout.quero.cloud."),
14430 "got {err:?}"
14431 );
14432 }
14433
14434 #[test]
14435 fn rejects_entrada_host_with_leading_dot() {
14436 let mut s = three_member_spec();
14437 s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
14438 let err = s.validate().unwrap_err();
14439 assert!(
14440 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14441 if reason.contains("empty label")),
14442 "got {err:?}"
14443 );
14444 }
14445
14446 #[test]
14447 fn rejects_entrada_host_with_consecutive_dots() {
14448 let mut s = three_member_spec();
14449 s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
14450 let err = s.validate().unwrap_err();
14451 assert!(
14452 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14453 if reason.contains("empty label")),
14454 "got {err:?}"
14455 );
14456 }
14457
14458 #[test]
14459 fn rejects_entrada_host_with_leading_hyphen_label() {
14460 let mut s = three_member_spec();
14461 s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
14462 let err = s.validate().unwrap_err();
14463 assert!(
14464 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14465 if reason.contains("alphanumeric")),
14466 "got {err:?}"
14467 );
14468 }
14469
14470 #[test]
14471 fn rejects_entrada_host_with_trailing_hyphen_label() {
14472 let mut s = three_member_spec();
14473 s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
14474 let err = s.validate().unwrap_err();
14475 assert!(
14476 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14477 if reason.contains("alphanumeric")),
14478 "got {err:?}"
14479 );
14480 }
14481
14482 #[test]
14483 fn rejects_entrada_host_with_inner_wildcard() {
14484 // Gateway API allows `*` only as the first label (`*.foo`);
14485 // any inner or trailing `*` is rejected.
14486 let mut s = three_member_spec();
14487 s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
14488 let err = s.validate().unwrap_err();
14489 assert!(
14490 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14491 if reason.contains("wildcard")),
14492 "got {err:?}"
14493 );
14494 }
14495
14496 #[test]
14497 fn rejects_entrada_host_bare_wildcard() {
14498 // `*.` with no domain is meaningless; Gateway API rejects it.
14499 let mut s = three_member_spec();
14500 s.entrada.as_mut().unwrap().host = "*.".into();
14501 let err = s.validate().unwrap_err();
14502 assert!(
14503 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14504 if reason.contains("wildcard")),
14505 "got {err:?}"
14506 );
14507 }
14508
14509 #[test]
14510 fn rejects_entrada_host_with_whitespace() {
14511 let mut s = three_member_spec();
14512 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
14513 let err = s.validate().unwrap_err();
14514 assert!(
14515 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14516 if reason.contains("whitespace")),
14517 "got {err:?}"
14518 );
14519 }
14520
14521 #[test]
14522 fn rejects_entrada_host_space_names_offending_byte() {
14523 // Embedded space in the `:entrada :host` axis surfaces the
14524 // byte-naming diagnostic through the lifted
14525 // `find_ascii_whitespace_byte` predicate. Peer with the
14526 // sibling `parse_rejects_leading_whitespace` pins on
14527 // `supervisor::duration_codec` (a7ae622) — same "the
14528 // diagnostic carries the offending byte's `0x{b:02x}` shape"
14529 // discipline extended from the shared duration codec to the
14530 // Gateway API v1 Hostname axis.
14531 let mut s = three_member_spec();
14532 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
14533 let err = s.validate().unwrap_err();
14534 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14535 panic!("expected EntradaHostInvalid, got {err:?}");
14536 };
14537 assert!(
14538 reason.contains("ASCII whitespace byte"),
14539 "expected byte-naming diagnostic, got {reason:?}"
14540 );
14541 assert!(
14542 reason.contains("0x20"),
14543 "expected offending space byte 0x20, got {reason:?}"
14544 );
14545 }
14546
14547 #[test]
14548 fn rejects_entrada_host_tab_names_offending_byte() {
14549 // Embedded tab byte in the `:entrada :host` axis — the
14550 // canonical paste-from-YAML-block-scalar / paste-from-
14551 // indented-doc footgun. Pins that the lifted predicate covers
14552 // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
14553 // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
14554 // not just the leading-space case the pre-lift `.bytes().any`
14555 // arm's opaque "must not contain whitespace" reason already
14556 // covered. Peer with `parse_rejects_tab_byte` on
14557 // `supervisor::duration_codec` (a7ae622).
14558 let mut s = three_member_spec();
14559 s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
14560 let err = s.validate().unwrap_err();
14561 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14562 panic!("expected EntradaHostInvalid, got {err:?}");
14563 };
14564 assert!(
14565 reason.contains("ASCII whitespace byte"),
14566 "expected byte-naming diagnostic, got {reason:?}"
14567 );
14568 assert!(
14569 reason.contains("0x09"),
14570 "expected offending tab byte 0x09, got {reason:?}"
14571 );
14572 }
14573
14574 #[test]
14575 fn rejects_entrada_host_lf_names_offending_byte() {
14576 // Embedded LF byte in the `:entrada :host` axis — the
14577 // canonical paste-from-shell-heredoc / paste-from-multiline-
14578 // doc footgun the caixa-mesh YAML emitter would silently
14579 // reinterpret at the Gateway API v1 HTTPRoute admission
14580 // layer (an embedded LF byte in a YAML plain scalar either
14581 // truncates the value at the emitter or crashes the parser
14582 // on the k8s-apiserver side). Pins the third representative
14583 // of the full ASCII-whitespace set through the shared
14584 // predicate.
14585 let mut s = three_member_spec();
14586 s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
14587 let err = s.validate().unwrap_err();
14588 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14589 panic!("expected EntradaHostInvalid, got {err:?}");
14590 };
14591 assert!(
14592 reason.contains("ASCII whitespace byte"),
14593 "expected byte-naming diagnostic, got {reason:?}"
14594 );
14595 assert!(
14596 reason.contains("0x0a"),
14597 "expected offending LF byte 0x0a, got {reason:?}"
14598 );
14599 }
14600
14601 #[test]
14602 fn rejects_entrada_host_nbsp_names_offending_codepoint() {
14603 // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
14604 // axis — the canonical paste-from-typography /
14605 // paste-from-word-processor footgun. Before the non-ASCII
14606 // Unicode `White_Space` scan lifted through the shared
14607 // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
14608 // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
14609 // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
14610 // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
14611 // with the far-from-source `label "…" must start and end
14612 // with an alphanumeric` diagnostic — burying the
14613 // paste-from-typography origin under a label-shape leak.
14614 // Peer with the sibling non-ASCII-whitespace pins at
14615 // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
14616 // — 1b75b38), `limits::parse_duration`,
14617 // `limits::parse_millicores`, and the shared duration codec
14618 // — same "the diagnostic carries the offending Unicode
14619 // codepoint's `U+XXXX` shape" discipline extended from every
14620 // typed-magnitude codec to the Gateway API v1 Hostname axis.
14621 let mut s = three_member_spec();
14622 s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
14623 let err = s.validate().unwrap_err();
14624 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14625 panic!("expected EntradaHostInvalid, got {err:?}");
14626 };
14627 assert!(
14628 reason.contains("non-ASCII Unicode whitespace character"),
14629 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14630 );
14631 assert!(
14632 reason.contains("U+00A0"),
14633 "expected offending NBSP codepoint U+00A0, got {reason:?}"
14634 );
14635 }
14636
14637 #[test]
14638 fn rejects_entrada_host_line_separator_names_offending_codepoint() {
14639 // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
14640 // `:entrada :host` axis — the canonical paste-from-web-doc /
14641 // paste-from-published-HTML footgun. `char::is_whitespace`
14642 // returns true for `U+2028` per the Unicode `White_Space`
14643 // property, so `str::trim` at any downstream site would
14644 // silently strip it — same drift class as NBSP but on a
14645 // different codepoint region. Pins the second representative
14646 // (non-Latin-1 `char::is_whitespace` member) through the
14647 // shared predicate. Peer with
14648 // `parse_byte_size_rejects_internal_line_separator` on
14649 // `limits::parse_byte_size` (1b75b38).
14650 let mut s = three_member_spec();
14651 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
14652 let err = s.validate().unwrap_err();
14653 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14654 panic!("expected EntradaHostInvalid, got {err:?}");
14655 };
14656 assert!(
14657 reason.contains("non-ASCII Unicode whitespace character"),
14658 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14659 );
14660 assert!(
14661 reason.contains("U+2028"),
14662 "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
14663 );
14664 }
14665
14666 #[test]
14667 fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
14668 // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
14669 // labels in the `:entrada :host` axis — the canonical
14670 // paste-from-CJK-typography footgun (CJK IMEs default to
14671 // full-width whitespace when the space bar is pressed in
14672 // Japanese / Chinese input modes). Pins the third
14673 // representative of the non-ASCII Unicode `White_Space` set
14674 // through the shared predicate: the CJK block, distinct from
14675 // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
14676 // SEPARATOR `U+2028` — covering the same axis breadth the
14677 // sibling `parse_byte_size_rejects_trailing_ideographic_space`
14678 // (1b75b38) pins on `limits::parse_byte_size`.
14679 let mut s = three_member_spec();
14680 s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
14681 let err = s.validate().unwrap_err();
14682 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14683 panic!("expected EntradaHostInvalid, got {err:?}");
14684 };
14685 assert!(
14686 reason.contains("non-ASCII Unicode whitespace character"),
14687 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14688 );
14689 assert!(
14690 reason.contains("U+3000"),
14691 "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
14692 );
14693 }
14694
14695 #[test]
14696 fn rejects_entrada_host_too_long() {
14697 // Total length cap = 253; build a 254-byte host out of two
14698 // 63-byte labels + one 62-byte label + dots.
14699 let mut s = three_member_spec();
14700 let big = format!(
14701 "{}.{}.{}.{}",
14702 "a".repeat(63),
14703 "b".repeat(63),
14704 "c".repeat(63),
14705 "d".repeat(254 - 63 * 3 - 3)
14706 );
14707 assert_eq!(big.len(), 254);
14708 s.entrada.as_mut().unwrap().host = big;
14709 let err = s.validate().unwrap_err();
14710 assert!(
14711 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14712 if reason.contains("max length of 253")),
14713 "got {err:?}"
14714 );
14715 }
14716
14717 #[test]
14718 fn rejects_entrada_host_label_too_long() {
14719 let mut s = three_member_spec();
14720 // 64-byte label — one over the per-label cap.
14721 s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
14722 let err = s.validate().unwrap_err();
14723 assert!(
14724 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14725 if reason.contains("label max length of 63")),
14726 "got {err:?}"
14727 );
14728 }
14729
14730 #[test]
14731 fn entrada_host_diagnostic_carries_offending_host() {
14732 // Diagnostic-shape pin — the offending host + a non-empty
14733 // reason flow through verbatim so the author can grep their
14734 // caixa.lisp for `:host "<host>"` and fix it in one edit.
14735 let mut s = three_member_spec();
14736 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
14737 let err = s.validate().unwrap_err();
14738 match err {
14739 AplicacaoError::EntradaHostInvalid { host, reason } => {
14740 assert_eq!(host, "checkout.quero.cloud:8080");
14741 assert!(!reason.is_empty(), "reason field must be non-empty");
14742 }
14743 other => panic!("expected EntradaHostInvalid, got {other:?}"),
14744 }
14745 }
14746
14747 #[test]
14748 fn entrada_host_empty_takes_precedence_over_invalid() {
14749 // Ordering pin: `EmptyEntradaHost` is the more self-locating
14750 // diagnostic on `""` and must lead — `validate_entrada_host`
14751 // is only reached after the empty-check fires at the call
14752 // site. (The predicate itself defends against direct
14753 // invocation by returning the same error on `""`.)
14754 let mut s = three_member_spec();
14755 s.entrada.as_mut().unwrap().host = String::new();
14756 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
14757 }
14758
14759 #[test]
14760 fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
14761 // Ordering pin: a missing :para member is the more
14762 // self-locating diagnostic and fires before the host gate.
14763 let mut s = three_member_spec();
14764 let e = s.entrada.as_mut().unwrap();
14765 e.para = "ghost".into();
14766 e.host = "BAD HOST".into();
14767 let err = s.validate().unwrap_err();
14768 assert!(
14769 matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
14770 "got {err:?}"
14771 );
14772 }
14773
14774 #[test]
14775 fn entrada_host_invalid_fires_before_port_zero() {
14776 // Ordering pin: the host gate fires before the port gate so
14777 // a malformed host is named even when the port is also wrong.
14778 let mut s = three_member_spec();
14779 let e = s.entrada.as_mut().unwrap();
14780 e.host = "Checkout.quero.cloud".into();
14781 e.port = 0;
14782 let err = s.validate().unwrap_err();
14783 assert!(
14784 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14785 if host == "Checkout.quero.cloud"),
14786 "got {err:?}"
14787 );
14788 }
14789
14790 #[test]
14791 fn entrada_accepts_canonical_hosts() {
14792 // Positive-control sweep — every form the Gateway API
14793 // apiserver accepts must round-trip through validate. Covers
14794 // a plain DNS subdomain, a leading wildcard, a single-label
14795 // host (cluster-internal), a max-length-edge label, a
14796 // hyphen-bearing label, and a Punycode IDN label.
14797 for host in [
14798 "checkout.quero.cloud",
14799 "*.quero.cloud",
14800 "checkout",
14801 // 63-byte label — exactly the per-label cap.
14802 "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
14803 "foo-bar.quero.cloud",
14804 // Punycode IDN — valid because the author pre-encoded.
14805 "xn--bcher-kva.example.com",
14806 ] {
14807 let mut s = three_member_spec();
14808 s.entrada.as_mut().unwrap().host = host.into();
14809 s.validate()
14810 .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
14811 }
14812 }
14813
14814 #[test]
14815 fn entrada_host_max_length_validates() {
14816 // 253-byte host is the cap exactly — must validate. Build a
14817 // 253-byte host out of three 63-byte labels + one 61-byte
14818 // label + 3 dots = 252 bytes, then pad one byte to 253.
14819 let mut s = three_member_spec();
14820 let host = format!(
14821 "{}.{}.{}.{}",
14822 "a".repeat(63),
14823 "b".repeat(63),
14824 "c".repeat(63),
14825 "d".repeat(253 - 63 * 3 - 3)
14826 );
14827 assert_eq!(host.len(), 253);
14828 s.entrada.as_mut().unwrap().host = host;
14829 s.validate().unwrap();
14830 }
14831
14832 #[test]
14833 fn entrada_host_total_length_cap_threads_lifted_render_const() {
14834 // Cross-crate-side pin: the aplicacao-side `:entrada :host`
14835 // total-length gate now reads the K8s Gateway API v1 Hostname
14836 // `maxLength: 253` cap from the lifted
14837 // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
14838 // of truth — the same constant every future Gateway-API-Hostname
14839 // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
14840 // materializer's per-host validator, the future per-`Certificate`
14841 // SAN emitter for cert-manager, the multi-`:entrada`
14842 // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
14843 // from. Before the lift, the aplicacao-side reader consumed a
14844 // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
14845 // 253-byte value as the peer render-side canonical bounds
14846 // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
14847 // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
14848 // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
14849 // module boundary — a future 253-byte drift on either side would
14850 // silently split into two axes' worth of admission-schema mismatch
14851 // without a build-time signal. Pin the cap through a fresh 254-
14852 // byte host that hits the total-length arm, then read the reason
14853 // for the exact byte count the shared constant carries: any future
14854 // regression on the lift (a private alias reintroduced, a hard-
14855 // coded literal at the arm, a mismatch between the aplicacao-side
14856 // and render-side canonicals) surfaces as this pin's diagnostic
14857 // failing to match, not as a per-cluster admission rejection far
14858 // from the caixa.lisp source line.
14859 let mut s = three_member_spec();
14860 let over_cap = format!(
14861 "{}.{}.{}.{}",
14862 "a".repeat(63),
14863 "b".repeat(63),
14864 "c".repeat(63),
14865 "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
14866 );
14867 assert_eq!(
14868 over_cap.len(),
14869 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
14870 );
14871 s.entrada.as_mut().unwrap().host = over_cap;
14872 let err = s.validate().unwrap_err();
14873 match err {
14874 AplicacaoError::EntradaHostInvalid { reason, .. } => {
14875 let needle = format!(
14876 "max length of {} bytes",
14877 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
14878 );
14879 assert!(
14880 reason.contains(&needle),
14881 "diagnostic must name the lifted \
14882 GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
14883 );
14884 }
14885 other => panic!("expected EntradaHostInvalid, got {other:?}"),
14886 }
14887 }
14888
14889 #[test]
14890 fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
14891 // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
14892 // on the per-label-cap axis. Before the lift, the aplicacao-side
14893 // per-label arm consumed a private const alias
14894 // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
14895 // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
14896 // split from it at the module boundary — every `.`-separated
14897 // label in a Gateway API v1 Hostname is a DNS-1123 label under
14898 // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
14899 // so the private alias's 63 and the canonical const's 63 were
14900 // pinning the same underlying rule twice. Pin the cap through a
14901 // 64-byte label that hits the per-label arm, then read the reason
14902 // for the exact byte count the shared constant carries: any
14903 // future drift on either side (a private alias reintroduced, a
14904 // hard-coded literal at the arm, a mismatch between the two
14905 // 63-byte pins) surfaces at this pin's diagnostic rather than at
14906 // a per-cluster admission rejection whose "field is invalid"
14907 // opacity misframes the root cause.
14908 let mut s = three_member_spec();
14909 let over_cap_label = format!(
14910 "{}.quero.cloud",
14911 "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
14912 );
14913 s.entrada.as_mut().unwrap().host = over_cap_label;
14914 let err = s.validate().unwrap_err();
14915 match err {
14916 AplicacaoError::EntradaHostInvalid { reason, .. } => {
14917 let needle = format!(
14918 "label max length of {} bytes",
14919 crate::render::DNS_1123_LABEL_MAX_LEN,
14920 );
14921 assert!(
14922 reason.contains(&needle),
14923 "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
14924 cap verbatim on the per-label arm, got: {reason:?}",
14925 );
14926 }
14927 other => panic!("expected EntradaHostInvalid, got {other:?}"),
14928 }
14929 }
14930
14931 #[test]
14932 fn entrada_with_empty_paths_validates() {
14933 // Empty `:paths` is the documented "match every path" form;
14934 // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
14935 let mut s = three_member_spec();
14936 s.entrada.as_mut().unwrap().paths = vec![];
14937 s.validate().unwrap();
14938 }
14939
14940 #[test]
14941 fn entrada_root_path_validates() {
14942 // The author-supplied bare-root `:entrada :paths` entry is the
14943 // same byte-shape the peer emit-side catch-all constant
14944 // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
14945 // the author's `:paths` list is empty — sweeping the test-side
14946 // probe literal onto the lifted const closes the two-axis pin
14947 // (author-side admit + emit-side canonical fallback) around
14948 // one `&'static str`, so a future rebrand of the catch-all
14949 // reaches both consumers by construction. Peer to
14950 // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
14951 // on the canonical-literal pin surface.
14952 let mut s = three_member_spec();
14953 s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
14954 s.validate().unwrap();
14955 }
14956
14957 #[test]
14958 fn placement_strategy_variants_round_trip() {
14959 for s in [
14960 PlacementStrategy::SingleNode,
14961 PlacementStrategy::Replicated,
14962 PlacementStrategy::Sharded,
14963 ] {
14964 let p = Placement {
14965 estrategia: s,
14966 clusters: vec!["rio".into()],
14967 affinity: None,
14968 // Route the paired `:shard-key` fixture-builder through the
14969 // typed cross-slot invariant predicate
14970 // [`PlacementStrategy::requires_shard_key`] rather than the
14971 // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
14972 // arm-identity predicate — the two answer the same
14973 // question under today's closed accept-set but a future
14974 // arm addition that consumed `:shard-key` under a
14975 // non-`Sharded` name would silently mis-attach the
14976 // fixture's `:shard-key` if the builder read through the
14977 // arm-identity predicate. The cross-slot-invariant
14978 // predicate migrates through one caixa-core edit on any
14979 // future arm addition; the fixture keeps producing a
14980 // `validate()`-passing round-trip by construction.
14981 shard_key: if s.requires_shard_key() {
14982 Some("$key".into())
14983 } else {
14984 None
14985 },
14986 };
14987 let json = serde_json::to_string(&p).unwrap();
14988 let back: Placement = serde_json::from_str(&json).unwrap();
14989 assert_eq!(back, p);
14990 }
14991 }
14992
14993 #[test]
14994 fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
14995 // The fail-before-pass-after pin: pre-lift there was no
14996 // single-source binding between the [`PlacementStrategy`]
14997 // variant name the `Serialize` derive emits and the byte-
14998 // string every downstream cluster-side dispatcher (the
14999 // `lareira-fleet-programs` aggregator's per-entry strategy
15000 // branch, the future `app-operator` reconciler, the M3
15001 // Adaptive compression pass's per-strategy weighting) probes
15002 // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
15003 // future `#[serde(rename_all = "kebab-case")]` attribute on
15004 // the enum — or a variant rename in the source — would
15005 // silently rebrand the emitted scalar under one spelling
15006 // while every downstream dispatcher still probed the other,
15007 // with the failure surfacing at the aggregator's dispatch
15008 // step or the operator's reconcile posture (workloads coming
15009 // up under the `default()` `Replicated` arm rather than the
15010 // typed slot's declared strategy) far from the source
15011 // rebrand commit and with no field naming the drift. Pinning
15012 // the two paths (the `Serialize` derive's serialized string
15013 // AND the [`PlacementStrategy::as_str`] helper) to the same
15014 // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
15015 // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15016 // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
15017 // makes any future drift on either endpoint fail here at
15018 // caixa-core build time.
15019 for (variant, expected) in [
15020 (
15021 PlacementStrategy::SingleNode,
15022 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15023 ),
15024 (
15025 PlacementStrategy::Replicated,
15026 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15027 ),
15028 (
15029 PlacementStrategy::Sharded,
15030 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15031 ),
15032 ] {
15033 let json = serde_json::to_string(&variant).unwrap();
15034 assert_eq!(
15035 json,
15036 format!("\"{expected}\""),
15037 "PlacementStrategy::{variant:?} must serialize to {expected:?}"
15038 );
15039 assert_eq!(
15040 variant.as_str(),
15041 expected,
15042 "PlacementStrategy::{variant:?}.as_str() must return the lifted \
15043 M3_PLACEMENT_ESTRATEGIA_* constant"
15044 );
15045 }
15046 }
15047
15048 #[test]
15049 fn m3_placement_estrategia_consts_are_pairwise_distinct() {
15050 // Cross-arm drift-detection pin on the M3
15051 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
15052 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15053 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
15054 // scalar-value pentad: a future collapse of two canonical
15055 // variant byte-strings onto the same value (an accidental
15056 // copy-paste flip of
15057 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
15058 // read `"SingleNode"`, a per-arm rebrand that lands one const
15059 // without touching its paired peer) would silently reroute
15060 // every downstream operator's per-strategy dispatch onto the
15061 // sibling arm's reconcile branch and pass every
15062 // propagation-probe test that expected only the stale arm's
15063 // value — a `Replicated`-declared Aplicacao would come up
15064 // under the `SingleNode` primary-and-standby reconcile
15065 // posture, so every-cluster active-active workload would
15066 // silently collapse onto one-cluster-runs-at-a-time takeover
15067 // semantics against its declared strategy, with no field
15068 // naming the strategy-value drift root cause. Peer of the
15069 // sibling
15070 // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
15071 // (09ffb2d) /
15072 // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
15073 // (ccdf955) /
15074 // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
15075 // (d739850) distinctness pins on the sibling OTP-shape /
15076 // caixa-kind closed-set typed-enum discriminator axes — the
15077 // fourth (and structurally the M3 mesh-primitive-defining)
15078 // closed-set typed-enum axis to converge on the same
15079 // "pairwise-distinct-by-construction" discipline.
15080 //
15081 // Fail-before-pass-after locally verified by mutating
15082 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
15083 // also read `"SingleNode"` — this pin fires as expected;
15084 // restoring passes.
15085 let all = [
15086 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15087 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15088 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15089 ];
15090 for (i, a) in all.iter().enumerate() {
15091 for (j, b) in all.iter().enumerate() {
15092 if i != j {
15093 assert_ne!(
15094 a, b,
15095 "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
15096 distinct — got duplicate {a:?} at indices {i} and {j}",
15097 );
15098 }
15099 }
15100 }
15101 }
15102
15103 #[test]
15104 fn placement_strategy_display_routes_through_as_str_helper() {
15105 // The fail-before-pass-after pin: pre-lift the sibling
15106 // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
15107 // / [`crate::supervisor::RestartPolicy`] both carried a stable
15108 // [`std::fmt::Display`] surface via their
15109 // `#[discriminant(also_display)]` gen-platform derive, but
15110 // [`PlacementStrategy`] did not — every consumer reaching for
15111 // a strategy byte-string past the wire format had to pick
15112 // between three paths ([`PlacementStrategy::as_str`], the
15113 // `Serialize` derive's serialized string, or `format!("{v:?}")`
15114 // on the `Debug` derive), any two of which a future variant
15115 // rename or `#[serde(rename_all = "kebab-case")]` attribute
15116 // would silently desynchronize. Wiring [`std::fmt::Display`]
15117 // through [`PlacementStrategy::as_str`] closes the third path:
15118 // every `format!("{v}")` call reaches the same lifted
15119 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
15120 // and the [`PlacementStrategy::as_str`] helper already route
15121 // through, so a future variant rename lands at exactly one
15122 // place. Pin the routing here so a future
15123 // `impl std::fmt::Display for PlacementStrategy` reimplementation
15124 // that hand-rolls the arms instead of delegating to
15125 // [`PlacementStrategy::as_str`] fails at caixa-core build time.
15126 for variant in [
15127 PlacementStrategy::SingleNode,
15128 PlacementStrategy::Replicated,
15129 PlacementStrategy::Sharded,
15130 ] {
15131 assert_eq!(
15132 variant.to_string(),
15133 variant.as_str(),
15134 "PlacementStrategy::{variant:?} Display must route through \
15135 PlacementStrategy::as_str (single source of truth: the lifted \
15136 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
15137 );
15138 }
15139 }
15140
15141 #[test]
15142 fn placement_strategy_display_matches_serialized_wire_byte_string() {
15143 // The fail-before-pass-after pin on the second half of the
15144 // three-path convergence: `Display` (user-facing text) agrees
15145 // byte-for-byte with the `Serialize` derive's wire format
15146 // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
15147 // scalar) on every variant. Pre-lift the two paths were
15148 // structurally independent — a future
15149 // `#[serde(rename_all = "kebab-case")]` attribute on the enum
15150 // would silently rebrand the emitted wire scalar
15151 // (`single-node`, `replicated`, `sharded`) while every consumer
15152 // that pretty-prints the strategy (the M3 diagnostic templates,
15153 // the future `feira app graph` per-Aplicacao strategy line,
15154 // the future M4 CR materializer's admission-webhook rejection
15155 // body) would still emit the TitleCase form the `as_str` /
15156 // `Display` route returns, with the mismatch surfacing at
15157 // consumer parse time / operator dispatch time far from the
15158 // source rebrand commit. Pin the two paths byte-for-byte here
15159 // so any future serde-attribute or variant-rename drift is a
15160 // caixa-core-build-time test failure at this call, not a
15161 // silent per-consumer dispatch miss.
15162 for variant in [
15163 PlacementStrategy::SingleNode,
15164 PlacementStrategy::Replicated,
15165 PlacementStrategy::Sharded,
15166 ] {
15167 let wire = serde_json::to_string(&variant).unwrap();
15168 // Strip the outer `"…"` the JSON string form carries — the
15169 // wire scalar the K8s / YAML apiserver consumes is the
15170 // enclosed byte-string, not the quote wrapper.
15171 let unquoted = wire
15172 .strip_prefix('"')
15173 .and_then(|s| s.strip_suffix('"'))
15174 .expect("serialized PlacementStrategy is a JSON string");
15175 assert_eq!(
15176 variant.to_string(),
15177 unquoted,
15178 "PlacementStrategy::{variant:?} Display byte-string must match the \
15179 Serialize derive's wire byte-string (three-path convergence: \
15180 Display + as_str + Serialize all resolve to the same \
15181 M3_PLACEMENT_ESTRATEGIA_* const)"
15182 );
15183 }
15184 }
15185
15186 #[test]
15187 fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
15188 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
15189 // derive on [`PlacementStrategy`]: for each of the three variants
15190 // exactly one of the generated `is_single_node` / `is_replicated`
15191 // / `is_sharded` predicates returns `true` and the other two
15192 // return `false`. Prior to this derive the three per-arm
15193 // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
15194 // (the `placement_strategy_variants_round_trip` fixture, the
15195 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
15196 // fixture, and the
15197 // `validate_placement_reads_through_lifted_estrategia_accessor`
15198 // fixture) each open-coded a per-arm PartialEq compare against
15199 // the enum variant — three sites that expressed no compile-time
15200 // link back to the closed-set typed dispatch a future fourth
15201 // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
15202 // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
15203 // would have to thread through in lockstep or one fixture would
15204 // silently disagree with the others on which arms consume the
15205 // `:shard-key` axis. Peer of the sibling
15206 // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
15207 // / [`crate::supervisor::RestartPolicy`] /
15208 // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
15209 // the sibling closed-set typed-enum discriminator axes — extends
15210 // the same one-typed-dispatch-per-variant discipline onto the
15211 // fifth (and only remaining) closed-set typed-enum discriminator
15212 // on the caixa surface, closing the axis on the M3 mesh-slot
15213 // family.
15214 let rows: [(PlacementStrategy, [bool; 3]); 3] = [
15215 (PlacementStrategy::SingleNode, [true, false, false]),
15216 (PlacementStrategy::Replicated, [false, true, false]),
15217 (PlacementStrategy::Sharded, [false, false, true]),
15218 ];
15219 for (variant, expected) in rows {
15220 let observed = [
15221 variant.is_single_node(),
15222 variant.is_replicated(),
15223 variant.is_sharded(),
15224 ];
15225 assert_eq!(
15226 observed, expected,
15227 "PlacementStrategy::{variant:?} is_* predicates must partition \
15228 the arm set (single_node, replicated, sharded); got {observed:?}"
15229 );
15230 }
15231 }
15232
15233 #[test]
15234 fn placement_strategy_is_variant_predicates_are_const_fn() {
15235 // The [`gen_platform::IsVariant`] derive emits `const fn`
15236 // predicates on the peer [`crate::CaixaKind`] +
15237 // [`crate::upgrade::UpgradeInstruction`] +
15238 // [`crate::supervisor::RestartStrategy`] +
15239 // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
15240 // pin the same posture on [`PlacementStrategy`] so a future
15241 // accidental downgrade to non-`const` (an added runtime helper
15242 // reachable only from a non-`const` context, a manual hand-rolled
15243 // `impl` that shadows the derive-generated method) trips at
15244 // caixa-core build time rather than surfacing as a downstream
15245 // `const`-context regression far from the derive declaration.
15246 const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
15247 const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
15248 const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
15249 assert!(IS_SINGLE_NODE);
15250 assert!(IS_REPLICATED);
15251 assert!(IS_SHARDED);
15252 }
15253
15254 #[test]
15255 fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
15256 // Fail-before-pass-after pin on the substrate-lifted
15257 // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
15258 // per-arm predicate: for each variant in the closed accept-set the
15259 // predicate returns `true` iff the variant consumes the paired
15260 // [`Placement::shard_key`] axis under
15261 // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
15262 // partition. Today the accept-set is the singleton `{Sharded}` —
15263 // `Sharded` is the Akka-style hash-keyed distribution arm
15264 // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
15265 // §II.1) and `Replicated` (active-active) refuse the axis through
15266 // [`AplicacaoError::ShardKeyOnNonSharded`].
15267 //
15268 // Pins the per-arm truth-table so a future arm addition (an
15269 // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
15270 // roadmap names, a `WeightedShard` promotion the future M5
15271 // adaptive-placement engine acknowledges) that landed a variant
15272 // without extending this predicate's arm-set would surface as a
15273 // caixa-core build-time exhaustiveness error at the
15274 // `match self { … }` arm-fan below rather than a silent per-consumer
15275 // mis-classification at renderer emit time. The paired
15276 // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
15277 // predicate stays a distinct question — arm-identity (which the
15278 // sibling
15279 // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
15280 // pin already locks) is not cross-slot-invariant consumption; today
15281 // they trip on the same singleton but the pair migrates through
15282 // one caixa-core edit on any future arm addition.
15283 //
15284 // Peer of the sibling per-arm classifier pins
15285 // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
15286 // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
15287 // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
15288 // derived paired predicate on the post-projection typed-view axis
15289 // — same "per-arm semantic-classification predicate paired with
15290 // the arm-identity predicate the derive already emits" discipline
15291 // extended onto the M3 mesh-slot `:placement :estrategia` ↔
15292 // `:placement :shard-key` cross-slot-invariant axis.
15293 let rows: [(PlacementStrategy, bool); 3] = [
15294 (PlacementStrategy::SingleNode, false),
15295 (PlacementStrategy::Replicated, false),
15296 (PlacementStrategy::Sharded, true),
15297 ];
15298 for (variant, expected) in rows {
15299 assert_eq!(
15300 variant.requires_shard_key(),
15301 expected,
15302 "PlacementStrategy::{variant:?}.requires_shard_key() must \
15303 be {expected} (the substrate-canonical cross-slot invariant \
15304 on the :placement :shard-key axis; today `Sharded` is the \
15305 singleton consuming arm — MESH-COMPOSITION §II.4)",
15306 );
15307 }
15308 }
15309
15310 #[test]
15311 fn placement_strategy_requires_shard_key_is_const_fn() {
15312 // The [`PlacementStrategy::requires_shard_key`] cross-slot-
15313 // invariant per-arm predicate is declared `#[must_use] pub const
15314 // fn` — pin the `const`-eval posture here so a future accidental
15315 // downgrade to non-`const` (an added runtime helper reachable
15316 // only from a non-`const` context, a manual hand-rolled `impl`
15317 // that shadows the current three-arm `match self { … }` dispatch)
15318 // trips at caixa-core build time rather than surfacing as a
15319 // downstream `const`-context regression far from the declaration.
15320 // Same shape as the sibling
15321 // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
15322 // the peer [`gen_platform::IsVariant`]-derived arm-identity
15323 // predicate axis, but here the load-bearing assertions live in
15324 // module-scope `const _: () = assert!(…)` items so a violation
15325 // fails at compile time (const-eval trip) rather than test time —
15326 // strictly stronger than the runtime `assert!(CONST)` pattern the
15327 // sibling pin uses, and side-steps the
15328 // `clippy::assertions_on_constants` lint the runtime pattern
15329 // otherwise accumulates on the module baseline.
15330 //
15331 // The test body simply witnesses that the module-scope items
15332 // compiled and the runtime dispatch agrees with the const-eval
15333 // dispatch on every arm — the runtime read gives the test a
15334 // failure surface (rather than an empty test body clippy would
15335 // flag as a no-op).
15336 const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
15337 const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
15338 const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
15339 assert_eq!(
15340 [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
15341 [
15342 PlacementStrategy::SingleNode.requires_shard_key(),
15343 PlacementStrategy::Replicated.requires_shard_key(),
15344 PlacementStrategy::Sharded.requires_shard_key(),
15345 ],
15346 "runtime and const-eval dispatch on \
15347 PlacementStrategy::requires_shard_key must agree on every arm",
15348 );
15349 }
15350
15351 #[test]
15352 fn placement_estrategia_accessor_is_const_fn() {
15353 // The [`Placement::estrategia`] per-`:placement` distribution-
15354 // strategy `Copy`-return scalar accessor is declared
15355 // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
15356 // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
15357 // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
15358 // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
15359 // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
15360 // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
15361 // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
15362 // [`RateLimit`], every one a `pub const fn`). Pin the
15363 // `const`-eval posture here so a future accidental downgrade to
15364 // non-`const` (an added runtime helper reachable only from a
15365 // non-`const` context, a slot promotion to a non-`Copy` return
15366 // that would silently drop the `const` qualifier, a manual
15367 // hand-rolled shadow) trips at caixa-core build time rather
15368 // than surfacing as a downstream `const`-context regression far
15369 // from the declaration.
15370 //
15371 // Same shape as the sibling
15372 // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
15373 // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
15374 // predicate axis — the load-bearing witness lives in the
15375 // module-scope `const fn` wrapper `estrategia_via_const_fn`
15376 // below: a body that calls [`Placement::estrategia`] under a
15377 // `const fn` signature is well-formed only when the callee is
15378 // itself `const fn`, so any future accidental downgrade of
15379 // [`Placement::estrategia`] to non-`const` fails at caixa-core
15380 // build time (const-eval E0015 / E0658 depending on the arm),
15381 // strictly stronger than a runtime `assert!(CONST)` and
15382 // side-stepping the destructor-in-const restriction that
15383 // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
15384 // items on `Placement`'s `Vec<String>` / `Option<String>`
15385 // carriers.
15386 //
15387 // The runtime body witnesses that the const-eval-shaped
15388 // wrapper agrees with a direct call on every closed-set arm.
15389 const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
15390 p.estrategia()
15391 }
15392 for estrategia in [
15393 PlacementStrategy::SingleNode,
15394 PlacementStrategy::Replicated,
15395 PlacementStrategy::Sharded,
15396 ] {
15397 let placement = Placement {
15398 estrategia,
15399 clusters: Vec::new(),
15400 affinity: None,
15401 shard_key: None,
15402 };
15403 assert_eq!(
15404 estrategia_via_const_fn(&placement),
15405 placement.estrategia(),
15406 "const-fn-wrapped and direct dispatch on \
15407 Placement::estrategia must agree for {estrategia:?}",
15408 );
15409 }
15410 }
15411
15412 #[test]
15413 fn entrada_port_accessor_is_const_fn() {
15414 // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
15415 // scalar accessor is declared `#[must_use] pub const fn` —
15416 // matching the peer M3 mesh-slot `Copy`-return accessor family
15417 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
15418 // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
15419 // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
15420 // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
15421 // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
15422 // [`RateLimit::window`] on the sibling [`RateLimit`], the
15423 // sibling per-`:placement` [`Placement::estrategia`] pinned by
15424 // [`placement_estrategia_accessor_is_const_fn`] above — every
15425 // one a `pub const fn`). Pin the `const`-eval posture here so
15426 // a future accidental downgrade to non-`const` (an added
15427 // runtime helper reachable only from a non-`const` context, an
15428 // `Option<u16>`-shape migration once the substrate grows
15429 // per-`:membros` heterogeneous listener ports that would
15430 // silently drop the `const` qualifier, a manual hand-rolled
15431 // shadow) trips at caixa-core build time rather than surfacing
15432 // as a downstream `const`-context regression far from the
15433 // declaration.
15434 //
15435 // Same shape as the sibling
15436 // [`placement_estrategia_accessor_is_const_fn`] pin above — the
15437 // load-bearing witness lives in the module-scope `const fn`
15438 // wrapper `port_via_const_fn`: a body that calls
15439 // [`Entrada::port`] under a `const fn` signature is well-formed
15440 // only when the callee is itself `const fn`, side-stepping the
15441 // destructor-in-const restriction that would otherwise block a
15442 // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
15443 // `String` / `Vec<String>` carriers.
15444 //
15445 // The runtime body sweeps a representative port set spanning
15446 // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
15447 // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
15448 // ceiling — the const-fn-wrapped call must agree with a direct
15449 // call on every fixture (a violation trips the test) and every
15450 // returned scalar must byte-equal the input `port` (a violation
15451 // means the accessor stopped being a raw field-return copy).
15452 const fn port_via_const_fn(e: &Entrada) -> u16 {
15453 e.port()
15454 }
15455 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
15456 let entrada = Entrada {
15457 host: String::new(),
15458 para: String::new(),
15459 port,
15460 paths: Vec::new(),
15461 };
15462 assert_eq!(
15463 port_via_const_fn(&entrada),
15464 entrada.port(),
15465 "const-fn-wrapped and direct dispatch on Entrada::port \
15466 must agree for port={port}",
15467 );
15468 assert_eq!(
15469 entrada.port(),
15470 port,
15471 "Entrada::port must return the storage-side u16 verbatim \
15472 for port={port}",
15473 );
15474 }
15475 }
15476
15477 #[test]
15478 fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
15479 // Load-bearing cross-slot-partition pin closing the loop between
15480 // the substrate-lifted
15481 // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
15482 // the closed-set typed enum and the actual
15483 // [`AplicacaoSpec::validate_placement`] runtime behavior across
15484 // the paired `:placement :shard-key` axis: every validated
15485 // [`Placement`] past [`AplicacaoSpec::validate_placement`]
15486 // satisfies `placement.shard_key().is_some() ==
15487 // placement.estrategia().requires_shard_key()`. The four-cell
15488 // shape witness sweeps every combination of (variant in the
15489 // closed accept-set, `:shard-key` Some/None) and pins:
15490 //
15491 // * variant.requires_shard_key() && shard_key.is_some() →
15492 // validate() passes; the paired shape is the sole
15493 // `requires_shard_key` arm-family accepted shape.
15494 // * variant.requires_shard_key() && shard_key.is_none() →
15495 // validate() fails with [`AplicacaoError::ShardedWithoutKey`];
15496 // the paired shape is the refused missing-key shape on
15497 // Sharded-family arms.
15498 // * !variant.requires_shard_key() && shard_key.is_some() →
15499 // validate() fails with
15500 // [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
15501 // is the refused declared-but-inert shape on non-Sharded-
15502 // family arms.
15503 // * !variant.requires_shard_key() && shard_key.is_none() →
15504 // validate() passes; the paired shape is the sole
15505 // non-`requires_shard_key` arm-family accepted shape.
15506 //
15507 // The compile-time-exhaustive `match p.estrategia()` dispatch at
15508 // [`AplicacaoSpec::validate_placement`] preserves its structural
15509 // arm-fan (a future arm addition still surfaces a build-time
15510 // exhaustiveness error there); this pin closes the semantic loop
15511 // between the arm-fan's shape-gate cascades and the substrate-
15512 // canonical predicate every downstream consumer of the paired
15513 // shape reads through. Fail-before-pass-after locally verified by
15514 // mutating the predicate's `Sharded => true` arm to `false` — the
15515 // truthy `expects_ok` cell for `Sharded` + `Some` trips the
15516 // `validate() must pass` assertion; restoring passes. Same "close
15517 // the loop between the typed predicate and the runtime behavior"
15518 // discipline as the sibling
15519 // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
15520 // (7b97d26) cross-projection pin on the peer [`WitTarget`]
15521 // per-arm classifier axis.
15522 for variant in [
15523 PlacementStrategy::SingleNode,
15524 PlacementStrategy::Replicated,
15525 PlacementStrategy::Sharded,
15526 ] {
15527 for present in [false, true] {
15528 let mut spec = three_member_spec();
15529 spec.placement.estrategia = variant;
15530 spec.placement.shard_key = present.then(|| "tenantId".into());
15531 let expects_ok = variant.requires_shard_key() == present;
15532 let result = spec.validate();
15533 match (expects_ok, &result) {
15534 (true, Ok(())) => {}
15535 (false, Err(err)) => {
15536 // Cross-check the refusal diagnostic names the
15537 // right cell of the four-cell shape witness — the
15538 // `requires_shard_key && !present` cell must trip
15539 // [`AplicacaoError::ShardedWithoutKey`]; the
15540 // `!requires_shard_key && present` cell must trip
15541 // [`AplicacaoError::ShardKeyOnNonSharded`].
15542 match (variant.requires_shard_key(), present, err) {
15543 (true, false, AplicacaoError::ShardedWithoutKey) => {}
15544 (
15545 false,
15546 true,
15547 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
15548 ) => {
15549 assert_eq!(
15550 *e, variant,
15551 "ShardKeyOnNonSharded.estrategia must byte-equal \
15552 the paired PlacementStrategy",
15553 );
15554 }
15555 _ => panic!(
15556 "unexpected refusal for estrategia={variant:?} \
15557 present={present}: {err:?}"
15558 ),
15559 }
15560 }
15561 (true, Err(err)) => panic!(
15562 "validate() must pass for estrategia={variant:?} \
15563 present={present} (requires_shard_key={} == present={present}), \
15564 got {err:?}",
15565 variant.requires_shard_key(),
15566 ),
15567 (false, Ok(())) => panic!(
15568 "validate() must fail for estrategia={variant:?} \
15569 present={present} (requires_shard_key={} != present={present})",
15570 variant.requires_shard_key(),
15571 ),
15572 }
15573 }
15574 }
15575 }
15576
15577 #[test]
15578 fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
15579 // Pin the M3 diagnostic template routes through the typed
15580 // [`PlacementStrategy`] Display byte-string (rebound from the
15581 // prior `{estrategia:?}` `Debug` route). Pre-lift the two
15582 // routes emitted identical bytes (the `Debug` derive on a
15583 // unit variant emits the variant name verbatim, exactly what
15584 // `as_str` returns), but the two paths were structurally
15585 // independent — a future `#[serde(rename_all = "…")]`
15586 // attribute or variant rename would coordinate the wire /
15587 // `Display` / `as_str` triple through the lifted const but
15588 // leave the `Debug` route on the compiler-derived variant name,
15589 // silently desynchronizing the diagnostic byte-string from the
15590 // wire byte-string. Rebinding the template onto `Display`
15591 // ties the diagnostic to the same lifted
15592 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
15593 // emits — drift becomes structurally impossible. Pin the
15594 // byte-string here so a future edit that reverts the template
15595 // to `{estrategia:?}` is caught at caixa-core test time, not
15596 // at consumer dispatch time.
15597 for (variant, expected_scalar) in [
15598 (
15599 PlacementStrategy::SingleNode,
15600 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15601 ),
15602 (
15603 PlacementStrategy::Replicated,
15604 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15605 ),
15606 (
15607 PlacementStrategy::Sharded,
15608 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15609 ),
15610 ] {
15611 let err = AplicacaoError::PlacementWithoutClusters {
15612 estrategia: variant,
15613 };
15614 let msg = err.to_string();
15615 assert!(
15616 msg.starts_with(&format!(":placement {expected_scalar} requires")),
15617 "PlacementWithoutClusters diagnostic for {variant:?} must open \
15618 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
15619 );
15620 }
15621 }
15622
15623 #[test]
15624 fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
15625 // Peer of
15626 // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
15627 // on the second M3 diagnostic that carries the typed
15628 // [`PlacementStrategy`] in its `#[error(…)]` template. Both
15629 // diagnostics now route the strategy scalar through the same
15630 // [`std::fmt::Display`] surface, tying the diagnostic
15631 // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
15632 // const set the wire format also emits. The two non-Sharded
15633 // arms are exercised here (the diagnostic exists to flag a
15634 // `:shard-key` slot the current strategy will never consume);
15635 // the peer `Sharded` arm never reaches this diagnostic (the
15636 // `Sharded` strategy consumes `:shard-key` — the
15637 // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
15638 // slot instead).
15639 for (variant, expected_scalar) in [
15640 (
15641 PlacementStrategy::SingleNode,
15642 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15643 ),
15644 (
15645 PlacementStrategy::Replicated,
15646 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15647 ),
15648 ] {
15649 let err = AplicacaoError::ShardKeyOnNonSharded {
15650 estrategia: variant,
15651 shard_key: "$tenantId".into(),
15652 };
15653 let msg = err.to_string();
15654 assert!(
15655 msg.starts_with(&format!(":placement {expected_scalar} carries")),
15656 "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
15657 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
15658 );
15659 }
15660 }
15661
15662 #[test]
15663 fn placement_strategy_all_enumerates_every_variant_once() {
15664 // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
15665 // exhaustive-iteration surface: every variant appears exactly
15666 // once, and the slice length matches the arm count of the
15667 // closed set. Every consumer that walks the accepted-strategy
15668 // set (a future `feira app placement --list` CLI-side surfacing,
15669 // a future M4 admission-webhook's rejection body naming the
15670 // accepted-strategy list, the [`PlacementStrategy::from_wire`]
15671 // reverse-projection consumers that iterate the accept-set for
15672 // a "did you mean" hint) reads through this slice, so a future
15673 // variant addition (an `Anycast` mesh-anycast arm the
15674 // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
15675 // grows the enum but forgets to grow [`Self::ALL`] silently
15676 // truncates every downstream consumer's accept-set at the same
15677 // pre-addition boundary — this pin fails at caixa-core build
15678 // time on the pairwise-distinct + arm-count invariants.
15679 //
15680 // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
15681 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
15682 // pins on the peer closed-set typed-enum axes.
15683 let all: &[PlacementStrategy] = PlacementStrategy::ALL;
15684 assert_eq!(
15685 all.len(),
15686 3,
15687 "PlacementStrategy::ALL must enumerate every variant of the \
15688 three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
15689 );
15690 for (i, a) in all.iter().enumerate() {
15691 for (j, b) in all.iter().enumerate() {
15692 if i != j {
15693 assert_ne!(
15694 a, b,
15695 "PlacementStrategy::ALL must carry every variant exactly \
15696 once — got duplicate {a:?} at indices {i} and {j}"
15697 );
15698 }
15699 }
15700 }
15701 for variant in [
15702 PlacementStrategy::SingleNode,
15703 PlacementStrategy::Replicated,
15704 PlacementStrategy::Sharded,
15705 ] {
15706 assert!(
15707 all.contains(&variant),
15708 "PlacementStrategy::ALL must contain {variant:?} — a future variant \
15709 addition that grows the enum but forgets to grow the ALL slice \
15710 silently truncates every downstream consumer's accept-set at the \
15711 pre-addition boundary"
15712 );
15713 }
15714 }
15715
15716 #[test]
15717 fn placement_strategy_from_wire_accepts_every_lifted_constant() {
15718 // Fail-before-pass-after pin on the forward accept-set of the
15719 // [`PlacementStrategy::from_wire`] reverse projection: every
15720 // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
15721 // constant the [`PlacementStrategy::as_str`] emitter walks
15722 // parses back to its paired variant. Any future arm addition
15723 // that grows the emitter's `as_str` match but forgets to grow
15724 // the parser's `from_str` match silently splits the two halves
15725 // of the round-trip — the wire byte-string one non-serde
15726 // consumer parses from the one the emitter wrote — with the
15727 // failure surfacing at parse time far from the rebrand commit.
15728 // Pinning the three-arm accept-set here catches the drift at
15729 // caixa-core build time.
15730 //
15731 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
15732 // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
15733 // closed-set typed-enum `str → Self` axes.
15734 for (wire, expected) in [
15735 (
15736 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15737 PlacementStrategy::SingleNode,
15738 ),
15739 (
15740 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15741 PlacementStrategy::Replicated,
15742 ),
15743 (
15744 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15745 PlacementStrategy::Sharded,
15746 ),
15747 ] {
15748 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
15749 panic!(
15750 "PlacementStrategy::from_wire({wire:?}) must accept every \
15751 M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
15752 lifted canonical byte-string that PlacementStrategy::{expected:?} \
15753 serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
15754 )
15755 });
15756 assert_eq!(
15757 parsed, expected,
15758 "PlacementStrategy::from_wire({wire:?}) must return \
15759 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
15760 );
15761 }
15762 }
15763
15764 #[test]
15765 fn placement_strategy_from_wire_round_trips_through_as_str() {
15766 // Fail-before-pass-after pin on the closed round-trip between
15767 // the forward [`PlacementStrategy::as_str`] emitter and the
15768 // reverse [`PlacementStrategy::from_wire`] parser: for every
15769 // variant in [`PlacementStrategy::ALL`], parsing the emitter's
15770 // output must return exactly the same variant. Any per-arm
15771 // divergence — a future arm added to `as_str` but not
15772 // `from_str`, an accidental copy-paste flip in one but not the
15773 // other — silently splits the emit and parse halves and the
15774 // failure surfaces at consumer parse time far from the drift
15775 // site. The `ALL`-iterating shape means a future variant
15776 // addition picks up the coverage by construction.
15777 //
15778 // Peer of the sibling [`crate::kind::tests`] round-trip pin on
15779 // [`crate::CaixaKind::from_wire`] and the
15780 // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
15781 // sibling round-trip pin on [`RateLimitUnit`].
15782 for &variant in PlacementStrategy::ALL {
15783 let wire = variant.as_str();
15784 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
15785 panic!(
15786 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
15787 must be Some({variant:?}) — the two halves of the round-trip \
15788 dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
15789 got None on wire byte-string {wire:?}"
15790 )
15791 });
15792 assert_eq!(
15793 parsed, variant,
15794 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
15795 must round-trip to the same variant; got {parsed:?}"
15796 );
15797 }
15798 }
15799
15800 #[test]
15801 fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
15802 // Fail-before-pass-after pin on the closed-set refusal
15803 // discipline of [`PlacementStrategy::from_wire`]: every
15804 // byte-string outside the three-arm accept-set returns `None`
15805 // rather than silently collapsing onto the [`Default`]
15806 // (`Replicated`) arm or an arbitrary neighbor. The refusal set
15807 // exercised here sweeps the load-bearing drift shapes: the
15808 // empty string (a stripped serde-attribute drift), an all-
15809 // whitespace string (the canonical text-editor accidental
15810 // padding shape), the lowercased kebab-case forms a future
15811 // `#[serde(rename_all = "kebab-case")]` attribute would emit
15812 // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
15813 // coincidentally match the accepted canonical scalars, so only
15814 // `"single-node"` fires as a refusal, but pinning the case-
15815 // sensitivity of the accepted arms via the peer [`SingleNode`]
15816 // assertion in the round-trip pin makes the discipline
15817 // structurally clear), the lowercased single-word forms
15818 // (`"singlenode"`), the padded canonical scalar
15819 // (`" Sharded "`), the trailing-comma / trailing-newline shapes
15820 // (`"Sharded\n"`), and a pointer-different `&'static str` that
15821 // happens to alias a canonical byte-string by content but not
15822 // by identity (validated implicitly by the emitter's routing
15823 // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
15824 // identity a paired [`crate::assert_str_reexport_identity`] pin
15825 // in caixa-core's per-const declaration surface would catch).
15826 //
15827 // Peer of the sibling
15828 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
15829 // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
15830 for bad in [
15831 "",
15832 " ",
15833 "\n",
15834 "\t",
15835 "single-node",
15836 "singlenode",
15837 "SingleNodes",
15838 "single_node",
15839 "single node",
15840 "SINGLENODE",
15841 "SingleNode ",
15842 " SingleNode",
15843 " Sharded ",
15844 "Sharded\n",
15845 "replicated ",
15846 "sharded",
15847 "REPLICATED",
15848 "Anycast",
15849 "Global",
15850 "?",
15851 ] {
15852 assert!(
15853 PlacementStrategy::from_wire(bad).is_none(),
15854 "PlacementStrategy::from_wire({bad:?}) must return None — the \
15855 parser's accept-set is exactly the three PlacementStrategy::as_str \
15856 outputs (SingleNode, Replicated, Sharded), and this byte-string \
15857 is outside that closed set"
15858 );
15859 }
15860 }
15861
15862 #[test]
15863 fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
15864 // Fail-before-pass-after pin on the third path of the four-path
15865 // convergence: `from_str` (the reverse projection) inverts the
15866 // `Serialize` derive's wire byte-string on every variant.
15867 // Together with the pre-existing three-path convergence
15868 // (`Display` + `as_str` + `Serialize` all resolve to the same
15869 // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
15870 // the peer
15871 // [`placement_strategy_display_matches_serialized_wire_byte_string`])
15872 // this closes the round-trip: the wire byte-string the
15873 // `Serialize` derive emits parses back to the same variant
15874 // through `from_str`, so any future serde-attribute or variant-
15875 // rename drift on the emit half now surfaces as a matched drift
15876 // on the parse half at caixa-core build time — the two halves
15877 // migrate as a unit through the lifted consts on any future
15878 // rename, and the round-trip cannot silently split.
15879 //
15880 // Peer of the sibling
15881 // [`placement_strategy_display_matches_serialized_wire_byte_string`]
15882 // wire-format pin — extends the three-path convergence
15883 // (`Display` + `as_str` + `Serialize`) onto the fourth path
15884 // (`from_str`), closing the `str ↔ Self` round-trip on the
15885 // M3 `:placement :estrategia` closed-set axis.
15886 for &variant in PlacementStrategy::ALL {
15887 let wire = serde_json::to_string(&variant).unwrap();
15888 let unquoted = wire
15889 .strip_prefix('"')
15890 .and_then(|s| s.strip_suffix('"'))
15891 .expect("serialized PlacementStrategy is a JSON string");
15892 let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
15893 panic!(
15894 "PlacementStrategy::from_wire({unquoted:?}) must accept the \
15895 Serialize derive's wire byte-string for \
15896 PlacementStrategy::{variant:?} — the four-path convergence \
15897 (Display + as_str + Serialize + from_str) resolves through \
15898 the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
15899 )
15900 });
15901 assert_eq!(
15902 parsed, variant,
15903 "PlacementStrategy::from_wire of the Serialize derive's wire \
15904 byte-string for PlacementStrategy::{variant:?} must round-trip \
15905 to the same variant; got {parsed:?}"
15906 );
15907 }
15908 }
15909
15910 #[test]
15911 fn rejects_zero_policy_timeout() {
15912 let mut s = three_member_spec();
15913 s.politicas.timeout = Some(Duration::ZERO);
15914 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
15915 }
15916
15917 #[test]
15918 fn rejects_zero_policy_retries() {
15919 let mut s = three_member_spec();
15920 s.politicas.retries = Some(0);
15921 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
15922 }
15923
15924 #[test]
15925 fn rejects_policy_retries_above_cap() {
15926 // The fail-before-pass-after pin: `Some(11)` is structurally
15927 // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
15928 // passed validate on every pre-gate codebase because the
15929 // typed slot's only check was the zero-floor arm. The
15930 // thundering-herd amplification vector only surfaced at the
15931 // runtime substrate (Envoy / Cilium L7 retry overlay)
15932 // far from the source caixa.lisp with no field naming the
15933 // offending policy.
15934 let mut s = three_member_spec();
15935 s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
15936 assert_eq!(
15937 s.validate().unwrap_err(),
15938 AplicacaoError::PolicyRetriesExceedsCap {
15939 retries: POLICY_RETRIES_MAX + 1
15940 }
15941 );
15942 }
15943
15944 #[test]
15945 fn rejects_policy_retries_far_above_cap() {
15946 // The `u32::MAX` worst case — the four-billion-retry policy
15947 // a typo (`(:retries 4294967295)`) or struct-literal
15948 // copy-paste lands in the slot. Pin the cap arm's coverage
15949 // explicitly across the full `u32` overflow so a future
15950 // relaxation that drops the upper bound surfaces here.
15951 let mut s = three_member_spec();
15952 s.politicas.retries = Some(u32::MAX);
15953 assert_eq!(
15954 s.validate().unwrap_err(),
15955 AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
15956 );
15957 }
15958
15959 #[test]
15960 fn accepts_policy_retries_at_cap() {
15961 // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
15962 // must validate. The cap is inclusive on the top edge,
15963 // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
15964 // discipline on the sibling [`crate::LimitsSpec::memory`]
15965 // axis. Pin the boundary explicitly so a future off-by-one
15966 // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
15967 // surfaces here as a test failure rather than a silent
15968 // contract narrowing.
15969 let mut s = three_member_spec();
15970 s.politicas.retries = Some(POLICY_RETRIES_MAX);
15971 s.validate()
15972 .expect("retries == POLICY_RETRIES_MAX must validate");
15973 }
15974
15975 #[test]
15976 fn accepts_policy_retries_typical_values() {
15977 // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
15978 // every value in the validated set must pass. The
15979 // Envoy / Istio production-playbook recommendation band
15980 // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
15981 // (`maxRetries ≤ 10`) both lie within this set.
15982 for r in 1..=POLICY_RETRIES_MAX {
15983 let mut s = three_member_spec();
15984 s.politicas.retries = Some(r);
15985 s.validate()
15986 .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
15987 }
15988 }
15989
15990 #[test]
15991 fn policy_retries_zero_takes_precedence_over_cap() {
15992 // The cross-arm ordering pin: `Some(0)` is structurally
15993 // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
15994 // (cap), but the zero-floor diagnostic is the more
15995 // self-locating one (it directly names the omit-axis
15996 // remediation), so the validate gate must fire on zero
15997 // first. Pin the order so a future refactor that reorders
15998 // the arms surfaces here as a test failure rather than a
15999 // silent diagnostic regression. Same shape every other
16000 // zero-then-shape ordering on this surface uses
16001 // ([`AplicacaoError::PolicyTimeoutZero`] then
16002 // [`AplicacaoError::PolicyTimeoutNotCanonical`];
16003 // [`AplicacaoError::PolicyBreakerZeroWindow`] then
16004 // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
16005 let mut s = three_member_spec();
16006 s.politicas.retries = Some(0);
16007 assert_eq!(
16008 s.validate().unwrap_err(),
16009 AplicacaoError::PolicyRetriesZero,
16010 "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
16011 );
16012 }
16013
16014 #[test]
16015 fn policy_retries_cap_diagnostic_carries_offending_value() {
16016 // The diagnostic-shape pin: the offending `u32` is carried
16017 // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
16018 // variant so the surfaced error message names the value the
16019 // author wrote (`":politicas :retries (47) exceeds the
16020 // mesh-policy ceiling …"`), not just the cap. Same
16021 // self-locating diagnostic shape every other typed-cap arm
16022 // on this surface carries
16023 // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16024 // offending byte count verbatim).
16025 let mut s = three_member_spec();
16026 s.politicas.retries = Some(47);
16027 let err = s.validate().unwrap_err();
16028 assert!(
16029 matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
16030 "got {err:?}"
16031 );
16032 let msg = err.to_string();
16033 assert!(
16034 msg.contains("47"),
16035 ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
16036 );
16037 }
16038
16039 #[test]
16040 fn policy_retries_cap_is_aws_app_mesh_aligned() {
16041 // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
16042 // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
16043 // schema cap — the only upstream mesh-policy schema that
16044 // documents an explicit hard cap. Pinning the literal value
16045 // here surfaces a future drift (a relaxation to 20, a
16046 // tightening to 5) as a deliberate test edit, not a silent
16047 // contract narrowing.
16048 assert_eq!(POLICY_RETRIES_MAX, 10);
16049 }
16050
16051 #[test]
16052 fn rejects_circuit_breaker_zero_max_failures() {
16053 let mut s = three_member_spec();
16054 s.politicas.circuit_breaker = Some(CircuitBreaker {
16055 max_failures: 0,
16056 window: Duration::from_secs(60),
16057 });
16058 assert_eq!(
16059 s.validate().unwrap_err(),
16060 AplicacaoError::PolicyBreakerZeroFailures
16061 );
16062 }
16063
16064 #[test]
16065 fn rejects_circuit_breaker_max_failures_above_cap() {
16066 // The fail-before-pass-after pin: `1001` is structurally one
16067 // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
16068 // silently passed validate on every pre-gate codebase
16069 // because the typed slot's only check was the zero-floor
16070 // arm. The breaker-no-op vector only surfaced at the runtime
16071 // substrate (Envoy / Cilium L7 outlier-detection overlay)
16072 // far from the source caixa.lisp with no field naming the
16073 // offending policy.
16074 let mut s = three_member_spec();
16075 s.politicas.circuit_breaker = Some(CircuitBreaker {
16076 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16077 window: Duration::from_secs(60),
16078 });
16079 assert_eq!(
16080 s.validate().unwrap_err(),
16081 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16082 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16083 }
16084 );
16085 }
16086
16087 #[test]
16088 fn rejects_circuit_breaker_max_failures_far_above_cap() {
16089 // The `u32::MAX` worst case — the four-billion-failure
16090 // threshold a typo (`(:max-failures 4294967295)`) or a
16091 // struct-literal copy-paste lands in the slot. Pin the cap
16092 // arm's coverage explicitly across the full `u32` overflow
16093 // so a future relaxation that drops the upper bound surfaces
16094 // here.
16095 let mut s = three_member_spec();
16096 s.politicas.circuit_breaker = Some(CircuitBreaker {
16097 max_failures: u32::MAX,
16098 window: Duration::from_secs(60),
16099 });
16100 assert_eq!(
16101 s.validate().unwrap_err(),
16102 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16103 max_failures: u32::MAX,
16104 }
16105 );
16106 }
16107
16108 #[test]
16109 fn accepts_circuit_breaker_max_failures_at_cap() {
16110 // The boundary value — exactly
16111 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
16112 // cap is inclusive on the top edge, matching the
16113 // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16114 // discipline on the sibling capped axes. Pin the boundary
16115 // explicitly so a future off-by-one tightening
16116 // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
16117 // surfaces here as a test failure rather than a silent
16118 // contract narrowing.
16119 let mut s = three_member_spec();
16120 s.politicas.circuit_breaker = Some(CircuitBreaker {
16121 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
16122 window: Duration::from_secs(60),
16123 });
16124 s.validate()
16125 .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
16126 }
16127
16128 #[test]
16129 fn accepts_circuit_breaker_max_failures_typical_values() {
16130 // The documented production-playbook band positive-control
16131 // sweep — every value Hystrix / Istio / Envoy / Polly /
16132 // Resilience4j recommend (5..=50) must pass, plus a sweep
16133 // through the hyperscale band (100, 500, 1000) the cap
16134 // accepts. Pin the inclusive validated set explicitly so a
16135 // future tightening of the ceiling surfaces here.
16136 for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
16137 let mut s = three_member_spec();
16138 s.politicas.circuit_breaker = Some(CircuitBreaker {
16139 max_failures: n,
16140 window: Duration::from_secs(60),
16141 });
16142 s.validate()
16143 .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
16144 }
16145 }
16146
16147 #[test]
16148 fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
16149 // The cross-arm ordering pin: `0` is structurally outside
16150 // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
16151 // (cap), but the zero-floor diagnostic is the more
16152 // self-locating one (it directly names the omit-axis
16153 // remediation), so the validate gate must fire on zero
16154 // first. Same shape every other zero-then-shape ordering on
16155 // this surface uses
16156 // ([`AplicacaoError::PolicyRetriesZero`] then
16157 // [`AplicacaoError::PolicyRetriesExceedsCap`];
16158 // [`AplicacaoError::PolicyTimeoutZero`] then
16159 // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
16160 let mut s = three_member_spec();
16161 s.politicas.circuit_breaker = Some(CircuitBreaker {
16162 max_failures: 0,
16163 window: Duration::from_secs(60),
16164 });
16165 assert_eq!(
16166 s.validate().unwrap_err(),
16167 AplicacaoError::PolicyBreakerZeroFailures,
16168 "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
16169 );
16170 }
16171
16172 #[test]
16173 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
16174 // The cross-arm ordering pin between the cap and the
16175 // sibling `:window` gates (zero-window, canonical-window).
16176 // A breaker carrying both an over-cap `max_failures` AND a
16177 // structurally invalid window (zero, sub-ms) must surface
16178 // the cap diagnostic first — the cap arm is wired
16179 // immediately after the zero-failure arm and strictly
16180 // before the window arms, so the offending value the
16181 // diagnostic names matches the order the author would
16182 // discover the gates by reading top-to-bottom through
16183 // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
16184 // future refactor that reorders the arms surfaces here as a
16185 // test failure rather than a silent diagnostic regression.
16186 let mut s = three_member_spec();
16187 s.politicas.circuit_breaker = Some(CircuitBreaker {
16188 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16189 window: Duration::ZERO,
16190 });
16191 assert_eq!(
16192 s.validate().unwrap_err(),
16193 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16194 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16195 },
16196 "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
16197 );
16198 }
16199
16200 #[test]
16201 fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
16202 // The diagnostic-shape pin: the offending `u32` is carried
16203 // verbatim into the
16204 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
16205 // variant so the surfaced error message names the value the
16206 // author wrote (`":politicas :circuit-breaker :max-failures
16207 // (50000) exceeds the mesh-policy ceiling …"`), not just
16208 // the cap. Same self-locating diagnostic shape every other
16209 // typed-cap arm on this surface carries
16210 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
16211 // offending retry count verbatim,
16212 // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16213 // offending byte count verbatim).
16214 let mut s = three_member_spec();
16215 s.politicas.circuit_breaker = Some(CircuitBreaker {
16216 max_failures: 50_000,
16217 window: Duration::from_secs(60),
16218 });
16219 let err = s.validate().unwrap_err();
16220 assert!(
16221 matches!(
16222 err,
16223 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16224 max_failures: 50_000
16225 }
16226 ),
16227 "got {err:?}"
16228 );
16229 let msg = err.to_string();
16230 assert!(
16231 msg.contains("50000"),
16232 ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
16233 );
16234 }
16235
16236 #[test]
16237 fn policy_breaker_max_failures_cap_pins_canonical_value() {
16238 // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
16239 // value at 1000 — an order of magnitude above every
16240 // documented production-playbook recommendation band
16241 // (Hystrix `requestVolumeThreshold` default 20, Istio
16242 // `outlierDetection.consecutive5xxErrors` default 5, Envoy
16243 // `outlier_detection.consecutive_5xx` default 5, Polly /
16244 // Resilience4j typical 5..=50) and below the
16245 // clearly-pathological "effectively no protection" floor
16246 // (10_000, 100_000, u32::MAX). Pinning the literal value
16247 // here surfaces a future drift (a relaxation to 10_000, a
16248 // tightening to 100) as a deliberate test edit, not a
16249 // silent contract narrowing.
16250 assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
16251 }
16252
16253 #[test]
16254 fn rejects_circuit_breaker_zero_window() {
16255 let mut s = three_member_spec();
16256 s.politicas.circuit_breaker = Some(CircuitBreaker {
16257 max_failures: 5,
16258 window: Duration::ZERO,
16259 });
16260 assert_eq!(
16261 s.validate().unwrap_err(),
16262 AplicacaoError::PolicyBreakerZeroWindow
16263 );
16264 }
16265
16266 #[test]
16267 fn rejects_zero_rate_limit() {
16268 let mut s = three_member_spec();
16269 s.politicas.rate_limit = Some(RateLimit {
16270 rate: 0,
16271 window: Duration::from_secs(1),
16272 });
16273 assert_eq!(
16274 s.validate().unwrap_err(),
16275 AplicacaoError::PolicyRateLimitZero
16276 );
16277 }
16278
16279 #[test]
16280 fn rejects_rate_limit_zero_window() {
16281 // `RateLimit { rate: 100, window: Duration::ZERO }` is
16282 // constructible programmatically (the typed `Duration` field
16283 // imposes no nonzero invariant) but renders through
16284 // `rate_limit_codec::render` as `"100/0s"` — a fragment the
16285 // codec's `parse` rejects as `unknown rate-limit window unit
16286 // "0s"`. Until this validate-time gate landed the typed slot
16287 // accepted the value silently and the round-trip break only
16288 // surfaced at deserialize time (potentially in a downstream
16289 // consumer that never re-validates). Pin the rejection at
16290 // `AplicacaoSpec::validate` so the typed slot's valid set
16291 // matches the codec's round-trippable set structurally.
16292 let mut s = three_member_spec();
16293 s.politicas.rate_limit = Some(RateLimit {
16294 rate: 100,
16295 window: Duration::ZERO,
16296 });
16297 assert_eq!(
16298 s.validate().unwrap_err(),
16299 AplicacaoError::PolicyRateLimitWindowNotCanonical {
16300 window: Duration::ZERO
16301 }
16302 );
16303 }
16304
16305 #[test]
16306 fn rejects_rate_limit_arbitrary_seconds_window() {
16307 // 45 seconds is a valid `Duration` but not one of the three
16308 // canonical rate-limit windows the codec round-trips
16309 // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
16310 // refuses on round-trip — same round-trip-break shape the
16311 // zero-window arm above pins, with a non-zero magnitude to
16312 // guard against a future "reject only zero" half-measure.
16313 let mut s = three_member_spec();
16314 let window = Duration::from_secs(45);
16315 s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
16316 assert_eq!(
16317 s.validate().unwrap_err(),
16318 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16319 );
16320 }
16321
16322 #[test]
16323 fn rejects_rate_limit_two_minute_window() {
16324 // 120 seconds = 2 minutes is a "looks-canonical" but
16325 // not-canonical window: it's a clean integer multiple of the
16326 // minute unit, but the codec only round-trips the
16327 // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
16328 // A `Duration::from_secs(120)` window renders as `"100/120s"`
16329 // which the parser rejects. Pinning this case rules out a
16330 // future "accept any clean multiple of s/m/h" relaxation
16331 // that would silently break the codec contract.
16332 let mut s = three_member_spec();
16333 let window = Duration::from_secs(120);
16334 s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
16335 assert_eq!(
16336 s.validate().unwrap_err(),
16337 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16338 );
16339 }
16340
16341 #[test]
16342 fn rejects_rate_limit_subsecond_window() {
16343 // A sub-second window (e.g. 500ms) is a valid `Duration` but
16344 // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
16345 // Pin the rejection so a future relaxation can't silently
16346 // admit fractional-second windows that the codec can't
16347 // round-trip.
16348 let mut s = three_member_spec();
16349 let window = Duration::from_millis(500);
16350 s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
16351 assert_eq!(
16352 s.validate().unwrap_err(),
16353 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16354 );
16355 }
16356
16357 #[test]
16358 fn rejects_policy_rate_limit_above_cap() {
16359 // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
16360 // is structurally one past the cap and silently passed
16361 // validate on every pre-gate codebase because the typed slot's
16362 // only `rate` check was the zero-floor arm. The no-op-limiter
16363 // shape only surfaced at the runtime substrate (Envoy's
16364 // `local_rate_limit.token_bucket.max_tokens`, the future
16365 // Cilium L7 rate-limit overlay) far from the source caixa.lisp
16366 // with no field naming the offending policy.
16367 let mut s = three_member_spec();
16368 s.politicas.rate_limit = Some(RateLimit {
16369 rate: POLICY_RATE_LIMIT_MAX + 1,
16370 window: Duration::from_secs(1),
16371 });
16372 assert_eq!(
16373 s.validate().unwrap_err(),
16374 AplicacaoError::PolicyRateLimitExceedsCap {
16375 rate: POLICY_RATE_LIMIT_MAX + 1
16376 }
16377 );
16378 }
16379
16380 #[test]
16381 fn rejects_policy_rate_limit_far_above_cap() {
16382 // The `u32::MAX` worst case — the four-billion-token rate-limit
16383 // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
16384 // copy-paste lands in the slot. Pin the cap arm's coverage
16385 // explicitly across the full `u32` overflow so a future
16386 // relaxation that drops the upper bound surfaces here. Peer to
16387 // `rejects_policy_retries_far_above_cap` on the sibling
16388 // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
16389 // on the sibling `:max-failures` axis.
16390 let mut s = three_member_spec();
16391 s.politicas.rate_limit = Some(RateLimit {
16392 rate: u32::MAX,
16393 window: Duration::from_secs(1),
16394 });
16395 assert_eq!(
16396 s.validate().unwrap_err(),
16397 AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
16398 );
16399 }
16400
16401 #[test]
16402 fn accepts_policy_rate_limit_at_cap() {
16403 // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
16404 // must validate. The cap is inclusive on the top edge, matching
16405 // every other typed upper bound in this crate
16406 // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
16407 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
16408 // across all three canonical windows so a future off-by-one
16409 // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
16410 // window-conditional cap surfaces here as a test failure rather
16411 // than a silent contract narrowing.
16412 for secs in [1u64, 60, 3600] {
16413 let mut s = three_member_spec();
16414 s.politicas.rate_limit = Some(RateLimit {
16415 rate: POLICY_RATE_LIMIT_MAX,
16416 window: Duration::from_secs(secs),
16417 });
16418 s.validate().unwrap_or_else(|e| {
16419 panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
16420 });
16421 }
16422 }
16423
16424 #[test]
16425 fn accepts_policy_rate_limit_typical_values() {
16426 // The documented production-playbook recommendation band —
16427 // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
16428 // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
16429 // Enterprise ~1M per-hour. Every value in the validated set
16430 // must pass; pin the band explicitly so a future tightening
16431 // surfaces here.
16432 for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
16433 for secs in [1u64, 60, 3600] {
16434 let mut s = three_member_spec();
16435 s.politicas.rate_limit = Some(RateLimit {
16436 rate,
16437 window: Duration::from_secs(secs),
16438 });
16439 s.validate().unwrap_or_else(|e| {
16440 panic!("rate={rate} window={secs}s must validate; got {e:?}")
16441 });
16442 }
16443 }
16444 }
16445
16446 #[test]
16447 fn policy_rate_limit_zero_takes_precedence_over_cap() {
16448 // The cross-arm ordering pin: `rate == 0` is structurally
16449 // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
16450 // (cap), but the zero-floor diagnostic is the more
16451 // self-locating one (it directly names the omit-axis
16452 // remediation). Pin the order so a future refactor that
16453 // reorders the arms surfaces here as a test failure rather
16454 // than a silent diagnostic regression. Same shape every other
16455 // zero-then-cap ordering on this surface uses
16456 // ([`AplicacaoError::PolicyRetriesZero`] then
16457 // [`AplicacaoError::PolicyRetriesExceedsCap`];
16458 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
16459 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
16460 let mut s = three_member_spec();
16461 s.politicas.rate_limit = Some(RateLimit {
16462 rate: 0,
16463 window: Duration::from_secs(1),
16464 });
16465 assert_eq!(
16466 s.validate().unwrap_err(),
16467 AplicacaoError::PolicyRateLimitZero,
16468 "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
16469 );
16470 }
16471
16472 #[test]
16473 fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
16474 // Two-axis-bad pin: rate above cap *and* window non-canonical.
16475 // The validate gate must fire on the rate cap first — the
16476 // amplification-shape (no-op limiter) diagnostic is the more
16477 // fundamental one; the window-canonical diagnostic is the
16478 // narrower codec-round-trip shape. Pin the ordering so a future
16479 // refactor that reorders the rate-then-window check arms
16480 // surfaces here as a test failure rather than a silent
16481 // diagnostic regression.
16482 let mut s = three_member_spec();
16483 s.politicas.rate_limit = Some(RateLimit {
16484 rate: POLICY_RATE_LIMIT_MAX + 1,
16485 window: Duration::from_secs(45),
16486 });
16487 assert_eq!(
16488 s.validate().unwrap_err(),
16489 AplicacaoError::PolicyRateLimitExceedsCap {
16490 rate: POLICY_RATE_LIMIT_MAX + 1
16491 },
16492 "above-cap rate must surface the cap diagnostic, not the window diagnostic"
16493 );
16494 }
16495
16496 #[test]
16497 fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
16498 // The diagnostic-shape pin: the offending `u32` is carried
16499 // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
16500 // variant so the surfaced error message names the value the
16501 // author wrote (`":politicas :rate-limit rate (5000000) exceeds
16502 // the mesh-policy ceiling …"`), not just the cap. Same
16503 // self-locating diagnostic shape every other typed-cap arm on
16504 // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
16505 // carries the offending retries count verbatim,
16506 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
16507 // the offending failure count verbatim).
16508 let mut s = three_member_spec();
16509 s.politicas.rate_limit = Some(RateLimit {
16510 rate: 5_000_000,
16511 window: Duration::from_secs(1),
16512 });
16513 let err = s.validate().unwrap_err();
16514 assert!(
16515 matches!(
16516 err,
16517 AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
16518 ),
16519 "got {err:?}"
16520 );
16521 let msg = err.to_string();
16522 assert!(
16523 msg.contains("5000000"),
16524 ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
16525 );
16526 }
16527
16528 #[test]
16529 fn policy_rate_limit_cap_pins_canonical_value() {
16530 // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
16531 // 1_000_000 — two-to-three orders of magnitude above every
16532 // documented production-playbook recommendation band (Envoy /
16533 // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
16534 // Gateway 10_000..=100_000 per-minute) and below the
16535 // clearly-pathological "paste-from-binary blob" floor
16536 // (100_000_000, u32::MAX). Pinning the literal value here
16537 // surfaces a future drift (a relaxation to 10_000_000, a
16538 // tightening to 100_000) as a deliberate test edit, not a
16539 // silent contract narrowing.
16540 assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
16541 }
16542
16543 #[test]
16544 fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
16545 // Both axes are invalid here: rate == 0 *and* window is
16546 // non-canonical. The validate gate must fire on rate first
16547 // (matching the existing `rejects_zero_rate_limit` ordering),
16548 // so the existing diagnostic continues to lead with the
16549 // simpler "zero rate" framing. Pinning the order of checks
16550 // so a future refactor that reorders the arms surfaces here
16551 // as a test failure rather than a silent diagnostic
16552 // regression.
16553 let mut s = three_member_spec();
16554 s.politicas.rate_limit = Some(RateLimit {
16555 rate: 0,
16556 window: Duration::from_secs(45),
16557 });
16558 assert_eq!(
16559 s.validate().unwrap_err(),
16560 AplicacaoError::PolicyRateLimitZero
16561 );
16562 }
16563
16564 #[test]
16565 fn rate_limit_canonical_windows_validate() {
16566 // The three canonical windows the codec round-trips
16567 // losslessly — 1s / 60s / 3600s — must all pass `validate()`
16568 // unchanged. Pin the full canonical set as a positive case
16569 // (the existing `rate_limit_round_trip_seconds` /
16570 // `rate_limit_round_trip_minutes` tests pin the
16571 // serialize-then-deserialize property at the codec layer; this
16572 // test pins the validate-side complement so a future tightening
16573 // of the canonical set — e.g. dropping `:hour` — surfaces here
16574 // as a test failure rather than a silent contract narrowing).
16575 for secs in [1u64, 60, 3600] {
16576 let mut s = three_member_spec();
16577 s.politicas.rate_limit = Some(RateLimit {
16578 rate: 100,
16579 window: Duration::from_secs(secs),
16580 });
16581 s.validate().expect("canonical window must validate");
16582 }
16583 }
16584
16585 #[test]
16586 fn rate_limit_validated_value_round_trips_through_codec() {
16587 // The structural property the validate gate enforces:
16588 // every `RateLimit` past `AplicacaoSpec::validate` round-trips
16589 // losslessly through the `rate_limit_codec` (serialize → string
16590 // → deserialize → equal value). Pin this end-to-end so a future
16591 // change to either side (the validate gate's accepted window
16592 // set, the codec's parse/render unit set) that breaks the
16593 // alignment surfaces here. The previous-state shape (typed
16594 // slot accepts arbitrary `Duration`, codec only round-trips
16595 // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
16596 // window — the validate gate now forecloses that.
16597 for secs in [1u64, 60, 3600] {
16598 let mut s = three_member_spec();
16599 s.politicas.rate_limit = Some(RateLimit {
16600 rate: 250,
16601 window: Duration::from_secs(secs),
16602 });
16603 s.validate().unwrap();
16604 let json = serde_json::to_string(&s.politicas).unwrap();
16605 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16606 assert_eq!(
16607 back.rate_limit, s.politicas.rate_limit,
16608 "every validated :rate-limit must round-trip losslessly through the codec"
16609 );
16610 }
16611 }
16612
16613 #[test]
16614 fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
16615 // The hour-window canonical form (`"<n>/h"`) was missing from
16616 // the prior `rate_limit_round_trip_seconds` / `_minutes` test
16617 // pair. Now that the validate gate pins 3600s as part of the
16618 // canonical set, pin its serialize-side render shape too so
16619 // the third leg of the s/m/h tripod is explicitly tested.
16620 let policy = MeshPolicy {
16621 rate_limit: Some(RateLimit {
16622 rate: 10000,
16623 window: Duration::from_secs(3600),
16624 }),
16625 ..Default::default()
16626 };
16627 let json = serde_json::to_string(&policy).unwrap();
16628 assert!(
16629 json.contains("\"10000/h\""),
16630 "hour-window canonical form must render with `h` suffix (got: {json})"
16631 );
16632 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16633 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
16634 }
16635
16636 #[test]
16637 fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
16638 // Pin the substrate-primitive [`RateLimit::canonical_unit`]
16639 // typed accessor's accepted-window set against the codec's
16640 // accepted set explicitly. A future addition to the codec
16641 // (e.g. accepting `:day`/`:week` as authoring units) must be
16642 // accompanied by a parallel addition here, and a regression
16643 // that drops one of the three canonical units from either
16644 // side surfaces as a test failure. The accessor is the
16645 // single source of truth for the canonical-window set —
16646 // [`AplicacaoSpec::validate_politicas`]'s canonical-window
16647 // gate and [`rate_limit_codec::render`]'s canonical arm both
16648 // read through it — this test enshrines that its
16649 // `Duration → Option<RateLimitUnit>` projection matches the
16650 // codec's parse / render arms' accepted-window set exactly.
16651 //
16652 // Predecessor: this pin previously read the module-private
16653 // free helper `is_canonical_rate_limit_window` — a delegate
16654 // that composed [`RateLimitUnit::from_window`] with `.is_some()`
16655 // — but the helper had no production consumers left after the
16656 // validate-gate migration onto [`RateLimit::canonical_unit`]
16657 // and was deleted; the closed-set arm-window bijection now
16658 // lives on exactly one typed dispatch on the substrate
16659 // primitive.
16660 let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
16661 RateLimit { rate: 1, window }.canonical_unit()
16662 };
16663 assert!(canonical_unit(Duration::from_secs(1)).is_some());
16664 assert!(canonical_unit(Duration::from_secs(60)).is_some());
16665 assert!(canonical_unit(Duration::from_secs(3600)).is_some());
16666 // Non-canonical windows the accessor rejects.
16667 assert!(canonical_unit(Duration::ZERO).is_none());
16668 assert!(canonical_unit(Duration::from_secs(2)).is_none());
16669 assert!(canonical_unit(Duration::from_secs(30)).is_none());
16670 assert!(canonical_unit(Duration::from_secs(120)).is_none());
16671 assert!(canonical_unit(Duration::from_secs(86400)).is_none());
16672 // Sub-second windows: even `Duration::from_millis(1000)` is
16673 // exactly 1s and accepted; `Duration::from_millis(500)` is
16674 // sub-second and rejected.
16675 assert!(canonical_unit(Duration::from_millis(1000)).is_some());
16676 assert!(canonical_unit(Duration::from_millis(500)).is_none());
16677 assert!(canonical_unit(Duration::from_millis(1500)).is_none());
16678 }
16679
16680 #[test]
16681 fn rate_limit_unit_table_projections_are_mutual_inverses() {
16682 // Bidirection pin against the closed-set typed enum
16683 // [`RateLimitUnit`] arm-table (the canonical
16684 // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
16685 // of the rate-limit unit surface reads from). The two
16686 // projection directions [`RateLimitUnit::from_suffix`] /
16687 // [`RateLimitUnit::window`] (str → Duration, exposed as one
16688 // typed dispatch through [`RateLimitUnit::window_from_suffix`])
16689 // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
16690 // (Duration → str, exposed as one typed dispatch through
16691 // [`RateLimit::canonical_unit`] composed with
16692 // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
16693 // codec's parse arm ([`rate_limit_codec::parse`] via
16694 // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
16695 // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
16696 // and the validate gate ([`AplicacaoSpec::validate_politicas`]
16697 // via [`RateLimit::canonical_unit`]) all key off. A future
16698 // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
16699 // sub-second window) is one variant + one arm per method on the
16700 // closed-set enum; the compiler-enforced exhaustiveness on
16701 // every consumer's `match self` arms picks it up by
16702 // construction. This pin enshrines that both projection
16703 // directions agree on every canonical arm row and neither
16704 // leaks a spurious entry the other doesn't recognize.
16705 //
16706 // Predecessor: this test previously read the two vestigial
16707 // module-private free helpers `rate_limit_window_unit` and
16708 // `rate_limit_window_from_unit` on the `Duration → &str` and
16709 // `&str → Duration` axes; the former was deleted after its
16710 // sole production consumer ([`rate_limit_codec::render`])
16711 // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
16712 // the latter is folded here into the substrate primitive
16713 // [`RateLimitUnit::window_from_suffix`] so both projection
16714 // directions live on the closed-set enum's arm-table.
16715 for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
16716 let window = super::RateLimitUnit::window_from_suffix(unit)
16717 .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
16718 assert_eq!(
16719 window,
16720 Duration::from_secs(secs),
16721 "unit {unit:?} must resolve to {secs}s"
16722 );
16723 let projected_suffix = RateLimit { rate: 1, window }
16724 .canonical_unit()
16725 .map(super::RateLimitUnit::as_suffix);
16726 assert_eq!(
16727 projected_suffix,
16728 Some(unit),
16729 "Duration({secs}s) must render as {unit:?} \
16730 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
16731 );
16732 }
16733 // Non-table units yield None on the `unit → Duration`
16734 // projection — a future `"d"` addition to the table would
16735 // flip this arm; today it pins the current three-row table's
16736 // rejection semantics.
16737 assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
16738 assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
16739 assert!(super::RateLimitUnit::window_from_suffix("").is_none());
16740 // Non-table Durations yield None on the `Duration → unit`
16741 // projection — pins that the two projections agree on the
16742 // "not in the table" semantic too, so a drift where the
16743 // parse-side accepts a value the render-side can't emit is
16744 // a build error at the two-arm pair, not a silent codec
16745 // round-trip break.
16746 let projected_suffix = |window: Duration| -> Option<&'static str> {
16747 RateLimit { rate: 1, window }
16748 .canonical_unit()
16749 .map(super::RateLimitUnit::as_suffix)
16750 };
16751 assert!(projected_suffix(Duration::from_secs(2)).is_none());
16752 assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
16753 assert!(projected_suffix(Duration::from_millis(1500)).is_none());
16754 }
16755
16756 #[test]
16757 fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
16758 // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
16759 // substrate-primitive `&str → Duration` associated method the
16760 // codec's parse arm ([`rate_limit_codec::parse`]) now routes
16761 // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
16762 // to the same [`Duration`] the two-step composition
16763 // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
16764 // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
16765 // `"MIN"`) must project to [`None`] on both paths. A future
16766 // implementation of `window_from_suffix` that took a shortcut
16767 // through a per-suffix `match` table (bypassing the arm-table's
16768 // `Self::from_suffix` scan and the arm-table's `Self::window`
16769 // dispatch) would silently split the accept-set — the parse
16770 // arm would accept a suffix the enum's arm-table doesn't know,
16771 // or reject a suffix the enum's arm-table does; this pin
16772 // surfaces that drift at caixa-core build time rather than at a
16773 // downstream serde round-trip audit on a live `MeshPolicy`.
16774 //
16775 // Same byte-parity discipline the sibling
16776 // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
16777 // pin carries on the peer `Duration → RateLimitUnit` axis via
16778 // [`RateLimit::canonical_unit`], and the peer
16779 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
16780 // carries on the bidirectional arm-table axis — extended here
16781 // onto the fifth (and last unlifted) projection axis on the
16782 // closed-set enum's arm-table.
16783 let composition = |suffix: &str| -> Option<Duration> {
16784 super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
16785 };
16786 for suffix in ["s", "m", "h"] {
16787 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
16788 let via_composition = composition(suffix);
16789 assert_eq!(
16790 via_method, via_composition,
16791 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
16792 from_suffix({suffix:?}).map(window) — the substrate-primitive \
16793 method must delegate to the arm-table's two typed dispatches, \
16794 not shortcut through a per-suffix match table"
16795 );
16796 assert!(
16797 via_method.is_some(),
16798 "canonical suffix {suffix:?} must resolve to Some(Duration) via \
16799 RateLimitUnit::window_from_suffix"
16800 );
16801 }
16802 for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
16803 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
16804 let via_composition = composition(suffix);
16805 assert_eq!(
16806 via_method, via_composition,
16807 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
16808 from_suffix({suffix:?}).map(window) on the non-arm rejection \
16809 axis too"
16810 );
16811 assert!(
16812 via_method.is_none(),
16813 "non-arm suffix {suffix:?} must project to None via \
16814 RateLimitUnit::window_from_suffix — a future extension that \
16815 accepted this suffix without a corresponding arm on the enum \
16816 would split the codec's parse-accepted set from the enum's \
16817 arm-table"
16818 );
16819 }
16820 // And the codec's parse arm now reads through this method: a
16821 // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
16822 // the same `Duration` the method returns for its unit, closing
16823 // the two-consumer drift surface (the codec's parse arm and the
16824 // enum's arm-table) with one typed dispatch on the substrate
16825 // primitive.
16826 for suffix in ["s", "m", "h"] {
16827 let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
16828 let mp: MeshPolicy = serde_json::from_str(&wire)
16829 .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
16830 let parsed = mp.rate_limit().expect("rate_limit payload present");
16831 let via_method = super::RateLimitUnit::window_from_suffix(suffix)
16832 .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
16833 assert_eq!(
16834 parsed.window(),
16835 via_method,
16836 "codec parse arm on {wire:?} must resolve the window through \
16837 RateLimitUnit::window_from_suffix, not a divergent path"
16838 );
16839 }
16840 }
16841
16842 #[test]
16843 fn rate_limit_unit_all_enumerates_every_arm_once() {
16844 // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
16845 // enumerate every arm of the closed-set enum exactly once, in
16846 // the canonical shortest-to-longest window order (Second before
16847 // Minute before Hour) — the same order the sibling
16848 // [`crate::supervisor::RestartStrategy`] /
16849 // [`crate::supervisor::RestartPolicy`] /
16850 // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
16851 // typed enums carry (the arm declared first is the arm listed
16852 // first). A future variant addition that extends the enum
16853 // without appending to [`RateLimitUnit::ALL`] leaves the
16854 // exhaustive iteration surface silently short one arm — the
16855 // codec's parse arm would then reject the new suffix even
16856 // though the enum knows it. This pin closes the drift.
16857 assert_eq!(
16858 super::RateLimitUnit::ALL,
16859 &[
16860 super::RateLimitUnit::Second,
16861 super::RateLimitUnit::Minute,
16862 super::RateLimitUnit::Hour,
16863 ],
16864 "RateLimitUnit::ALL must enumerate every arm exactly once, \
16865 in canonical shortest-to-longest window order"
16866 );
16867 }
16868
16869 #[test]
16870 fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
16871 // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
16872 // every arm's [`RateLimitUnit::as_suffix`] output must parse
16873 // back through [`RateLimitUnit::from_suffix`] to the same
16874 // variant. A future arm addition that lands `as_suffix` but
16875 // forgets `from_suffix` (`from_suffix` iterates
16876 // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
16877 // is the load-bearing carrier of the round-trip; the sibling
16878 // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
16879 // the `ALL` half) trips here at caixa-core build time rather
16880 // than surfacing as a codec round-trip miss (a `render` emit
16881 // that lands a suffix the paired `parse` cannot decode).
16882 for unit in super::RateLimitUnit::ALL {
16883 let suffix = unit.as_suffix();
16884 let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
16885 panic!(
16886 "RateLimitUnit::from_suffix({suffix:?}) must accept every \
16887 RateLimitUnit::as_suffix output — got None for {unit:?}"
16888 )
16889 });
16890 assert_eq!(
16891 parsed, *unit,
16892 "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
16893 must return RateLimitUnit::{unit:?}"
16894 );
16895 }
16896 }
16897
16898 #[test]
16899 fn rate_limit_unit_from_window_and_window_round_trip() {
16900 // Total round-trip pin on the `(from_window, window)` pair:
16901 // every arm's [`RateLimitUnit::window`] output must parse back
16902 // through [`RateLimitUnit::from_window`] to the same variant.
16903 // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
16904 // on the peer `Duration` axis — the two round-trip pins
16905 // together enshrine that both projections of the typed
16906 // canonical-unit bijection are total on the arm-set.
16907 for unit in super::RateLimitUnit::ALL {
16908 let window = unit.window();
16909 let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
16910 panic!(
16911 "RateLimitUnit::from_window({window:?}) must accept every \
16912 RateLimitUnit::window output — got None for {unit:?}"
16913 )
16914 });
16915 assert_eq!(
16916 parsed, *unit,
16917 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
16918 must return RateLimitUnit::{unit:?}"
16919 );
16920 }
16921 }
16922
16923 #[test]
16924 fn rate_limit_unit_from_window_accessor_is_const_fn() {
16925 // Fail-before-pass-after pin: witnesses the
16926 // [`RateLimitUnit::from_window`] `const`-eval posture via a
16927 // `const fn` wrapper `from_window_via_const_fn(window: Duration)
16928 // -> Option<RateLimitUnit>` whose body calls
16929 // `RateLimitUnit::from_window(window)`, well-formed only when
16930 // the callee is itself `const fn` (any future downgrade to
16931 // non-`const` fails at caixa-core build time with E0015 `cannot
16932 // call non-const function`, strictly stronger than a runtime
16933 // `assert!`, side-stepping the destructor-in-const restriction
16934 // that blocks direct `const _: Option<RateLimitUnit> =
16935 // RateLimitUnit::from_window(...)` items on `Duration`'s
16936 // carrier). The runtime body sweeps every closed-set
16937 // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
16938 // rejection sample (`Duration::from_millis(500)` sub-second
16939 // residue) and asserts the wrapped and direct dispatches agree
16940 // — a violation means the wrapper stopped compiling under a
16941 // future `const`-posture downgrade, or the reverse resolver's
16942 // arm-set silently split from the peer `Self::window` emitter's
16943 // arm-set. Peer of the sibling
16944 // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
16945 // (152c868) /
16946 // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
16947 // (152c868) /
16948 // [`entrada_port_accessor_is_const_fn`] (bafa004) /
16949 // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
16950 // `const`-eval-surface pins on the peer M2 / M3 substrate-
16951 // primitive `Copy`-return accessor axes, extended onto the
16952 // reverse `Duration → RateLimitUnit` projection axis on the
16953 // M3 mesh-slot rate-limit closed-set typed enum.
16954 const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
16955 super::RateLimitUnit::from_window(window)
16956 }
16957 for unit in super::RateLimitUnit::ALL {
16958 let window = unit.window();
16959 let via_wrapper = from_window_via_const_fn(window);
16960 let direct = super::RateLimitUnit::from_window(window);
16961 assert_eq!(
16962 via_wrapper, direct,
16963 "RateLimitUnit::from_window({window:?}) via const fn \
16964 wrapper must agree with direct dispatch for {unit:?}"
16965 );
16966 assert_eq!(
16967 via_wrapper,
16968 Some(*unit),
16969 "RateLimitUnit::from_window({window:?}) via const fn \
16970 wrapper must return Some({unit:?}) for the peer \
16971 window() output"
16972 );
16973 }
16974 assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
16975 assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
16976 }
16977
16978 #[test]
16979 fn rate_limit_unit_from_window_composes_through_window_accessor() {
16980 // Composition-witness pin on the routing-through-peer discipline:
16981 // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
16982 // through the peer `pub const fn` [`RateLimitUnit::window`]
16983 // canonical-`Duration` projection rather than a hand-authored
16984 // per-arm second-magnitude literal — a future arm-magnitude edit
16985 // on the sibling `window()` accessor (a `Second → 2s` typo, a
16986 // `Hour → 3599s` off-by-one) must therefore reach this reverse
16987 // resolver by construction. A pin that hard-coded the three
16988 // second-magnitudes here would silently split from the peer
16989 // emitter on any such edit; instead, this pin asserts the
16990 // composition invariant `from_window(u.window()) == Some(u)`
16991 // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
16992 // arm — a violation means either the peer `Self::window`
16993 // accessor drifted (breaking every downstream consumer that
16994 // reads through it), or the reverse resolver stopped routing
16995 // through the peer (introducing a hand-authored literal that
16996 // silently disagrees with the emitter). Either failure is a
16997 // caixa-core-build-time surface, not a downstream renderer
16998 // round-trip regression.
16999 //
17000 // Peer of the sibling
17001 // [`crate::render::assert_str_reexport_identity`] discipline on
17002 // the substrate-primitive `&'static str` re-export axis and the
17003 // [`rate_limit_unit_from_window_and_window_round_trip`]
17004 // round-trip pin on the peer projection direction; extends the
17005 // one-canonical-dispatch-per-projection discipline onto the
17006 // reverse-resolver's per-arm probe axis.
17007 for unit in super::RateLimitUnit::ALL {
17008 let window_via_peer = unit.window();
17009 let resolved = super::RateLimitUnit::from_window(window_via_peer);
17010 assert_eq!(
17011 resolved,
17012 Some(*unit),
17013 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17014 must return Some({unit:?}) — the reverse resolver's per-arm \
17015 probes must route through the peer `Self::window` accessor \
17016 so any future arm-magnitude edit reaches both projection \
17017 directions by construction"
17018 );
17019 }
17020 }
17021
17022 #[test]
17023 fn rate_limit_canonical_unit_accessor_is_const_fn() {
17024 // Fail-before-pass-after pin: witnesses the
17025 // [`RateLimit::canonical_unit`] `const`-eval posture via a
17026 // `const fn` wrapper
17027 // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
17028 // whose body calls `rl.canonical_unit()`, well-formed only when
17029 // the callee is itself `const fn` (any future downgrade to
17030 // non-`const` fails at caixa-core build time with E0015 `cannot
17031 // call non-const method`). The runtime body sweeps every
17032 // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
17033 // constructs a typed [`RateLimit`] with the peer `Self::window`
17034 // canonical `Duration`, then asserts both the wrapper and the
17035 // direct dispatch agree and both return `Some(unit)`. Composes
17036 // with the sibling
17037 // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
17038 // typed [`RateLimit`] projection layer's `const`-posture is
17039 // load-bearing on the reverse resolver's `const`-posture, and
17040 // both must migrate together (a downgrade of either surface
17041 // splits the paired `const`-eval-surface pass on the M3
17042 // mesh-slot rate-limit `Duration ↔ Self` bijection).
17043 const fn canonical_unit_via_const_fn(
17044 rl: &super::RateLimit,
17045 ) -> Option<super::RateLimitUnit> {
17046 rl.canonical_unit()
17047 }
17048 for unit in super::RateLimitUnit::ALL {
17049 let rl = super::RateLimit {
17050 rate: 1,
17051 window: unit.window(),
17052 };
17053 let via_wrapper = canonical_unit_via_const_fn(&rl);
17054 let direct = rl.canonical_unit();
17055 assert_eq!(
17056 via_wrapper, direct,
17057 "RateLimit::canonical_unit() via const fn wrapper must \
17058 agree with direct dispatch for {unit:?}"
17059 );
17060 assert_eq!(
17061 via_wrapper,
17062 Some(*unit),
17063 "RateLimit::canonical_unit() via const fn wrapper must \
17064 return Some({unit:?}) for a RateLimit whose window is \
17065 the peer RateLimitUnit::{unit:?}.window() output"
17066 );
17067 }
17068 }
17069
17070 #[test]
17071 fn rate_limit_unit_projections_are_pairwise_distinct() {
17072 // Distinctness pin: [`RateLimitUnit::as_suffix`] and
17073 // [`RateLimitUnit::window`] outputs must be pairwise distinct
17074 // across every arm — an accidental copy-paste flip that
17075 // reroutes one arm's suffix or window to also match another
17076 // silently collapses two arms onto one, so
17077 // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
17078 // (both using `find` on `Self::ALL`) would return whichever
17079 // arm the linear scan lands on first — a match-arm-ordering-
17080 // dependent outcome the closed-set typed-enum shape is meant
17081 // to rule out structurally. Peer of the sibling
17082 // `caixa_kind_wire_consts_are_pairwise_distinct` /
17083 // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
17084 // other closed-set typed-enum discriminator axes.
17085 let all = super::RateLimitUnit::ALL;
17086 for (i, a) in all.iter().enumerate() {
17087 for (j, b) in all.iter().enumerate() {
17088 if i != j {
17089 assert_ne!(
17090 a.as_suffix(),
17091 b.as_suffix(),
17092 "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
17093 must be distinct — a collision silently collapses two \
17094 arms onto one under from_suffix's linear scan"
17095 );
17096 assert_ne!(
17097 a.window(),
17098 b.window(),
17099 "RateLimitUnit::{a:?}.window() and {b:?}.window() \
17100 must be distinct — a collision silently collapses two \
17101 arms onto one under from_window's linear scan"
17102 );
17103 }
17104 }
17105 }
17106 }
17107
17108 #[test]
17109 fn rate_limit_unit_display_routes_through_as_suffix() {
17110 // Route pin: [`std::fmt::Display`] must byte-equal
17111 // [`RateLimitUnit::as_suffix`] on every arm — the single
17112 // source of truth for the canonical suffix. A future
17113 // reimplementation that hand-rolls the arms instead of
17114 // delegating to [`RateLimitUnit::as_suffix`] would silently
17115 // desynchronize `format!("{u}")` from the codec's parse arm
17116 // (which uses `as_suffix` to compare suffixes). Peer of the
17117 // sibling `caixa_kind_display_routes_through_as_str_helper` /
17118 // `placement_strategy_display_routes_through_as_str_helper`
17119 // pins on the peer closed-set typed-enum Display axes.
17120 for unit in super::RateLimitUnit::ALL {
17121 assert_eq!(
17122 unit.to_string(),
17123 unit.as_suffix(),
17124 "RateLimitUnit::{unit:?} Display must route through \
17125 as_suffix (single source of truth: the canonical suffix \
17126 the codec parses and renders)"
17127 );
17128 }
17129 }
17130
17131 #[test]
17132 fn rate_limit_unit_from_window_rejects_non_canonical() {
17133 // Rejection pin on the parser's accept-set: any Duration
17134 // outside the three-arm [`RateLimitUnit::window`] output set
17135 // (sub-second residue, or a second-magnitude outside `{1, 60,
17136 // 3600}`) must return `None`. A future accidental widening of
17137 // the accept-set (rounding down sub-second residue to the
17138 // nearest arm, admitting `Duration::from_secs(30)` as a
17139 // half-minute unit) would silently drift the parser's accept-
17140 // set from the emitter's — a validated slot with a
17141 // non-canonical window would then round-trip through the
17142 // codec to a canonical form the author never wrote.
17143 assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
17144 assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
17145 assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
17146 assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
17147 assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
17148 assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
17149 assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
17150 }
17151
17152 #[test]
17153 fn rate_limit_unit_from_suffix_rejects_unknown() {
17154 // Rejection pin on the suffix parser's accept-set: any string
17155 // outside the three-arm [`RateLimitUnit::as_suffix`] output
17156 // set must return `None`. Peer of the sibling
17157 // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
17158 // the [`crate::CaixaKind`] `from_wire` accept-set.
17159 for bad in [
17160 "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
17161 " s",
17162 ] {
17163 assert!(
17164 super::RateLimitUnit::from_suffix(bad).is_none(),
17165 "RateLimitUnit::from_suffix({bad:?}) must return None — the \
17166 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
17167 outputs"
17168 );
17169 }
17170 }
17171
17172 #[test]
17173 fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
17174 // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
17175 // every canonical `:window` magnitude the validate gate
17176 // accepts must map to the paired [`RateLimitUnit`] arm through
17177 // this accessor. A future validate-gate rebrand that widened
17178 // the accepted-window set without extending [`RateLimitUnit`]
17179 // would silently split the accessor's `Some`-return set from
17180 // the validate gate's accept-set — a slot that satisfies
17181 // validate would land at the accessor with `None`, so a
17182 // consumer past validate that pattern-matches on the returned
17183 // `Some` would silently miss the newly-accepted magnitude.
17184 for (window_secs, expected) in [
17185 (1u64, super::RateLimitUnit::Second),
17186 (60, super::RateLimitUnit::Minute),
17187 (3600, super::RateLimitUnit::Hour),
17188 ] {
17189 let rl = RateLimit {
17190 rate: 100,
17191 window: Duration::from_secs(window_secs),
17192 };
17193 assert_eq!(
17194 rl.canonical_unit(),
17195 Some(expected),
17196 "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
17197 must return Some({expected:?})"
17198 );
17199 }
17200 // Non-canonical windows the validate gate rejects also return
17201 // None here — the accessor is the typed-enum projection of
17202 // the sibling `is_canonical_rate_limit_window` predicate.
17203 let bad = RateLimit {
17204 rate: 100,
17205 window: Duration::from_secs(30),
17206 };
17207 assert!(
17208 bad.canonical_unit().is_none(),
17209 "RateLimit with a non-canonical window must return None from \
17210 canonical_unit — the validate gate rejects the same set"
17211 );
17212 }
17213
17214 #[test]
17215 fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
17216 // Fail-before-pass-after byte-parity pin: for every canonical
17217 // window the [`rate_limit_codec::render`] arm's emitted string
17218 // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
17219 // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
17220 // the vestigial free helper [`rate_limit_window_unit`] (a
17221 // `find_map`-walked `Duration → &'static str` delegate) onto the
17222 // substrate primitive [`RateLimit::canonical_unit`] typed method
17223 // (a closed-set `match self.window` arm on
17224 // [`RateLimitUnit::from_window`], projected through
17225 // [`RateLimitUnit::as_suffix`] via the enum's
17226 // [`std::fmt::Display`] impl). A future re-routing of the render
17227 // arm through a differently-computed unit projection would break
17228 // this pin at build time rather than as a silent per-consumer
17229 // codec round-trip drift far from the substrate primitive edit.
17230 //
17231 // Sibling to the peer
17232 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17233 // on the free-helper axis: that pin locks the two projections
17234 // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
17235 // on the closed-set arm table; this pin locks the codec's render
17236 // arm reads through the typed accessor rather than the free
17237 // helper. Two production consumers of the canonical-unit axis
17238 // now key off one typed dispatch on the substrate primitive.
17239 for (window_secs, unit) in [
17240 (1u64, super::RateLimitUnit::Second),
17241 (60, super::RateLimitUnit::Minute),
17242 (3600, super::RateLimitUnit::Hour),
17243 ] {
17244 let rl = RateLimit {
17245 rate: 42,
17246 window: Duration::from_secs(window_secs),
17247 };
17248 let policy = MeshPolicy {
17249 rate_limit: Some(rl),
17250 ..Default::default()
17251 };
17252 let json = serde_json::to_string(&policy).unwrap();
17253 let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
17254 assert!(
17255 json.contains(&expected),
17256 "rate_limit_codec::render must emit {expected} (via \
17257 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
17258 for a {window_secs}s window; serialized MeshPolicy was: {json}"
17259 );
17260 // And the accessor route resolves to the same typed unit
17261 // the render arm's Display formatting is asked to produce —
17262 // so a future edit that split the two paths (one through
17263 // the accessor, one through a re-introduced free helper)
17264 // trips this pin.
17265 assert_eq!(
17266 rl.canonical_unit(),
17267 Some(unit),
17268 "RateLimit::canonical_unit must return Some({unit:?}) for a \
17269 {window_secs}s window; the codec render arm reads the same \
17270 typed unit through this accessor"
17271 );
17272 }
17273 }
17274
17275 #[test]
17276 fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
17277 // Fail-before-pass-after byte-parity pin on the validate gate's
17278 // canonical-window shape probe: every non-canonical `:window`
17279 // the free-helper predicate [`is_canonical_rate_limit_window`]
17280 // rejects is also rejected by the substrate primitive
17281 // [`RateLimit::canonical_unit`] `.is_none()` route the validate
17282 // gate now reads through, and vice versa on the accepted set
17283 // (the three canonical windows). Locks the migration from the
17284 // free helper onto the substrate primitive: a future re-routing
17285 // of one of the two paths through a differently-computed unit
17286 // projection would silently split the codec's accepted set from
17287 // the validate gate's accepted set — a two-consumer drift the
17288 // codec-round-trip pin
17289 // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
17290 // above closes on the render arm and this pin closes on the
17291 // validate arm.
17292 for canonical_window_secs in [1u64, 60, 3600] {
17293 let mut s = three_member_spec();
17294 let rl = RateLimit {
17295 rate: 100,
17296 window: Duration::from_secs(canonical_window_secs),
17297 };
17298 s.politicas.rate_limit = Some(rl);
17299 assert!(
17300 s.validate().is_ok(),
17301 "canonical {canonical_window_secs}s window must pass \
17302 validate_politicas — the validate gate now reads \
17303 RateLimit::canonical_unit().is_none() and the accessor \
17304 returns Some on every canonical arm"
17305 );
17306 assert!(
17307 rl.canonical_unit().is_some(),
17308 "canonical {canonical_window_secs}s window must resolve to \
17309 Some on RateLimit::canonical_unit — the validate gate reads \
17310 this accessor directly"
17311 );
17312 }
17313 for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
17314 let mut s = three_member_spec();
17315 let rl = RateLimit {
17316 rate: 100,
17317 window: Duration::from_secs(non_canonical_window_secs),
17318 };
17319 s.politicas.rate_limit = Some(rl);
17320 assert_eq!(
17321 s.validate().unwrap_err(),
17322 AplicacaoError::PolicyRateLimitWindowNotCanonical {
17323 window: rl.window(),
17324 },
17325 "non-canonical {non_canonical_window_secs}s window must be \
17326 rejected by validate_politicas — the validate gate now \
17327 keys off RateLimit::canonical_unit().is_none()"
17328 );
17329 assert!(
17330 rl.canonical_unit().is_none(),
17331 "non-canonical {non_canonical_window_secs}s window must \
17332 resolve to None on RateLimit::canonical_unit — the two \
17333 paths (the free helper the validate gate previously read \
17334 and the substrate primitive the validate gate now reads) \
17335 must agree on the same rejected set"
17336 );
17337 }
17338 // And the substrate-primitive [`RateLimit::canonical_unit`]
17339 // accessor's accepted-window set matches the codec's parse arm's
17340 // accepted-suffix set on every canonical / non-canonical shape,
17341 // so a future silent drift between the codec's accepted set and
17342 // the validate gate's accepted set is a build error at test time
17343 // (both consumers key off the same closed-set enum's `match self`
17344 // arms). The predecessor free helper `is_canonical_rate_limit_window`
17345 // — a delegate that composed [`RateLimitUnit::from_window`] with
17346 // `.is_some()` — was deleted after this migration; the
17347 // canonical-window set now lives on exactly one typed dispatch
17348 // on the substrate primitive.
17349 for (secs, expected) in [
17350 (1u64, true),
17351 (60, true),
17352 (3600, true),
17353 (2, false),
17354 (30, false),
17355 (86_400, false),
17356 ] {
17357 let window = Duration::from_secs(secs);
17358 let rl = RateLimit { rate: 1, window };
17359 assert_eq!(
17360 rl.canonical_unit().is_some(),
17361 expected,
17362 "RateLimit::canonical_unit().is_some() must agree with the \
17363 codec-accepted canonical-window set on {secs}s"
17364 );
17365 let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
17366 1 => "s",
17367 60 => "m",
17368 3600 => "h",
17369 _ => return,
17370 })
17371 .is_some_and(|d| d == window);
17372 if expected {
17373 assert!(
17374 suffix_from_axis,
17375 "the codec's `&str → Duration` axis \
17376 ({secs}s) must round-trip to the same Duration the \
17377 substrate primitive's accessor returns Some on"
17378 );
17379 }
17380 }
17381 }
17382
17383 #[test]
17384 fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
17385 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
17386 // derive: for each of the three variants, exactly one of the
17387 // generated `is_second` / `is_minute` / `is_hour` predicates
17388 // returns `true` and the other two return `false`. Peer of
17389 // the sibling
17390 // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
17391 // sibling `IsVariant`-derived closed-set typed-enum pins.
17392 let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
17393 (super::RateLimitUnit::Second, [true, false, false]),
17394 (super::RateLimitUnit::Minute, [false, true, false]),
17395 (super::RateLimitUnit::Hour, [false, false, true]),
17396 ];
17397 for (variant, expected) in rows {
17398 let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
17399 assert_eq!(
17400 observed, expected,
17401 "RateLimitUnit::{variant:?} is_* predicates must partition \
17402 the arm set (second, minute, hour); got {observed:?}"
17403 );
17404 }
17405 }
17406
17407 #[test]
17408 fn rejects_policy_timeout_sub_millisecond() {
17409 // A purely sub-millisecond `Duration` (`from_micros(500)` =
17410 // 500_000 ns) is not the zero `Duration` — the `is_zero()`
17411 // arm passes — but `as_millis() == 0`, so the shared codec's
17412 // `render` arm returns the literal `"0s"`, which the
17413 // codec's `parse` arm then deserializes as `Duration::ZERO`
17414 // and the `PolicyTimeoutZero` zero-floor gate would reject
17415 // on re-validate. Pin the rejection at the typed slot's
17416 // canonical-floor gate so the round-trip break surfaces at
17417 // validate time, naming the offending `Duration`, rather
17418 // than at the next serialize → deserialize round-trip far
17419 // from the source `caixa.lisp`.
17420 let mut s = three_member_spec();
17421 let timeout = Duration::from_micros(500);
17422 s.politicas.timeout = Some(timeout);
17423 assert_eq!(
17424 s.validate().unwrap_err(),
17425 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
17426 );
17427 }
17428
17429 #[test]
17430 fn rejects_policy_timeout_non_integer_millisecond() {
17431 // A `Duration` with non-integer-millisecond residue
17432 // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
17433 // through the shared codec's `render` arm as `"1ms"` (the
17434 // `as_millis()` floor truncates), which the codec's `parse`
17435 // arm then deserializes as `Duration::from_millis(1)` =
17436 // 1_000_000 ns — silently *different* from the original.
17437 // Pin the rejection so this round-trip break surfaces at
17438 // validate time, where the offending `Duration` is named,
17439 // rather than as a silent value-laundered round-trip on the
17440 // next codec round-trip.
17441 let mut s = three_member_spec();
17442 let timeout = Duration::from_micros(1500);
17443 s.politicas.timeout = Some(timeout);
17444 assert_eq!(
17445 s.validate().unwrap_err(),
17446 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
17447 );
17448 }
17449
17450 #[test]
17451 fn accepts_policy_timeout_integer_millisecond_forms() {
17452 // The codec's accepted set — integer multiples of 1ms — is
17453 // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
17454 // `1h` all pass the canonical gate. Pin the canonical-forms
17455 // sweep so a future tightening of the codec's grammar (e.g.
17456 // dropping `:ms`) surfaces here as a test failure rather
17457 // than a silent contract narrowing on the typed slot.
17458 for timeout in [
17459 Duration::from_millis(1),
17460 Duration::from_millis(500),
17461 Duration::from_millis(1500),
17462 Duration::from_secs(30),
17463 Duration::from_secs(120),
17464 Duration::from_secs(3600),
17465 ] {
17466 let mut s = three_member_spec();
17467 s.politicas.timeout = Some(timeout);
17468 s.validate()
17469 .expect("integer-millisecond :timeout must validate");
17470 }
17471 }
17472
17473 #[test]
17474 fn policy_timeout_zero_takes_precedence_over_canonical() {
17475 // `Duration::ZERO` carries `subsec_nanos() == 0` and would
17476 // pass the canonical-millisecond gate; the more self-locating
17477 // `PolicyTimeoutZero` arm (which names the omit-axis
17478 // remediation directly) must fire first. Pin the ordering so
17479 // a future refactor that reorders the arms surfaces here as a
17480 // test failure rather than a silent diagnostic regression.
17481 let mut s = three_member_spec();
17482 s.politicas.timeout = Some(Duration::ZERO);
17483 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
17484 }
17485
17486 #[test]
17487 fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
17488 // The diagnostic envelope carries the offending `Duration`
17489 // verbatim so the author can grep their `caixa.lisp` for
17490 // `:timeout "<value>"` and fix it in one edit. Same
17491 // diagnostic shape every other typed-slot canonical-form
17492 // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
17493 // peer `:rate-limit :window` axis.
17494 let mut s = three_member_spec();
17495 let timeout = Duration::from_nanos(1_000_001);
17496 s.politicas.timeout = Some(timeout);
17497 match s.validate().unwrap_err() {
17498 AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
17499 assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
17500 }
17501 other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
17502 }
17503 }
17504
17505 #[test]
17506 fn rejects_policy_timeout_above_cap() {
17507 // The fail-before-pass-after pin: 3601s = 1h + 1s is
17508 // structurally one canonical-tick past the
17509 // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
17510 // integer-millisecond magnitude the canonical-form arm above
17511 // accepts cleanly, that the codec round-trips losslessly as
17512 // `"3601s"`, and that silently passed validate on every
17513 // pre-gate codebase because the typed slot's only checks were
17514 // the zero-floor and canonical-form arms. The mesh-level
17515 // deadline degenerates only at the runtime substrate (Envoy
17516 // / Cilium L7 timeout overlay) far from the source
17517 // `caixa.lisp` with no field naming the offending policy.
17518 let mut s = three_member_spec();
17519 let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
17520 s.politicas.timeout = Some(timeout);
17521 assert_eq!(
17522 s.validate().unwrap_err(),
17523 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17524 );
17525 }
17526
17527 #[test]
17528 fn rejects_policy_timeout_one_millisecond_above_cap() {
17529 // Boundary case: exactly 1ms past the cap (the granularity
17530 // the canonical-form gate enforces). Catches a future
17531 // "strictly less than" half-measure and pins the diagnostic
17532 // to name the offending `Duration` verbatim. Peer of
17533 // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
17534 // boundary pin on the sibling `:limits :memory` top edge.
17535 let mut s = three_member_spec();
17536 let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
17537 s.politicas.timeout = Some(timeout);
17538 assert_eq!(
17539 s.validate().unwrap_err(),
17540 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17541 );
17542 }
17543
17544 #[test]
17545 fn rejects_policy_timeout_far_above_cap() {
17546 // The "obvious authoring footgun" case: a `(:timeout "24h")`
17547 // or `(:timeout "86400s")` — values the canonical-form arm
17548 // accepts as integer-millisecond magnitudes, the codec
17549 // round-trips losslessly through serde, but the mesh-level
17550 // policy cannot honor (a 24-hour synchronous-`:contratos`
17551 // deadline is operationally indistinguishable from
17552 // omit-the-axis). Until this gate landed validate accepted
17553 // it. Pin both common above-cap values (24h, 7d) so a future
17554 // relaxation that drops the upper bound surfaces here.
17555 for timeout in [
17556 Duration::from_secs(86_400), // 24h
17557 Duration::from_secs(604_800), // 7d
17558 Duration::from_secs(1_000_000), // ~11.5 days
17559 ] {
17560 let mut s = three_member_spec();
17561 s.politicas.timeout = Some(timeout);
17562 assert_eq!(
17563 s.validate().unwrap_err(),
17564 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17565 );
17566 }
17567 }
17568
17569 #[test]
17570 fn accepts_policy_timeout_at_cap() {
17571 // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
17572 // must validate. The cap is inclusive on the top edge,
17573 // matching the [`POLICY_RETRIES_MAX`] /
17574 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
17575 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
17576 // sibling capped axes. Pin the boundary explicitly so a
17577 // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
17578 // instead of `>`) surfaces here as a test failure rather
17579 // than a silent contract narrowing.
17580 let mut s = three_member_spec();
17581 s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
17582 s.validate()
17583 .expect("timeout == POLICY_TIMEOUT_MAX must validate");
17584 }
17585
17586 #[test]
17587 fn accepts_policy_timeout_typical_values() {
17588 // The documented production-playbook band positive-control
17589 // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
17590 // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
17591 // plus a sweep through the long-running-workflow band
17592 // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
17593 // validated set explicitly so a future tightening of the
17594 // ceiling surfaces here as a deliberate test edit, not a
17595 // silent contract narrowing.
17596 for timeout in [
17597 Duration::from_millis(1),
17598 Duration::from_millis(500),
17599 Duration::from_secs(1),
17600 Duration::from_secs(10),
17601 Duration::from_secs(15), // Envoy default
17602 Duration::from_secs(30),
17603 Duration::from_secs(60), // AWS App Mesh typical
17604 Duration::from_secs(300),
17605 Duration::from_secs(900),
17606 Duration::from_secs(1800),
17607 Duration::from_secs(3600), // exactly 1h, the cap
17608 ] {
17609 let mut s = three_member_spec();
17610 s.politicas.timeout = Some(timeout);
17611 s.validate()
17612 .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
17613 }
17614 }
17615
17616 #[test]
17617 fn policy_timeout_zero_takes_precedence_over_cap() {
17618 // The cross-arm ordering pin: `Duration::ZERO` is
17619 // structurally outside both `>= 1ms` (zero-floor) and
17620 // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
17621 // diagnostic is the more self-locating one (it directly
17622 // names the omit-axis remediation), so the validate gate
17623 // must fire on zero first. Same shape every other
17624 // zero-then-shape ordering on this surface uses
17625 // ([`AplicacaoError::PolicyRetriesZero`] then
17626 // [`AplicacaoError::PolicyRetriesExceedsCap`];
17627 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17628 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17629 let mut s = three_member_spec();
17630 s.politicas.timeout = Some(Duration::ZERO);
17631 assert_eq!(
17632 s.validate().unwrap_err(),
17633 AplicacaoError::PolicyTimeoutZero,
17634 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
17635 );
17636 }
17637
17638 #[test]
17639 fn policy_timeout_canonical_takes_precedence_over_cap() {
17640 // The cross-arm ordering pin: a `Duration` that is *both*
17641 // sub-millisecond (non-canonical-form) and structurally
17642 // above the cap surfaces the canonical-form diagnostic
17643 // first, because the round-trip-shape break is the more
17644 // fundamental issue (the value can't even round-trip
17645 // through the codec, so the cap diagnostic naming
17646 // `1ms..=1h` would be misleading — there's no integer-ms
17647 // form of the offending value). Pin the order so a future
17648 // refactor that reorders the arms surfaces here as a test
17649 // failure rather than a silent diagnostic regression.
17650 let mut s = three_member_spec();
17651 // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
17652 // *and* total magnitude above the 1h cap.
17653 let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
17654 s.politicas.timeout = Some(timeout);
17655 assert_eq!(
17656 s.validate().unwrap_err(),
17657 AplicacaoError::PolicyTimeoutNotCanonical { timeout },
17658 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
17659 );
17660 }
17661
17662 #[test]
17663 fn policy_timeout_cap_diagnostic_carries_offending_value() {
17664 // The diagnostic-shape pin: the offending `Duration` is
17665 // carried verbatim into the
17666 // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
17667 // surfaced error message names the value the author wrote
17668 // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
17669 // exceeds the mesh-policy ceiling …"`), not just the cap.
17670 // Same self-locating diagnostic shape every other typed-cap
17671 // arm on this surface carries
17672 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
17673 // offending retry count verbatim).
17674 let mut s = three_member_spec();
17675 let timeout = Duration::from_secs(7200); // 2h
17676 s.politicas.timeout = Some(timeout);
17677 let err = s.validate().unwrap_err();
17678 assert!(
17679 matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
17680 "got {err:?}"
17681 );
17682 let msg = err.to_string();
17683 assert!(
17684 msg.contains("7200"),
17685 ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
17686 );
17687 }
17688
17689 #[test]
17690 fn policy_timeout_cap_pins_canonical_value() {
17691 // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
17692 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
17693 // the shared duration codec emits as a clean canonical
17694 // string (`"<n>h"`). Pinning the literal value here surfaces
17695 // a future drift (a relaxation to 24h, a tightening to 5m)
17696 // as a deliberate test edit, not a silent contract
17697 // narrowing. Same shape every other typed-cap value pin on
17698 // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
17699 assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
17700 assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
17701 }
17702
17703 #[test]
17704 fn policy_timeout_cap_value_round_trips_through_codec() {
17705 // The codec round-trip property the cap arm preserves: the
17706 // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
17707 // the shared duration codec — every value at the cap renders
17708 // to a clean canonical string (`"1h"`) and parses back to
17709 // the same `Duration`. Pin this so a future drift between
17710 // the cap constant and the codec's largest emitted unit
17711 // surfaces here. Same shape every other typed boundary pin
17712 // on this surface uses
17713 // (`wasm32_memory_cap_matches_parsed_4_gib`).
17714 let policy = MeshPolicy {
17715 timeout: Some(POLICY_TIMEOUT_MAX),
17716 ..Default::default()
17717 };
17718 let json = serde_json::to_string(&policy).unwrap();
17719 // The codec emits `"1h"` for the canonical 1-hour magnitude.
17720 assert!(
17721 json.contains("\"1h\""),
17722 "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
17723 );
17724 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17725 assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
17726 }
17727
17728 #[test]
17729 fn rejects_circuit_breaker_window_sub_millisecond() {
17730 // Peer of the `:timeout` sub-millisecond arm on the second
17731 // typed-`Duration` `:politicas` axis: a purely sub-ms
17732 // `Duration` (`from_micros(500)`) renders through the shared
17733 // codec as `"0s"`, which the codec parses back to
17734 // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
17735 // zero-floor gate then rejects on re-validate.
17736 let mut s = three_member_spec();
17737 let window = Duration::from_micros(500);
17738 s.politicas.circuit_breaker = Some(CircuitBreaker {
17739 max_failures: 5,
17740 window,
17741 });
17742 assert_eq!(
17743 s.validate().unwrap_err(),
17744 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
17745 );
17746 }
17747
17748 #[test]
17749 fn rejects_circuit_breaker_window_non_integer_millisecond() {
17750 // Peer of the `:timeout` non-integer-ms arm: a `Duration`
17751 // with non-integer-millisecond residue renders through the
17752 // shared codec as the truncated `"<n>ms"` form, parsing back
17753 // to a *different* `Duration` on the next round-trip.
17754 let mut s = three_member_spec();
17755 let window = Duration::from_micros(1500);
17756 s.politicas.circuit_breaker = Some(CircuitBreaker {
17757 max_failures: 5,
17758 window,
17759 });
17760 assert_eq!(
17761 s.validate().unwrap_err(),
17762 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
17763 );
17764 }
17765
17766 #[test]
17767 fn accepts_circuit_breaker_window_integer_millisecond_forms() {
17768 // The canonical-forms sweep on the breaker axis: every
17769 // integer-ms multiple the codec round-trips losslessly
17770 // passes the canonical gate.
17771 for window in [
17772 Duration::from_millis(1),
17773 Duration::from_millis(500),
17774 Duration::from_millis(1500),
17775 Duration::from_secs(30),
17776 Duration::from_secs(60),
17777 Duration::from_secs(3600),
17778 ] {
17779 let mut s = three_member_spec();
17780 s.politicas.circuit_breaker = Some(CircuitBreaker {
17781 max_failures: 5,
17782 window,
17783 });
17784 s.validate()
17785 .expect("integer-millisecond :circuit-breaker :window must validate");
17786 }
17787 }
17788
17789 #[test]
17790 fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
17791 // `Duration::ZERO` would pass the canonical-ms gate (the
17792 // sub-ns residue is zero) but must surface the narrower
17793 // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
17794 // remediation.
17795 let mut s = three_member_spec();
17796 s.politicas.circuit_breaker = Some(CircuitBreaker {
17797 max_failures: 5,
17798 window: Duration::ZERO,
17799 });
17800 assert_eq!(
17801 s.validate().unwrap_err(),
17802 AplicacaoError::PolicyBreakerZeroWindow
17803 );
17804 }
17805
17806 #[test]
17807 fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
17808 // Both axes invalid: max_failures == 0 *and* window is
17809 // sub-ms. The validate gate must fire on max_failures first
17810 // (matching the existing ordering pin
17811 // `rejects_circuit_breaker_zero_max_failures` enshrines), so
17812 // the existing diagnostic continues to lead with the simpler
17813 // "zero threshold" framing.
17814 let mut s = three_member_spec();
17815 s.politicas.circuit_breaker = Some(CircuitBreaker {
17816 max_failures: 0,
17817 window: Duration::from_micros(500),
17818 });
17819 assert_eq!(
17820 s.validate().unwrap_err(),
17821 AplicacaoError::PolicyBreakerZeroFailures
17822 );
17823 }
17824
17825 #[test]
17826 fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
17827 let mut s = three_member_spec();
17828 let window = Duration::from_nanos(60_000_000_001);
17829 s.politicas.circuit_breaker = Some(CircuitBreaker {
17830 max_failures: 5,
17831 window,
17832 });
17833 match s.validate().unwrap_err() {
17834 AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
17835 assert_eq!(w, window, "diagnostic must carry the offending Duration");
17836 }
17837 other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
17838 }
17839 }
17840
17841 #[test]
17842 fn rejects_circuit_breaker_window_above_cap() {
17843 // The fail-before-pass-after pin: 3601s = 1h + 1s is
17844 // structurally one canonical-tick past the
17845 // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
17846 // integer-millisecond magnitude the canonical-form arm above
17847 // accepts cleanly, that the codec round-trips losslessly as
17848 // `"3601s"`, and that silently passed validate on every
17849 // pre-gate codebase because the typed slot's only checks were
17850 // the zero-floor and canonical-form arms. The
17851 // rolling-window-to-lifetime-counter degeneration surfaces
17852 // only at the runtime substrate (Envoy's outlier_detection
17853 // interval, the future CiliumClusterwideEnvoyConfig overlay)
17854 // far from the source `caixa.lisp` with no field naming the
17855 // offending policy.
17856 let mut s = three_member_spec();
17857 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
17858 s.politicas.circuit_breaker = Some(CircuitBreaker {
17859 max_failures: 5,
17860 window,
17861 });
17862 assert_eq!(
17863 s.validate().unwrap_err(),
17864 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17865 );
17866 }
17867
17868 #[test]
17869 fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
17870 // Boundary case: exactly 1ms past the cap (the granularity the
17871 // canonical-form gate enforces). Catches a future "strictly
17872 // less than" half-measure and pins the diagnostic to name the
17873 // offending `Duration` verbatim. Peer of
17874 // `rejects_policy_timeout_one_millisecond_above_cap` on the
17875 // sibling duration-typed `:politicas :timeout` top edge.
17876 let mut s = three_member_spec();
17877 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
17878 s.politicas.circuit_breaker = Some(CircuitBreaker {
17879 max_failures: 5,
17880 window,
17881 });
17882 assert_eq!(
17883 s.validate().unwrap_err(),
17884 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17885 );
17886 }
17887
17888 #[test]
17889 fn rejects_circuit_breaker_window_far_above_cap() {
17890 // The "obvious authoring footgun" case: a `(:window "24h")` or
17891 // `(:window "86400s")` — values the canonical-form arm
17892 // accepts as integer-millisecond magnitudes, the codec
17893 // round-trips losslessly through serde, but the
17894 // rolling-window breaker contract cannot honor (a 24-hour
17895 // rolling failure window is operationally a lifetime counter).
17896 // Until this gate landed validate accepted it. Pin both common
17897 // above-cap values (24h, 7d) so a future relaxation that
17898 // drops the upper bound surfaces here.
17899 for window in [
17900 Duration::from_secs(86_400), // 24h
17901 Duration::from_secs(604_800), // 7d
17902 Duration::from_secs(1_000_000), // ~11.5 days
17903 ] {
17904 let mut s = three_member_spec();
17905 s.politicas.circuit_breaker = Some(CircuitBreaker {
17906 max_failures: 5,
17907 window,
17908 });
17909 assert_eq!(
17910 s.validate().unwrap_err(),
17911 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17912 );
17913 }
17914 }
17915
17916 #[test]
17917 fn accepts_circuit_breaker_window_at_cap() {
17918 // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
17919 // (1h) — must validate. The cap is inclusive on the top edge,
17920 // matching the [`POLICY_TIMEOUT_MAX`] /
17921 // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
17922 // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
17923 // sibling capped axes. Pin the boundary explicitly so a
17924 // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
17925 // instead of `>`) surfaces here as a test failure rather than
17926 // a silent contract narrowing.
17927 let mut s = three_member_spec();
17928 s.politicas.circuit_breaker = Some(CircuitBreaker {
17929 max_failures: 5,
17930 window: POLICY_BREAKER_WINDOW_MAX,
17931 });
17932 s.validate()
17933 .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
17934 }
17935
17936 #[test]
17937 fn accepts_circuit_breaker_window_typical_values() {
17938 // The documented production-playbook band positive-control
17939 // sweep — every value Hystrix / resilience4j / Istio / Envoy
17940 // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
17941 // through the long-tail failure-detection band (15m, 30m, 1h)
17942 // the cap accepts. Pin the inclusive validated set explicitly
17943 // so a future tightening of the ceiling surfaces here as a
17944 // deliberate test edit, not a silent contract narrowing.
17945 for window in [
17946 Duration::from_millis(1),
17947 Duration::from_millis(500),
17948 Duration::from_secs(1),
17949 Duration::from_secs(10), // Hystrix / Istio / Envoy default
17950 Duration::from_secs(30),
17951 Duration::from_secs(60), // resilience4j typical
17952 Duration::from_secs(300), // AWS App Mesh typical
17953 Duration::from_secs(900),
17954 Duration::from_secs(1800),
17955 Duration::from_secs(3600), // exactly 1h, the cap
17956 ] {
17957 let mut s = three_member_spec();
17958 s.politicas.circuit_breaker = Some(CircuitBreaker {
17959 max_failures: 5,
17960 window,
17961 });
17962 s.validate()
17963 .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
17964 }
17965 }
17966
17967 #[test]
17968 fn circuit_breaker_zero_window_takes_precedence_over_cap() {
17969 // The cross-arm ordering pin: `Duration::ZERO` is structurally
17970 // outside both `>= 1ms` (zero-floor) and
17971 // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
17972 // diagnostic is the more self-locating one (it directly names
17973 // the omit-axis remediation), so the validate gate must fire
17974 // on zero first. Same shape every other zero-then-cap
17975 // ordering on this surface uses
17976 // ([`AplicacaoError::PolicyTimeoutZero`] then
17977 // [`AplicacaoError::PolicyTimeoutExceedsCap`];
17978 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17979 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17980 let mut s = three_member_spec();
17981 s.politicas.circuit_breaker = Some(CircuitBreaker {
17982 max_failures: 5,
17983 window: Duration::ZERO,
17984 });
17985 assert_eq!(
17986 s.validate().unwrap_err(),
17987 AplicacaoError::PolicyBreakerZeroWindow,
17988 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
17989 );
17990 }
17991
17992 #[test]
17993 fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
17994 // The cross-arm ordering pin: a `Duration` that is *both*
17995 // sub-millisecond (non-canonical-form) and structurally above
17996 // the cap surfaces the canonical-form diagnostic first,
17997 // because the round-trip-shape break is the more fundamental
17998 // issue (the value can't even round-trip through the codec, so
17999 // the cap diagnostic naming `1ms..=1h` would be misleading —
18000 // there's no integer-ms form of the offending value). Pin the
18001 // order so a future refactor that reorders the arms surfaces
18002 // here as a test failure rather than a silent diagnostic
18003 // regression. Peer of
18004 // `policy_timeout_canonical_takes_precedence_over_cap` on the
18005 // sibling duration-typed `:politicas :timeout` axis.
18006 let mut s = three_member_spec();
18007 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
18008 s.politicas.circuit_breaker = Some(CircuitBreaker {
18009 max_failures: 5,
18010 window,
18011 });
18012 assert_eq!(
18013 s.validate().unwrap_err(),
18014 AplicacaoError::PolicyBreakerWindowNotCanonical { window },
18015 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18016 );
18017 }
18018
18019 #[test]
18020 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
18021 // The cross-arm ordering pin between the two breaker axes: a
18022 // `CircuitBreaker` whose *both* `max_failures` is above its
18023 // cap *and* `window` is above its cap surfaces the
18024 // max-failures cap diagnostic first, because the validate
18025 // gate visits the failures arm before the window arm. Pin the
18026 // order so a future refactor that reorders the breaker arms
18027 // surfaces here.
18028 let mut s = three_member_spec();
18029 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18030 s.politicas.circuit_breaker = Some(CircuitBreaker {
18031 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18032 window,
18033 });
18034 assert_eq!(
18035 s.validate().unwrap_err(),
18036 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18037 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
18038 },
18039 "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
18040 );
18041 }
18042
18043 #[test]
18044 fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
18045 // The diagnostic-shape pin: the offending `Duration` is
18046 // carried verbatim into the
18047 // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
18048 // the surfaced error message names the value the author wrote
18049 // (`":politicas :circuit-breaker :window (Duration { secs:
18050 // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
18051 // just the cap. Same self-locating diagnostic shape every
18052 // other typed-cap arm on this surface carries
18053 // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
18054 // offending `Duration` verbatim).
18055 let mut s = three_member_spec();
18056 let window = Duration::from_secs(7200); // 2h
18057 s.politicas.circuit_breaker = Some(CircuitBreaker {
18058 max_failures: 5,
18059 window,
18060 });
18061 let err = s.validate().unwrap_err();
18062 assert!(
18063 matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
18064 "got {err:?}"
18065 );
18066 let msg = err.to_string();
18067 assert!(
18068 msg.contains("7200"),
18069 ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
18070 );
18071 }
18072
18073 #[test]
18074 fn circuit_breaker_window_cap_pins_canonical_value() {
18075 // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
18076 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
18077 // shared duration codec emits as a clean canonical string
18078 // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
18079 // the sibling duration-typed `:politicas :timeout` axis (the
18080 // two duration-typed `:politicas` axes share a uniform top
18081 // edge). Pinning the literal value here surfaces a future
18082 // drift (a relaxation to 24h, a tightening to 5m) as a
18083 // deliberate test edit, not a silent contract narrowing. Same
18084 // shape every other typed-cap value pin on this surface uses
18085 // (`policy_timeout_cap_pins_canonical_value`).
18086 assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
18087 assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
18088 assert_eq!(
18089 POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
18090 "the two duration-typed `:politicas` caps share the same top edge"
18091 );
18092 }
18093
18094 #[test]
18095 fn circuit_breaker_window_cap_value_round_trips_through_codec() {
18096 // The codec round-trip property the cap arm preserves: the
18097 // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
18098 // through the shared duration codec — every value at the cap
18099 // renders to a clean canonical string (`"1h"`) and parses back
18100 // to the same `Duration`. Pin this so a future drift between
18101 // the cap constant and the codec's largest emitted unit
18102 // surfaces here. Same shape every other typed boundary pin on
18103 // this surface uses
18104 // (`policy_timeout_cap_value_round_trips_through_codec`).
18105 let policy = MeshPolicy {
18106 circuit_breaker: Some(CircuitBreaker {
18107 max_failures: 5,
18108 window: POLICY_BREAKER_WINDOW_MAX,
18109 }),
18110 ..Default::default()
18111 };
18112 let json = serde_json::to_string(&policy).unwrap();
18113 // The codec emits `"1h"` for the canonical 1-hour magnitude.
18114 assert!(
18115 json.contains("\"1h\""),
18116 "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
18117 );
18118 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18119 assert_eq!(
18120 back.circuit_breaker.unwrap().window,
18121 POLICY_BREAKER_WINDOW_MAX
18122 );
18123 }
18124
18125 #[test]
18126 fn is_integer_millisecond_duration_predicate_tracks_codec() {
18127 // Pin the predicate's accepted set against the codec's
18128 // accepted set explicitly. The codec parses
18129 // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
18130 // accepted value is an integer-millisecond multiple — so the
18131 // predicate must accept exactly that set. Same shape every
18132 // other predicate-on-the-typed-slot helper carries
18133 // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
18134 // Read directly from the codec-owned predicate — the crate's
18135 // single source of truth every typed-`Duration` axis now routes
18136 // through via
18137 // [`crate::render::require_positive_canonical_bounded_duration`].
18138 use super::supervisor::duration_codec::is_integer_millisecond_duration;
18139 assert!(is_integer_millisecond_duration(Duration::ZERO));
18140 assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
18141 assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
18142 assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
18143 assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
18144 assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
18145 // Non-integer-millisecond residue: rejected.
18146 assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
18147 assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
18148 assert!(!is_integer_millisecond_duration(Duration::from_micros(
18149 1500
18150 )));
18151 assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
18152 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
18153 999_999
18154 )));
18155 // The 1-ns-past-1ms boundary: rejected (no longer a clean
18156 // integer-millisecond multiple).
18157 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
18158 1_000_001
18159 )));
18160 }
18161
18162 #[test]
18163 fn policy_timeout_validated_value_round_trips_through_codec() {
18164 // The structural property the canonical-ms gate enforces:
18165 // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
18166 // round-trips losslessly through the shared `duration_codec`
18167 // (serialize → string → deserialize → equal value). Pin this
18168 // end-to-end so a future change to either side (the validate
18169 // gate's accepted granularity, the codec's parse/render unit
18170 // set) that breaks the alignment surfaces here. The
18171 // previous-state shape (typed slot accepts arbitrary
18172 // `Duration`, codec only round-trips integer-ms) would fail
18173 // this test for any `Duration::from_micros(1500)` timeout —
18174 // the validate gate now forecloses that.
18175 for timeout in [
18176 Duration::from_millis(1),
18177 Duration::from_millis(1500),
18178 Duration::from_secs(30),
18179 Duration::from_secs(3600),
18180 ] {
18181 let mut s = three_member_spec();
18182 s.politicas.timeout = Some(timeout);
18183 s.validate().unwrap();
18184 let json = serde_json::to_string(&s.politicas).unwrap();
18185 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18186 assert_eq!(
18187 back.timeout, s.politicas.timeout,
18188 "every validated :timeout must round-trip losslessly through the codec"
18189 );
18190 }
18191 }
18192
18193 #[test]
18194 fn circuit_breaker_window_validated_value_round_trips_through_codec() {
18195 // Peer of the `:timeout` round-trip property on the breaker
18196 // axis.
18197 for window in [
18198 Duration::from_millis(1),
18199 Duration::from_millis(1500),
18200 Duration::from_secs(30),
18201 Duration::from_secs(3600),
18202 ] {
18203 let mut s = three_member_spec();
18204 s.politicas.circuit_breaker = Some(CircuitBreaker {
18205 max_failures: 5,
18206 window,
18207 });
18208 s.validate().unwrap();
18209 let json = serde_json::to_string(&s.politicas).unwrap();
18210 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18211 assert_eq!(
18212 back.circuit_breaker.unwrap().window,
18213 window,
18214 "every validated :circuit-breaker :window must round-trip losslessly"
18215 );
18216 }
18217 }
18218
18219 #[test]
18220 fn empty_politicas_validates() {
18221 // Omitting every policy axis is fine — defaults express "no
18222 // policy on this axis", not "policy = 0". The fixture's typical
18223 // values continue to validate; this test pins that
18224 // MeshPolicy::default() is a clean pass through validate().
18225 let mut s = three_member_spec();
18226 s.politicas = MeshPolicy::default();
18227 s.validate().unwrap();
18228 }
18229
18230 #[test]
18231 fn typical_politicas_validates_with_every_axis_set() {
18232 // The full §III.1 example block (timeout + retries + breaker +
18233 // mtls + rate-limit) — every axis nonzero — must remain a
18234 // clean pass.
18235 let mut s = three_member_spec();
18236 s.politicas = MeshPolicy {
18237 timeout: Some(Duration::from_secs(30)),
18238 retries: Some(3),
18239 circuit_breaker: Some(CircuitBreaker {
18240 max_failures: 5,
18241 window: Duration::from_secs(60),
18242 }),
18243 mtls_required: Some(true),
18244 rate_limit: Some(RateLimit {
18245 rate: 100,
18246 window: Duration::from_secs(1),
18247 }),
18248 };
18249 s.validate().unwrap();
18250 }
18251
18252 #[test]
18253 fn rejects_empty_cluster_name() {
18254 let mut s = three_member_spec();
18255 s.placement.clusters = vec!["rio".into(), "".into()];
18256 assert_eq!(
18257 s.validate().unwrap_err(),
18258 AplicacaoError::PlacementClusterEmpty
18259 );
18260 }
18261
18262 #[test]
18263 fn rejects_duplicate_cluster_names() {
18264 let mut s = three_member_spec();
18265 s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
18266 let err = s.validate().unwrap_err();
18267 assert!(
18268 matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
18269 "got {err:?}"
18270 );
18271 }
18272
18273 #[test]
18274 fn rejects_placement_cluster_with_uppercase() {
18275 // The canonical "I copied the cluster's display name verbatim"
18276 // typo — K8s context names are lowercase per DNS-1123 label
18277 // rule, but org docs often round-trip a TitleCase identifier
18278 // (`Rio`, `Mar-East`) from an ADR. Mirrors the
18279 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
18280 // on the peer name axis.
18281 let mut s = three_member_spec();
18282 s.placement.clusters = vec!["Rio".into(), "mar".into()];
18283 let err = s.validate().unwrap_err();
18284 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18285 panic!("expected PlacementClusterInvalid, got other variant");
18286 };
18287 assert_eq!(cluster, "Rio");
18288 assert!(
18289 reason.contains("uppercase"),
18290 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
18291 );
18292 assert!(
18293 reason.contains("\"rio\""),
18294 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
18295 );
18296 }
18297
18298 #[test]
18299 fn rejects_placement_cluster_with_underscore() {
18300 // The canonical "I'm thinking of an env var / hostname slug"
18301 // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
18302 // schema. K8s context filtering on `my_cluster` silently misses
18303 // the cluster the author intended; the gate moves it to caixa-
18304 // build time. Same shape as `rejects_membro_caixa_with_underscore`
18305 // (3f9d7a0).
18306 let mut s = three_member_spec();
18307 s.placement.clusters = vec!["my_cluster".into()];
18308 let err = s.validate().unwrap_err();
18309 assert!(
18310 matches!(
18311 err,
18312 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18313 if cluster == "my_cluster" && reason.contains('_')
18314 ),
18315 "got {err:?}"
18316 );
18317 }
18318
18319 #[test]
18320 fn rejects_placement_cluster_with_dot() {
18321 // A `:placement :clusters` entry is a single DNS-1123 *label*,
18322 // not a subdomain — even though K8s context names sometimes
18323 // carry a dotted form via kubeconfig conventions, the strictest
18324 // floor among the use sites (DNS-1035 cluster.x-k8s.io
18325 // `metadata.name`, Cilium identity label values) wins. The "I
18326 // want to namespace my cluster names with `.`" intent is
18327 // expressed via `-` (`mar-east`).
18328 let mut s = three_member_spec();
18329 s.placement.clusters = vec!["team.rio".into()];
18330 let err = s.validate().unwrap_err();
18331 assert!(
18332 matches!(
18333 err,
18334 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18335 if cluster == "team.rio" && reason.contains('.')
18336 ),
18337 "got {err:?}"
18338 );
18339 }
18340
18341 #[test]
18342 fn rejects_placement_cluster_with_leading_hyphen() {
18343 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
18344 // with an alphanumeric. The K8s apiserver rejects `-rio`
18345 // outright; the rendered fan-out would emit a `metadata.name:
18346 // "-rio"` that fails admission far from the source caixa.lisp.
18347 let mut s = three_member_spec();
18348 s.placement.clusters = vec!["-rio".into()];
18349 let err = s.validate().unwrap_err();
18350 assert!(
18351 matches!(
18352 err,
18353 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18354 if cluster == "-rio" && reason.contains("start and end")
18355 ),
18356 "got {err:?}"
18357 );
18358 }
18359
18360 #[test]
18361 fn rejects_placement_cluster_with_trailing_hyphen() {
18362 // The symmetric arm of the boundary rule. Pin separately so
18363 // both ends are covered against a future relaxation that only
18364 // checks one boundary (parallel to
18365 // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
18366 let mut s = three_member_spec();
18367 s.placement.clusters = vec!["rio-".into()];
18368 let err = s.validate().unwrap_err();
18369 assert!(
18370 matches!(
18371 err,
18372 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18373 if cluster == "rio-"
18374 ),
18375 "got {err:?}"
18376 );
18377 }
18378
18379 #[test]
18380 fn rejects_placement_cluster_with_unicode() {
18381 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
18382 // before it reaches K8s. The byte-by-byte ASCII validity check
18383 // rejects multi-byte UTF-8 sequences by the first byte that
18384 // fails `[a-z0-9-]`.
18385 let mut s = three_member_spec();
18386 s.placement.clusters = vec!["rió".into()];
18387 let err = s.validate().unwrap_err();
18388 assert!(
18389 matches!(
18390 err,
18391 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18392 if cluster == "rió"
18393 ),
18394 "got {err:?}"
18395 );
18396 }
18397
18398 #[test]
18399 fn rejects_placement_cluster_with_whitespace() {
18400 // Whitespace is the canonical "I pasted from a sketch / doc"
18401 // footgun. The apiserver rejects every cluster `metadata.name`
18402 // value carrying whitespace.
18403 let mut s = three_member_spec();
18404 s.placement.clusters = vec!["rio cluster".into()];
18405 let err = s.validate().unwrap_err();
18406 assert!(
18407 matches!(
18408 err,
18409 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18410 if cluster == "rio cluster"
18411 ),
18412 "got {err:?}"
18413 );
18414 }
18415
18416 #[test]
18417 fn rejects_placement_cluster_too_long() {
18418 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
18419 // pin. The diagnostic names both the cap (63) and the actual
18420 // length so the author can shorten in one edit. Mirrors
18421 // `rejects_membro_caixa_too_long` (3f9d7a0).
18422 let mut s = three_member_spec();
18423 let too_long = "a".repeat(64);
18424 s.placement.clusters = vec![too_long.clone()];
18425 let err = s.validate().unwrap_err();
18426 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18427 panic!("expected PlacementClusterInvalid");
18428 };
18429 assert_eq!(cluster, too_long);
18430 assert!(
18431 reason.contains("63") && reason.contains("64"),
18432 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18433 );
18434 }
18435
18436 #[test]
18437 fn placement_cluster_max_length_validates() {
18438 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
18439 // future tightening (e.g. dropping to 62) surfaces here as a
18440 // regression, mirroring `membro_caixa_max_length_validates`
18441 // (3f9d7a0).
18442 let mut s = three_member_spec();
18443 s.placement.clusters = vec!["a".repeat(63)];
18444 s.validate().unwrap();
18445 }
18446
18447 #[test]
18448 fn accepts_canonical_placement_cluster_forms() {
18449 // The DNS-1123 label shapes a caixa author is realistically
18450 // going to write for cluster names: single-word lowercase
18451 // (`rio`), regional hyphen-joined (`mar-east`), single
18452 // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
18453 // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
18454 // Pin every leg so a future tightening that bans (e.g.) digit-
18455 // start identifiers surfaces here.
18456 for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
18457 let mut s = three_member_spec();
18458 s.placement.clusters = vec![form.into()];
18459 s.validate().unwrap_or_else(|e| {
18460 panic!("canonical cluster form {form:?} must validate, got {e:?}")
18461 });
18462 }
18463 }
18464
18465 #[test]
18466 fn placement_cluster_empty_takes_precedence_over_invalid() {
18467 // Order pin: the existing `PlacementClusterEmpty` diagnostic
18468 // (which doesn't try to parse) fires before the new
18469 // `PlacementClusterInvalid` parse-side diagnostic, so an empty
18470 // `:clusters` entry keeps its narrower error message — the new
18471 // gate would also reject `""`, but the empty-string arm is the
18472 // more self-locating diagnostic. Mirrors the
18473 // `membro_caixa_empty_takes_precedence_over_invalid` pin
18474 // (3f9d7a0).
18475 let mut s = three_member_spec();
18476 s.placement.clusters = vec!["rio".into(), "".into()];
18477 let err = s.validate().unwrap_err();
18478 assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
18479 }
18480
18481 #[test]
18482 fn placement_cluster_invalid_fires_before_duplicate_check() {
18483 // Order pin: a malformed-shape `:clusters` entry surfaces *its
18484 // own* diagnostic, even when a later entry would otherwise
18485 // collapse onto a duplicate name. The per-entry shape gate runs
18486 // inline before the duplicate-key insert, parallel to
18487 // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
18488 let mut s = three_member_spec();
18489 s.placement.clusters = vec!["Rio".into(), "rio".into()];
18490 let err = s.validate().unwrap_err();
18491 assert!(
18492 matches!(
18493 err,
18494 AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
18495 ),
18496 "got {err:?}"
18497 );
18498 }
18499
18500 #[test]
18501 fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
18502 // The diagnostic-shape pin: the error names the offending
18503 // `:clusters` value verbatim so the author can grep their
18504 // caixa.lisp without re-running the build, and carries a
18505 // non-empty `reason` naming the specific violation. Same shape
18506 // every typed-shape gate enshrines
18507 // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
18508 // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
18509 let mut s = three_member_spec();
18510 s.placement.clusters = vec!["BAD_CLUSTER".into()];
18511 let err = s.validate().unwrap_err();
18512 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18513 panic!("expected PlacementClusterInvalid");
18514 };
18515 assert_eq!(cluster, "BAD_CLUSTER");
18516 assert!(
18517 !reason.is_empty(),
18518 "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
18519 );
18520 }
18521
18522 #[test]
18523 fn rejects_sharded_with_empty_clusters() {
18524 // §III.1: Sharded uses :clusters as the shard pool. An empty
18525 // pool means "shard across no clusters" — meaningless, same as
18526 // Replicated with no hosts.
18527 let mut s = three_member_spec();
18528 s.placement.estrategia = PlacementStrategy::Sharded;
18529 s.placement.shard_key = Some("$tenantId".into());
18530 s.placement.clusters = vec![];
18531 assert!(matches!(
18532 s.validate().unwrap_err(),
18533 AplicacaoError::PlacementWithoutClusters {
18534 estrategia: PlacementStrategy::Sharded
18535 }
18536 ));
18537 }
18538
18539 #[test]
18540 fn rejects_sharded_with_empty_shard_key() {
18541 let mut s = three_member_spec();
18542 s.placement.estrategia = PlacementStrategy::Sharded;
18543 s.placement.shard_key = Some("".into());
18544 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
18545 }
18546
18547 #[test]
18548 fn rejects_shard_key_under_replicated_strategy() {
18549 // The fail-before-pass-after pin: a `:placement (:estrategia
18550 // Replicated :shard-key "tenantId")` manifest carries the
18551 // hash-keyed-distribution slot on a strategy that never consumes
18552 // it. Before the gate the typed slot's value silently vanished
18553 // at the renderer layer (caixa-mesh emits `placement.shardKey`
18554 // verbatim regardless of strategy; the Akka-style cluster-
18555 // sharding reconciler keys off `estrategia == Sharded` and
18556 // ignores the slot otherwise), with no diagnostic. Lifting the
18557 // rejection to a build-time gate makes the
18558 // `shard_key.is_some() == matches!(estrategia, Sharded)`
18559 // partition a structural property of every validated
18560 // [`Placement`].
18561 let mut s = three_member_spec();
18562 // The fixture already uses Replicated; just add a shard-key.
18563 s.placement.shard_key = Some("$tenantId".into());
18564 let err = s.validate().unwrap_err();
18565 let AplicacaoError::ShardKeyOnNonSharded {
18566 estrategia,
18567 shard_key,
18568 } = err
18569 else {
18570 panic!("expected ShardKeyOnNonSharded, got {err:?}");
18571 };
18572 assert_eq!(estrategia, PlacementStrategy::Replicated);
18573 assert_eq!(shard_key, "$tenantId");
18574 }
18575
18576 #[test]
18577 fn rejects_shard_key_under_singlenode_strategy() {
18578 // Peer of the Replicated case above on the SingleNode arm: OTP
18579 // distributed-app takeover (one cluster runs at a time) has no
18580 // hash-keyed routing axis to consume `:shard-key` either, so
18581 // the rejection fires on both non-Sharded arms uniformly.
18582 let mut s = three_member_spec();
18583 s.placement.estrategia = PlacementStrategy::SingleNode;
18584 s.placement.shard_key = Some("$tenantId".into());
18585 let err = s.validate().unwrap_err();
18586 let AplicacaoError::ShardKeyOnNonSharded {
18587 estrategia,
18588 shard_key,
18589 } = err
18590 else {
18591 panic!("expected ShardKeyOnNonSharded, got {err:?}");
18592 };
18593 assert_eq!(estrategia, PlacementStrategy::SingleNode);
18594 assert_eq!(shard_key, "$tenantId");
18595 }
18596
18597 #[test]
18598 fn rejects_empty_shard_key_under_replicated_strategy() {
18599 // The `Some("")` case under non-Sharded is rejected by
18600 // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
18601 // fires before the empty-value gate), not
18602 // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
18603 // the `Sharded` arm). Pin the partition so a future reorder of
18604 // the validate_placement match arms doesn't silently swap which
18605 // diagnostic the author sees — both are author errors, but
18606 // ShardKeyOnNonSharded names which strategy is the actual fix
18607 // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
18608 // only says "pick a non-empty key".
18609 let mut s = three_member_spec();
18610 s.placement.shard_key = Some(String::new());
18611 let err = s.validate().unwrap_err();
18612 assert!(
18613 matches!(
18614 err,
18615 AplicacaoError::ShardKeyOnNonSharded {
18616 estrategia: PlacementStrategy::Replicated,
18617 ref shard_key,
18618 } if shard_key.is_empty()
18619 ),
18620 "got {err:?}"
18621 );
18622 }
18623
18624 #[test]
18625 fn replicated_without_shard_key_validates() {
18626 // The complement of the rejection: `:placement :estrategia
18627 // Replicated` with `:shard-key None` is the canonical happy
18628 // path on every existing fixture. Pin the no-shard-key case so
18629 // the new gate doesn't accidentally fire on `None`.
18630 let mut s = three_member_spec();
18631 assert!(matches!(
18632 s.placement.estrategia,
18633 PlacementStrategy::Replicated
18634 ));
18635 s.placement.shard_key = None;
18636 s.validate().unwrap();
18637 }
18638
18639 #[test]
18640 fn singlenode_without_shard_key_validates() {
18641 // Peer of the Replicated no-shard-key case on the SingleNode
18642 // arm — both non-Sharded strategies must validate cleanly when
18643 // the slot is omitted.
18644 let mut s = three_member_spec();
18645 s.placement.estrategia = PlacementStrategy::SingleNode;
18646 s.placement.shard_key = None;
18647 s.validate().unwrap();
18648 }
18649
18650 fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
18651 // Fixture builder for the `:placement :shard-key` shape gate
18652 // tests: a three-member Aplicacao on the `Sharded` strategy
18653 // with the supplied `:shard-key` slot. Co-locates the
18654 // arm-construction so every test below carries one line of
18655 // setup (the offending `:shard-key` value) and the assertion.
18656 let mut s = three_member_spec();
18657 s.placement.estrategia = PlacementStrategy::Sharded;
18658 s.placement.shard_key = Some(key.into());
18659 s
18660 }
18661
18662 #[test]
18663 fn rejects_shard_key_with_embedded_space() {
18664 // The canonical paste-from-aligned-doc footgun:
18665 // `:shard-key "$tenant Id"` — the Akka-style entity-id
18666 // extractor reads the slot as a single-token reference, and an
18667 // embedded space breaks the token boundary at the runtime
18668 // hash-extractor pass with no diagnostic naming the offending
18669 // entry.
18670 let s = sharded_spec_with_key("$tenant Id");
18671 let err = s.validate().unwrap_err();
18672 assert!(
18673 matches!(
18674 err,
18675 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18676 if shard_key == "$tenant Id" && reason.contains("space")
18677 ),
18678 "got {err:?}"
18679 );
18680 }
18681
18682 #[test]
18683 fn rejects_shard_key_with_leading_space() {
18684 // Leading-space arm of the embedded-whitespace footgun — the
18685 // paste-from-aligned-doc / paste-from-CSV-cell variant where
18686 // the leading column-padding leaked into the slot.
18687 let s = sharded_spec_with_key(" $tenantId");
18688 let err = s.validate().unwrap_err();
18689 assert!(
18690 matches!(
18691 err,
18692 AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
18693 if shard_key == " $tenantId"
18694 ),
18695 "got {err:?}"
18696 );
18697 }
18698
18699 #[test]
18700 fn rejects_shard_key_with_trailing_newline() {
18701 // The canonical paste-from-shell-heredoc footgun — every
18702 // `<<EOF` heredoc terminator paste leaves a trailing newline
18703 // the YAML emitter then folds away inconsistently across
18704 // emitter implementations.
18705 let s = sharded_spec_with_key("$tenantId\n");
18706 let err = s.validate().unwrap_err();
18707 assert!(
18708 matches!(
18709 err,
18710 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18711 if shard_key == "$tenantId\n" && reason.contains("0x0a")
18712 ),
18713 "got {err:?}"
18714 );
18715 }
18716
18717 #[test]
18718 fn rejects_shard_key_with_embedded_tab() {
18719 // The paste-from-aligned-doc tab-stop variant — tabs land
18720 // alongside spaces in copy-paste from formatted columns.
18721 let s = sharded_spec_with_key("$tenant\tId");
18722 let err = s.validate().unwrap_err();
18723 assert!(
18724 matches!(
18725 err,
18726 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18727 if shard_key == "$tenant\tId" && reason.contains("tab")
18728 ),
18729 "got {err:?}"
18730 );
18731 }
18732
18733 #[test]
18734 fn rejects_shard_key_with_control_character() {
18735 // The paste-from-binary / paste-from-screen-cleared-terminal
18736 // footgun — an embedded `\x01` (SOH) byte that some YAML
18737 // emitters silently strip and others escape as ``,
18738 // breaking round-trip across emitter implementations.
18739 let s = sharded_spec_with_key("$tenant\u{0001}Id");
18740 let err = s.validate().unwrap_err();
18741 assert!(
18742 matches!(
18743 err,
18744 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18745 if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
18746 ),
18747 "got {err:?}"
18748 );
18749 }
18750
18751 #[test]
18752 fn rejects_shard_key_with_non_ascii() {
18753 // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
18754 // footgun — non-ASCII bytes normalize differently between the
18755 // caixa-mesh-side YAML emitter and the in-cluster reconciler's
18756 // YAML parser, the same entity ID can silently map to two
18757 // distinct shards on a re-render.
18758 let s = sharded_spec_with_key("$tenàntId");
18759 let err = s.validate().unwrap_err();
18760 assert!(
18761 matches!(
18762 err,
18763 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18764 if shard_key == "$tenàntId" && reason.contains("non-ASCII")
18765 ),
18766 "got {err:?}"
18767 );
18768 }
18769
18770 #[test]
18771 fn rejects_shard_key_too_long() {
18772 // Length cap pin: 64 bytes — one byte over the
18773 // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
18774 // here is a paste-from-doc multi-line blob landing in
18775 // `:shard-key` instead of a single-token extractor expression.
18776 let too_long = "a".repeat(64);
18777 let s = sharded_spec_with_key(&too_long);
18778 let err = s.validate().unwrap_err();
18779 let AplicacaoError::ShardKeyInvalid {
18780 ref shard_key,
18781 ref reason,
18782 } = err
18783 else {
18784 panic!("expected ShardKeyInvalid, got {err:?}");
18785 };
18786 assert_eq!(shard_key, &too_long);
18787 assert!(
18788 reason.contains("63") && reason.contains("64"),
18789 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18790 );
18791 }
18792
18793 #[test]
18794 fn shard_key_max_length_validates() {
18795 // Boundary pin: 63 bytes exactly — the
18796 // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
18797 // dropping to 62) surfaces here as a regression, mirroring
18798 // `placement_cluster_max_length_validates` /
18799 // `placement_affinity_max_length_validates` on the peer
18800 // identifier-shaped slots.
18801 let s = sharded_spec_with_key(&"a".repeat(63));
18802 s.validate().unwrap();
18803 }
18804
18805 #[test]
18806 fn accepts_canonical_shard_key_forms() {
18807 // The Akka-style entity-id extractor shapes a caixa author is
18808 // realistically going to write — pin every leg so a future
18809 // tightening that bans (e.g.) the `${...}` interpolation
18810 // variant or the `metadata.<field>` JSONPath form surfaces
18811 // here as a regression. The canonical forms span:
18812 //
18813 // - bare property name (`tenantId`, `customerId`)
18814 // - Akka `ExtractEntityId` placeholder (`$tenantId`)
18815 // - JSONPath-style nested reference (`metadata.tenantId`,
18816 // `$.user.id`)
18817 // - interpolation-style template (`${tenant}`)
18818 // - snake_case property name (`customer_id`)
18819 // - kebab-case property name (`customer-id` — accepted
18820 // because the slot is a printable-ASCII single-token
18821 // reference, not a DNS-1123 label like
18822 // `:placement :affinity` / `:clusters`)
18823 // - single character (`a`, `$` — boundary)
18824 for form in [
18825 "tenantId",
18826 "customerId",
18827 "$tenantId",
18828 "metadata.tenantId",
18829 "$.user.id",
18830 "${tenant}",
18831 "customer_id",
18832 "customer-id",
18833 "a",
18834 "$",
18835 ] {
18836 let s = sharded_spec_with_key(form);
18837 s.validate().unwrap_or_else(|e| {
18838 panic!("canonical shard-key form {form:?} must validate, got {e:?}")
18839 });
18840 }
18841 }
18842
18843 #[test]
18844 fn shard_key_empty_takes_precedence_over_invalid() {
18845 // Order pin: the existing `ShardedKeyEmpty` diagnostic
18846 // (reserved for the `Sharded` `Some("")` arm) fires before the
18847 // new `ShardKeyInvalid` parse-side diagnostic, so an empty
18848 // `:shard-key` keeps its narrower error message — the new gate
18849 // would also reject `""` defensively, but the empty-string arm
18850 // is the more self-locating diagnostic. Mirrors the
18851 // `placement_cluster_empty_takes_precedence_over_invalid` pin
18852 // on the peer identifier-shaped slot.
18853 let s = sharded_spec_with_key("");
18854 let err = s.validate().unwrap_err();
18855 assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
18856 }
18857
18858 #[test]
18859 fn shard_key_invalid_diagnostic_carries_offending_value() {
18860 // The diagnostic-shape pin: the error names the offending
18861 // `:shard-key` value verbatim so the author can grep their
18862 // caixa.lisp without re-running the build, and carries a
18863 // parser-shaped `reason:` naming the specific violation —
18864 // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
18865 // on the peer identifier-shaped slot.
18866 let s = sharded_spec_with_key("$tenant Id");
18867 let err = s.validate().unwrap_err();
18868 let AplicacaoError::ShardKeyInvalid {
18869 ref shard_key,
18870 ref reason,
18871 } = err
18872 else {
18873 panic!("expected ShardKeyInvalid, got {err:?}");
18874 };
18875 assert_eq!(shard_key, "$tenant Id");
18876 assert!(
18877 !reason.is_empty(),
18878 "reason must name the specific violation, got empty string"
18879 );
18880 }
18881
18882 #[test]
18883 fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
18884 // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
18885 // `:shard-key` carried on non-Sharded strategies) fires before
18886 // the shape gate, so a malformed `:shard-key` carried on (e.g.)
18887 // a `Replicated` strategy surfaces the more self-locating
18888 // strategy-mismatch diagnostic (naming the actual fix — drop
18889 // the slot, or switch to Sharded) rather than the shape
18890 // diagnostic. The strategy-mismatch arm is the more actionable
18891 // diagnostic: a malformed shard-key on Replicated is "you
18892 // shouldn't have a :shard-key here at all", not "your
18893 // :shard-key value is malformed".
18894 let mut s = three_member_spec();
18895 // Replicated is the default fixture strategy.
18896 s.placement.shard_key = Some("$tenant Id".into());
18897 let err = s.validate().unwrap_err();
18898 assert!(
18899 matches!(
18900 err,
18901 AplicacaoError::ShardKeyOnNonSharded {
18902 estrategia: PlacementStrategy::Replicated,
18903 ..
18904 }
18905 ),
18906 "got {err:?}"
18907 );
18908 }
18909
18910 #[test]
18911 fn rejects_empty_affinity_hint() {
18912 let mut s = three_member_spec();
18913 s.placement.affinity = Some("".into());
18914 assert_eq!(
18915 s.validate().unwrap_err(),
18916 AplicacaoError::PlacementAffinityEmpty
18917 );
18918 }
18919
18920 #[test]
18921 fn placement_without_affinity_validates() {
18922 // Omitting :affinity is fine — the placement engine falls back
18923 // to the default heuristic. Pin the no-hint case so the
18924 // affinity-empty rejection doesn't accidentally fire on `None`.
18925 let mut s = three_member_spec();
18926 s.placement.affinity = None;
18927 s.validate().unwrap();
18928 }
18929
18930 #[test]
18931 fn rejects_placement_affinity_with_uppercase() {
18932 // The canonical "I copied the ADR's display name verbatim" typo
18933 // — placement hints land verbatim in K8s label-selector
18934 // territory, where the apiserver enforces the DNS-1123 label
18935 // rule (lowercase-only) on every identity-keyed admission axis.
18936 // Mirrors `rejects_placement_cluster_with_uppercase` on the
18937 // sibling slot.
18938 let mut s = three_member_spec();
18939 s.placement.affinity = Some("DataLocality".into());
18940 let err = s.validate().unwrap_err();
18941 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18942 panic!("expected PlacementAffinityInvalid, got other variant");
18943 };
18944 assert_eq!(affinity, "DataLocality");
18945 assert!(
18946 reason.contains("uppercase"),
18947 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
18948 );
18949 assert!(
18950 reason.contains("\"datalocality\""),
18951 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
18952 );
18953 }
18954
18955 #[test]
18956 fn rejects_placement_affinity_with_underscore() {
18957 // The canonical "I'm thinking of an env var / Python identifier"
18958 // leak — `_` is forbidden by every DNS-1123 label schema. Same
18959 // shape as `rejects_placement_cluster_with_underscore` on the
18960 // sibling slot.
18961 let mut s = three_member_spec();
18962 s.placement.affinity = Some("data_locality".into());
18963 let err = s.validate().unwrap_err();
18964 assert!(
18965 matches!(
18966 err,
18967 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18968 if affinity == "data_locality" && reason.contains('_')
18969 ),
18970 "got {err:?}"
18971 );
18972 }
18973
18974 #[test]
18975 fn rejects_placement_affinity_with_dot() {
18976 // A `:placement :affinity` value is a single DNS-1123 *label*
18977 // (it lands as a K8s label value selector key), not a subdomain.
18978 // The "I want to namespace my hint with `.`" intent is expressed
18979 // via `-` (`data-locality-east`).
18980 let mut s = three_member_spec();
18981 s.placement.affinity = Some("data.locality".into());
18982 let err = s.validate().unwrap_err();
18983 assert!(
18984 matches!(
18985 err,
18986 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18987 if affinity == "data.locality" && reason.contains('.')
18988 ),
18989 "got {err:?}"
18990 );
18991 }
18992
18993 #[test]
18994 fn rejects_placement_affinity_with_unicode() {
18995 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
18996 // before it reaches K8s. The byte-by-byte ASCII validity check
18997 // rejects multi-byte UTF-8 sequences by the first byte that
18998 // fails `[a-z0-9-]`.
18999 let mut s = three_member_spec();
19000 s.placement.affinity = Some("data-localité".into());
19001 let err = s.validate().unwrap_err();
19002 assert!(
19003 matches!(
19004 err,
19005 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19006 if affinity == "data-localité"
19007 ),
19008 "got {err:?}"
19009 );
19010 }
19011
19012 #[test]
19013 fn rejects_placement_affinity_with_leading_hyphen() {
19014 // DNS-1123 boundary rule: labels must start with an
19015 // alphanumeric. Pin separately from the trailing-hyphen arm so
19016 // a future relaxation that only checks one boundary surfaces
19017 // here as a regression (parallel to
19018 // `rejects_placement_cluster_with_leading_hyphen`).
19019 let mut s = three_member_spec();
19020 s.placement.affinity = Some("-data-locality".into());
19021 let err = s.validate().unwrap_err();
19022 assert!(
19023 matches!(
19024 err,
19025 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19026 if affinity == "-data-locality" && reason.contains("start and end")
19027 ),
19028 "got {err:?}"
19029 );
19030 }
19031
19032 #[test]
19033 fn rejects_placement_affinity_with_trailing_hyphen() {
19034 // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
19035 // ends are covered against a future relaxation.
19036 let mut s = three_member_spec();
19037 s.placement.affinity = Some("data-locality-".into());
19038 let err = s.validate().unwrap_err();
19039 assert!(
19040 matches!(
19041 err,
19042 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19043 if affinity == "data-locality-"
19044 ),
19045 "got {err:?}"
19046 );
19047 }
19048
19049 #[test]
19050 fn rejects_placement_affinity_with_whitespace() {
19051 // Whitespace is the canonical "I pasted from a sketch / doc"
19052 // footgun. The apiserver rejects every label-selector value
19053 // carrying whitespace.
19054 let mut s = three_member_spec();
19055 s.placement.affinity = Some("data locality".into());
19056 let err = s.validate().unwrap_err();
19057 assert!(
19058 matches!(
19059 err,
19060 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19061 if affinity == "data locality"
19062 ),
19063 "got {err:?}"
19064 );
19065 }
19066
19067 #[test]
19068 fn rejects_placement_affinity_too_long() {
19069 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19070 // pin. The diagnostic names both the cap (63) and the actual
19071 // length so the author can shorten in one edit. Mirrors
19072 // `rejects_placement_cluster_too_long`.
19073 let mut s = three_member_spec();
19074 let too_long = "a".repeat(64);
19075 s.placement.affinity = Some(too_long.clone());
19076 let err = s.validate().unwrap_err();
19077 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19078 panic!("expected PlacementAffinityInvalid");
19079 };
19080 assert_eq!(affinity, too_long);
19081 assert!(
19082 reason.contains("63") && reason.contains("64"),
19083 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19084 );
19085 }
19086
19087 #[test]
19088 fn placement_affinity_max_length_validates() {
19089 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19090 // future tightening (e.g. dropping to 62) surfaces here as a
19091 // regression, mirroring `placement_cluster_max_length_validates`.
19092 let mut s = three_member_spec();
19093 s.placement.affinity = Some("a".repeat(63));
19094 s.validate().unwrap();
19095 }
19096
19097 #[test]
19098 fn accepts_canonical_placement_affinity_forms() {
19099 // The DNS-1123 label shapes a caixa author is realistically
19100 // going to write for placement hints: the M3 canonical examples
19101 // (`data-locality`, `low-latency`, `anti-affinity`), the
19102 // single-token form (`affinity`), the single-character boundary
19103 // (`a`), the digit-start (DNS-1123 allows this, unlike
19104 // DNS-1035), and a regional-suffixed form. Pin every leg so a
19105 // future tightening that bans (e.g.) digit-start identifiers
19106 // surfaces here.
19107 for form in [
19108 "data-locality",
19109 "low-latency",
19110 "anti-affinity",
19111 "affinity",
19112 "a",
19113 "3-tier",
19114 "locality-east",
19115 ] {
19116 let mut s = three_member_spec();
19117 s.placement.affinity = Some(form.into());
19118 s.validate().unwrap_or_else(|e| {
19119 panic!("canonical affinity form {form:?} must validate, got {e:?}")
19120 });
19121 }
19122 }
19123
19124 #[test]
19125 fn placement_affinity_empty_takes_precedence_over_invalid() {
19126 // Order pin: the existing `PlacementAffinityEmpty` diagnostic
19127 // (which doesn't try to parse) fires before the new
19128 // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
19129 // `:affinity` keeps its narrower error message — the new gate
19130 // would also reject `""`, but the empty-string arm is the more
19131 // self-locating diagnostic. Mirrors the
19132 // `placement_cluster_empty_takes_precedence_over_invalid` pin.
19133 let mut s = three_member_spec();
19134 s.placement.affinity = Some(String::new());
19135 let err = s.validate().unwrap_err();
19136 assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
19137 }
19138
19139 #[test]
19140 fn placement_affinity_invalid_diagnostic_carries_offending_value() {
19141 // The diagnostic shape pin: every rejection carries the offending
19142 // `affinity:` verbatim plus a parser-shaped `reason:` so the
19143 // author can grep their caixa.lisp for `:affinity "<hint>"` and
19144 // fix it in one edit. Mirrors the
19145 // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19146 // pin on the sibling slot.
19147 let mut s = three_member_spec();
19148 s.placement.affinity = Some("Data_Locality".into());
19149 let err = s.validate().unwrap_err();
19150 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19151 panic!("expected PlacementAffinityInvalid");
19152 };
19153 assert_eq!(affinity, "Data_Locality");
19154 assert!(
19155 !reason.is_empty(),
19156 "diagnostic reason must not be empty (got: {reason:?})"
19157 );
19158 }
19159
19160 #[test]
19161 fn singlenode_with_takeover_candidates_validates() {
19162 // OTP distributed-application convention (MESH-COMPOSITION
19163 // §II.1): SingleNode runs on one cluster at a time but the
19164 // :clusters list enumerates the takeover candidates. Multiple
19165 // entries are not a contradiction — they are the failover pool.
19166 let mut s = three_member_spec();
19167 s.placement.estrategia = PlacementStrategy::SingleNode;
19168 s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
19169 s.validate().unwrap();
19170 }
19171
19172 // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
19173
19174 #[test]
19175 fn mesh_policy_default_is_empty() {
19176 // The Default impl carries None on every axis — the typed
19177 // analog of an unset `:politicas (())` slot. Renderers that
19178 // overlay the policy onto a cluster artifact key off this
19179 // predicate to skip the slot entirely; pinning so a future
19180 // axis added to MeshPolicy can't silently break the contract
19181 // (a new field whose Default is non-None would flip is_empty
19182 // to false on every existing caixa, surfacing here).
19183 assert!(MeshPolicy::default().is_empty());
19184 }
19185
19186 #[test]
19187 fn mesh_policy_with_only_timeout_is_not_empty() {
19188 let p = MeshPolicy {
19189 timeout: Some(Duration::from_secs(30)),
19190 ..Default::default()
19191 };
19192 assert!(!p.is_empty());
19193 }
19194
19195 #[test]
19196 fn mesh_policy_with_only_retries_is_not_empty() {
19197 let p = MeshPolicy {
19198 retries: Some(3),
19199 ..Default::default()
19200 };
19201 assert!(!p.is_empty());
19202 }
19203
19204 #[test]
19205 fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
19206 let p = MeshPolicy {
19207 circuit_breaker: Some(CircuitBreaker {
19208 max_failures: 5,
19209 window: Duration::from_secs(60),
19210 }),
19211 ..Default::default()
19212 };
19213 assert!(!p.is_empty());
19214 }
19215
19216 #[test]
19217 fn mesh_policy_with_only_mtls_required_is_not_empty() {
19218 // Even `mtls_required: Some(false)` (an explicit opt-out) is
19219 // not empty — the author *named* the axis, the renderer needs
19220 // to honor that vs. fall back to the cluster default.
19221 let p = MeshPolicy {
19222 mtls_required: Some(false),
19223 ..Default::default()
19224 };
19225 assert!(!p.is_empty());
19226 }
19227
19228 #[test]
19229 fn mesh_policy_with_only_rate_limit_is_not_empty() {
19230 let p = MeshPolicy {
19231 rate_limit: Some(RateLimit {
19232 rate: 100,
19233 window: Duration::from_secs(1),
19234 }),
19235 ..Default::default()
19236 };
19237 assert!(!p.is_empty());
19238 }
19239
19240 #[test]
19241 fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
19242 // The three-member happy-path fixture sets timeout + retries +
19243 // mtls_required — every populated axis must read non-empty.
19244 // Pin the round-trip so the M3.x per-:politicas emitter (the
19245 // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
19246 // on is_empty() to decide whether to emit at all without
19247 // re-deriving the contract from inline field probes.
19248 assert!(!three_member_spec().politicas.is_empty());
19249 }
19250
19251 // ── shared duration codec: cross-slot integer-magnitude gate ──
19252 //
19253 // The integer-magnitude discipline applied to
19254 // `supervisor::duration_codec::parse` lifts onto every typed slot
19255 // that routes through the shared codec — `MeshPolicy::timeout`
19256 // (`:politicas :timeout`) and `CircuitBreaker::window`
19257 // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
19258 // These cross-slot tests pin that the gate fires at the serde
19259 // layer for both typed slots, not just for the supervisor side.
19260
19261 #[test]
19262 fn policy_timeout_serde_rejects_fractional_seconds() {
19263 // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
19264 // so the shared codec's integer-magnitude gate applies on
19265 // deserialize. `"1.5s"` previously parsed to 1500ms and round-
19266 // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
19267 // deserialize with the canonical-form diagnostic naming the
19268 // offending `"1.5"` and the remediation `"1500ms"`.
19269 let payload = r#"{"timeout":"1.5s"}"#;
19270 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19271 let msg = err.to_string();
19272 assert!(
19273 msg.contains("not a non-negative integer"),
19274 "expected integer-magnitude diagnostic in {msg:?}"
19275 );
19276 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
19277 assert!(
19278 msg.contains("\"1500ms\""),
19279 "missing canonical-form remediation in {msg:?}"
19280 );
19281 }
19282
19283 #[test]
19284 fn policy_timeout_serde_rejects_leading_plus_sign() {
19285 // Pin the leading-`+` arm cross-slot — the prior f64 parser
19286 // accepted `"+30s"` silently and round-tripped to `"30s"`.
19287 let payload = r#"{"timeout":"+30s"}"#;
19288 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19289 let msg = err.to_string();
19290 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
19291 }
19292
19293 #[test]
19294 fn circuit_breaker_window_serde_rejects_fractional_minutes() {
19295 // `CircuitBreaker::window` uses `with =
19296 // "supervisor::duration_codec_required"` (the required-Duration
19297 // variant that delegates to the same shared parser). `"0.5m"`
19298 // parsed to 30s and round-tripped to `"30s"` on next emit —
19299 // DRIFT closed.
19300 let payload = format!(
19301 r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
19302 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
19303 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
19304 );
19305 let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
19306 let msg = err.to_string();
19307 assert!(
19308 msg.contains("not a non-negative integer"),
19309 "expected integer-magnitude diagnostic in {msg:?}"
19310 );
19311 assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
19312 assert!(
19313 msg.contains("\"30s\""),
19314 "missing canonical-form remediation in {msg:?}"
19315 );
19316 }
19317
19318 #[test]
19319 fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
19320 // Pin the happy-path on the cross-slot side: every canonical
19321 // author shape `render` ever emits parses cleanly through the
19322 // shared codec on the `CircuitBreaker` slot. The
19323 // codec's accepted set (post-gate) is exactly its emitted set
19324 // for the integer-magnitude class.
19325 for window_lit in ["30s", "500ms", "2m", "1h"] {
19326 let payload = format!(
19327 r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
19328 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
19329 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
19330 );
19331 let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
19332 panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
19333 });
19334 assert_eq!(cb.max_failures, 5);
19335 }
19336 }
19337
19338 // ── rate_limit_codec: integer-magnitude gate ──
19339 //
19340 // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
19341 // / 737a676 / d53c922 trajectory landed on every typed-duration /
19342 // typed-byte-size codec in caixa-core lifts onto the fifth typed
19343 // codec — `rate_limit_codec` — through the digit-only magnitude
19344 // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
19345 // These tests pin the gate at the serde layer for `:politicas
19346 // :rate-limit` (the only typed slot the codec backs), and at the
19347 // codec-internal `parse` layer for the canonical positive cases.
19348
19349 #[test]
19350 fn rate_limit_serde_rejects_fractional_rate() {
19351 // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
19352 // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
19353 // wording, which didn't name the canonical-form remediation or
19354 // the round-trip drift the next emit would produce. Now refused
19355 // at deserialize with the canonical-form diagnostic naming the
19356 // offending `"1.5"` magnitude and the round-trip drift wording.
19357 let payload = r#"{"rateLimit":"1.5/s"}"#;
19358 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19359 let msg = err.to_string();
19360 assert!(
19361 msg.contains("not a non-negative integer"),
19362 "expected integer-magnitude diagnostic in {msg:?}"
19363 );
19364 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
19365 assert!(
19366 msg.contains("THEORY.md"),
19367 "missing render-determinism contract citation in {msg:?}"
19368 );
19369 }
19370
19371 #[test]
19372 fn rate_limit_serde_rejects_leading_plus_sign() {
19373 // `u32::from_str("+100")` returns `Ok(100)` (Rust's
19374 // permissive-`+` parse), so `"+100/s"` silently parsed to
19375 // `RateLimit { 100, 1s }` and round-tripped through `render` to
19376 // `"100/s"` — a *different* canonical string on the next emit,
19377 // breaking the THEORY.md Part V render-determinism contract
19378 // exactly the way the peer duration codecs' `"+30s"` case did.
19379 // This is the load-bearing class the digit-only gate closes
19380 // beyond what `u32::from_str`'s strictness covers on its own.
19381 let payload = r#"{"rateLimit":"+100/s"}"#;
19382 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19383 let msg = err.to_string();
19384 assert!(
19385 msg.contains("not a non-negative integer"),
19386 "expected integer-magnitude diagnostic in {msg:?}"
19387 );
19388 assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
19389 }
19390
19391 #[test]
19392 fn rate_limit_serde_rejects_leading_minus_sign() {
19393 // The signed-negative arm: `"-1/s"` lands on the
19394 // non-canonical-but-numeric branch via the `i64` fallback (the
19395 // `f64` parse also succeeds), surfacing the canonical-form
19396 // diagnostic. Replaces the prior value-laundered "not a u32"
19397 // wording with the unified diagnostic across signs.
19398 let payload = r#"{"rateLimit":"-1/s"}"#;
19399 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19400 let msg = err.to_string();
19401 assert!(
19402 msg.contains("not a non-negative integer"),
19403 "expected integer-magnitude diagnostic in {msg:?}"
19404 );
19405 assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
19406 }
19407
19408 #[test]
19409 fn rate_limit_serde_rejects_decimal_shaped_integer() {
19410 // `"100.0/s"` is integer-valued numerically but not in the
19411 // codec's accepted set — `render` emits `"100/s"`, so the
19412 // round-trip would drift. Lifted to the canonical-form
19413 // diagnostic peer with the duration codec's `"1.0s"` case
19414 // (1c55a2a).
19415 let payload = r#"{"rateLimit":"100.0/s"}"#;
19416 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19417 let msg = err.to_string();
19418 assert!(
19419 msg.contains("not a non-negative integer"),
19420 "expected integer-magnitude diagnostic in {msg:?}"
19421 );
19422 assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
19423 }
19424
19425 #[test]
19426 fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
19427 // Non-numeric, non-digit-only input lands on the existing
19428 // narrower `"not a u32"` arm (preserved for diagnostic-shape
19429 // stability on the parser-shape footgun case). Pin this so a
19430 // future relaxation of the numeric-fallback predicate doesn't
19431 // silently collapse garbage onto the canonical-form arm — same
19432 // partition the peer duration codecs draw between
19433 // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
19434 let payload = r#"{"rateLimit":"abc/s"}"#;
19435 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19436 let msg = err.to_string();
19437 assert!(
19438 msg.contains("not a u32"),
19439 "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
19440 );
19441 assert!(
19442 !msg.contains("not a non-negative integer"),
19443 "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
19444 );
19445 }
19446
19447 #[test]
19448 fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
19449 // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
19450 // u32's range. The digit-only gate passes; `u32::from_str`
19451 // fails on overflow. Surface that with the overflow-shaped
19452 // diagnostic naming the offending magnitude verbatim, peer
19453 // with `supervisor::duration_codec`'s overflow arm. Pinning
19454 // the wording so a future refactor doesn't silently collapse
19455 // overflow onto the canonical-form arm.
19456 let payload = r#"{"rateLimit":"4294967296/s"}"#;
19457 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19458 let msg = err.to_string();
19459 assert!(
19460 msg.contains("overflows u32"),
19461 "expected overflow diagnostic in {msg:?}"
19462 );
19463 assert!(
19464 msg.contains("\"4294967296\""),
19465 "missing offending magnitude in {msg:?}"
19466 );
19467 }
19468
19469 #[test]
19470 fn rate_limit_serde_rejects_leading_zero_magnitude() {
19471 // `"0100/s"` is digit-only, so the existing
19472 // non-digit-only / sign / fractional arm doesn't catch it —
19473 // `u32::from_str("0100")` returns `Ok(100)`, so before this
19474 // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
19475 // round-tripped through `render` to `"100/s"` — a *different*
19476 // canonical string on the next emit, breaking the THEORY.md
19477 // Part V render-determinism contract exactly the way the
19478 // peer `"+100/s"` case did before the leading-`+` arm landed.
19479 // This is the load-bearing class the leading-zero gate closes
19480 // beyond what the existing digit-only / sign / fractional
19481 // gates cover, and the peer arm to the leading-`+` test
19482 // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
19483 // canonical-form-drift axis.
19484 let payload = r#"{"rateLimit":"0100/s"}"#;
19485 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19486 let msg = err.to_string();
19487 assert!(
19488 msg.contains("non-canonical leading zero"),
19489 "expected leading-zero diagnostic in {msg:?}"
19490 );
19491 assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
19492 assert!(
19493 msg.contains("THEORY.md"),
19494 "missing render-determinism contract citation in {msg:?}"
19495 );
19496 }
19497
19498 #[test]
19499 fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
19500 // `"00/s"` is the degenerate leading-zero case — every byte
19501 // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
19502 // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
19503 // a *different* canonical string, same render-determinism
19504 // violation. The single-byte `"0/s"` itself is in the
19505 // accepted set (round-trips losslessly through `render`,
19506 // refused downstream by `PolicyRateLimitZero`); the
19507 // multi-byte `"00/s"` is not. Pins the boundary between the
19508 // accepted single-`0` and the rejected leading-zero class.
19509 let payload = r#"{"rateLimit":"00/s"}"#;
19510 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19511 let msg = err.to_string();
19512 assert!(
19513 msg.contains("non-canonical leading zero"),
19514 "expected leading-zero diagnostic in {msg:?}"
19515 );
19516 assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
19517 }
19518
19519 #[test]
19520 fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
19521 // Cross-window pin — the gate is window-agnostic; the
19522 // leading-zero class is a property of the magnitude, not the
19523 // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
19524 // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
19525 // single-window coverage extended across the three canonical
19526 // windows the codec accepts.
19527 let payload = r#"{"rateLimit":"007/h"}"#;
19528 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19529 let msg = err.to_string();
19530 assert!(
19531 msg.contains("non-canonical leading zero"),
19532 "expected leading-zero diagnostic in {msg:?}"
19533 );
19534 assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
19535 }
19536
19537 #[test]
19538 fn rate_limit_serde_rejects_leading_whitespace() {
19539 // `" 100/s"` — the canonical paste-from-aligned-doc /
19540 // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
19541 // the top-level `s.trim()` silently ate the leading space and
19542 // parsed the value to `RateLimit { 100, 1s }`, which then
19543 // round-tripped through `render` to `"100/s"` (a *different*
19544 // canonical string on the next emit) — the exact
19545 // canonical-form-drift class the leading-`+` / leading-zero
19546 // arms already close, extended to the whitespace byte class.
19547 let payload = r#"{"rateLimit":" 100/s"}"#;
19548 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19549 let msg = err.to_string();
19550 assert!(
19551 msg.contains("contains whitespace byte"),
19552 "expected whitespace diagnostic in {msg:?}"
19553 );
19554 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19555 assert!(
19556 msg.contains("THEORY.md"),
19557 "missing render-determinism contract citation in {msg:?}"
19558 );
19559 }
19560
19561 #[test]
19562 fn rate_limit_serde_rejects_trailing_whitespace() {
19563 // `"100/s "` — the canonical shell-history / trailing-space
19564 // paste footgun. Before this gate the top-level `s.trim()`
19565 // silently ate the trailing space and parsed to
19566 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
19567 // next emit — same canonical-form drift as the leading-space
19568 // sibling, closed on the same whitespace-byte arm.
19569 let payload = r#"{"rateLimit":"100/s "}"#;
19570 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19571 let msg = err.to_string();
19572 assert!(
19573 msg.contains("contains whitespace byte"),
19574 "expected whitespace diagnostic in {msg:?}"
19575 );
19576 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19577 }
19578
19579 #[test]
19580 fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
19581 // `"100 / s"` — the canonical typographically-spaced author
19582 // shape (the same idiom every prose reference to a rate limit
19583 // renders as, mistakenly retained when the value is pasted
19584 // into a codec-shaped slot). Before this gate the per-part
19585 // `rate_str.trim()` / `unit.trim()` calls silently ate both
19586 // spaces on either side of `/` and parsed to
19587 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
19588 // codec's *internal* whitespace-tolerance vector, orthogonal
19589 // to the leading / trailing surface but the same canonical-
19590 // form-drift class. Pins the arm as strictly stronger than the
19591 // pre-existing top-level `s.trim()` behavior: it fires on
19592 // whitespace anywhere in the value, not just at the string
19593 // boundary.
19594 let payload = r#"{"rateLimit":"100 / s"}"#;
19595 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19596 let msg = err.to_string();
19597 assert!(
19598 msg.contains("contains whitespace byte"),
19599 "expected whitespace diagnostic in {msg:?}"
19600 );
19601 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19602 }
19603
19604 #[test]
19605 fn rate_limit_serde_rejects_tab_byte() {
19606 // `"\t100/s"` — the canonical paste-from-indented-doc /
19607 // paste-from-YAML-block-scalar footgun where a tab byte leads
19608 // the magnitude. Pins that the gate covers tab (`0x09`) as
19609 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
19610 // members and both would be silently swallowed by `s.trim()`
19611 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
19612 // space alone to the full ASCII-whitespace set (space `0x20`,
19613 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
19614 // the tab arm as a representative of the non-space members.
19615 let payload = r#"{"rateLimit":"\t100/s"}"#;
19616 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19617 let msg = err.to_string();
19618 assert!(
19619 msg.contains("contains whitespace byte"),
19620 "expected whitespace diagnostic in {msg:?}"
19621 );
19622 assert!(
19623 msg.contains("0x09"),
19624 "missing offending tab byte in {msg:?}"
19625 );
19626 }
19627
19628 // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
19629 //
19630 // Successor to the ASCII-whitespace arm (1ad7755) on
19631 // `rate_limit_codec` — closes the strictly-complementary class the
19632 // byte-scan cannot see, through the lifted
19633 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
19634
19635 #[test]
19636 fn rate_limit_serde_rejects_leading_nbsp() {
19637 // NBSP prefix — paste-from-typography footgun. Byte-scan
19638 // misses, `str::trim` silently strips it, value drifts to
19639 // `"100/s"` on next serialize.
19640 let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
19641 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19642 let msg = err.to_string();
19643 assert!(
19644 msg.contains("non-ASCII Unicode whitespace character"),
19645 "expected non-ASCII whitespace diagnostic in {msg:?}"
19646 );
19647 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
19648 }
19649
19650 #[test]
19651 fn rate_limit_serde_rejects_internal_em_space() {
19652 // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
19653 // paste-from-typography footgun on the `<integer>/<unit>`
19654 // shape.
19655 let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
19656 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19657 let msg = err.to_string();
19658 assert!(
19659 msg.contains("non-ASCII Unicode whitespace character"),
19660 "expected non-ASCII whitespace diagnostic in {msg:?}"
19661 );
19662 assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
19663 }
19664
19665 #[test]
19666 fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
19667 // Positive-control pin: every ASCII-only canonical form the
19668 // renderer emits stays accepted through the new arm.
19669 for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
19670 let payload = format!(r#"{{"rateLimit":{lit}}}"#);
19671 let p: MeshPolicy = serde_json::from_str(&payload)
19672 .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
19673 assert!(p.rate_limit.is_some());
19674 }
19675 }
19676
19677 #[test]
19678 fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
19679 // The boundary case — `"0/s"` is the canonical form
19680 // `render(RateLimit { 0, 1s })` emits, so the codec accepts
19681 // it at the parse layer; the downstream
19682 // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
19683 // `rate == 0` at the typed-validate layer above. Pins the
19684 // partition: the leading-zero gate at the codec layer does
19685 // not poach the rate-zero semantic-validation arm at the
19686 // typed-validate layer above (a future stricter codec must
19687 // not reject `"0/s"` here, or it'd collapse the diagnostic
19688 // partitioning that lets `PolicyRateLimitZero` name the
19689 // offending typed slot).
19690 let payload = r#"{"rateLimit":"0/s"}"#;
19691 let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
19692 panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
19693 });
19694 let rl = policy.rate_limit.expect("rate_limit must be Some");
19695 assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
19696 assert_eq!(
19697 rl.window,
19698 Duration::from_secs(1),
19699 "single-`0` magnitude with `s` unit must parse to window=1s"
19700 );
19701 }
19702
19703 #[test]
19704 fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
19705 // The complementary boundary pin — every magnitude
19706 // `render` emits starts with `[1-9]` (or is the single byte
19707 // `"0"`), so the canonical-form predicate is `(len == 1) ||
19708 // (first byte != '0')`. Pinning the `len > 1 && first byte ==
19709 // '1'` case explicitly so a future tightening of the gate
19710 // (e.g. an over-eager "no leading digit < 5" rule, or a
19711 // mistakenly anchored start-of-magnitude byte check) lands
19712 // here before the canonical-forms-iterating test would catch
19713 // it.
19714 let payload = r#"{"rateLimit":"100/s"}"#;
19715 let policy: MeshPolicy = serde_json::from_str(payload)
19716 .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
19717 let rl = policy.rate_limit.expect("rate_limit must be Some");
19718 assert_eq!(
19719 rl.rate, 100,
19720 "canonical-100 magnitude must parse to rate=100"
19721 );
19722 }
19723
19724 #[test]
19725 fn rate_limit_serde_accepts_integer_canonical_forms() {
19726 // Pin the happy-path: every canonical author shape `render`
19727 // ever emits parses cleanly through the codec post-gate. The
19728 // codec's accepted set (post-gate) is exactly its emitted set
19729 // for the integer-magnitude class — same property
19730 // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
19731 // gates guarantee on the peer codecs. Iterating across rate
19732 // magnitudes (including `"0"`, which the codec accepts even
19733 // though `validate_politicas` rejects `rate == 0` at the typed
19734 // layer above) closes the codec contract at the parse layer
19735 // independently of the validate layer.
19736 for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
19737 for unit_lit in ["s", "m", "h"] {
19738 let lit = format!("{rate_lit}/{unit_lit}");
19739 let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
19740 let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
19741 panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
19742 });
19743 let rl = policy.rate_limit.expect("rate_limit must be Some");
19744 assert_eq!(
19745 rl.rate,
19746 rate_lit.parse::<u32>().unwrap(),
19747 "rate mismatch for {lit:?}"
19748 );
19749 }
19750 }
19751 }
19752
19753 #[test]
19754 fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
19755 // The structural property the gate enforces: serialize ∘
19756 // deserialize is the identity on every canonical author shape.
19757 // Peer of `parse_byte_size`'s and `parse_duration`'s
19758 // `_round_trips_through_render_for_every_canonical_form` tests
19759 // on the rate-limit axis. Before the gate, `"+100/s"` violated
19760 // this (`parse` → `RateLimit { 100, 1s }` → `render` →
19761 // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
19762 for rate in [1u32, 100, 5000, 1_000_000] {
19763 for (window, unit) in [
19764 (Duration::from_secs(1), "s"),
19765 (Duration::from_secs(60), "m"),
19766 (Duration::from_secs(3600), "h"),
19767 ] {
19768 let policy = MeshPolicy {
19769 rate_limit: Some(RateLimit { rate, window }),
19770 ..Default::default()
19771 };
19772 let json = serde_json::to_string(&policy).unwrap();
19773 let expected = format!("\"{rate}/{unit}\"");
19774 assert!(
19775 json.contains(&expected),
19776 "expected {expected:?} in {json:?}"
19777 );
19778 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19779 assert_eq!(
19780 back.rate_limit, policy.rate_limit,
19781 "round-trip for {json:?}"
19782 );
19783 }
19784 }
19785 }
19786
19787 // ── self-membership cross-slot gate ──────────────────────────────
19788
19789 #[test]
19790 fn validate_no_self_membership_rejects_self_named_membro() {
19791 // An Aplicacao whose `:membros` lists its own `:nome` is a
19792 // one-node lacre-closure recursion — rejected, naming the parent.
19793 let membros = vec![
19794 membro("catalog", "^0.1"),
19795 membro("checkout", "^0.1"),
19796 membro("cart", "^0.1"),
19797 ];
19798 let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
19799 assert!(
19800 matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
19801 "got {err:?}"
19802 );
19803 }
19804
19805 #[test]
19806 fn validate_no_self_membership_accepts_distinct_membros() {
19807 // Positive control: distinct member names (including a member
19808 // that is itself an Aplicacao — recursive composition is valid,
19809 // MESH-COMPOSITION §V) pass the gate.
19810 let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
19811 validate_no_self_membership(&membros, "checkout").unwrap();
19812 }
19813
19814 #[test]
19815 fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
19816 // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
19817 // `NoMembros` arm (the more-fundamental "graph must have nodes"
19818 // gate), not by this cross-slot self-edge gate. Keeping the
19819 // self-membership predicate vacuously-ok on the empty input
19820 // matches its supervisor-axis peer
19821 // (`validate_no_self_supervision_empty_children_is_ok`) and
19822 // makes the gate composable from any future call site (an M4
19823 // CR materializer's per-membros validator) without re-checking
19824 // emptiness.
19825 validate_no_self_membership(&[], "checkout").unwrap();
19826 }
19827
19828 #[test]
19829 fn validate_no_self_membership_diagnostic_names_offending_caixa() {
19830 // Pinning the Display: the self-membership diagnostic must name
19831 // the offending caixa verbatim + the "lists itself" framing the
19832 // author can grep for, so the cluster-far failure surfaces at
19833 // build time with one-line remediation. Same diagnostic shape
19834 // as the supervisor-axis `ChildSupervisesSelf` peer.
19835 let membros = vec![membro("orquestra", "^0.1")];
19836 let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
19837 let msg = err.to_string();
19838 assert!(
19839 msg.contains("orquestra"),
19840 "diagnostic must name the offending caixa nome (got: {msg:?})"
19841 );
19842 assert!(
19843 msg.contains("lists itself"),
19844 "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
19845 );
19846 }
19847
19848 #[test]
19849 fn default_servico_port_constant_pins_canonical_8080_literal() {
19850 // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
19851 // at the verbatim `8080` literal both consumers (the
19852 // `Entrada::port` serde default via [`default_port`] and the
19853 // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
19854 // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
19855 // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
19856 // discipline (a085b26) on the per-renderer canonical-K8s-axis
19857 // string-constant axis: a future refactor that drifts the
19858 // constant out from under either consumer surfaces here ahead
19859 // of every per-renderer's first emission. The literal value
19860 // matches the well-known HTTP-alt port the `pleme-computeunit`
19861 // library chart already emits as its `trigger.service.port`
19862 // default — by construction the same value the substrate
19863 // assumes about every Servico's in-cluster L4 listener.
19864 assert_eq!(
19865 DEFAULT_SERVICO_PORT, 8080,
19866 "canonical Servico port literal must remain `8080` verbatim — \
19867 this is the value both the `Entrada::port` serde default and the \
19868 caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
19869 );
19870 }
19871
19872 #[test]
19873 fn default_port_helper_returns_canonical_servico_port_constant() {
19874 // The bridge-arm — pins that the [`default_port`] helper
19875 // [`Entrada::port`]'s `#[serde(default = "default_port")]`
19876 // attribute hooks routes through the lifted
19877 // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
19878 // literal. A future refactor that re-introduces the `8080`
19879 // literal at the helper's return site (silently re-opening
19880 // the drift footgun this lift closed) surfaces here ahead of
19881 // every author-side `(:entrada (:host … :para …))` slot
19882 // without an explicit `:port`. Peer with the
19883 // `default_namespace_re_export_points_at_caixa_core_canonical`
19884 // pin on the caixa-mesh-side re-export axis.
19885 assert_eq!(
19886 default_port(),
19887 DEFAULT_SERVICO_PORT,
19888 "the serde-default helper must route through the lifted constant"
19889 );
19890 }
19891
19892 #[test]
19893 fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
19894 // The end-to-end pin — an author-surface `(:entrada (:host …
19895 // :para …))` without an explicit `:port` slot deserializes to
19896 // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
19897 // verbatim. Routes the canonical lifted constant through both
19898 // the serde-default machinery (the `#[serde(default =
19899 // "default_port")]` attribute) and the typed-value-shape
19900 // contract (the resulting [`Entrada::port`] value). A future
19901 // refactor that drifts either axis — replacing the serde
19902 // hook's helper, changing the typed slot's wire shape — would
19903 // surface here before any per-renderer's CNP / Gateway /
19904 // HTTPRoute emission consumed the drifted default.
19905 let entrada: Entrada =
19906 serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
19907 assert_eq!(
19908 entrada.port, DEFAULT_SERVICO_PORT,
19909 "the serde default must materialize as the lifted canonical Servico port"
19910 );
19911 }
19912
19913 #[test]
19914 fn servico_port_min_pins_canonical_accept_set_floor() {
19915 // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
19916 // verbatim `1` literal every typed `:entrada :port` acceptance
19917 // gate keys off. Peer with the
19918 // [`default_servico_port_constant_pins_canonical_8080_literal`]
19919 // discipline on the canonical-Servico-port-constant axis: a
19920 // future refactor that drifts the accept-set floor out from
19921 // under the sole consumer at [`AplicacaoSpec::validate`]'s
19922 // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
19923 // every per-`:entrada` `EntradaPortZero` diagnostic. The
19924 // literal value matches the IANA-registered TCP/UDP port
19925 // space floor (`1..=65535` — port `0` is the "any ephemeral"
19926 // sentinel, not a well-defined destination the substrate's
19927 // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
19928 // axis can honor).
19929 assert_eq!(
19930 SERVICO_PORT_MIN, 1,
19931 "canonical Servico port accept-set floor must remain `1` verbatim — \
19932 this is the value the `AplicacaoSpec::validate` gate at \
19933 `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
19934 );
19935 }
19936
19937 #[test]
19938 fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
19939 // The cross-const invariant pin — the substrate's canonical
19940 // default port must satisfy its own accept-set floor by
19941 // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
19942 // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
19943 // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
19944 // override the operator pins through a future
19945 // `:placement :default-port` slot that lands out-of-range, a
19946 // per-edition Servico-port migration that lifted the floor
19947 // above the previous default without coordinating the pair —
19948 // would silently invalidate the serde-default emission at
19949 // every author-side `(:entrada (:host … :para …))` slot
19950 // without an explicit `:port`: the default port would fall
19951 // below the accept-set floor, the `AplicacaoSpec::validate`
19952 // gate would reject every default-carrying Aplicacao as
19953 // `EntradaPortZero`, and the substrate's typed
19954 // `(defcaixa … :kind Aplicacao)` surface would fail validate
19955 // on every Aplicacao whose author omitted `:entrada :port`
19956 // for the substrate's chosen default — a class of authoring-
19957 // surface footguns the compile-time pin structurally closes.
19958 // Peer with the
19959 // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
19960 // (27f9b34) cross-const invariant pin discipline on the peer
19961 // canonical-Helm-per-values-block child-chart-enablement-toggle
19962 // axis pair.
19963 assert!(
19964 SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
19965 "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
19966 satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
19967 every default-carrying `(:entrada (:host … :para …))` slot without an \
19968 explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
19969 hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
19970 );
19971 }
19972
19973 #[test]
19974 fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
19975 // The gate-site pin — asserts the `AplicacaoSpec::validate`
19976 // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
19977 // `EntradaPortZero` diagnostic on the below-floor input
19978 // `port: 0` (the only below-floor value the `u16` field can
19979 // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
19980 // is the singleton `{0}`). A future refactor that drifts the
19981 // gate off the lifted const (silently re-introducing an
19982 // inline `if e.port == 0` byte-check) surfaces here — the
19983 // pin cannot distinguish `< 1` from `== 0` on the current
19984 // floor, but it *does* pin that the diagnostic fires on `0`
19985 // through whichever gate is wired, so any future accept-set
19986 // floor migration (a hypothetical unprivileged-only
19987 // migration lifting `SERVICO_PORT_MIN` to `1024`) must
19988 // update this test alongside the const declaration —
19989 // structurally guaranteeing the gate + accept-set + pin
19990 // trio move together. Peer with the
19991 // [`rejects_zero_entrada_port`] behavioral pin on the same
19992 // per-`:entrada :port` axis — that pin asserts the pre-lift
19993 // behavioral contract (`port: 0` → `EntradaPortZero`); this
19994 // pin adds the structural link to the lifted floor const.
19995 assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
19996 let mut s = three_member_spec();
19997 s.entrada.as_mut().unwrap().port = 0;
19998 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
19999 }
20000
20001 // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
20002
20003 #[test]
20004 fn membro_serde_keys_match_lifted_membro_key_consts() {
20005 // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
20006 // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
20007 // name the exact camelCase JSON keys the
20008 // `#[serde(rename_all = "camelCase")]` attribute on
20009 // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
20010 // that each canonical byte-sequence appears verbatim in the
20011 // JSON — a future accidental `rename_all = "snake_case"` /
20012 // `"kebab-case"` / verbatim-field-name flip at the derive
20013 // attribute (any of which would silently break every downstream
20014 // JSON consumer that reaches for one of the two consts via
20015 // `Value::get(...)`) surfaces here as a build-time test failure
20016 // at `aplicacao.rs`, not as an apply-time
20017 // `.get(<stale-canonical-const>)` returning `None` far from the
20018 // derive-attr drift's commit. Peer with the sibling
20019 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
20020 // (40cc4e5) pin on the M2 supervision-tree top-level axis —
20021 // same discipline the SupervisorSpec top-level lift established,
20022 // extended here to the M3 [`Membro`] per-`:membros` axis.
20023 let m = Membro {
20024 caixa: "catalog".into(),
20025 versao: "^0.1".into(),
20026 };
20027 let json = serde_json::to_string(&m).unwrap();
20028 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
20029 let quoted = format!("\"{key}\"");
20030 assert!(
20031 json.contains("ed),
20032 "serialized Membro must carry the lifted MEMBRO_KEY_* \
20033 byte-sequence {quoted} verbatim in the JSON emission \
20034 (got: {json})",
20035 );
20036 }
20037 }
20038
20039 #[test]
20040 fn membro_key_consts_are_pairwise_distinct() {
20041 // Cross-axis drift-detection pin: a future collapse of the two
20042 // canonical [`Membro`] per-entry byte-strings onto the same
20043 // value (e.g. an accidental copy-paste flip of
20044 // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
20045 // silently reroute every downstream probe on one axis onto the
20046 // sibling axis's overlay entry and pass every propagation-probe
20047 // test that expected only the stale axis's value. Peer of the
20048 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
20049 // (40cc4e5).
20050 let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
20051 for (i, a) in all.iter().enumerate() {
20052 for b in all.iter().skip(i + 1) {
20053 assert_ne!(
20054 a, b,
20055 "MEMBRO_KEY_* consts must be pairwise-distinct \
20056 canonical byte-sequences — got `{a}` == `{b}`",
20057 );
20058 }
20059 }
20060 }
20061
20062 // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
20063 // URL-path fallback resolver every HTTPRoute-aware renderer
20064 // reaching for a per-rule path-list resolution routes through.
20065 // The four pin tests below fix the four-way accept-set the
20066 // resolver must always honor: (:paths-non-empty-verbatim,
20067 // :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
20068 // :paths-preserves-order-across-multiple-entries) — drift on any
20069 // arm surfaces at caixa-core build time rather than at cluster-
20070 // apply time. Peer discipline with `MeshPolicy::is_empty` on the
20071 // sibling `:politicas` typed-primitive dispatch axis.
20072
20073 fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
20074 Entrada {
20075 host: "example.com".into(),
20076 para: "cart".into(),
20077 paths: paths.into_iter().map(String::from).collect(),
20078 port: DEFAULT_SERVICO_PORT,
20079 }
20080 }
20081
20082 #[test]
20083 fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
20084 // The typed `:entrada :paths` slot carries an author-declared
20085 // list — the resolver returns each entry verbatim, no
20086 // catch-all substitution. The canonical "author declared
20087 // paths, honor them verbatim" arm of the path-list dispatch.
20088 let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20089 assert_eq!(
20090 e.resolved_paths(),
20091 vec!["/api/cart", "/api/products"],
20092 "resolved_paths must return each `:entrada :paths` entry \
20093 verbatim when the typed slot is non-empty (got {:?})",
20094 e.resolved_paths(),
20095 );
20096 }
20097
20098 #[test]
20099 fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
20100 // Empty `:entrada :paths` slot — the resolver substitutes the
20101 // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
20102 // catch-all fallback verbatim. Pins the empty-arm of the
20103 // resolver's four-way accept-set against a future silent
20104 // detour that returned an empty Vec (which would emit an
20105 // HTTPRoute with zero rules — silently dropping every
20106 // external `:entrada` flow at admission time), routed to a
20107 // different fallback shape, or dropped the catch-all
20108 // altogether.
20109 let e = entrada_with_paths(vec![]);
20110 assert_eq!(
20111 e.resolved_paths(),
20112 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
20113 "resolved_paths on empty `:entrada :paths` must fall back \
20114 to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
20115 all — got {:?}",
20116 e.resolved_paths(),
20117 );
20118 }
20119
20120 #[test]
20121 fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
20122 // Single-entry `:entrada :paths` — the resolver returns the
20123 // single declared path verbatim, NOT the catch-all fallback
20124 // (author declared a path, honor it — the empty-arm and the
20125 // len-1 arm are semantically distinct axes of the resolver's
20126 // accept-set). Pins that the resolver treats "author declared
20127 // one path" as authored input, not as the empty case.
20128 let e = entrada_with_paths(vec!["/api/only"]);
20129 assert_eq!(
20130 e.resolved_paths(),
20131 vec!["/api/only"],
20132 "resolved_paths on single-entry `:entrada :paths` must \
20133 return the declared path verbatim, NOT the catch-all \
20134 fallback (got {:?})",
20135 e.resolved_paths(),
20136 );
20137 }
20138
20139 #[test]
20140 fn resolved_paths_preserves_author_declared_order() {
20141 // The `:entrada :paths` list is author-ordered — the resolver
20142 // preserves the author's declaration order verbatim, since
20143 // per-rule dispatch order at the K8s Gateway API HTTPRoute
20144 // consumer is significant (first-match-wins under the
20145 // path-prefix matcher). Pins against a future silent
20146 // re-sort / dedup / normalize detour that reordered author
20147 // input.
20148 let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
20149 assert_eq!(
20150 e.resolved_paths(),
20151 vec!["/z/last", "/a/first", "/m/mid"],
20152 "resolved_paths must preserve author-declared `:entrada \
20153 :paths` order verbatim — got {:?}",
20154 e.resolved_paths(),
20155 );
20156 }
20157
20158 // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
20159 // slot `&[String]` slice accessor every per-`:entrada` consumer
20160 // that must see the author's declaration verbatim (not the
20161 // fallback-applied projection the sibling `resolved_paths`
20162 // returns) routes through. The three pin tests below fix the
20163 // accept-set the accessor must honor: (:non-empty-byte-equal,
20164 // :empty-projects-empty-slice, :preserves-author-declared-order)
20165 // — drift on any arm surfaces at caixa-core build time rather
20166 // than at cluster-apply time. Peer discipline with the sibling
20167 // [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
20168 // peer M3 mesh-slot `Vec<String>`-carry axis.
20169
20170 #[test]
20171 fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
20172 // Byte-equal pin: [`Entrada::paths`] must project the raw
20173 // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
20174 // slice borrowed from the typed slot's own [`Vec<String>`]
20175 // storage — no re-ordering, no dedup, no per-entry normalization,
20176 // no fallback substitution (the fallback-applying projection is
20177 // the sibling [`Entrada::resolved_paths`] resolver). Pins against
20178 // a future silent detour that re-normalized the list, dropped
20179 // duplicates the [`AplicacaoSpec::validate`]
20180 // `EntradaPathDuplicate` refusal already rejects at build time,
20181 // or (most severe) accidentally routed through the fallback-
20182 // applying sibling and returned the substrate catch-all when
20183 // the author declared an empty list — collapsing the raw-slot
20184 // and fallback-applied axes into one and breaking the
20185 // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
20186 //
20187 // Peer of the sibling
20188 // [`Placement::clusters`]-shape byte-equal pin
20189 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20190 // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
20191 let fixtures: Vec<Vec<String>> = vec![
20192 Vec::new(),
20193 vec!["/api/cart".into()],
20194 vec!["/api/cart".into(), "/api/products".into()],
20195 vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
20196 ];
20197 for paths in fixtures {
20198 let e = Entrada {
20199 host: "example.com".into(),
20200 para: "cart".into(),
20201 paths: paths.clone(),
20202 port: DEFAULT_SERVICO_PORT,
20203 };
20204 assert_eq!(
20205 e.paths(),
20206 paths.as_slice(),
20207 "Entrada::paths must return :entrada :paths verbatim \
20208 (got {:?}, expected {:?})",
20209 e.paths(),
20210 paths.as_slice(),
20211 );
20212 assert_eq!(
20213 e.paths(),
20214 e.paths.as_slice(),
20215 "Entrada::paths accessor and .paths.as_slice() field \
20216 access must byte-equal — the accessor is the substrate-\
20217 primitive typed dispatch every downstream per-`:entrada` \
20218 raw-slot path-list consumer must route through",
20219 );
20220 assert_eq!(
20221 e.paths().len(),
20222 e.paths.len(),
20223 "Entrada::paths().len() must byte-equal self.paths.len() \
20224 — a length drift would silently split the paired \
20225 pre-flight cascade-head `.is_empty()` probe input in \
20226 the sibling [`Entrada::resolved_paths`] resolver from \
20227 the per-entry validate loop's traversal input in \
20228 [`AplicacaoSpec::validate`]",
20229 );
20230 }
20231 }
20232
20233 #[test]
20234 fn resolved_paths_reads_through_lifted_paths_accessor() {
20235 // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
20236 // pre-flight `.paths().is_empty()` cascade-head probe (which
20237 // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
20238 // catch-all fallback arm when the accessor projects the empty
20239 // slice) and the per-entry `.paths().iter().map(String::as_str)`
20240 // projection (which must reach every entry in the same order
20241 // the accessor projects, so the sibling
20242 // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
20243 // per-entry projection stay in lockstep by construction) must
20244 // both key off the lifted accessor. Pins the two-site coherence
20245 // by exercising each production consumer end-to-end: (1) the
20246 // catch-all-fallback arm under the empty slice, (2) the
20247 // author-declared-verbatim arm under a two-entry cohort whose
20248 // per-entry projection must byte-equal the input's per-entry
20249 // author-declared paths in the author's declared order.
20250 //
20251 // Peer of the sibling M3
20252 // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
20253 // `validate_placement_reads_through_lifted_clusters_accessor`
20254 // on the sibling `Placement::clusters` reader-site convergence.
20255 let empty = entrada_with_paths(vec![]);
20256 assert_eq!(
20257 empty.resolved_paths(),
20258 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
20259 "resolved_paths on empty :entrada :paths must trip the \
20260 lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
20261 catch-all fallback — routing through the lifted paths() \
20262 accessor must not silently drop the fallback arm",
20263 );
20264
20265 let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20266 assert_eq!(
20267 declared.resolved_paths(),
20268 vec!["/api/cart", "/api/products"],
20269 "resolved_paths on non-empty :entrada :paths must return each \
20270 entry verbatim in the author's declared order — routing \
20271 through the lifted paths() accessor must not silently \
20272 reorder or drop entries",
20273 );
20274 // Byte-equal pin against the raw-slot accessor to keep the
20275 // fallback-applying resolver's per-entry projection input in
20276 // lockstep with the raw-slot accessor's projection.
20277 let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
20278 assert_eq!(
20279 declared.resolved_paths(),
20280 raw_projected,
20281 "resolved_paths non-empty projection must byte-equal the \
20282 lifted paths() accessor's per-entry String::as_str projection \
20283 — the two projections share the same input slice by \
20284 construction, so any drift here would surface a silent \
20285 re-ordering / dedup / normalization detour in the resolver",
20286 );
20287 }
20288
20289 #[test]
20290 fn validate_reads_through_lifted_entrada_paths_accessor() {
20291 // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
20292 // per-entry value-shape gate's `for p in e.paths()` traversal
20293 // (which must reach every entry in the same order the accessor
20294 // projects, so both the per-entry `EntradaPathEmpty` /
20295 // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
20296 // the duplicate-detection HashSet insert that trips
20297 // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
20298 // projection) must route through the lifted accessor. Pins the
20299 // coherence by exercising each production consumer end-to-end:
20300 // (1) the `EntradaPathEmpty` refusal fires on the second entry
20301 // of a two-entry cohort whose head is valid but tail is empty
20302 // (which requires the loop to reach the second entry through
20303 // the accessor), and (2) the `EntradaPathDuplicate` refusal
20304 // fires on the second entry of a two-entry cohort that shares
20305 // a path (which requires the loop to reach both entries — a
20306 // first-entry-only projection would silently pass since the
20307 // dedup HashSet has room for the first insert).
20308 //
20309 // Peer of the sibling
20310 // `validate_placement_reads_through_lifted_clusters_accessor`
20311 // on the sibling `Placement::clusters` reader-site convergence.
20312 let base = crate::AplicacaoSpec {
20313 membros: vec![crate::Membro {
20314 caixa: "cart".into(),
20315 versao: "^0.1".into(),
20316 }],
20317 contratos: Vec::new(),
20318 politicas: crate::MeshPolicy::default(),
20319 placement: crate::Placement {
20320 estrategia: crate::PlacementStrategy::SingleNode,
20321 clusters: vec!["rio".into()],
20322 shard_key: None,
20323 affinity: None,
20324 },
20325 entrada: Some(Entrada {
20326 host: "example.com".into(),
20327 para: "cart".into(),
20328 paths: vec!["/api/cart".into(), String::new()],
20329 port: DEFAULT_SERVICO_PORT,
20330 }),
20331 };
20332 assert_eq!(
20333 base.validate(),
20334 Err(crate::AplicacaoError::EntradaPathEmpty),
20335 "validate must trip EntradaPathEmpty on the second entry of \
20336 a two-entry cohort — routing through the lifted paths() \
20337 accessor must not silently short-circuit the loop at the \
20338 valid head entry",
20339 );
20340
20341 let mut dup = base;
20342 dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
20343 assert_eq!(
20344 dup.validate(),
20345 Err(crate::AplicacaoError::EntradaPathDuplicate {
20346 path: "/api/cart".into(),
20347 }),
20348 "validate must trip EntradaPathDuplicate on the second entry \
20349 of a two-entry cohort that shares a path — routing through \
20350 the lifted paths() accessor must not silently short-circuit \
20351 the dedup HashSet insert at the first entry",
20352 );
20353 }
20354
20355 // ── Entrada::hostname / Entrada::hostnames — the substrate-
20356 // canonical per-`:entrada` DNS-hostname resolver pair every
20357 // Gateway-API-aware renderer reaching for a per-listener
20358 // singular `hostname:` filter (Gateway) or a per-route plural
20359 // `spec.hostnames[]` filter list (HTTPRoute) routes through.
20360 // The three pin tests below fix the two-way accept-set the pair
20361 // must always honor: (:singular-byte-equal-to-host,
20362 // :plural-is-singleton-of-singular, :plural-len-is-one) — drift
20363 // on any arm surfaces at caixa-core build time rather than at
20364 // cluster-apply time when the API server refuses the HTTPRoute
20365 // for non-intersecting hostname filters. Peer discipline with
20366 // the sibling `resolved_paths` accept-set pin block above on the
20367 // per-`:entrada` path-list resolver axis.
20368
20369 fn entrada_with_host(host: &str) -> Entrada {
20370 Entrada {
20371 host: host.into(),
20372 para: "cart".into(),
20373 paths: Vec::new(),
20374 port: DEFAULT_SERVICO_PORT,
20375 }
20376 }
20377
20378 #[test]
20379 fn hostname_returns_entrada_host_byte_equal() {
20380 // The canonical singular-axis pin: [`Entrada::hostname`] must
20381 // return the `:entrada :host` field byte-for-byte, borrowed
20382 // from the typed slot's own [`String`] storage. Pins against a
20383 // future silent detour that re-normalized the host (an
20384 // accidental `.to_lowercase()` — validate_entrada_host already
20385 // enforces lowercase, so any re-normalization is redundant + a
20386 // drift surface between the validator and the accessor), a
20387 // trailing-`.` fully-qualified DNS shape substitution, or a
20388 // Punycode round-trip that lowered a Unicode host through IDNA.
20389 let e = entrada_with_host("checkout.quero.cloud");
20390 assert_eq!(
20391 e.hostname(),
20392 "checkout.quero.cloud",
20393 "Entrada::hostname must return :entrada :host verbatim \
20394 (got {:?})",
20395 e.hostname(),
20396 );
20397 assert_eq!(
20398 e.hostname(),
20399 e.host.as_str(),
20400 "Entrada::hostname must byte-equal the .host field access",
20401 );
20402 }
20403
20404 #[test]
20405 fn hostnames_returns_singleton_of_hostname_accessor() {
20406 // The pair-invariant pin: [`Entrada::hostnames`] must always
20407 // return exactly `vec![hostname()]` — the singleton list whose
20408 // sole entry is the substrate's canonical per-`:entrada`
20409 // singular hostname. Pins the two-consumer coherence axis: the
20410 // Gateway listener's singular `hostname:` filter and the
20411 // HTTPRoute's plural `spec.hostnames[]` filter list must
20412 // agree, else the Gateway API v1.x conformance layer rejects
20413 // the HTTPRoute at attach time with
20414 // `Accepted:False/NoMatchingParent` (the parent Gateway's
20415 // listener hostname doesn't intersect the route's hostname
20416 // filter list) — a divergence whose apply-time symptom is far
20417 // from any single-site commit and never surfaces in the
20418 // emitted YAML. Pinning the pair-invariant here makes any
20419 // future accidental split (an accidental `.to_string() + "."`
20420 // trailing-`.` on the plural side that didn't land on the
20421 // singular side, an accidental prefix stripping on one axis,
20422 // an accidental wildcard prepend the SNI fan-out overlay
20423 // authors on the plural side without a paired singular
20424 // migration) trip at caixa-core build time.
20425 let e = entrada_with_host("checkout.quero.cloud");
20426 assert_eq!(
20427 e.hostnames(),
20428 vec![e.hostname()],
20429 "Entrada::hostnames must return `vec![hostname()]` under \
20430 the pair-invariant — got {:?} vs. singleton {:?}",
20431 e.hostnames(),
20432 vec![e.hostname()],
20433 );
20434 }
20435
20436 #[test]
20437 fn hostnames_is_singleton_under_single_host_author_surface() {
20438 // The singleton-shape pin: under today's single-hostname-per-
20439 // `:entrada` author surface (the `:host` slot is a single
20440 // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
20441 // must always return a list of length exactly one. Pins
20442 // against a future silent detour that returned an empty list
20443 // (which would emit an HTTPRoute with `spec.hostnames: []` —
20444 // matching every incoming Host header regardless of the
20445 // Aplicacao's declared ingress apex, silently over-matching
20446 // every foreign VirtualHost the parent Gateway also fronts) or
20447 // a duplicated entry (which the Gateway API v1.x parser
20448 // accepts as a `[]-length-2 list of equal hostnames]` but
20449 // whose semantics differ from the intended singleton). The
20450 // author-surface extension point ("a future `:entrada
20451 // :alt-hosts` list overlay" the docstring names) is the sole
20452 // future axis that flips this pin — that migration will re-
20453 // author this test to pin the new plural cardinality.
20454 let e = entrada_with_host("checkout.quero.cloud");
20455 assert_eq!(
20456 e.hostnames().len(),
20457 1,
20458 "Entrada::hostnames must be a singleton under today's \
20459 single-hostname-per-`:entrada` author surface — got \
20460 length {}: {:?}",
20461 e.hostnames().len(),
20462 e.hostnames(),
20463 );
20464 }
20465
20466 // ── Entrada::destination — the substrate-canonical per-`:entrada`
20467 // destination-Servico scalar accessor every Gateway-API
20468 // HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
20469 // discriminator arg (HTTPRoute name composer) or a per-rule
20470 // `backendRefs[0].name` axis routes through. The two pin tests
20471 // below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
20472 // either arm surfaces at caixa-core build time rather than at
20473 // cluster-apply time when an HTTPRoute's `metadata.name` and
20474 // `backendRefs[]` silently disagree on which destination Servico
20475 // the ingress fronts. Peer discipline with the sibling
20476 // `resolved_paths` + `hostname` + `hostnames` accept-set pin
20477 // blocks above on the per-`:entrada` path-list / DNS-hostname
20478 // resolver axes.
20479
20480 #[test]
20481 fn destination_returns_entrada_para_byte_equal() {
20482 // The canonical destination-scalar pin: [`Entrada::destination`]
20483 // must return the `:entrada :para` field byte-for-byte, borrowed
20484 // from the typed slot's own [`String`] storage. Pins against a
20485 // future silent detour that re-normalized the destination (an
20486 // accidental `.to_lowercase()` — the destination Servico is
20487 // already validated as a DNS-1123 label upstream, so any
20488 // re-normalization is redundant + a drift surface between the
20489 // validator and the accessor), a namespace-prefix rewrite (an
20490 // accidental `format!("{namespace}/{para}")` per-CR fully-
20491 // qualified rewrite that didn't land on the peer axis), or a
20492 // per-cluster suffix stamp the operator authors on one
20493 // consumer without the other.
20494 for para in ["cart", "checkout", "catalog", "orders-v2"] {
20495 let e = Entrada {
20496 host: "checkout.quero.cloud".into(),
20497 para: para.into(),
20498 paths: Vec::new(),
20499 port: DEFAULT_SERVICO_PORT,
20500 };
20501 assert_eq!(
20502 e.destination(),
20503 para,
20504 "Entrada::destination must return :entrada :para verbatim \
20505 (got {:?}, expected {para:?})",
20506 e.destination(),
20507 );
20508 assert_eq!(
20509 e.destination(),
20510 e.para.as_str(),
20511 "Entrada::destination must byte-equal the .para field access",
20512 );
20513 }
20514 }
20515
20516 #[test]
20517 fn destination_borrows_from_entrada_para_storage() {
20518 // The borrow-not-copy pin: [`Entrada::destination`] must
20519 // return a `&str` slice that borrows from the typed slot's
20520 // own [`String`] storage — same-address invariant with
20521 // `entrada.para.as_str()`. Pins against a future silent detour
20522 // that allocated a fresh `String` (`self.para.clone()` in the
20523 // body would type-check but silently drop the borrow, and
20524 // every downstream consumer that assumed the returned slice
20525 // outlives `&self` would break on a stale-reference use-after-
20526 // free). Peer with the sibling `hostname_returns_entrada_
20527 // host_byte_equal` on the singular-DNS-hostname axis.
20528 let e = entrada_with_host("checkout.quero.cloud");
20529 let dest = e.destination();
20530 let para_slice = e.para.as_str();
20531 assert_eq!(
20532 dest.as_ptr(),
20533 para_slice.as_ptr(),
20534 "Entrada::destination must borrow from the .para String's \
20535 backing storage — a fresh allocation here means the \
20536 accessor no longer names the substrate-primitive typed \
20537 dispatch and every downstream consumer would silently \
20538 carry a detached copy",
20539 );
20540 assert_eq!(
20541 dest.len(),
20542 para_slice.len(),
20543 "Entrada::destination and .para.as_str() must byte-equal in \
20544 length as well as in address",
20545 );
20546 }
20547
20548 #[test]
20549 fn port_returns_entrada_port_verbatim_across_permutations() {
20550 // The canonical L4-port-scalar pin: [`Entrada::port`] must
20551 // return the `:entrada :port` field verbatim as a `u16` across
20552 // every author-declared value in the validated accept-set
20553 // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
20554 // silent detour that clamped the port (an accidental
20555 // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
20556 // land on the peer [`AplicacaoSpec::port_for_destination`]
20557 // resolver), rewrote it through a per-cluster port-remap table
20558 // the operator authors on one consumer without the other, or
20559 // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
20560 // serde-default value (which would silently collapse the
20561 // distinction between "author explicitly declared `:port 8080`"
20562 // and "author omitted the slot and inherited the default" the
20563 // future per-cluster override slot depends on). Peer with the
20564 // sibling `destination_returns_entrada_para_byte_equal` +
20565 // `hostname_returns_entrada_host_byte_equal` pins on the
20566 // per-`:entrada` `&str` scalar axes.
20567 for port in [
20568 SERVICO_PORT_MIN,
20569 DEFAULT_SERVICO_PORT,
20570 8443u16,
20571 9090u16,
20572 u16::MAX,
20573 ] {
20574 let e = Entrada {
20575 host: "checkout.quero.cloud".into(),
20576 para: "cart".into(),
20577 paths: Vec::new(),
20578 port,
20579 };
20580 assert_eq!(
20581 e.port(),
20582 port,
20583 "Entrada::port must return :entrada :port verbatim \
20584 (got {}, expected {port})",
20585 e.port(),
20586 );
20587 assert_eq!(
20588 e.port(),
20589 e.port,
20590 "Entrada::port accessor and .port field access must \
20591 byte-equal — the accessor is the substrate-primitive \
20592 typed dispatch every downstream L4-port consumer must \
20593 route through",
20594 );
20595 }
20596 }
20597
20598 #[test]
20599 fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
20600 // Two-consumer coherence pin: the
20601 // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
20602 // (which reads through [`Entrada::port`] to compare against
20603 // [`SERVICO_PORT_MIN`]) and the
20604 // [`AplicacaoSpec::port_for_destination`] resolver (which reads
20605 // through [`Entrada::port`] to emit the per-destination
20606 // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
20607 // lifted accessor, so any future rebrand on the typed slot's
20608 // reader shape lands at exactly one place. Pins the two-site
20609 // coherence by exercising a below-floor port through validate
20610 // (which must reject) and a validated in-accept-set port through
20611 // port_for_destination (which must emit the same value the
20612 // accessor returns).
20613 let mut spec = three_member_spec();
20614 if let Some(e) = spec.entrada.as_mut() {
20615 e.port = 0;
20616 }
20617 assert_eq!(
20618 spec.validate().unwrap_err(),
20619 AplicacaoError::EntradaPortZero,
20620 "validate must reject `:entrada :port 0` through the lifted \
20621 Entrada::port accessor — port zero lies below \
20622 SERVICO_PORT_MIN and the validator routes through port() \
20623 to name the floor",
20624 );
20625
20626 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
20627 let mut spec = three_member_spec();
20628 if let Some(e) = spec.entrada.as_mut() {
20629 e.port = port;
20630 }
20631 spec.validate().expect(
20632 "entrada with in-accept-set :port must validate — the \
20633 structural-floor gate reads through Entrada::port",
20634 );
20635 let entrada_ref = spec.entrada().expect(":entrada present");
20636 assert_eq!(
20637 spec.port_for_destination(entrada_ref.destination()),
20638 entrada_ref.port(),
20639 "port_for_destination(entrada.destination()) must equal \
20640 entrada.port() — the two consumers of the per-:entrada \
20641 L4-port axis (validator, per-destination resolver) both \
20642 route through Entrada::port",
20643 );
20644 }
20645 }
20646
20647 #[test]
20648 fn wit_contract_source_returns_de_byte_equal_across_permutations() {
20649 // The canonical caller-Servico-scalar pin: [`WitContract::source`]
20650 // must return the `:contratos :de` field byte-for-byte, borrowed
20651 // from the typed slot's own [`String`] storage. Peer of the
20652 // sibling `destination_returns_entrada_para_byte_equal` pin on
20653 // the per-`:entrada` axis — same "the substrate-primitive
20654 // accessor must byte-equal the raw field access verbatim across
20655 // every author-declared value" discipline extended to the
20656 // per-`:contratos` caller arm. Pins against a future silent
20657 // detour that re-normalized the caller (an accidental
20658 // `.to_lowercase()` — every `:contratos :de` is validated as a
20659 // DNS-1123 label upstream via `validate_contrato_caixa`, so any
20660 // re-normalization is redundant + a drift surface between the
20661 // validator and the accessor), a namespace-prefix rewrite (an
20662 // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
20663 // rewrite that didn't land on the peer axis), or a per-cluster
20664 // suffix stamp the operator authors on one consumer without the
20665 // other.
20666 for de in ["cart", "checkout", "catalog", "orders-v2"] {
20667 let c = WitContract {
20668 de: de.into(),
20669 para: "downstream".into(),
20670 wit: "wasi:http/proxy".into(),
20671 endpoint: Some("/lookup".into()),
20672 subject: None,
20673 slot: None,
20674 };
20675 assert_eq!(
20676 c.source(),
20677 de,
20678 "WitContract::source must return :contratos :de verbatim \
20679 (got {:?}, expected {de:?})",
20680 c.source(),
20681 );
20682 assert_eq!(
20683 c.source(),
20684 c.de.as_str(),
20685 "WitContract::source must byte-equal the .de field access",
20686 );
20687 }
20688 }
20689
20690 #[test]
20691 fn wit_contract_source_borrows_from_de_storage() {
20692 // The borrow-not-copy pin: [`WitContract::source`] must return a
20693 // `&str` slice that borrows from the typed slot's own [`String`]
20694 // storage — same-address invariant with `c.de.as_str()`. Pins
20695 // against a future silent detour that allocated a fresh `String`
20696 // (`self.de.clone()` in the body would type-check but silently
20697 // drop the borrow, and every downstream consumer that assumed
20698 // the returned slice outlives `&self` would break on a stale-
20699 // reference use-after-free). Peer of the sibling
20700 // `destination_borrows_from_entrada_para_storage` on the
20701 // per-`:entrada` axis.
20702 let c = WitContract {
20703 de: "cart".into(),
20704 para: "catalog".into(),
20705 wit: "wasi:http/proxy".into(),
20706 endpoint: Some("/lookup".into()),
20707 subject: None,
20708 slot: None,
20709 };
20710 let src = c.source();
20711 let de_slice = c.de.as_str();
20712 assert_eq!(
20713 src.as_ptr(),
20714 de_slice.as_ptr(),
20715 "WitContract::source must borrow from the .de String's \
20716 backing storage — a fresh allocation here means the \
20717 accessor no longer names the substrate-primitive typed \
20718 dispatch and every downstream consumer would silently \
20719 carry a detached copy",
20720 );
20721 assert_eq!(
20722 src.len(),
20723 de_slice.len(),
20724 "WitContract::source and .de.as_str() must byte-equal in \
20725 length as well as in address",
20726 );
20727 }
20728
20729 #[test]
20730 fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
20731 // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
20732 // must return the `:contratos :para` field byte-for-byte,
20733 // borrowed from the typed slot's own [`String`] storage. Peer of
20734 // the sibling `destination_returns_entrada_para_byte_equal` on
20735 // the per-`:entrada` axis — both accessors name "the destination-
20736 // Servico byte-string" concept on their respective mesh-slot
20737 // atoms (per-ingress apex vs. per-typed-edge callee) and both
20738 // must project the underlying `.para` field verbatim so every
20739 // downstream renderer that composes them with peer accessors
20740 // (e.g. `spec.port_for_destination(c.destination())` at the CNP
20741 // per-edge L4 port emit site) reads the same byte-string the
20742 // author declared.
20743 for para in ["catalog", "payment", "orders", "inventory-v3"] {
20744 let c = WitContract {
20745 de: "cart".into(),
20746 para: para.into(),
20747 wit: "wasi:http/proxy".into(),
20748 endpoint: Some("/lookup".into()),
20749 subject: None,
20750 slot: None,
20751 };
20752 assert_eq!(
20753 c.destination(),
20754 para,
20755 "WitContract::destination must return :contratos :para \
20756 verbatim (got {:?}, expected {para:?})",
20757 c.destination(),
20758 );
20759 assert_eq!(
20760 c.destination(),
20761 c.para.as_str(),
20762 "WitContract::destination must byte-equal the .para \
20763 field access",
20764 );
20765 }
20766 }
20767
20768 #[test]
20769 fn wit_contract_destination_borrows_from_para_storage() {
20770 // The borrow-not-copy pin: [`WitContract::destination`] must
20771 // return a `&str` slice that borrows from the typed slot's own
20772 // [`String`] storage — same-address invariant with
20773 // `c.para.as_str()`. Peer of the sibling
20774 // `destination_borrows_from_entrada_para_storage` on the
20775 // per-`:entrada` axis.
20776 let c = WitContract {
20777 de: "cart".into(),
20778 para: "catalog".into(),
20779 wit: "wasi:http/proxy".into(),
20780 endpoint: Some("/lookup".into()),
20781 subject: None,
20782 slot: None,
20783 };
20784 let dest = c.destination();
20785 let para_slice = c.para.as_str();
20786 assert_eq!(
20787 dest.as_ptr(),
20788 para_slice.as_ptr(),
20789 "WitContract::destination must borrow from the .para \
20790 String's backing storage — a fresh allocation here means \
20791 the accessor no longer names the substrate-primitive typed \
20792 dispatch and every downstream consumer would silently \
20793 carry a detached copy",
20794 );
20795 assert_eq!(
20796 dest.len(),
20797 para_slice.len(),
20798 "WitContract::destination and .para.as_str() must byte-equal \
20799 in length as well as in address",
20800 );
20801 }
20802
20803 #[test]
20804 fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
20805 // The canonical per-`:contratos` WIT-world-reference scalar pin:
20806 // [`WitContract::world_ref`] must return the `:contratos :wit`
20807 // field byte-for-byte, borrowed from the typed slot's own
20808 // [`String`] storage. Sibling of the peer per-`:contratos`
20809 // [`WitContract::source`] / [`WitContract::destination`]
20810 // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
20811 // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
20812 // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
20813 // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
20814 // "the substrate-primitive accessor must byte-equal the raw
20815 // field access verbatim across every author-declared value"
20816 // discipline extended to the per-`:contratos` WIT-world arm.
20817 // Pins against a future silent detour that re-canonicalized the
20818 // WIT world reference (an accidental `.to_lowercase()` pass that
20819 // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
20820 // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
20821 // gate is already lowercase-prefixed so any re-normalization is
20822 // redundant + a drift surface between the validator and the
20823 // accessor), an M4-promotion-shape rewrite that formatted a
20824 // typed WIT-world enum through [`Display`] and silently drifted
20825 // the printer output from the source `caixa.lisp`, or a per-
20826 // cluster WIT-alias rewrite that didn't land on the peer field-
20827 // access sites. Five values sweep the shape-dispatch accept-set
20828 // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
20829 // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
20830 // `wasi:keyvalue/`).
20831 for (wit, endpoint, subject, slot) in [
20832 ("wasi:http/proxy", Some("/lookup"), None, None),
20833 ("http:proxy", Some("/health"), None, None),
20834 ("nats:pub-sub", None, Some("orders.paid"), None),
20835 ("kafka:events", None, Some("checkout-events"), None),
20836 ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
20837 ] {
20838 let c = WitContract {
20839 de: "cart".into(),
20840 para: "downstream".into(),
20841 wit: wit.into(),
20842 endpoint: endpoint.map(str::to_string),
20843 subject: subject.map(str::to_string),
20844 slot: slot.map(str::to_string),
20845 };
20846 assert_eq!(
20847 c.world_ref(),
20848 wit,
20849 "WitContract::world_ref must return :contratos :wit \
20850 verbatim (got {:?}, expected {wit:?})",
20851 c.world_ref(),
20852 );
20853 assert_eq!(
20854 c.world_ref(),
20855 c.wit.as_str(),
20856 "WitContract::world_ref must byte-equal the .wit field \
20857 access",
20858 );
20859 }
20860 }
20861
20862 #[test]
20863 fn wit_contract_world_ref_borrows_from_wit_storage() {
20864 // The borrow-not-copy pin: [`WitContract::world_ref`] must
20865 // return a `&str` slice that borrows from the typed slot's own
20866 // [`String`] storage — same-address invariant with
20867 // `c.wit.as_str()`. Pins against a future silent detour that
20868 // allocated a fresh `String` (`self.wit.clone()` in the body
20869 // would type-check but silently drop the borrow, and every
20870 // downstream consumer that assumed the returned slice outlives
20871 // `&self` would break on a stale-reference use-after-free — the
20872 // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
20873 // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
20874 // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
20875 // / [`is_pubsub`][WitContract::is_pubsub] /
20876 // [`is_store`][WitContract::is_store] methods route through —
20877 // each borrow from the WitContract's own storage and each would
20878 // silently misbehave if this accessor produced a detached copy).
20879 // Peer of the sibling per-`:contratos` [`WitContract::source`] /
20880 // [`WitContract::destination`] and per-`:entrada`
20881 // [`Entrada::destination`] / [`Entrada::hostname`] and
20882 // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
20883 // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
20884 let c = WitContract {
20885 de: "cart".into(),
20886 para: "catalog".into(),
20887 wit: "wasi:http/proxy".into(),
20888 endpoint: Some("/lookup".into()),
20889 subject: None,
20890 slot: None,
20891 };
20892 let world = c.world_ref();
20893 let wit_slice = c.wit.as_str();
20894 assert_eq!(
20895 world.as_ptr(),
20896 wit_slice.as_ptr(),
20897 "WitContract::world_ref must borrow from the .wit String's \
20898 backing storage — a fresh allocation here means the \
20899 accessor no longer names the substrate-primitive typed \
20900 dispatch and every downstream consumer would silently carry \
20901 a detached copy",
20902 );
20903 assert_eq!(
20904 world.len(),
20905 wit_slice.len(),
20906 "WitContract::world_ref and .wit.as_str() must byte-equal in \
20907 length as well as in address",
20908 );
20909 }
20910
20911 #[test]
20912 fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
20913 // Sibling-triple invariant pin composing all three per-`:contratos`
20914 // substrate-primitive typed dispatches — [`WitContract::source`]
20915 // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
20916 // [`WitContract::world_ref`] — at the joint
20917 // `(source(), destination(), world_ref())` call shape every
20918 // renderer that fans on per-edge caller-callee-shape identity
20919 // keys off. The invariant, evaluated per-contract:
20920 //
20921 // (c.source(), c.destination(), c.world_ref())
20922 // == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
20923 //
20924 // Closes the last unlifted per-`:contratos` scalar axis — every
20925 // downstream consumer that reads the triple now routes through
20926 // exactly three typed dispatches on the substrate primitive,
20927 // not two typed + one open-coded field access. A future refactor
20928 // that silently split any one accessor's projection (an
20929 // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
20930 // canonicalization that didn't reach the peer `source`/
20931 // `destination` arms, an accidental `source()` per-cluster
20932 // caller-alias rewrite that didn't land on the `world_ref` peer)
20933 // surfaces at caixa-core build time. Peer of the sibling per-
20934 // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
20935 // per-`:entrada` `(hostname(), destination())` (6db982c /
20936 // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
20937 // axes, extended to the per-`:contratos` triple.
20938 for (de, para, wit, endpoint, subject, slot) in [
20939 (
20940 "cart",
20941 "catalog",
20942 "wasi:http/proxy",
20943 Some("/lookup"),
20944 None,
20945 None,
20946 ),
20947 (
20948 "checkout",
20949 "orders",
20950 "nats:pub-sub",
20951 None,
20952 Some("orders.paid"),
20953 None,
20954 ),
20955 (
20956 "cart",
20957 "kv",
20958 "wasi:keyvalue/store",
20959 None,
20960 None,
20961 Some("carts/{cart_id}"),
20962 ),
20963 (
20964 "orders-v2",
20965 "inventory-v3",
20966 "http:proxy",
20967 Some("/reserve"),
20968 None,
20969 None,
20970 ),
20971 ] {
20972 let c = WitContract {
20973 de: de.into(),
20974 para: para.into(),
20975 wit: wit.into(),
20976 endpoint: endpoint.map(str::to_string),
20977 subject: subject.map(str::to_string),
20978 slot: slot.map(str::to_string),
20979 };
20980 assert_eq!(
20981 (c.source(), c.destination(), c.world_ref()),
20982 (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
20983 "(WitContract::source, ::destination, ::world_ref) must \
20984 project (.de, .para, .wit) verbatim across every author-\
20985 declared triple (got ({:?}, {:?}, {:?}), expected \
20986 ({de:?}, {para:?}, {wit:?}))",
20987 c.source(),
20988 c.destination(),
20989 c.world_ref(),
20990 );
20991 }
20992 }
20993
20994 #[test]
20995 fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
20996 // The canonical per-`:contratos` owned-form caller-callee-pair
20997 // pin: [`WitContract::edge_pair`] must return the
20998 // `(source(), destination())` tuple in owned form byte-for-byte,
20999 // projected through the lifted [`WitContract::source`] /
21000 // [`WitContract::destination`] scalar accessors. Pins the
21001 // composite-projection invariant on the per-`:contratos`
21002 // mesh-slot atom — every author-declared `(de, para)` pair must
21003 // round-trip verbatim through the substrate primitive's typed
21004 // dispatch, so the nine [`AplicacaoError`] diagnostic-
21005 // construction sites the accessor now feeds
21006 // ([`AplicacaoError::EmptyWit`],
21007 // [`AplicacaoError::ContratoEndpointEmpty`],
21008 // [`AplicacaoError::ContratoEndpointNotAbsolute`],
21009 // [`AplicacaoError::ContratoEndpointInvalid`],
21010 // [`AplicacaoError::ContratoSubjectEmpty`],
21011 // [`AplicacaoError::ContratoSubjectInvalid`],
21012 // [`AplicacaoError::ContratoSlotEmpty`],
21013 // [`AplicacaoError::ContratoSlotInvalid`],
21014 // [`AplicacaoError::ContratoDuplicate`]) all read the same
21015 // `(de, para)` label pair every author sees at the source
21016 // `caixa.lisp`. Pins against a future silent detour that swapped
21017 // the `.0` / `.1` arms (an accidental `(destination(),
21018 // source())` re-order in the body would silently invert every
21019 // downstream diagnostic's `de:` / `para:` label pair, silently
21020 // reversing the direction of every operator-facing typed error
21021 // arrow), a fresh-allocation shape drift (an accidental
21022 // `.to_string()` on one arm but not the other would leave the
21023 // owned/borrowed pair mismatched vs. the sibling `source()` /
21024 // `destination()` returns), or an M4 per-cluster caller/callee-
21025 // alias rewrite that landed on `source()` without reaching
21026 // `destination()` (or vice versa). Peer of the sibling per-
21027 // `:contratos` `(source, destination, world_ref)` triple
21028 // pin above on the mesh-slot-atom scalar-value axes, extended
21029 // to the owned-form pair-projection axis.
21030 for (de, para, wit, endpoint, subject, slot) in [
21031 (
21032 "cart",
21033 "catalog",
21034 "wasi:http/proxy",
21035 Some("/lookup"),
21036 None,
21037 None,
21038 ),
21039 (
21040 "checkout",
21041 "orders",
21042 "nats:pub-sub",
21043 None,
21044 Some("orders.paid"),
21045 None,
21046 ),
21047 (
21048 "cart",
21049 "kv",
21050 "wasi:keyvalue/store",
21051 None,
21052 None,
21053 Some("carts/{cart_id}"),
21054 ),
21055 (
21056 "orders-v2",
21057 "inventory-v3",
21058 "http:proxy",
21059 Some("/reserve"),
21060 None,
21061 None,
21062 ),
21063 ] {
21064 let c = WitContract {
21065 de: de.into(),
21066 para: para.into(),
21067 wit: wit.into(),
21068 endpoint: endpoint.map(str::to_string),
21069 subject: subject.map(str::to_string),
21070 slot: slot.map(str::to_string),
21071 };
21072 assert_eq!(
21073 c.edge_pair(),
21074 (de.to_string(), para.to_string()),
21075 "WitContract::edge_pair must return (:contratos :de, \
21076 :contratos :para) as an owned tuple verbatim (got {:?}, \
21077 expected ({de:?}, {para:?}))",
21078 c.edge_pair(),
21079 );
21080 }
21081 }
21082
21083 #[test]
21084 fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
21085 // The composition pin: [`WitContract::edge_pair`] must return
21086 // exactly `(source().to_string(), destination().to_string())` —
21087 // the owned form of the sibling accessor pair — so any future
21088 // refactor that silently re-authored the caller-arm / callee-arm
21089 // projection to bypass the lifted scalar accessors (an accidental
21090 // `(self.de.clone(), self.para.clone())` regression back to the
21091 // raw field-access shape, an M4-typed-caller-enum `Display`
21092 // re-canonicalization on `source()` that didn't reach
21093 // `edge_pair()`, a per-cluster alias rewrite the operator lands
21094 // on `destination()` without reaching this composite projection)
21095 // trips at caixa-core build time. Pins the "typed dispatch
21096 // composes with typed dispatch, not with raw field access"
21097 // discipline every downstream diagnostic-construction site now
21098 // routes through — a `de:` / `para:` label pair whose
21099 // projection silently drifted off the substrate primitive's
21100 // scalar accessors would silently split the diagnostic's self-
21101 // locating signal from the source `caixa.lisp` author's view.
21102 // Peer of the sibling per-`:politicas` `is_empty` /
21103 // `validate_politicas` accessor-routing-pin family on the M3
21104 // mesh-slot family (18575, 18739, 18918, 19140, 19371).
21105 let c = WitContract {
21106 de: "cart".into(),
21107 para: "catalog".into(),
21108 wit: "wasi:http/proxy".into(),
21109 endpoint: Some("/lookup".into()),
21110 subject: None,
21111 slot: None,
21112 };
21113 assert_eq!(
21114 c.edge_pair(),
21115 (c.source().to_string(), c.destination().to_string()),
21116 "WitContract::edge_pair must compose exactly \
21117 (source().to_string(), destination().to_string()) — a \
21118 bypass of either sibling accessor here would silently \
21119 decouple the composite-projection axis from the \
21120 substrate-primitive scalar accessors every downstream \
21121 consumer routes through",
21122 );
21123 }
21124
21125 #[test]
21126 fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
21127 {
21128 // The canonical per-`:contratos` owned-form
21129 // caller-callee-world-ref-triple pin:
21130 // [`WitContract::edge_triple`] must return the
21131 // `(source(), destination(), world_ref())` tuple in owned form
21132 // byte-for-byte, projected through the lifted
21133 // [`WitContract::source`] / [`WitContract::destination`] /
21134 // [`WitContract::world_ref`] scalar accessors. Pins the
21135 // composite-projection invariant on the per-`:contratos`
21136 // mesh-slot atom — every author-declared `(de, para, wit)`
21137 // triple must round-trip verbatim through the substrate
21138 // primitive's typed dispatch, so the nine
21139 // [`AplicacaoError`] diagnostic-construction sites the
21140 // accessor now feeds (the [`WitTarget`]-dispatch's eight
21141 // wrong-target / missing-target / invalid-wit / capability-
21142 // with-payload arms in [`WitContract::target`], plus the
21143 // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
21144 // diagnostic constructor in [`AplicacaoSpec::validate`]) all
21145 // read the same `(de, para, wit)` triple every author sees at
21146 // the source `caixa.lisp`. Pins against a future silent
21147 // detour that swapped any two arms (an accidental `(destination(),
21148 // source(), world_ref())` re-order in the body would silently
21149 // invert every downstream diagnostic's `de:` / `para:` label
21150 // pair, silently reversing the direction of every operator-
21151 // facing typed error arrow), a fresh-allocation shape drift
21152 // (an accidental `.to_string()` skipped on one arm would leave
21153 // the owned/borrowed triple mismatched vs. the sibling
21154 // `source()` / `destination()` / `world_ref()` returns), or an
21155 // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
21156 // canonicalization pass that landed on one accessor without
21157 // reaching the peers. Peer of the sibling per-`:contratos`
21158 // caller-callee-pair
21159 // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
21160 // pin on the mesh-slot-atom composite-projection axis,
21161 // extended to the triple-projection axis.
21162 for (de, para, wit, endpoint, subject, slot) in [
21163 (
21164 "cart",
21165 "catalog",
21166 "wasi:http/proxy",
21167 Some("/lookup"),
21168 None,
21169 None,
21170 ),
21171 (
21172 "checkout",
21173 "orders",
21174 "nats:pub-sub",
21175 None,
21176 Some("orders.paid"),
21177 None,
21178 ),
21179 (
21180 "cart",
21181 "kv",
21182 "wasi:keyvalue/store",
21183 None,
21184 None,
21185 Some("carts/{cart_id}"),
21186 ),
21187 (
21188 "orders-v2",
21189 "inventory-v3",
21190 "http:proxy",
21191 Some("/reserve"),
21192 None,
21193 None,
21194 ),
21195 ] {
21196 let c = WitContract {
21197 de: de.into(),
21198 para: para.into(),
21199 wit: wit.into(),
21200 endpoint: endpoint.map(str::to_string),
21201 subject: subject.map(str::to_string),
21202 slot: slot.map(str::to_string),
21203 };
21204 assert_eq!(
21205 c.edge_triple(),
21206 (de.to_string(), para.to_string(), wit.to_string()),
21207 "WitContract::edge_triple must return (:contratos :de, \
21208 :contratos :para, :contratos :wit) as an owned triple \
21209 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
21210 c.edge_triple(),
21211 );
21212 }
21213 }
21214
21215 #[test]
21216 fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
21217 // The composition pin: [`WitContract::edge_triple`] must return
21218 // exactly `(source().to_string(), destination().to_string(),
21219 // world_ref().to_string())` — the owned form of the sibling
21220 // scalar-accessor triple — so any future refactor that silently
21221 // re-authored one arm's projection to bypass the lifted scalar
21222 // accessors (an accidental `(self.de.clone(), self.para.clone(),
21223 // self.wit.clone())` regression back to the raw field-access
21224 // shape the internal `edge` closure and the ContratoDuplicate
21225 // diagnostic both carried before this lift landed, an
21226 // M4-typed-caller-enum `Display` re-canonicalization on
21227 // `source()` that didn't reach `edge_triple()`, a per-cluster
21228 // alias rewrite the operator lands on `destination()` /
21229 // `world_ref()` without reaching this composite projection)
21230 // trips at caixa-core build time. Pins the "typed dispatch
21231 // composes with typed dispatch, not with raw field access"
21232 // discipline every downstream diagnostic-construction site now
21233 // routes through — a `de:` / `para:` / `wit:` triple whose
21234 // projection silently drifted off the substrate primitive's
21235 // scalar accessors would silently split the diagnostic's self-
21236 // locating signal from the source `caixa.lisp` author's view.
21237 // Peer of the sibling per-`:contratos` edge_pair composition-
21238 // pin above on the mesh-slot-atom composite-projection axis.
21239 let c = WitContract {
21240 de: "cart".into(),
21241 para: "catalog".into(),
21242 wit: "wasi:http/proxy".into(),
21243 endpoint: Some("/lookup".into()),
21244 subject: None,
21245 slot: None,
21246 };
21247 assert_eq!(
21248 c.edge_triple(),
21249 (
21250 c.source().to_string(),
21251 c.destination().to_string(),
21252 c.world_ref().to_string(),
21253 ),
21254 "WitContract::edge_triple must compose exactly \
21255 (source().to_string(), destination().to_string(), \
21256 world_ref().to_string()) — a bypass of any sibling accessor \
21257 here would silently decouple the composite-projection axis \
21258 from the substrate-primitive scalar accessors every \
21259 downstream consumer routes through",
21260 );
21261 }
21262
21263 #[test]
21264 fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
21265 // The canonical semantics-pin: [`WitContract::edge_triple`] must
21266 // project the full `(de, para, wit)` identity of a `:contratos`
21267 // edge — the sub-triple every triple-carrying
21268 // [`AplicacaoError::Contrato*`] diagnostic weaves into its
21269 // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
21270 // missing-target, capability-with-payload, invalid-wit, and the
21271 // duplicate-gate). Rejects a drift in shape (an accidental
21272 // silent detour that returned a `(de, para)` pair or added an
21273 // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
21274 // would trip here because the return type would no longer
21275 // pattern-match the eight `let (de, para, wit) = edge();`
21276 // destructures the [`WitContract::target`] dispatch feeds off
21277 // + the paired duplicate-gate `let (de, para, wit) =
21278 // c.edge_triple();` destructure in
21279 // [`AplicacaoSpec::validate`]). Peer of the sibling per-
21280 // `:contratos` caller-callee-pair pin above extended to the
21281 // triple projection surface: closes the "one composite
21282 // accessor per typed diagnostic-construction sub-tuple"
21283 // discipline on the per-`:contratos` mesh-slot-atom axis.
21284 let c = WitContract {
21285 de: "checkout".into(),
21286 para: "orders".into(),
21287 wit: "nats:pub-sub".into(),
21288 endpoint: None,
21289 subject: Some("orders.paid".into()),
21290 slot: None,
21291 };
21292 let (de, para, wit) = c.edge_triple();
21293 assert_eq!(de, "checkout");
21294 assert_eq!(para, "orders");
21295 assert_eq!(wit, "nats:pub-sub");
21296 }
21297
21298 #[test]
21299 fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
21300 {
21301 // The composition pin: [`WitContract::identity`] must return
21302 // exactly `(source(), destination(), world_ref(), endpoint(),
21303 // subject(), slot())` — the borrowed form of the six-scalar-
21304 // accessor identity axis. Any future refactor that silently
21305 // re-authored one arm's projection to bypass a scalar accessor
21306 // (a `self.de.as_str()` regression back to raw field access on
21307 // any of the three required arms, a `self.endpoint.as_deref()`
21308 // regression on any of the three optional arms, an M4 per-
21309 // cluster caller/callee-alias rewrite the operator lands on
21310 // `source()` / `destination()` without reaching this composite
21311 // projection) trips at caixa-core build time. Sweeps four
21312 // permutations of the WIT-shape × payload lattice — HTTP with
21313 // endpoint, pub-sub with subject, store with slot, payload-less
21314 // capability — so every payload arm is exercised. Peer of the
21315 // sibling per-`:contratos`
21316 // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
21317 // composition pin on the mesh-slot-atom composite-projection
21318 // axis; extends the discipline from the (de, para, wit) prefix
21319 // onto the full-identity axis carrying the three payload arms.
21320 for (de, para, wit, endpoint, subject, slot) in [
21321 (
21322 "cart",
21323 "catalog",
21324 "wasi:http/proxy",
21325 Some("/lookup"),
21326 None,
21327 None,
21328 ),
21329 (
21330 "checkout",
21331 "orders",
21332 "nats:pub-sub",
21333 None,
21334 Some("orders.paid"),
21335 None,
21336 ),
21337 (
21338 "cart",
21339 "kv",
21340 "wasi:keyvalue/store",
21341 None,
21342 None,
21343 Some("carts/{cart_id}"),
21344 ),
21345 ("audit", "sink", "wasi:logging", None, None, None),
21346 ] {
21347 let c = WitContract {
21348 de: de.into(),
21349 para: para.into(),
21350 wit: wit.into(),
21351 endpoint: endpoint.map(str::to_owned),
21352 subject: subject.map(str::to_owned),
21353 slot: slot.map(str::to_owned),
21354 };
21355 assert_eq!(
21356 c.identity(),
21357 (
21358 c.source(),
21359 c.destination(),
21360 c.world_ref(),
21361 c.endpoint(),
21362 c.subject(),
21363 c.slot(),
21364 ),
21365 "WitContract::identity must compose exactly \
21366 (source(), destination(), world_ref(), endpoint(), \
21367 subject(), slot()) — a bypass of any sibling accessor \
21368 here would silently decouple the identity-projection \
21369 axis from the substrate-primitive scalar accessors \
21370 every dedup-key consumer routes through",
21371 );
21372 }
21373 }
21374
21375 #[test]
21376 fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
21377 // The canonical semantics-pin: [`WitContract::identity`] must
21378 // project the six-axis (de, para, wit, endpoint, subject, slot)
21379 // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21380 // gate keys off — two `WitContract`s that agree on all six axes
21381 // are the same typed edge declared twice, the graph-edge
21382 // analogue of duplicate `:membros` / `:placement :clusters` /
21383 // `:entrada :paths` entries. Rejects a shape drift (an
21384 // accidental silent detour that returned a prefix tuple or
21385 // added an extra field) by pattern-matching the six-arm shape.
21386 // Peer of the sibling per-`:contratos`
21387 // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
21388 // pin extended from the (de, para, wit) prefix onto the full
21389 // six-axis identity that the dedup key rides.
21390 let c = WitContract {
21391 de: "cart".into(),
21392 para: "catalog".into(),
21393 wit: "wasi:http/proxy".into(),
21394 endpoint: Some("/products/:id".into()),
21395 subject: None,
21396 slot: None,
21397 };
21398 let (de, para, wit, endpoint, subject, slot) = c.identity();
21399 assert_eq!(de, "cart");
21400 assert_eq!(para, "catalog");
21401 assert_eq!(wit, "wasi:http/proxy");
21402 assert_eq!(endpoint, Some("/products/:id"));
21403 assert_eq!(subject, None);
21404 assert_eq!(slot, None);
21405
21406 // Two byte-identical contracts must produce equal identities —
21407 // the dedup key's foundational invariant.
21408 let c2 = c.clone();
21409 assert_eq!(c.identity(), c2.identity());
21410
21411 // Any change on any of the six axes must break the identity —
21412 // sweeps by mutating one axis at a time.
21413 let mut mutated = c.clone();
21414 mutated.de = "search".into();
21415 assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
21416 let mut mutated = c.clone();
21417 mutated.para = "warehouse".into();
21418 assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
21419 let mut mutated = c.clone();
21420 mutated.wit = "http:legacy".into();
21421 assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
21422 let mut mutated = c.clone();
21423 mutated.endpoint = Some("/search".into());
21424 assert_ne!(
21425 c.identity(),
21426 mutated.identity(),
21427 "endpoint axis must partition"
21428 );
21429 let mut mutated = c.clone();
21430 mutated.subject = Some("orders.paid".into());
21431 assert_ne!(
21432 c.identity(),
21433 mutated.identity(),
21434 "subject axis must partition"
21435 );
21436 let mut mutated = c;
21437 mutated.slot = Some("carts/{id}".into());
21438 assert_ne!(mutated.identity().5, None, "slot axis must partition");
21439 }
21440
21441 #[test]
21442 fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
21443 // The canonical per-`:contratos` structural-self-edge pin:
21444 // [`WitContract::is_self_loop`] must return `true` when the
21445 // `:de` and `:para` fields agree byte-for-byte, across every
21446 // WIT-shape variant the per-edge shape family carries. Pins
21447 // the shape-agnostic identity-space partition the
21448 // [`AplicacaoSpec::validate`] self-edge gate at
21449 // caixa-core/src/aplicacao.rs:5559 fires against — all four
21450 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
21451 // under the same one predicate. Four permutations sweep the
21452 // accept-set: HTTP with endpoint, pub-sub with subject, KV
21453 // store with slot, and payload-less capability.
21454 for (nome, wit, endpoint, subject, slot) in [
21455 ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
21456 ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
21457 (
21458 "kv",
21459 "wasi:keyvalue/store",
21460 None,
21461 None,
21462 Some("carts/{cart_id}"),
21463 ),
21464 ("audit", "wasi:logging", None, None, None),
21465 ] {
21466 let c = WitContract {
21467 de: nome.into(),
21468 para: nome.into(),
21469 wit: wit.into(),
21470 endpoint: endpoint.map(str::to_string),
21471 subject: subject.map(str::to_string),
21472 slot: slot.map(str::to_string),
21473 };
21474 assert!(
21475 c.is_self_loop(),
21476 "WitContract::is_self_loop must return true when \
21477 :contratos :de == :contratos :para (got false on \
21478 {nome:?} under {wit:?})",
21479 );
21480 }
21481 }
21482
21483 #[test]
21484 fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
21485 // The complement pin: [`WitContract::is_self_loop`] must return
21486 // `false` on every well-shaped inter-Servico contract (the
21487 // author-intended `:contratos` shape MESH-COMPOSITION §III.1
21488 // names — "Servico A calls Servico B" between two distinct
21489 // graph nodes). Pins against a future silent detour that
21490 // inverted the predicate (an accidental `!= ` swap for `==`
21491 // would silently reject every legitimate inter-Servico edge
21492 // and admit every self-edge — the exact inversion of the
21493 // author-intended shape). Four permutations sweep the same
21494 // WIT-shape accept-set the sibling positive-arm test carries.
21495 for (de, para, wit, endpoint, subject, slot) in [
21496 (
21497 "cart",
21498 "catalog",
21499 "wasi:http/proxy",
21500 Some("/lookup"),
21501 None,
21502 None,
21503 ),
21504 (
21505 "checkout",
21506 "orders",
21507 "nats:pub-sub",
21508 None,
21509 Some("orders.paid"),
21510 None,
21511 ),
21512 (
21513 "cart",
21514 "kv",
21515 "wasi:keyvalue/store",
21516 None,
21517 None,
21518 Some("carts/{cart_id}"),
21519 ),
21520 ("audit", "sink", "wasi:logging", None, None, None),
21521 ] {
21522 let c = WitContract {
21523 de: de.into(),
21524 para: para.into(),
21525 wit: wit.into(),
21526 endpoint: endpoint.map(str::to_string),
21527 subject: subject.map(str::to_string),
21528 slot: slot.map(str::to_string),
21529 };
21530 assert!(
21531 !c.is_self_loop(),
21532 "WitContract::is_self_loop must return false when \
21533 :contratos :de differs from :contratos :para (got true \
21534 on {de:?} → {para:?} under {wit:?})",
21535 );
21536 }
21537 }
21538
21539 #[test]
21540 fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
21541 // The composition pin: [`WitContract::is_self_loop`] must
21542 // resolve to exactly `self.source() == self.destination()` —
21543 // the equality probe of the sibling scalar-accessor pair — so
21544 // any future refactor that silently re-authored the predicate
21545 // to bypass the lifted scalar accessors (an accidental
21546 // `self.de == self.para` regression back to the raw field-
21547 // access shape, an M4-typed-caller-enum identity-comparison
21548 // rule that landed on `source()` without reaching
21549 // `destination()`, a per-cluster alias rewrite the operator
21550 // pins on `destination()` without reaching this predicate)
21551 // trips at caixa-core build time. Pins the "typed dispatch
21552 // composes with typed dispatch, not with raw field access"
21553 // discipline the sibling [`WitContract::edge_pair`] /
21554 // [`WitContract::edge_triple`] composite-projection accessors
21555 // already carry, extended onto the per-edge endpoint-equality
21556 // predicate axis. Positive and complement arms both fire.
21557 let self_edge = WitContract {
21558 de: "cart".into(),
21559 para: "cart".into(),
21560 wit: "wasi:http/proxy".into(),
21561 endpoint: Some("/lookup".into()),
21562 subject: None,
21563 slot: None,
21564 };
21565 assert_eq!(
21566 self_edge.is_self_loop(),
21567 self_edge.source() == self_edge.destination(),
21568 "WitContract::is_self_loop must compose exactly \
21569 `source() == destination()` — a bypass of either sibling \
21570 accessor here would silently decouple the endpoint-\
21571 equality predicate from the substrate-primitive scalar \
21572 accessors every downstream consumer routes through",
21573 );
21574 let inter_edge = WitContract {
21575 de: "cart".into(),
21576 para: "catalog".into(),
21577 wit: "wasi:http/proxy".into(),
21578 endpoint: Some("/lookup".into()),
21579 subject: None,
21580 slot: None,
21581 };
21582 assert_eq!(
21583 inter_edge.is_self_loop(),
21584 inter_edge.source() == inter_edge.destination(),
21585 "WitContract::is_self_loop must compose exactly \
21586 `source() == destination()` on the complement arm too",
21587 );
21588 }
21589
21590 #[test]
21591 fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
21592 // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
21593 // pin: [`WitContract::endpoint`] must return the `:contratos
21594 // :endpoint` field byte-for-byte, borrowed from the typed slot's
21595 // own `Option<String>` storage. Peer of the sibling
21596 // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
21597 // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
21598 // mesh-slot `Option<String>` optional-scalar axes — same "the
21599 // substrate-primitive accessor must byte-equal the raw field
21600 // access verbatim across every author-declared value" discipline
21601 // extended to the per-`:contratos` HTTP-payload-carrier arm.
21602 // Pins against a future silent detour that re-canonicalized the
21603 // endpoint (an accidental percent-encoding pass that didn't
21604 // reach the peer field-access site at the dedup key, a per-CR
21605 // fully-qualified prefix rewrite the operator authors on one
21606 // consumer without the other, or an M4 typed-path-template
21607 // `Display` re-canonicalization that silently drifted the
21608 // printer output from the source `caixa.lisp`). Four values
21609 // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
21610 // gate upstream admits (short root-path, dashed, param-shaped,
21611 // deep-hierarchy).
21612 for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
21613 let c = WitContract {
21614 de: "cart".into(),
21615 para: "catalog".into(),
21616 wit: "wasi:http/proxy".into(),
21617 endpoint: Some(endpoint.into()),
21618 subject: None,
21619 slot: None,
21620 };
21621 assert_eq!(
21622 c.endpoint(),
21623 Some(endpoint),
21624 "WitContract::endpoint must return :contratos :endpoint \
21625 verbatim (got {:?}, expected Some({endpoint:?}))",
21626 c.endpoint(),
21627 );
21628 assert_eq!(
21629 c.endpoint(),
21630 c.endpoint.as_deref(),
21631 "WitContract::endpoint must byte-equal the .endpoint \
21632 field's `.as_deref()` projection",
21633 );
21634 }
21635 }
21636
21637 #[test]
21638 fn wit_contract_endpoint_none_when_field_is_none() {
21639 // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
21640 // payload-carrier accessor pin: when the typed slot is absent —
21641 // the canonical shape under a non-HTTP `:wit` world per the
21642 // [`WitContract::target`]-enforced shape ↔ target partition
21643 // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
21644 // carries `:slot`, [`WitTarget::Capability`] carries none) —
21645 // [`WitContract::endpoint`] must return `None`. Pins against a
21646 // future silent detour that projected the absent slot to a
21647 // `Some("")` empty-string default (the canonical `Option<String>`
21648 // → `String` collapse footgun the sibling M2
21649 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21650 // emptiness predicates already guard on the peer M2 typed-slot
21651 // surfaces), a `Some("None")` stringified-None round-trip, or a
21652 // `Some` arm whose contents were derived from a sibling slot (an
21653 // accidental fallback to the `:subject` / `:slot` payload that
21654 // read the pub-sub / store payload into the endpoint axis).
21655 // Three contracts sweep the accept-set every non-HTTP `:wit`
21656 // world lands on — pub-sub NATS, key/value, and payload-less
21657 // capability.
21658 for (wit, subject, slot) in [
21659 ("nats:pub-sub", Some("orders.paid"), None),
21660 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
21661 ("wasi:cli/environment", None, None),
21662 ] {
21663 let c = WitContract {
21664 de: "cart".into(),
21665 para: "downstream".into(),
21666 wit: wit.into(),
21667 endpoint: None,
21668 subject: subject.map(str::to_string),
21669 slot: slot.map(str::to_string),
21670 };
21671 assert!(
21672 c.endpoint().is_none(),
21673 "WitContract::endpoint must return None when the typed \
21674 slot is absent under :wit {wit:?} (got {:?})",
21675 c.endpoint(),
21676 );
21677 assert_eq!(
21678 c.endpoint(),
21679 c.endpoint.as_deref(),
21680 "WitContract::endpoint must byte-equal the .endpoint \
21681 field's `.as_deref()` projection in the absent arm",
21682 );
21683 }
21684 }
21685
21686 #[test]
21687 fn wit_contract_endpoint_borrows_from_endpoint_storage() {
21688 // The borrow-not-copy pin: [`WitContract::endpoint`] must return
21689 // an `Option<&str>` whose `Some` arm borrows from the typed
21690 // slot's own [`String`] storage — same-address invariant with
21691 // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
21692 // detour that allocated a fresh `String`
21693 // (`self.endpoint.clone().map(...)` in the body would type-check
21694 // but silently drop the borrow, and every downstream consumer
21695 // that assumed the returned slice outlives `&self` would break
21696 // on a stale-reference use-after-free — the [`WitContract::target`]
21697 // Http-arm payload extraction rebinds the returned `Option<&str>`
21698 // through `.ok_or_else(...)` and threads the `&str` payload into
21699 // [`WitTarget::Http { endpoint: &'a str }`], the
21700 // [`AplicacaoSpec::validate`] duplicate-`:contratos`
21701 // [`ContratoIdentity`] dedup key threads the returned
21702 // `Option<&str>` into the six-tuple's HTTP arm — each borrow
21703 // from the WitContract's own storage and each would silently
21704 // misbehave if this accessor produced a detached copy). Peer of
21705 // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
21706 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
21707 // shaped optional-scalar axes — first extension of the
21708 // `Option<&str>` borrow-not-copy discipline onto the
21709 // per-`:contratos` HTTP-shaped payload-carrier axis.
21710 let c = WitContract {
21711 de: "cart".into(),
21712 para: "catalog".into(),
21713 wit: "wasi:http/proxy".into(),
21714 endpoint: Some("/lookup".into()),
21715 subject: None,
21716 slot: None,
21717 };
21718 let ep = c.endpoint().expect("Some arm");
21719 let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
21720 assert_eq!(
21721 ep.as_ptr(),
21722 storage_slice.as_ptr(),
21723 "WitContract::endpoint must borrow from the .endpoint \
21724 String's backing storage — a fresh allocation here means \
21725 the accessor no longer names the substrate-primitive typed \
21726 dispatch and every downstream consumer would silently \
21727 carry a detached copy",
21728 );
21729 assert_eq!(
21730 ep.len(),
21731 storage_slice.len(),
21732 "WitContract::endpoint and .endpoint.as_deref() must byte-\
21733 equal in length as well as in address",
21734 );
21735 }
21736
21737 #[test]
21738 fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
21739 // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
21740 // pin: [`WitContract::subject`] must return the `:contratos
21741 // :subject` field byte-for-byte, borrowed from the typed slot's
21742 // own `Option<String>` storage. Peer of the sibling per-`:contratos`
21743 // [`WitContract::endpoint`] (7020470) accessor pin on the M3
21744 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
21745 // optional-scalar axis — same "the substrate-primitive accessor
21746 // must byte-equal the raw field access verbatim across every
21747 // author-declared value" discipline extended to the pub-sub arm.
21748 // Pins against a future silent detour that re-canonicalized the
21749 // subject (an accidental `.to_lowercase()` normalization that
21750 // didn't reach the peer field-access site at the dedup key, a
21751 // per-CR fully-qualified prefix rewrite the operator authors on
21752 // one consumer without the other, or an M4 typed-subject-template
21753 // `Display` re-canonicalization that silently drifted the printer
21754 // output from the source `caixa.lisp`). Four values sweep the
21755 // NATS accept-set every pub-sub author-declared subject lands on
21756 // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
21757 for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
21758 let c = WitContract {
21759 de: "cart".into(),
21760 para: "notifier".into(),
21761 wit: "nats:pub-sub".into(),
21762 endpoint: None,
21763 subject: Some(subject.into()),
21764 slot: None,
21765 };
21766 assert_eq!(
21767 c.subject(),
21768 Some(subject),
21769 "WitContract::subject must return :contratos :subject \
21770 verbatim (got {:?}, expected Some({subject:?}))",
21771 c.subject(),
21772 );
21773 assert_eq!(
21774 c.subject(),
21775 c.subject.as_deref(),
21776 "WitContract::subject must byte-equal the .subject \
21777 field's `.as_deref()` projection",
21778 );
21779 }
21780 }
21781
21782 #[test]
21783 fn wit_contract_subject_none_when_field_is_none() {
21784 // The absent-`:subject` arm of the per-`:contratos` pub-sub-
21785 // shaped payload-carrier accessor pin: when the typed slot is
21786 // absent — the canonical shape under a non-pub-sub `:wit` world
21787 // per the [`WitContract::target`]-enforced shape ↔ target
21788 // partition ([`WitTarget::Http`] carries `:endpoint`,
21789 // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
21790 // carries none) — [`WitContract::subject`] must return `None`.
21791 // Pins against a future silent detour that projected the absent
21792 // slot to a `Some("")` empty-string default (the canonical
21793 // `Option<String>` → `String` collapse footgun the sibling M2
21794 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21795 // emptiness predicates already guard on the peer M2 typed-slot
21796 // surfaces), a `Some("None")` stringified-None round-trip, or a
21797 // `Some` arm whose contents were derived from a sibling slot (an
21798 // accidental fallback to the `:endpoint` / `:slot` payload that
21799 // read the HTTP / store payload into the subject axis). Three
21800 // contracts sweep the accept-set every non-pub-sub `:wit` world
21801 // lands on — HTTP proxy, key/value store, and payload-less
21802 // capability.
21803 for (wit, endpoint, slot) in [
21804 ("wasi:http/proxy", Some("/lookup"), None),
21805 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
21806 ("wasi:cli/environment", None, None),
21807 ] {
21808 let c = WitContract {
21809 de: "cart".into(),
21810 para: "downstream".into(),
21811 wit: wit.into(),
21812 endpoint: endpoint.map(str::to_string),
21813 subject: None,
21814 slot: slot.map(str::to_string),
21815 };
21816 assert!(
21817 c.subject().is_none(),
21818 "WitContract::subject must return None when the typed \
21819 slot is absent under :wit {wit:?} (got {:?})",
21820 c.subject(),
21821 );
21822 assert_eq!(
21823 c.subject(),
21824 c.subject.as_deref(),
21825 "WitContract::subject must byte-equal the .subject \
21826 field's `.as_deref()` projection in the absent arm",
21827 );
21828 }
21829 }
21830
21831 #[test]
21832 fn wit_contract_subject_borrows_from_subject_storage() {
21833 // The borrow-not-copy pin: [`WitContract::subject`] must return
21834 // an `Option<&str>` whose `Some` arm borrows from the typed
21835 // slot's own [`String`] storage — same-address invariant with
21836 // `c.subject.as_deref().unwrap()`. Pins against a future silent
21837 // detour that allocated a fresh `String`
21838 // (`self.subject.clone().map(...)` in the body would type-check
21839 // but silently drop the borrow, and every downstream consumer
21840 // that assumed the returned slice outlives `&self` would break
21841 // on a stale-reference use-after-free — the [`WitContract::target`]
21842 // PubSub-arm payload extraction rebinds the returned
21843 // `Option<&str>` through `.ok_or_else(...)` and threads the
21844 // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
21845 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21846 // [`ContratoIdentity`] dedup key threads the returned
21847 // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
21848 // from the WitContract's own storage and each would silently
21849 // misbehave if this accessor produced a detached copy). Peer of
21850 // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
21851 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
21852 // shaped optional-scalar axis — second extension of the
21853 // `Option<&str>` borrow-not-copy discipline onto the
21854 // per-`:contratos` payload-carrier family, this time on the
21855 // pub-sub arm.
21856 let c = WitContract {
21857 de: "cart".into(),
21858 para: "notifier".into(),
21859 wit: "nats:pub-sub".into(),
21860 endpoint: None,
21861 subject: Some("orders.paid".into()),
21862 slot: None,
21863 };
21864 let sub = c.subject().expect("Some arm");
21865 let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
21866 assert_eq!(
21867 sub.as_ptr(),
21868 storage_slice.as_ptr(),
21869 "WitContract::subject must borrow from the .subject \
21870 String's backing storage — a fresh allocation here means \
21871 the accessor no longer names the substrate-primitive typed \
21872 dispatch and every downstream consumer would silently \
21873 carry a detached copy",
21874 );
21875 assert_eq!(
21876 sub.len(),
21877 storage_slice.len(),
21878 "WitContract::subject and .subject.as_deref() must byte-\
21879 equal in length as well as in address",
21880 );
21881 }
21882
21883 #[test]
21884 fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
21885 // The canonical per-`:contratos` key/value-store-shaped
21886 // `:slot`-scalar pin: [`WitContract::slot`] must return the
21887 // `:contratos :slot` field byte-for-byte, borrowed from the
21888 // typed slot's own `Option<String>` storage. Peer of the
21889 // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
21890 // [`WitContract::subject`] (90de675) accessor pins on the M3
21891 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
21892 // optional-scalar axis — same "the substrate-primitive
21893 // accessor must byte-equal the raw field access verbatim
21894 // across every author-declared value" discipline extended to
21895 // the store arm. Pins against a future silent detour that
21896 // re-canonicalized the slot template (an accidental
21897 // `.to_lowercase()` bucket-prefix normalization that didn't
21898 // reach the peer field-access site at the dedup key, a per-CR
21899 // fully-qualified prefix rewrite the operator authors on one
21900 // consumer without the other, or an M4 typed-key-template
21901 // `Display` re-canonicalization that silently drifted the
21902 // printer output from the source `caixa.lisp`). Four values
21903 // sweep the wasi:keyvalue accept-set every store-shaped
21904 // author-declared slot lands on (flat bucket, single-param
21905 // template, multi-param template, nested-hierarchy template).
21906 for slot in [
21907 "sessions",
21908 "carts/{cart_id}",
21909 "orders/{tenant}/{order_id}",
21910 "cache/tenant-a/orders/{id}",
21911 ] {
21912 let c = WitContract {
21913 de: "cart".into(),
21914 para: "kv".into(),
21915 wit: "wasi:keyvalue/store".into(),
21916 endpoint: None,
21917 subject: None,
21918 slot: Some(slot.into()),
21919 };
21920 assert_eq!(
21921 c.slot(),
21922 Some(slot),
21923 "WitContract::slot must return :contratos :slot \
21924 verbatim (got {:?}, expected Some({slot:?}))",
21925 c.slot(),
21926 );
21927 assert_eq!(
21928 c.slot(),
21929 c.slot.as_deref(),
21930 "WitContract::slot must byte-equal the .slot field's \
21931 `.as_deref()` projection",
21932 );
21933 }
21934 }
21935
21936 #[test]
21937 fn wit_contract_slot_none_when_field_is_none() {
21938 // The absent-`:slot` arm of the per-`:contratos` store-shaped
21939 // payload-carrier accessor pin: when the typed slot is absent —
21940 // the canonical shape under a non-store `:wit` world per the
21941 // [`WitContract::target`]-enforced shape ↔ target partition
21942 // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
21943 // carries `:subject`, [`WitTarget::Capability`] carries none) —
21944 // [`WitContract::slot`] must return `None`. Pins against a
21945 // future silent detour that projected the absent slot to a
21946 // `Some("")` empty-string default (the canonical
21947 // `Option<String>` → `String` collapse footgun the sibling M2
21948 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21949 // emptiness predicates already guard on the peer M2 typed-slot
21950 // surfaces), a `Some("None")` stringified-None round-trip, or
21951 // a `Some` arm whose contents were derived from a sibling
21952 // slot (an accidental fallback to the `:endpoint` / `:subject`
21953 // payload that read the HTTP / pub-sub payload into the store
21954 // axis). Three contracts sweep the accept-set every non-store
21955 // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
21956 // payload-less capability.
21957 for (wit, endpoint, subject) in [
21958 ("wasi:http/proxy", Some("/lookup"), None),
21959 ("nats:pub-sub", None, Some("orders.paid")),
21960 ("wasi:cli/environment", None, None),
21961 ] {
21962 let c = WitContract {
21963 de: "cart".into(),
21964 para: "downstream".into(),
21965 wit: wit.into(),
21966 endpoint: endpoint.map(str::to_string),
21967 subject: subject.map(str::to_string),
21968 slot: None,
21969 };
21970 assert!(
21971 c.slot().is_none(),
21972 "WitContract::slot must return None when the typed \
21973 slot is absent under :wit {wit:?} (got {:?})",
21974 c.slot(),
21975 );
21976 assert_eq!(
21977 c.slot(),
21978 c.slot.as_deref(),
21979 "WitContract::slot must byte-equal the .slot field's \
21980 `.as_deref()` projection in the absent arm",
21981 );
21982 }
21983 }
21984
21985 #[test]
21986 fn wit_contract_slot_borrows_from_slot_storage() {
21987 // The borrow-not-copy pin: [`WitContract::slot`] must return
21988 // an `Option<&str>` whose `Some` arm borrows from the typed
21989 // slot's own [`String`] storage — same-address invariant with
21990 // `c.slot.as_deref().unwrap()`. Pins against a future silent
21991 // detour that allocated a fresh `String`
21992 // (`self.slot.clone().map(...)` in the body would type-check
21993 // but silently drop the borrow, and every downstream consumer
21994 // that assumed the returned slice outlives `&self` would
21995 // break on a stale-reference use-after-free — the
21996 // [`WitContract::target`] Store-arm payload extraction rebinds
21997 // the returned `Option<&str>` through `.ok_or_else(...)` and
21998 // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
21999 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22000 // [`ContratoIdentity`] dedup key threads the returned
22001 // `Option<&str>` into the six-tuple's store arm — each borrow
22002 // from the WitContract's own storage and each would silently
22003 // misbehave if this accessor produced a detached copy). Peer
22004 // of the sibling per-`:contratos` [`WitContract::endpoint`]
22005 // (7020470) / [`WitContract::subject`] (90de675)
22006 // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
22007 // shaped optional-scalar axis — third and final extension of
22008 // the `Option<&str>` borrow-not-copy discipline onto the
22009 // per-`:contratos` payload-carrier family, this time on the
22010 // store arm.
22011 let c = WitContract {
22012 de: "cart".into(),
22013 para: "kv".into(),
22014 wit: "wasi:keyvalue/store".into(),
22015 endpoint: None,
22016 subject: None,
22017 slot: Some("carts/{cart_id}".into()),
22018 };
22019 let slot = c.slot().expect("Some arm");
22020 let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
22021 assert_eq!(
22022 slot.as_ptr(),
22023 storage_slice.as_ptr(),
22024 "WitContract::slot must borrow from the .slot String's \
22025 backing storage — a fresh allocation here means the \
22026 accessor no longer names the substrate-primitive typed \
22027 dispatch and every downstream consumer would silently \
22028 carry a detached copy",
22029 );
22030 assert_eq!(
22031 slot.len(),
22032 storage_slice.len(),
22033 "WitContract::slot and .slot.as_deref() must byte-equal \
22034 in length as well as in address",
22035 );
22036 }
22037
22038 #[test]
22039 fn membro_nome_returns_caixa_byte_equal_across_permutations() {
22040 // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
22041 // [`Membro::nome`] must return the `:membros :caixa` field
22042 // byte-for-byte, borrowed from the typed slot's own [`String`]
22043 // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
22044 // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22045 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22046 // slot-atom scalar-value axes — same "the substrate-primitive
22047 // accessor must byte-equal the raw field access verbatim across
22048 // every author-declared value" discipline extended to the
22049 // per-`:membros` member-identity arm. Pins against a future
22050 // silent detour that re-normalized the member identity (an
22051 // accidental `.to_lowercase()` — every `:membros :caixa` is
22052 // validated as a DNS-1123 label upstream via
22053 // [`validate_membro_caixa`], so any re-normalization is
22054 // redundant + a drift surface between the validator and the
22055 // accessor), a namespace-prefix rewrite (an accidental
22056 // `format!("{namespace}/{caixa}")` per-CR fully-qualified
22057 // rewrite that didn't land on the peer axes), or a per-cluster
22058 // alias stamp the operator authors on one consumer without the
22059 // other. Four values sweep the accept-set the DNS-1123 gate
22060 // upstream admits (short single-word / dashed / v-suffixed
22061 // member names).
22062 for name in ["cart", "checkout", "catalog", "orders-v2"] {
22063 let m = Membro {
22064 caixa: name.into(),
22065 versao: "^0.1".into(),
22066 };
22067 assert_eq!(
22068 m.nome(),
22069 name,
22070 "Membro::nome must return :membros :caixa verbatim \
22071 (got {:?}, expected {name:?})",
22072 m.nome(),
22073 );
22074 assert_eq!(
22075 m.nome(),
22076 m.caixa.as_str(),
22077 "Membro::nome must byte-equal the .caixa field access",
22078 );
22079 }
22080 }
22081
22082 #[test]
22083 fn membro_nome_borrows_from_caixa_storage() {
22084 // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
22085 // slice that borrows from the typed slot's own [`String`]
22086 // storage — same-address invariant with `m.caixa.as_str()`. Pins
22087 // against a future silent detour that allocated a fresh `String`
22088 // (`self.caixa.clone()` in the body would type-check but
22089 // silently drop the borrow, and every downstream consumer that
22090 // assumed the returned slice outlives `&self` would break on a
22091 // stale-reference use-after-free — the `HashSet<&str>` collector
22092 // at [`AplicacaoSpec::validate`]'s `names` seed, the
22093 // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
22094 // [`AplicacaoSpec::detect_sync_cycles`], the
22095 // [`crate::render::insert_first_seen`] dedup key at
22096 // [`AplicacaoSpec::validate_membros`] — each borrow from the
22097 // Membro's own storage and each would silently misbehave if
22098 // this accessor produced a detached copy). Peer of the sibling
22099 // per-`:contratos` [`WitContract::source`] /
22100 // [`WitContract::destination`] and per-`:entrada`
22101 // [`Entrada::destination`] borrow-invariant pins on the mesh-
22102 // slot-atom scalar-value axes.
22103 let m = Membro {
22104 caixa: "checkout".into(),
22105 versao: "^0.1".into(),
22106 };
22107 let name = m.nome();
22108 let caixa_slice = m.caixa.as_str();
22109 assert_eq!(
22110 name.as_ptr(),
22111 caixa_slice.as_ptr(),
22112 "Membro::nome must borrow from the .caixa String's backing \
22113 storage — a fresh allocation here means the accessor no \
22114 longer names the substrate-primitive typed dispatch and \
22115 every downstream consumer would silently carry a detached \
22116 copy",
22117 );
22118 assert_eq!(
22119 name.len(),
22120 caixa_slice.len(),
22121 "Membro::nome and .caixa.as_str() must byte-equal in length \
22122 as well as in address",
22123 );
22124 }
22125
22126 #[test]
22127 fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
22128 // The canonical per-`:membros` member-`:versao`-scalar pin:
22129 // [`Membro::versao_requirement`] must return the
22130 // `:membros :versao` field byte-for-byte, borrowed from the typed
22131 // slot's own [`String`] storage. Sibling of the peer
22132 // `membro_nome_returns_caixa_byte_equal_across_permutations`
22133 // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
22134 // — same "the substrate-primitive accessor must byte-equal the
22135 // raw field access verbatim across every author-declared value"
22136 // discipline extended to the per-`:membros` member-`:versao`
22137 // requirement-string arm. Pins against a future silent detour
22138 // that re-canonicalized the requirement (an accidental
22139 // `.to_string()` via [`parse_requirement`] → [`Display`] round-
22140 // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
22141 // drifted the printer output away from the source `caixa.lisp`,
22142 // an accidental whitespace trim on `"^ 0.1"` that no consumer
22143 // ever produced from the field-access side, an accidental
22144 // per-cluster lacre-projected concrete-version rewrite that
22145 // didn't land on the peer field-access sites). Five values sweep
22146 // the accept-set the shared
22147 // [`crate::render::require_valid_versao_requirement`] gate
22148 // admits (caret / tilde / exact / wildcard / bare-major).
22149 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
22150 let m = Membro {
22151 caixa: "cart".into(),
22152 versao: req.into(),
22153 };
22154 assert_eq!(
22155 m.versao_requirement(),
22156 req,
22157 "Membro::versao_requirement must return :membros :versao \
22158 verbatim (got {:?}, expected {req:?})",
22159 m.versao_requirement(),
22160 );
22161 assert_eq!(
22162 m.versao_requirement(),
22163 m.versao.as_str(),
22164 "Membro::versao_requirement must byte-equal the .versao \
22165 field access",
22166 );
22167 }
22168 }
22169
22170 #[test]
22171 fn membro_versao_requirement_borrows_from_versao_storage() {
22172 // The borrow-not-copy pin: [`Membro::versao_requirement`] must
22173 // return a `&str` slice that borrows from the typed slot's own
22174 // [`String`] storage — same-address invariant with
22175 // `m.versao.as_str()`. Pins against a future silent detour that
22176 // allocated a fresh `String` (`self.versao.clone()` in the body
22177 // would type-check but silently drop the borrow, and every
22178 // downstream consumer that assumed the returned slice outlives
22179 // `&self` would break on a stale-reference use-after-free). Peer
22180 // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
22181 // per-`:contratos` [`WitContract::source`] /
22182 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22183 // [`Entrada::destination`] (6db982c) borrow-invariant pins on
22184 // the mesh-slot-atom scalar-value axes.
22185 let m = Membro {
22186 caixa: "checkout".into(),
22187 versao: "^0.1".into(),
22188 };
22189 let req = m.versao_requirement();
22190 let versao_slice = m.versao.as_str();
22191 assert_eq!(
22192 req.as_ptr(),
22193 versao_slice.as_ptr(),
22194 "Membro::versao_requirement must borrow from the .versao \
22195 String's backing storage — a fresh allocation here means \
22196 the accessor no longer names the substrate-primitive typed \
22197 dispatch and every downstream consumer would silently carry \
22198 a detached copy",
22199 );
22200 assert_eq!(
22201 req.len(),
22202 versao_slice.len(),
22203 "Membro::versao_requirement and .versao.as_str() must byte-\
22204 equal in length as well as in address",
22205 );
22206 }
22207
22208 #[test]
22209 fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
22210 // Sibling-pair invariant pin composing both per-`:membros`
22211 // substrate-primitive typed dispatches — [`Membro::nome`]
22212 // (4a32abf) and [`Membro::versao_requirement`] — at the joint
22213 // `(nome(), versao_requirement())` call shape every renderer
22214 // that fans on per-member identity + version pin keys off. The
22215 // invariant, evaluated per-member:
22216 //
22217 // (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
22218 //
22219 // Closes the last unlifted per-`:membros` scalar axis — every
22220 // downstream consumer that reads the pair now routes through
22221 // exactly two typed dispatches on the substrate primitive, not
22222 // one typed + one open-coded field access. A future refactor
22223 // that silently split either accessor's projection (an
22224 // accidental `nome()` namespace-prefix rewrite that didn't
22225 // reach the peer, an accidental `versao_requirement()` lacre-
22226 // projected concrete-version rewrite that didn't land on the
22227 // `nome()` peer) surfaces at caixa-core build time. Peer of the
22228 // sibling per-`:entrada` `(hostname(), destination())` and
22229 // per-`:contratos` `(source(), destination())` pair invariants
22230 // on the mesh-slot-atom scalar-value axes.
22231 for (caixa, versao) in [
22232 ("cart", "^0.1"),
22233 ("checkout", "~0.1.2"),
22234 ("catalog", "0.1.0"),
22235 ("orders-v2", "*"),
22236 ] {
22237 let m = Membro {
22238 caixa: caixa.into(),
22239 versao: versao.into(),
22240 };
22241 assert_eq!(
22242 (m.nome(), m.versao_requirement()),
22243 (m.caixa.as_str(), m.versao.as_str()),
22244 "(Membro::nome, Membro::versao_requirement) must project \
22245 (.caixa, .versao) verbatim across every author-declared \
22246 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
22247 m.nome(),
22248 m.versao_requirement(),
22249 );
22250 }
22251 }
22252
22253 #[test]
22254 fn validate_membros_empty_gate_routes_through_nome_accessor() {
22255 // Composition pin: [`AplicacaoSpec::validate_membros`]'s
22256 // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
22257 // not the raw `.caixa` field access. Structurally: setting
22258 // ONLY the `.caixa` field to `""` on an otherwise-well-formed
22259 // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
22260 // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
22261 // (i.e. the empty string) — so the emptiness predicate the
22262 // refusal arm reaches under is the accessor-projected value,
22263 // not a peer field that would silently drift under a future
22264 // accessor-side rewrite.
22265 //
22266 // Pins against a future silent detour that (a) re-derived the
22267 // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
22268 // instead of `self.nome().is_empty()`, silently disagreeing with
22269 // every peer consumer (the `validate_membro_caixa(m.nome())`
22270 // call one line below, the dedup-key `insert_first_seen(&mut
22271 // seen, m.nome(), …)` two lines below, the emit-side per-
22272 // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
22273 // (b) accessor-side introduced a per-tenant alias arm the
22274 // caller was unaware of, silently rewriting an author-declared
22275 // `:caixa "checkout"` to `""` — the raw-field-access gate
22276 // would fail-open while the accessor-routed peer consumers
22277 // would fail-closed, splitting the diagnostic from the actual
22278 // failure surface.
22279 //
22280 // Peer of the sibling
22281 // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
22282 // (c0110f1) composition pin — same "the shape-gate predicate
22283 // must route through the substrate-primitive typed dispatch"
22284 // discipline extended onto the per-`:membros` empty-`:caixa`
22285 // refusal-arm axis. Closes the last unlifted `.caixa` production-
22286 // code read site on `Membro` — after this converge every
22287 // caixa-core `.caixa` field access outside the accessor's own
22288 // body is either a test-side field-setter (in-module tests
22289 // constructing invalid-shape inputs) or a doc-comment reference.
22290 let mut s = three_member_spec();
22291 s.membros[1].caixa = String::new();
22292 assert!(
22293 s.membros[1].nome().is_empty(),
22294 "Membro::nome must byte-equal the .caixa field access — an \
22295 accessor-side detour that no longer projects the raw field \
22296 would silently split this drift-detection test from the \
22297 validate() refusal arm",
22298 );
22299 assert_eq!(
22300 s.membros[1].nome(),
22301 s.membros[1].caixa.as_str(),
22302 "Membro::nome and .caixa.as_str() must byte-equal on an \
22303 empty-`:caixa` entry — the emptiness gate keys off the \
22304 accessor by construction",
22305 );
22306 assert_eq!(
22307 s.validate().unwrap_err(),
22308 AplicacaoError::MembroCaixaEmpty,
22309 "validate_membros' emptiness gate must fire MembroCaixaEmpty \
22310 on an entry whose accessor-projected `nome()` is empty",
22311 );
22312 }
22313
22314 #[test]
22315 fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
22316 // The canonical per-`:placement` Akka-cluster-sharding
22317 // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
22318 // the `:placement :shard-key` field byte-for-byte, borrowed
22319 // from the typed slot's own `Option<String>` storage. Peer of
22320 // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
22321 // per-`:contratos` [`WitContract::source`] /
22322 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22323 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22324 // slot-atom scalar-value axes — same "the substrate-primitive
22325 // accessor must byte-equal the raw field access verbatim across
22326 // every author-declared value" discipline extended to the
22327 // per-`:placement` Akka-cluster-sharding key extractor arm.
22328 // Pins against a future silent detour that re-normalized the
22329 // key (an accidental `.to_lowercase()` — every non-empty
22330 // `:shard-key` is validated as a printable-ASCII single-token
22331 // reference upstream via [`validate_placement_shard_key`], so
22332 // any re-normalization is redundant + a drift surface between
22333 // the validator and the accessor), a per-cluster alias rewrite
22334 // the operator authors on one consumer without the other, or an
22335 // accidental variable-prefix strip (`$tenantId` → `tenantId`)
22336 // that didn't land on the peer field-access sites. Four values
22337 // sweep the accept-set the shape gate admits — bare identifier,
22338 // `$`-prefixed variable, dotted path, `${}`-quoted variable —
22339 // the four canonical Akka-style entity-id extractor shapes the
22340 // future M4 cluster-sharding reconciler hashes.
22341 for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
22342 let p = Placement {
22343 estrategia: PlacementStrategy::Sharded,
22344 clusters: vec!["rio".into()],
22345 affinity: None,
22346 shard_key: Some(key.into()),
22347 };
22348 assert_eq!(
22349 p.shard_key(),
22350 Some(key),
22351 "Placement::shard_key must return :placement :shard-key \
22352 verbatim (got {:?}, expected Some({key:?}))",
22353 p.shard_key(),
22354 );
22355 assert_eq!(
22356 p.shard_key(),
22357 p.shard_key.as_deref(),
22358 "Placement::shard_key must byte-equal the .shard_key \
22359 field's `.as_deref()` projection",
22360 );
22361 }
22362 }
22363
22364 #[test]
22365 fn placement_shard_key_none_when_field_is_none() {
22366 // The absent-`:shard-key` arm of the per-`:placement`
22367 // Akka-cluster-sharding accessor pin: when the typed slot is
22368 // absent — the canonical shape under `:estrategia Replicated` /
22369 // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
22370 // enforced `shard_key.is_some() == matches!(estrategia,
22371 // Sharded)` partition — [`Placement::shard_key`] must return
22372 // `None`. Pins against a future silent detour that projected
22373 // the absent slot to a `Some("")` empty-string default (the
22374 // canonical `Option<String>` → `String` collapse footgun the
22375 // sibling M2 [`crate::LimitsSpec::is_empty`] /
22376 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
22377 // already guard on the peer M2 typed-slot surfaces), a
22378 // `Some("None")` stringified-None round-trip, or a `Some` arm
22379 // whose contents were derived from a sibling slot (an
22380 // accidental fallback to `estrategia.as_str()` that read the
22381 // strategy discriminator into the key axis). Two placements
22382 // sweep the accept-set every `validate`-passing non-`Sharded`
22383 // shape lands on — `Replicated` (Erlang/OTP distributed-app
22384 // takeover) and `SingleNode` (single-node hosting).
22385 for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
22386 let p = Placement {
22387 estrategia,
22388 clusters: vec!["rio".into()],
22389 affinity: None,
22390 shard_key: None,
22391 };
22392 assert!(
22393 p.shard_key().is_none(),
22394 "Placement::shard_key must return None when the typed \
22395 slot is absent under :estrategia {estrategia:?} (got {:?})",
22396 p.shard_key(),
22397 );
22398 assert_eq!(
22399 p.shard_key(),
22400 p.shard_key.as_deref(),
22401 "Placement::shard_key must byte-equal the .shard_key \
22402 field's `.as_deref()` projection in the absent arm",
22403 );
22404 }
22405 }
22406
22407 #[test]
22408 fn placement_shard_key_borrows_from_shard_key_storage() {
22409 // The borrow-not-copy pin: [`Placement::shard_key`] must return
22410 // an `Option<&str>` whose `Some` arm borrows from the typed
22411 // slot's own [`String`] storage — same-address invariant with
22412 // `p.shard_key.as_deref().unwrap()`. Pins against a future
22413 // silent detour that allocated a fresh `String`
22414 // (`self.shard_key.clone().map(...)` in the body would type-
22415 // check but silently drop the borrow, and every downstream
22416 // consumer that assumed the returned slice outlives `&self`
22417 // would break on a stale-reference use-after-free — the
22418 // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
22419 // gate's `Some(k)`-bound match arm reads `k: &str` under the
22420 // accessor's return type and would silently misbehave if this
22421 // accessor produced a detached copy). Peer of the sibling
22422 // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
22423 // [`WitContract::source`] / [`WitContract::destination`]
22424 // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
22425 // (6db982c) borrow-invariant pins on the mesh-slot-atom
22426 // scalar-value axes — first extension of the discipline onto
22427 // an `Option<String>`-shaped optional-scalar axis.
22428 let p = Placement {
22429 estrategia: PlacementStrategy::Sharded,
22430 clusters: vec!["rio".into()],
22431 affinity: None,
22432 shard_key: Some("tenantId".into()),
22433 };
22434 let key = p.shard_key().expect("Some arm");
22435 let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
22436 assert_eq!(
22437 key.as_ptr(),
22438 storage_slice.as_ptr(),
22439 "Placement::shard_key must borrow from the .shard_key \
22440 String's backing storage — a fresh allocation here means \
22441 the accessor no longer names the substrate-primitive typed \
22442 dispatch and every downstream consumer would silently \
22443 carry a detached copy",
22444 );
22445 assert_eq!(
22446 key.len(),
22447 storage_slice.len(),
22448 "Placement::shard_key and .shard_key.as_deref() must byte-\
22449 equal in length as well as in address",
22450 );
22451 }
22452
22453 #[test]
22454 fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
22455 // The canonical per-`:placement` M3-Adaptive-compression-hint
22456 // scalar pin: [`Placement::affinity`] must return the
22457 // `:placement :affinity` field byte-for-byte, borrowed from the
22458 // typed slot's own `Option<String>` storage. Peer of the sibling
22459 // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
22460 // pin on the sibling `Option<&str>` optional-scalar axis — same
22461 // "the substrate-primitive accessor must byte-equal the raw
22462 // field access verbatim across every author-declared value"
22463 // discipline extended to the peer per-`:placement` M3-Adaptive-
22464 // compression-hint arm. Pins against a future silent detour
22465 // that re-normalized the hint (an accidental `.to_lowercase()`
22466 // — every `:affinity` is already validated as a DNS-1123 label
22467 // upstream via [`validate_placement_affinity`], so any re-
22468 // normalization is redundant + a drift surface between the
22469 // validator and the accessor), a per-cluster alias rewrite the
22470 // operator authors on one consumer without the other, or an
22471 // accidental hint-family collapse (`low-latency` → `latency`
22472 // that dropped the qualifier prefix). Four values sweep the
22473 // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
22474 // canonical adaptive-compression-weight biases the future M4
22475 // placement engine reads.
22476 for hint in [
22477 "data-locality",
22478 "low-latency",
22479 "high-throughput",
22480 "cost-optimized",
22481 ] {
22482 let p = Placement {
22483 estrategia: PlacementStrategy::Replicated,
22484 clusters: vec!["rio".into()],
22485 affinity: Some(hint.into()),
22486 shard_key: None,
22487 };
22488 assert_eq!(
22489 p.affinity(),
22490 Some(hint),
22491 "Placement::affinity must return :placement :affinity \
22492 verbatim (got {:?}, expected Some({hint:?}))",
22493 p.affinity(),
22494 );
22495 assert_eq!(
22496 p.affinity(),
22497 p.affinity.as_deref(),
22498 "Placement::affinity must byte-equal the .affinity \
22499 field's `.as_deref()` projection",
22500 );
22501 }
22502 }
22503
22504 #[test]
22505 fn placement_affinity_none_when_field_is_none() {
22506 // The absent-`:affinity` arm of the per-`:placement`
22507 // M3-Adaptive-compression-hint accessor pin: when the typed
22508 // slot is absent — the canonical shape of an Aplicacao that
22509 // leaves the compression weighting up to the placement engine's
22510 // cluster-default arm — [`Placement::affinity`] must return
22511 // `None`. Pins against a future silent detour that projected
22512 // the absent slot to a `Some("")` empty-string default (the
22513 // canonical `Option<String>` → `String` collapse footgun the
22514 // sibling M2 [`crate::LimitsSpec::is_empty`] /
22515 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
22516 // already guard on the peer M2 typed-slot surfaces), a
22517 // `Some("None")` stringified-None round-trip, a `Some` arm
22518 // whose contents were derived from a sibling slot (an
22519 // accidental fallback to `estrategia.as_str()` that read the
22520 // strategy discriminator into the hint axis), or a
22521 // `Some("default")` implicit-default that would silently biases
22522 // the routing without the author having written one. Three
22523 // placements sweep the accept-set every `validate`-passing
22524 // `:affinity None` shape lands on — one per PlacementStrategy
22525 // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
22526 // with a shard-key), since `:affinity` is orthogonal to
22527 // `:estrategia` in the typed grammar.
22528 for (estrategia, shard_key) in [
22529 (PlacementStrategy::SingleNode, None),
22530 (PlacementStrategy::Replicated, None),
22531 (PlacementStrategy::Sharded, Some("tenantId".to_string())),
22532 ] {
22533 let p = Placement {
22534 estrategia,
22535 clusters: vec!["rio".into()],
22536 affinity: None,
22537 shard_key,
22538 };
22539 assert!(
22540 p.affinity().is_none(),
22541 "Placement::affinity must return None when the typed \
22542 slot is absent under :estrategia {estrategia:?} (got {:?})",
22543 p.affinity(),
22544 );
22545 assert_eq!(
22546 p.affinity(),
22547 p.affinity.as_deref(),
22548 "Placement::affinity must byte-equal the .affinity \
22549 field's `.as_deref()` projection in the absent arm",
22550 );
22551 }
22552 }
22553
22554 #[test]
22555 fn placement_affinity_borrows_from_affinity_storage() {
22556 // The borrow-not-copy pin: [`Placement::affinity`] must return
22557 // an `Option<&str>` whose `Some` arm borrows from the typed
22558 // slot's own [`String`] storage — same-address invariant with
22559 // `p.affinity.as_deref().unwrap()`. Pins against a future
22560 // silent detour that allocated a fresh `String`
22561 // (`self.affinity.clone().map(...)` in the body would type-
22562 // check but silently drop the borrow, and every downstream
22563 // consumer that assumed the returned slice outlives `&self`
22564 // would break on a stale-reference use-after-free — the
22565 // [`AplicacaoSpec::validate_placement`] per-hint value-shape
22566 // gate reads the accessor's `&str` return through the
22567 // [`validate_placement_affinity`] `&str` parameter and would
22568 // silently misbehave if this accessor produced a detached
22569 // copy). Peer of the sibling per-`:placement`
22570 // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
22571 // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
22572 // extends the discipline onto the sibling per-`:placement`
22573 // M3-Adaptive-compression-hint arm.
22574 let p = Placement {
22575 estrategia: PlacementStrategy::Replicated,
22576 clusters: vec!["rio".into()],
22577 affinity: Some("data-locality".into()),
22578 shard_key: None,
22579 };
22580 let hint = p.affinity().expect("Some arm");
22581 let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
22582 assert_eq!(
22583 hint.as_ptr(),
22584 storage_slice.as_ptr(),
22585 "Placement::affinity must borrow from the .affinity \
22586 String's backing storage — a fresh allocation here means \
22587 the accessor no longer names the substrate-primitive typed \
22588 dispatch and every downstream consumer would silently \
22589 carry a detached copy",
22590 );
22591 assert_eq!(
22592 hint.len(),
22593 storage_slice.len(),
22594 "Placement::affinity and .affinity.as_deref() must byte-\
22595 equal in length as well as in address",
22596 );
22597 }
22598
22599 #[test]
22600 fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
22601 // The canonical per-`:placement` distribution-strategy-scalar
22602 // pin: [`Placement::estrategia`] must return the `:placement
22603 // :estrategia` field verbatim as a [`PlacementStrategy`],
22604 // `Copy`-projected from the typed slot's own `PlacementStrategy`
22605 // storage across every variant in the closed accept-set
22606 // (`SingleNode` — Erlang/OTP distributed-app takeover;
22607 // `Replicated` — active-active across every named cluster;
22608 // `Sharded` — Akka-style hash-keyed entity distribution). Pins
22609 // against a future silent detour that re-derived the strategy
22610 // from a peer axis (an accidental fallback to
22611 // `if shard_key.is_some() { Sharded } else { Replicated }`
22612 // collapse that read the shard-key axis into the strategy
22613 // discriminator), a variant remap the operator authors on one
22614 // consumer without the other, or a stale-derive detour that
22615 // substituted [`PlacementStrategy::default`] when the field
22616 // held any explicit variant (which would silently collapse the
22617 // distinction between "author explicitly declared `:estrategia
22618 // Replicated`" and "author omitted the slot and inherited the
22619 // default" the future per-cluster override slot depends on).
22620 // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
22621 // pin on the `Copy`-return `u16` scalar axis — same "the
22622 // substrate-primitive accessor must byte-equal the raw field
22623 // access verbatim across every author-declared value" discipline
22624 // extended onto the per-`:placement` distribution-strategy
22625 // `Copy`-composite-enum scalar axis.
22626 for estrategia in [
22627 PlacementStrategy::SingleNode,
22628 PlacementStrategy::Replicated,
22629 PlacementStrategy::Sharded,
22630 ] {
22631 // Route the paired `:shard-key` fixture-builder through the
22632 // typed cross-slot invariant predicate
22633 // [`PlacementStrategy::requires_shard_key`] rather than the
22634 // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
22635 // arm-identity predicate — same discipline the sibling
22636 // `placement_strategy_variants_round_trip` fixture builder now
22637 // reads through.
22638 let shard_key = estrategia
22639 .requires_shard_key()
22640 .then(|| "tenantId".to_string());
22641 let p = Placement {
22642 estrategia,
22643 clusters: vec!["rio".into()],
22644 affinity: None,
22645 shard_key,
22646 };
22647 assert_eq!(
22648 p.estrategia(),
22649 estrategia,
22650 "Placement::estrategia must return :placement :estrategia \
22651 verbatim (got {:?}, expected {estrategia:?})",
22652 p.estrategia(),
22653 );
22654 assert_eq!(
22655 p.estrategia(),
22656 p.estrategia,
22657 "Placement::estrategia accessor and .estrategia field \
22658 access must byte-equal — the accessor is the substrate-\
22659 primitive typed dispatch every downstream distribution-\
22660 strategy consumer must route through",
22661 );
22662 }
22663 }
22664
22665 #[test]
22666 fn validate_placement_reads_through_lifted_estrategia_accessor() {
22667 // Three-consumer coherence pin: the
22668 // [`AplicacaoSpec::validate_placement`]
22669 // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
22670 // `estrategia:` field (which reads through
22671 // [`Placement::estrategia`] to name the strategy the empty
22672 // `:clusters` list was declared against), the same method's
22673 // `Sharded ↔ non-Sharded` `match` partition dispatch (which
22674 // reads through [`Placement::estrategia`] to fan across the
22675 // shape-gate cascades), and the non-`Sharded`-arm
22676 // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
22677 // `estrategia:` field (which reads through
22678 // [`Placement::estrategia`] to name the strategy the declared-
22679 // but-inert `:shard-key` was authored under) must all key off
22680 // the lifted accessor, so any future rebrand on the typed
22681 // slot's reader shape lands at exactly one place. Pins the
22682 // three-site coherence by exercising each error surface end-
22683 // to-end and asserting the surfaced `estrategia:` field byte-
22684 // equals the accessor's return. Peer of the sibling per-
22685 // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
22686 // pin on the M3 mesh-slot `Copy`-return scalar axis.
22687
22688 // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
22689 // whose `estrategia:` field must byte-equal the accessor's return
22690 // for every variant in the closed accept-set.
22691 for estrategia in [
22692 PlacementStrategy::SingleNode,
22693 PlacementStrategy::Replicated,
22694 PlacementStrategy::Sharded,
22695 ] {
22696 let mut spec = three_member_spec();
22697 spec.placement.estrategia = estrategia;
22698 spec.placement.clusters = Vec::new();
22699 // Route the paired `:shard-key` spec-mutator through the typed
22700 // cross-slot invariant predicate
22701 // [`PlacementStrategy::requires_shard_key`] rather than the
22702 // [`gen_platform::IsVariant`]-derived
22703 // [`PlacementStrategy::is_sharded`] arm-identity predicate —
22704 // same discipline the sibling
22705 // `placement_strategy_variants_round_trip` and
22706 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
22707 // fixture builders now read through.
22708 spec.placement.shard_key = estrategia
22709 .requires_shard_key()
22710 .then(|| "tenantId".to_string());
22711 let err = spec.validate().unwrap_err();
22712 match err {
22713 AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
22714 assert_eq!(
22715 e,
22716 spec.placement.estrategia(),
22717 "PlacementWithoutClusters.estrategia must byte-equal \
22718 Placement::estrategia() — the error carrier reads \
22719 through the lifted accessor",
22720 );
22721 }
22722 other => panic!(
22723 "expected PlacementWithoutClusters, got {other:?} for \
22724 estrategia={estrategia:?}"
22725 ),
22726 }
22727 }
22728
22729 // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
22730 // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
22731 // must byte-equal the accessor's return for both non-`Sharded`
22732 // strategies.
22733 for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
22734 let mut spec = three_member_spec();
22735 spec.placement.estrategia = estrategia;
22736 spec.placement.shard_key = Some("tenantId".into());
22737 let err = spec.validate().unwrap_err();
22738 match err {
22739 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
22740 assert_eq!(
22741 e,
22742 spec.placement.estrategia(),
22743 "ShardKeyOnNonSharded.estrategia must byte-equal \
22744 Placement::estrategia() — the non-Sharded-arm \
22745 refusal reads through the lifted accessor",
22746 );
22747 }
22748 other => panic!(
22749 "expected ShardKeyOnNonSharded, got {other:?} for \
22750 estrategia={estrategia:?}"
22751 ),
22752 }
22753 }
22754 }
22755
22756 // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
22757 //
22758 // The [`Placement::clusters`] accessor lift is the second slice-return
22759 // (`&[T]`) accessor on any typed slot — sibling to the seed M2
22760 // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
22761 // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
22762 // below cover (1) the accessor's byte-equal projection against the raw
22763 // field access across the empty / singleton / cohort fixtures the
22764 // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
22765 // and the per-cluster validate loop fan between, and (2) the two-
22766 // consumer coherence of the paired pre-flight refusal probe and the
22767 // per-cluster validate loop routing through the accessor on both arms.
22768
22769 #[test]
22770 fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
22771 // The canonical per-`:placement` cluster-pool-scalar-shape pin:
22772 // [`Placement::clusters`] must return the `:placement :clusters`
22773 // typed `Vec<String>` verbatim as a `&[String]` slice-view over
22774 // the same backing buffer the raw `self.clusters.as_slice()`
22775 // field access borrows from, byte-equal across every
22776 // representative fixture in the accept-set — the empty slice
22777 // (the pre-validation sentinel every
22778 // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
22779 // the singleton slice (the minimal `SingleNode`-shape cohort),
22780 // and multi-entry cohorts (the peer `Replicated` / `Sharded`
22781 // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
22782 //
22783 // Pins against a future silent detour that returned
22784 // `&Vec<String>` (which would type-check but leak the storage-
22785 // side `Vec`'s grow/push/reserve surface no consumer of the
22786 // typed view reaches for), a fresh-allocated `Vec<String>` copy
22787 // (which would type-check via a coercion but silently break
22788 // every downstream caller that relied on the slice sharing the
22789 // backing buffer's identity), or an out-of-order or length-
22790 // drifted projection (which would silently split the paired
22791 // pre-flight `.is_empty()` refusal probe's input from the per-
22792 // cluster validate loop's traversal input).
22793 //
22794 // Peer of the sibling M2
22795 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22796 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22797 // `:supervisor` static-child-list axis, extended onto the M3
22798 // per-`:placement` distribution-target-list `Vec`-carry axis.
22799 let fixtures: Vec<Vec<String>> = vec![
22800 Vec::new(),
22801 vec!["rio".into()],
22802 vec!["rio".into(), "mar".into()],
22803 vec!["rio".into(), "mar".into(), "plo".into()],
22804 ];
22805 for clusters in fixtures {
22806 let p = Placement {
22807 clusters: clusters.clone(),
22808 ..Placement::default()
22809 };
22810 assert_eq!(
22811 p.clusters(),
22812 clusters.as_slice(),
22813 "Placement::clusters must return :placement :clusters \
22814 verbatim (got {:?}, expected {:?})",
22815 p.clusters(),
22816 clusters.as_slice(),
22817 );
22818 assert_eq!(
22819 p.clusters(),
22820 p.clusters.as_slice(),
22821 "Placement::clusters accessor and .clusters.as_slice() \
22822 field access must byte-equal — the accessor is the \
22823 substrate-primitive typed dispatch every downstream \
22824 cluster-pool consumer must route through",
22825 );
22826 assert_eq!(
22827 p.clusters().len(),
22828 p.clusters.len(),
22829 "Placement::clusters().len() must byte-equal \
22830 self.clusters.len() — a length-drift would silently \
22831 split the paired pre-flight `.is_empty()` refusal \
22832 probe input from the per-cluster validate loop's \
22833 traversal input",
22834 );
22835 }
22836 }
22837
22838 #[test]
22839 fn validate_placement_reads_through_lifted_clusters_accessor() {
22840 // Two-consumer coherence pin: the
22841 // [`AplicacaoSpec::validate_placement`] pre-flight
22842 // `self.placement.clusters().is_empty()` refusal probe (which
22843 // must trip [`AplicacaoError::PlacementWithoutClusters`] when
22844 // the accessor projects the empty slice) and the per-cluster
22845 // validate loop's `for c in self.placement.clusters()`
22846 // traversal (which must reach every entry in the same order
22847 // the accessor projects, so both the per-entry value-shape
22848 // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
22849 // and the duplicate-detection HashSet insert that trips
22850 // [`AplicacaoError::PlacementClusterDuplicate`] key off the
22851 // accessor's projection) must both key off the lifted
22852 // accessor, so any future rebrand on the typed slot's reader
22853 // shape lands at exactly one place. Pins the two-site
22854 // coherence by exercising each production consumer end-to-end:
22855 // (1) the `PlacementWithoutClusters` refusal under the empty
22856 // slice, (2) the `PlacementClusterInvalid` refusal fires on
22857 // the second entry of a two-cluster cohort whose head is
22858 // valid but tail is not (which requires the loop to reach the
22859 // second entry through the accessor), and (3) the
22860 // `PlacementClusterDuplicate` refusal fires on the second
22861 // entry of a two-cluster cohort that shares a name (which
22862 // requires the loop to reach both entries — a first-entry-only
22863 // projection would silently pass since the dedup HashSet has
22864 // room for the first insert).
22865 //
22866 // Peer of the sibling M2
22867 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
22868 // (bc92bce) coherence pin on the per-`:supervisor` static-
22869 // child-list axis, extended onto the M3 per-`:placement`
22870 // distribution-target-list `Vec`-carry axis.
22871
22872 // (1) Pre-flight `.is_empty()` probe: the empty slice must
22873 // trip `PlacementWithoutClusters`.
22874 let mut spec = three_member_spec();
22875 spec.placement.clusters = Vec::new();
22876 match spec.validate().unwrap_err() {
22877 AplicacaoError::PlacementWithoutClusters { .. } => {}
22878 other => panic!("expected PlacementWithoutClusters, got {other:?}"),
22879 }
22880 assert!(
22881 spec.placement.clusters().is_empty(),
22882 "the pre-flight refusal input must be the empty slice per \
22883 the accessor's projection",
22884 );
22885
22886 // (2) Per-cluster validate loop: a two-cluster cohort with an
22887 // invalid tail entry must trip `PlacementClusterInvalid` on
22888 // the tail — the loop must reach the second entry through
22889 // the accessor.
22890 let mut spec = three_member_spec();
22891 spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
22892 match spec.validate().unwrap_err() {
22893 AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
22894 assert_eq!(
22895 cluster, "BAD_CLUSTER",
22896 "PlacementClusterInvalid.cluster must carry the \
22897 tail entry the loop reached through the accessor",
22898 );
22899 }
22900 other => panic!("expected PlacementClusterInvalid, got {other:?}"),
22901 }
22902 assert_eq!(
22903 spec.placement.clusters().len(),
22904 2,
22905 "the per-cluster validate loop's traversal input must be \
22906 a two-element slice per the accessor's projection",
22907 );
22908
22909 // (3) Per-cluster validate loop: a two-cluster cohort that
22910 // shares a name must trip `PlacementClusterDuplicate` on the
22911 // second entry — the loop must reach both entries through the
22912 // accessor for the dedup HashSet's second insert to collide.
22913 let mut spec = three_member_spec();
22914 spec.placement.clusters = vec!["rio".into(), "rio".into()];
22915 match spec.validate().unwrap_err() {
22916 AplicacaoError::PlacementClusterDuplicate { cluster } => {
22917 assert_eq!(
22918 cluster, "rio",
22919 "PlacementClusterDuplicate.cluster must carry the \
22920 shared cluster name verbatim",
22921 );
22922 }
22923 other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
22924 }
22925 assert_eq!(
22926 spec.placement.clusters().len(),
22927 2,
22928 "the per-cluster validate loop's traversal input must be \
22929 a two-element slice per the accessor's projection",
22930 );
22931 }
22932
22933 #[test]
22934 fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
22935 // The canonical per-`:membros` member-list-slice-shape pin:
22936 // [`AplicacaoSpec::membros`] must return the `:membros` typed
22937 // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
22938 // same backing buffer the raw `self.membros.as_slice()` field
22939 // access borrows from, byte-equal across every representative
22940 // fixture in the accept-set — the empty slice (the pre-
22941 // validation sentinel every [`AplicacaoError::NoMembros`]
22942 // refusal keys off), the singleton slice (the minimal one-
22943 // Servico Aplicacao shape), and multi-entry cohorts (the peer
22944 // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
22945 // load-bearing identity of the application graph).
22946 //
22947 // Pins against a future silent detour that returned
22948 // `&Vec<Membro>` (which would type-check but leak the storage-
22949 // side `Vec`'s grow/push/reserve surface no consumer of the
22950 // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
22951 // (which would type-check via a coercion but silently break
22952 // every downstream caller that relied on the slice sharing the
22953 // backing buffer's identity), or an out-of-order or length-
22954 // drifted projection (which would silently split the paired
22955 // `HashSet<&str>` name-set seed's collect input from the
22956 // pre-flight `.is_empty()` refusal probe's input from the per-
22957 // member validate loop's traversal input from the
22958 // programs.yaml emitter's per-entry fan-out loop's input from
22959 // the `feira app graph` per-member print traversal's input).
22960 //
22961 // Peer of the sibling M2
22962 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22963 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22964 // `:supervisor` static-child-list axis and the sibling M3
22965 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
22966 // (a6e18d7) `&[String]` byte-equal pin on the per-
22967 // `:placement` distribution-target-list axis — extends the
22968 // slice-return-accessor byte-equal-projection discipline onto
22969 // the outermost M3 mesh-slot type's per-Aplicacao member-list
22970 // `Vec`-carry axis.
22971 let fixtures: Vec<Vec<Membro>> = vec![
22972 Vec::new(),
22973 vec![membro("catalog", "^0.1")],
22974 vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
22975 vec![
22976 membro("catalog", "^0.1"),
22977 membro("cart", "^0.1"),
22978 membro("payment", "^0.2"),
22979 ],
22980 ];
22981 for membros in fixtures {
22982 let s = AplicacaoSpec {
22983 membros: membros.clone(),
22984 contratos: Vec::new(),
22985 politicas: MeshPolicy::default(),
22986 placement: Placement::default(),
22987 entrada: None,
22988 };
22989 assert_eq!(
22990 s.membros(),
22991 membros.as_slice(),
22992 "AplicacaoSpec::membros must return :membros verbatim \
22993 (got {:?}, expected {:?})",
22994 s.membros(),
22995 membros.as_slice(),
22996 );
22997 assert_eq!(
22998 s.membros(),
22999 s.membros.as_slice(),
23000 "AplicacaoSpec::membros accessor and .membros.as_slice() \
23001 field access must byte-equal — the accessor is the \
23002 substrate-primitive typed dispatch every downstream \
23003 member-list consumer must route through",
23004 );
23005 assert_eq!(
23006 s.membros().len(),
23007 s.membros.len(),
23008 "AplicacaoSpec::membros().len() must byte-equal \
23009 self.membros.len() — a length-drift would silently \
23010 split the paired `HashSet<&str>` name-set seed's \
23011 collect input from the pre-flight `.is_empty()` \
23012 refusal probe input from the per-member validate \
23013 loop's traversal input",
23014 );
23015 }
23016 }
23017
23018 #[test]
23019 fn validate_reads_through_lifted_membros_accessor() {
23020 // Three-consumer coherence pin: the
23021 // [`AplicacaoSpec::validate_membros`] pre-flight
23022 // `self.membros().is_empty()` refusal probe (which must trip
23023 // [`AplicacaoError::NoMembros`] when the accessor projects the
23024 // empty slice), the same method's per-member validate loop's
23025 // `for m in self.membros()` traversal (which must reach every
23026 // entry in the same order the accessor projects, so both the
23027 // per-entry empty-`:caixa` gate that trips
23028 // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
23029 // detection `insert_first_seen` that trips
23030 // [`AplicacaoError::MembroDuplicate`] key off the accessor's
23031 // projection), and the peer [`AplicacaoSpec::validate`]'s
23032 // `HashSet<&str>` name-set seed's
23033 // `self.membros().iter().map(Membro::nome).collect()` collect
23034 // input (which every `:contratos` `:de` / `:para` membership
23035 // lookup rejects an unknown name against) must all three key
23036 // off the lifted accessor, so any future rebrand on the typed
23037 // slot's reader shape lands at exactly one place. Pins the
23038 // three-site coherence by exercising each production consumer
23039 // end-to-end: (1) the `NoMembros` refusal under the empty
23040 // slice, (2) the `MembroCaixaEmpty` refusal fires on the
23041 // second entry of a two-member cohort whose head is valid but
23042 // tail has an empty `:caixa` (which requires the loop to
23043 // reach the second entry through the accessor), and (3) the
23044 // `MembroDuplicate` refusal fires on the second entry of a
23045 // two-member cohort that shares a `:caixa` name (which
23046 // requires the loop to reach both entries through the
23047 // accessor for the dedup HashSet's second insert to collide).
23048 //
23049 // Peer of the sibling M2
23050 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23051 // (bc92bce) coherence pin on the per-`:supervisor` static-
23052 // child-list axis and the sibling M3
23053 // `validate_placement_reads_through_lifted_clusters_accessor`
23054 // (a6e18d7) coherence pin on the per-`:placement` distribution-
23055 // target-list axis — extends the slice-return-accessor
23056 // multi-consumer coherence discipline onto the outermost M3
23057 // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
23058
23059 // (1) Pre-flight `.is_empty()` probe: the empty slice must
23060 // trip `NoMembros`.
23061 let mut spec = three_member_spec();
23062 spec.membros = Vec::new();
23063 assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
23064 assert!(
23065 spec.membros().is_empty(),
23066 "the pre-flight refusal input must be the empty slice per \
23067 the accessor's projection",
23068 );
23069
23070 // (2) Per-member validate loop: a two-member cohort with an
23071 // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
23072 // the tail — the loop must reach the second entry through
23073 // the accessor.
23074 let mut spec = three_member_spec();
23075 spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
23076 assert_eq!(
23077 spec.validate().unwrap_err(),
23078 AplicacaoError::MembroCaixaEmpty,
23079 );
23080 assert_eq!(
23081 spec.membros().len(),
23082 2,
23083 "the per-member validate loop's traversal input must be \
23084 a two-element slice per the accessor's projection",
23085 );
23086
23087 // (3) Per-member validate loop: a two-member cohort that
23088 // shares a `:caixa` name must trip `MembroDuplicate` on the
23089 // second entry — the loop must reach both entries through the
23090 // accessor for the dedup HashSet's second insert to collide.
23091 let mut spec = three_member_spec();
23092 spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
23093 match spec.validate().unwrap_err() {
23094 AplicacaoError::MembroDuplicate { caixa } => {
23095 assert_eq!(
23096 caixa, "catalog",
23097 "MembroDuplicate.caixa must carry the shared \
23098 member name verbatim",
23099 );
23100 }
23101 other => panic!("expected MembroDuplicate, got {other:?}"),
23102 }
23103 assert_eq!(
23104 spec.membros().len(),
23105 2,
23106 "the per-member validate loop's traversal input must be \
23107 a two-element slice per the accessor's projection",
23108 );
23109 }
23110
23111 #[test]
23112 fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
23113 // The canonical per-`:contratos` contract-list-slice-shape pin:
23114 // [`AplicacaoSpec::contratos`] must return the `:contratos`
23115 // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
23116 // slice-view over the same backing buffer the raw
23117 // `self.contratos.as_slice()` field access borrows from, byte-
23118 // equal across every representative fixture in the accept-set —
23119 // the empty slice (the pre-validation "internal-only mesh" shape
23120 // an Aplicacao whose members exchange no typed edges renders
23121 // through), the singleton slice (the minimal one-edge Aplicacao
23122 // shape), and multi-entry cohorts (the peer multi-edge shapes
23123 // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
23124 // of the application graph).
23125 //
23126 // Pins against a future silent detour that returned
23127 // `&Vec<WitContract>` (which would type-check but leak the
23128 // storage-side `Vec`'s grow/push/reserve surface no consumer of
23129 // the typed view reaches for), a fresh-allocated
23130 // `Vec<WitContract>` copy (which would type-check via a coercion
23131 // but silently break every downstream caller that relied on the
23132 // slice sharing the backing buffer's identity), or an out-of-
23133 // order or length-drifted projection (which would silently split
23134 // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
23135 // seed's traversal input from the `detect_sync_cycles` per-edge
23136 // adjacency-list seed's traversal input from the
23137 // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
23138 // BTreeMap grouping loop's traversal input from the
23139 // `feira app graph` per-contract print traversal's input).
23140 //
23141 // Peer of the immediately-adjacent sibling M3
23142 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
23143 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
23144 // node-list axis, the sibling M3
23145 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
23146 // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
23147 // distribution-target-list axis, and the sibling M2
23148 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23149 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23150 // `:supervisor` static-child-list axis — extends the slice-
23151 // return-accessor byte-equal-projection discipline onto the
23152 // outermost M3 mesh-slot type's per-Aplicacao contract-list
23153 // `Vec`-carry axis, closing the last unlifted per-
23154 // `AplicacaoSpec` `Vec`-carry axis.
23155 let fixtures: Vec<Vec<WitContract>> = vec![
23156 Vec::new(),
23157 vec![contract_http("cart", "catalog", "/products/:id")],
23158 vec![
23159 contract_http("cart", "catalog", "/products/:id"),
23160 contract_http("cart", "payment", "/charge"),
23161 ],
23162 vec![
23163 contract_http("cart", "catalog", "/products/:id"),
23164 contract_http("cart", "payment", "/charge"),
23165 contract_http("payment", "catalog", "/audit"),
23166 ],
23167 ];
23168 for contratos in fixtures {
23169 let s = AplicacaoSpec {
23170 membros: vec![
23171 membro("catalog", "^0.1"),
23172 membro("cart", "^0.1"),
23173 membro("payment", "^0.2"),
23174 ],
23175 contratos: contratos.clone(),
23176 politicas: MeshPolicy::default(),
23177 placement: Placement::default(),
23178 entrada: None,
23179 };
23180 assert_eq!(
23181 s.contratos(),
23182 contratos.as_slice(),
23183 "AplicacaoSpec::contratos must return :contratos verbatim \
23184 (got {:?}, expected {:?})",
23185 s.contratos(),
23186 contratos.as_slice(),
23187 );
23188 assert_eq!(
23189 s.contratos(),
23190 s.contratos.as_slice(),
23191 "AplicacaoSpec::contratos accessor and \
23192 .contratos.as_slice() field access must byte-equal — \
23193 the accessor is the substrate-primitive typed dispatch \
23194 every downstream contract-list consumer must route \
23195 through",
23196 );
23197 assert_eq!(
23198 s.contratos().len(),
23199 s.contratos.len(),
23200 "AplicacaoSpec::contratos().len() must byte-equal \
23201 self.contratos.len() — a length-drift would silently \
23202 split the paired per-edge validate-loop's traversal \
23203 input from the sync-cycle adjacency-list seed's \
23204 traversal input from the cilium_network_policies \
23205 per-`(:de, :para)` BTreeMap grouping loop's traversal \
23206 input from the `feira app graph` per-contract print \
23207 traversal's input",
23208 );
23209 }
23210 }
23211
23212 #[test]
23213 fn validate_reads_through_lifted_contratos_accessor() {
23214 // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
23215 // per-`:contratos` validate-loop's `for c in self.contratos()`
23216 // traversal (which must reach every entry in the same order the
23217 // accessor projects, so both the per-entry
23218 // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
23219 // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
23220 // dedup `HashSet` insert key off the accessor's projection),
23221 // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
23222 // `for c in self.contratos()` adjacency-list seed (which drives
23223 // the sync-subgraph deadlock-detection gate via
23224 // [`AplicacaoError::SyncCycle`]), and the peer
23225 // [`caixa_mesh::cilium_network_policies`]'s
23226 // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
23227 // grouping loop (which drives the per-CNP fan-out) must all
23228 // three key off the lifted accessor, so any future rebrand on
23229 // the typed slot's reader shape lands at exactly one place. Pins
23230 // the three-site coherence by exercising the two caixa-core
23231 // production consumers end-to-end: (1) the empty-`:contratos`
23232 // slice must validate without a per-edge diagnostic (the
23233 // per-edge loop is a no-op under the empty projection), (2) the
23234 // `ContratoMemberMissing` refusal fires on the second entry of a
23235 // two-edge cohort whose head references a valid member but tail
23236 // references a phantom name (which requires the loop to reach
23237 // the second entry through the accessor), and (3) the
23238 // `SyncCycle` refusal fires on a self-referential two-edge
23239 // cohort through the sync-cycle detector's peer projection
23240 // (which requires the detector to iterate the accessor's
23241 // projection to add the back-edge to its adjacency list).
23242 //
23243 // Peer of the sibling M3
23244 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23245 // three-consumer coherence pin on the per-`:membros` node-list
23246 // axis and the sibling M3
23247 // `validate_placement_reads_through_lifted_clusters_accessor`
23248 // (a6e18d7) coherence pin on the per-`:placement` distribution-
23249 // target-list axis — extends the slice-return-accessor multi-
23250 // consumer coherence discipline onto the outermost M3 mesh-slot
23251 // type's per-Aplicacao contract-list `Vec`-carry axis.
23252
23253 // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
23254 // and no per-edge diagnostic surfaces. Validate succeeds on
23255 // the well-formed `:membros` head.
23256 let mut spec = three_member_spec();
23257 spec.contratos = Vec::new();
23258 assert!(
23259 spec.validate().is_ok(),
23260 "empty :contratos must validate — the per-edge loop is a \
23261 no-op under the accessor's empty projection",
23262 );
23263 assert!(
23264 spec.contratos().is_empty(),
23265 "the per-edge validate loop's traversal input must be the \
23266 empty slice per the accessor's projection",
23267 );
23268
23269 // (2) Per-edge validate loop: a two-edge cohort whose tail
23270 // references a phantom `:para` member must trip
23271 // `ContratoMemberMissing` on the tail — the loop must reach
23272 // the second entry through the accessor for the membership
23273 // lookup to fail on the phantom name.
23274 let mut spec = three_member_spec();
23275 spec.contratos = vec![
23276 contract_http("cart", "catalog", "/products/:id"),
23277 contract_http("cart", "phantom", "/x"),
23278 ];
23279 let err = spec.validate().unwrap_err();
23280 assert!(
23281 matches!(
23282 err,
23283 AplicacaoError::ContratoMemberMissing { ref caixa }
23284 if caixa == "phantom"
23285 ),
23286 "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
23287 );
23288 assert_eq!(
23289 spec.contratos().len(),
23290 2,
23291 "the per-edge validate loop's traversal input must be \
23292 a two-element slice per the accessor's projection",
23293 );
23294
23295 // (3) Sync-cycle detector: a two-edge synchronous cohort
23296 // whose second edge closes the sync-subgraph back onto the
23297 // first must trip [`AplicacaoError::ContratoCycle`] — the
23298 // detector must iterate the accessor's projection to add
23299 // both edges to its adjacency list, so a length-drift on
23300 // the accessor's projection would silently disagree with
23301 // the sync-cycle detector on which edge closes the loop.
23302 // Peer projection to the `validate` per-edge loop above:
23303 // the sync-cycle detector routes through the same lifted
23304 // accessor, so a rebrand of the reader shape lands at one
23305 // place. Uses a two-edge cohort (cart → catalog → cart)
23306 // because the per-edge `ContratoSelfLoop` gate fires before
23307 // the sync-cycle detector on a single self-referential edge
23308 // (`cart → cart`) — the cycle-detector's input must be a
23309 // multi-edge cohort for its per-edge traversal input to be
23310 // observably wider than the per-edge validate loop's input.
23311 let mut spec = three_member_spec();
23312 spec.contratos = vec![
23313 contract_http("cart", "catalog", "/products/:id"),
23314 contract_http("catalog", "cart", "/callback"),
23315 ];
23316 let err = spec.validate().unwrap_err();
23317 assert!(
23318 matches!(err, AplicacaoError::ContratoCycle { .. }),
23319 "expected ContratoCycle from the sync-cycle detector on a \
23320 two-edge back-edge cohort, got {err:?}",
23321 );
23322 assert_eq!(
23323 spec.contratos().len(),
23324 2,
23325 "the sync-cycle detector's traversal input must be a \
23326 two-element slice per the accessor's projection",
23327 );
23328 }
23329
23330 #[test]
23331 fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
23332 // The canonical per-`:politicas` outer-composite-reference-shape
23333 // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
23334 // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
23335 // the same backing storage the raw `&self.politicas` field
23336 // access borrows from, byte-equal across every representative
23337 // fixture in the accept-set — the default `MeshPolicy` (the
23338 // author-empty "no policy on any axis" shape whose
23339 // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
23340 // shapes carrying one axis at a time
23341 // (`{mtls_required, timeout, retries, circuit_breaker,
23342 // rate_limit}` — the minimal five-axis fan-out over the
23343 // per-axis lifted accessor family every downstream mesh-artifact
23344 // emitter dispatches on), and the multi-axis composite (the
23345 // canonical `three_member_spec` fixture's `{timeout, retries,
23346 // mtls_required}` triple — the load-bearing shape every
23347 // Aplicacao-scoped fixture in this suite constructs).
23348 //
23349 // Pins against a future silent detour that returned a fresh-
23350 // cloned `MeshPolicy` copy (which would type-check via a `Clone`
23351 // impl but silently break every downstream caller that relied
23352 // on the reference sharing the composite's backing identity), a
23353 // reference to an operator-resolved overlay (the future
23354 // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
23355 // acknowledges — its resolution must land at exactly this
23356 // accessor body, not silently divert the raw slot away from a
23357 // second consumer), or an axis-shuffled projection (a future
23358 // detour that swapped `timeout` and `retries` through the
23359 // accessor would silently split the paired `validate_politicas`
23360 // per-axis bracket-dispatch's traversal input from the peer
23361 // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
23362 // emitter's fan-out input from the peer
23363 // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
23364 // overlay emitter's fan-out input).
23365 //
23366 // Peer of the sibling M3
23367 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
23368 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
23369 // node-list `Vec`-carry axis and the sibling M3
23370 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
23371 // (0dcc926) `&[WitContract]` byte-equal pin on the per-
23372 // `:contratos` edge-list `Vec`-carry axis — extends the outer-
23373 // accessor byte-equal-projection discipline onto the outermost
23374 // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
23375 // reference axis, the first `&Composite`-return accessor on the
23376 // outer [`AplicacaoSpec`] type.
23377 let fixtures: Vec<MeshPolicy> = vec![
23378 MeshPolicy::default(),
23379 MeshPolicy {
23380 mtls_required: Some(true),
23381 ..MeshPolicy::default()
23382 },
23383 MeshPolicy {
23384 mtls_required: Some(false),
23385 ..MeshPolicy::default()
23386 },
23387 MeshPolicy {
23388 timeout: Some(Duration::from_secs(30)),
23389 ..MeshPolicy::default()
23390 },
23391 MeshPolicy {
23392 retries: Some(3),
23393 ..MeshPolicy::default()
23394 },
23395 MeshPolicy {
23396 circuit_breaker: Some(CircuitBreaker {
23397 max_failures: 5,
23398 window: Duration::from_secs(30),
23399 }),
23400 ..MeshPolicy::default()
23401 },
23402 MeshPolicy {
23403 rate_limit: Some(RateLimit {
23404 rate: 100,
23405 window: Duration::from_secs(1),
23406 }),
23407 ..MeshPolicy::default()
23408 },
23409 MeshPolicy {
23410 timeout: Some(Duration::from_secs(30)),
23411 retries: Some(3),
23412 mtls_required: Some(true),
23413 ..MeshPolicy::default()
23414 },
23415 ];
23416 for politicas in fixtures {
23417 let s = AplicacaoSpec {
23418 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23419 contratos: Vec::new(),
23420 politicas: politicas.clone(),
23421 placement: Placement::default(),
23422 entrada: None,
23423 };
23424 assert_eq!(
23425 *s.politicas(),
23426 politicas,
23427 "AplicacaoSpec::politicas must return :politicas verbatim \
23428 (got {:?}, expected {:?})",
23429 s.politicas(),
23430 politicas,
23431 );
23432 assert!(
23433 std::ptr::eq(s.politicas(), &s.politicas),
23434 "AplicacaoSpec::politicas accessor and &self.politicas \
23435 field access must borrow the same backing storage — \
23436 the accessor is the substrate-primitive typed dispatch \
23437 every downstream mesh-policy composite consumer must \
23438 route through, and a reference-identity split would \
23439 silently break every consumer that relied on the \
23440 borrow sharing the composite's storage",
23441 );
23442 assert_eq!(
23443 s.politicas().is_empty(),
23444 s.politicas.is_empty(),
23445 "AplicacaoSpec::politicas().is_empty() must byte-equal \
23446 self.politicas.is_empty() — an emptiness-drift would \
23447 silently split the paired `validate_politicas` \
23448 per-axis bracket-dispatch's seed from the peer \
23449 caixa-mesh CNP mTLS-overlay emitter's key from the \
23450 peer caixa-mesh HTTPRoute timeout+retry overlay \
23451 emitter's key",
23452 );
23453 }
23454 }
23455
23456 #[test]
23457 fn validate_politicas_reads_through_lifted_politicas_accessor() {
23458 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
23459 // per-axis bracket-dispatch seed (`let p = self.politicas();`,
23460 // followed by the per-axis fan-out `p.timeout()` /
23461 // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
23462 // the lifted axis-level accessor family) must key off the
23463 // lifted outer accessor, so any future rebrand on the typed
23464 // slot's outer-composite reader shape lands at exactly one
23465 // place. Pins the multi-axis coherence by exercising each
23466 // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
23467 // a `Some(Duration::ZERO)` timeout under the outer accessor's
23468 // reference projection, (2) `PolicyRetriesZero` fires on a
23469 // `Some(0)` retries under the same projection, and (3) an
23470 // empty [`MeshPolicy::default`] passes `validate_politicas` —
23471 // the outer accessor's reference-projection reaches every
23472 // per-axis branch without silently short-circuiting any.
23473 //
23474 // Peer of the sibling M3
23475 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23476 // three-consumer coherence pin on the per-`:membros` node-list
23477 // axis and the sibling M3
23478 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
23479 // three-consumer coherence pin on the per-`:contratos`
23480 // edge-list axis — extends the multi-consumer coherence
23481 // discipline onto the outermost M3 mesh-slot type's per-
23482 // Aplicacao mesh-policy composite-reference axis, the first
23483 // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
23484 // type.
23485
23486 // (1) `PolicyTimeoutZero` refusal under the outer accessor's
23487 // reference projection: a `Some(Duration::ZERO)` timeout must
23488 // trip the zero-floor gate. The bracket-dispatch's first arm
23489 // reads `p.timeout()` on the reference returned by the outer
23490 // accessor.
23491 let mut spec = three_member_spec();
23492 spec.politicas.timeout = Some(Duration::ZERO);
23493 spec.politicas.retries = None;
23494 spec.politicas.circuit_breaker = None;
23495 spec.politicas.rate_limit = None;
23496 assert_eq!(
23497 spec.validate().unwrap_err(),
23498 AplicacaoError::PolicyTimeoutZero,
23499 );
23500 assert!(
23501 std::ptr::eq(spec.politicas(), &spec.politicas),
23502 "the `validate_politicas` per-axis bracket-dispatch's \
23503 traversal input must be the same backing composite the \
23504 accessor's reference projection borrows from",
23505 );
23506
23507 // (2) `PolicyRetriesZero` refusal under the outer accessor's
23508 // reference projection: a `Some(0)` retries must trip the
23509 // zero-floor gate. The bracket-dispatch's second arm reads
23510 // `p.retries()` on the reference returned by the outer accessor.
23511 let mut spec = three_member_spec();
23512 spec.politicas.timeout = None;
23513 spec.politicas.retries = Some(0);
23514 spec.politicas.circuit_breaker = None;
23515 spec.politicas.rate_limit = None;
23516 assert_eq!(
23517 spec.validate().unwrap_err(),
23518 AplicacaoError::PolicyRetriesZero,
23519 );
23520
23521 // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
23522 // — every per-axis arm short-circuits on `None`, so the outer
23523 // accessor's reference projection reaches the fall-through
23524 // `Ok(())` without any per-axis refusal firing.
23525 let mut spec = three_member_spec();
23526 spec.politicas = MeshPolicy::default();
23527 assert!(
23528 spec.validate().is_ok(),
23529 "an empty `MeshPolicy` must pass `validate_politicas` — \
23530 every per-axis arm short-circuits on `None` under the \
23531 outer accessor's reference projection",
23532 );
23533 assert!(
23534 spec.politicas().is_empty(),
23535 "the outer accessor's reference projection must be the \
23536 empty composite per the `MeshPolicy::default()` fixture",
23537 );
23538 }
23539
23540 #[test]
23541 #[allow(clippy::too_many_lines)]
23542 fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
23543 // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
23544 // per-axis bracket-dispatch's `:timeout` and `:retries` arms
23545 // must both key off the lifted axis-level accessors
23546 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
23547 // the peer `:circuit-breaker` / `:rate-limit` arms already
23548 // routing through [`MeshPolicy::circuit_breaker`] /
23549 // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
23550 // per axis on the substrate primitive" shape at the fan-out
23551 // (four axes, four accessors, no raw-field-access site
23552 // anywhere on the bracket-dispatch). Pins the per-axis
23553 // coherence at the accept-set boundaries the bracket carves:
23554 // 1. accessor byte-equal to raw field on every representative
23555 // accept-set value (`None`, sub-cap, at-cap, past-cap
23556 // sentinel) — a future accessor drift that no longer
23557 // shipped the raw slot verbatim would surface here,
23558 // 2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
23559 // routed through the accessor's projection, proving the
23560 // first arm reads through the accessor rather than a
23561 // silent-detour peer-axis field access,
23562 // 3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
23563 // through the accessor's projection, proving the second
23564 // arm reads through the accessor,
23565 // 4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
23566 // passes validate under the accessor projection (paired
23567 // with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
23568 // sibling axis), pinning the upper-boundary accept-arm
23569 // also routes through the accessor.
23570 //
23571 // Peer of the sibling M3
23572 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23573 // outer-composite-reference coherence pin (which asserts the
23574 // `let p = self.politicas()` seed); extends the discipline onto
23575 // the per-axis fan-out layer that consumes the seed's
23576 // reference. Same shape as
23577 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
23578 // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23579 // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
23580 // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
23581
23582 // (1) Accessor byte-equal to raw field on the `:timeout` axis
23583 // across the accept-set boundaries the bracket dispatch's
23584 // three-arm gate carves out
23585 // ([`crate::render::require_positive_canonical_bounded_duration`]
23586 // — zero-floor + canonical-form + upper-cap).
23587 for timeout in [
23588 None,
23589 Some(Duration::ZERO),
23590 Some(Duration::from_millis(1)),
23591 Some(POLICY_TIMEOUT_MAX),
23592 ] {
23593 let p = MeshPolicy {
23594 timeout,
23595 ..MeshPolicy::default()
23596 };
23597 assert_eq!(
23598 p.timeout(),
23599 p.timeout,
23600 "MeshPolicy::timeout accessor must byte-equal the raw \
23601 .timeout field across every accept-set boundary the \
23602 validate_politicas :timeout arm carves out — a drift \
23603 here would silently split the validate bracket's arm \
23604 from the peer caixa-mesh HTTPRoute timeout-overlay \
23605 emitter's read",
23606 );
23607 }
23608
23609 // (2) Accessor byte-equal to raw field on the `:retries` axis
23610 // across the accept-set boundaries the bracket dispatch's
23611 // two-arm gate carves out
23612 // ([`crate::render::require_positive_bounded_u32`] — zero-floor
23613 // + upper-cap).
23614 for retries in [
23615 None,
23616 Some(0u32),
23617 Some(1u32),
23618 Some(POLICY_RETRIES_MAX),
23619 Some(POLICY_RETRIES_MAX + 1),
23620 Some(u32::MAX),
23621 ] {
23622 let p = MeshPolicy {
23623 retries,
23624 ..MeshPolicy::default()
23625 };
23626 assert_eq!(
23627 p.retries(),
23628 p.retries,
23629 "MeshPolicy::retries accessor must byte-equal the raw \
23630 .retries field across every accept-set boundary the \
23631 validate_politicas :retries arm carves out — a drift \
23632 here would silently split the validate bracket's arm \
23633 from the peer caixa-mesh HTTPRoute retry-overlay \
23634 emitter's read",
23635 );
23636 }
23637
23638 // (3) `PolicyTimeoutZero` fires on the accessor-projected
23639 // zero-floor boundary. A silent detour that no longer read
23640 // through `p.timeout()` (a peer-axis field read, an accidental
23641 // Option::and-then chain that collapsed the None arm to Some,
23642 // an accessor rebrand that clamped the return through the
23643 // upper cap) would fail to refuse here.
23644 let mut spec = three_member_spec();
23645 spec.politicas.timeout = Some(Duration::ZERO);
23646 spec.politicas.retries = None;
23647 spec.politicas.circuit_breaker = None;
23648 spec.politicas.rate_limit = None;
23649 assert_eq!(
23650 spec.politicas().timeout(),
23651 Some(Duration::ZERO),
23652 "the accessor projection must reflect the fixture's \
23653 `Some(Duration::ZERO)` :timeout verbatim",
23654 );
23655 assert_eq!(
23656 spec.validate().unwrap_err(),
23657 AplicacaoError::PolicyTimeoutZero,
23658 "the validate_politicas :timeout zero-floor arm must fire \
23659 through the lifted accessor's projection — a silent \
23660 detour to a peer-axis field would fail to refuse",
23661 );
23662
23663 // (4) `PolicyRetriesZero` fires on the accessor-projected
23664 // zero-floor boundary on the sibling `:retries` axis.
23665 let mut spec = three_member_spec();
23666 spec.politicas.timeout = None;
23667 spec.politicas.retries = Some(0);
23668 spec.politicas.circuit_breaker = None;
23669 spec.politicas.rate_limit = None;
23670 assert_eq!(
23671 spec.politicas().retries(),
23672 Some(0),
23673 "the accessor projection must reflect the fixture's \
23674 `Some(0)` :retries verbatim",
23675 );
23676 assert_eq!(
23677 spec.validate().unwrap_err(),
23678 AplicacaoError::PolicyRetriesZero,
23679 "the validate_politicas :retries zero-floor arm must fire \
23680 through the lifted accessor's projection — a silent \
23681 detour to a peer-axis field would fail to refuse",
23682 );
23683
23684 // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
23685 // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
23686 // must pass validate under the accessor projection — pins the
23687 // upper-boundary accept-arm also routes through the lifted
23688 // accessor (a drift that clamped or short-circuited at the
23689 // upper boundary would fail the whole-spec validate here).
23690 let mut spec = three_member_spec();
23691 spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
23692 spec.politicas.retries = Some(POLICY_RETRIES_MAX);
23693 spec.politicas.circuit_breaker = None;
23694 spec.politicas.rate_limit = None;
23695 assert_eq!(
23696 spec.politicas().timeout(),
23697 Some(POLICY_TIMEOUT_MAX),
23698 "the accessor projection must reflect the fixture's \
23699 at-cap :timeout verbatim",
23700 );
23701 assert_eq!(
23702 spec.politicas().retries(),
23703 Some(POLICY_RETRIES_MAX),
23704 "the accessor projection must reflect the fixture's \
23705 at-cap :retries verbatim",
23706 );
23707 assert!(
23708 spec.validate().is_ok(),
23709 "at-cap :timeout + :retries must pass validate under the \
23710 accessor projection — the upper-boundary accept-arm on \
23711 both axes routes through the lifted accessor",
23712 );
23713 }
23714
23715 #[test]
23716 fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
23717 // The canonical per-`:placement` outer-composite-reference-shape
23718 // pin: [`AplicacaoSpec::placement`] must return the `:placement`
23719 // typed `Placement` verbatim as a `&Placement` reference over the
23720 // same backing storage the raw `&self.placement` field access
23721 // borrows from, byte-equal across every representative fixture in
23722 // the accept-set — the default `Placement` (the substrate seed
23723 // shape whose [`PlacementStrategy::default`] evaluates to
23724 // `SingleNode` with an empty `:clusters` pool and both
23725 // optional-scalar axes `None`), and every canonical strategy /
23726 // cluster-pool / optional-scalar combination the
23727 // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
23728 // three [`PlacementStrategy`] variants — `SingleNode`,
23729 // `Replicated`, `Sharded` — cross-projected with a non-empty
23730 // `:clusters` pool and, on the `Sharded` arm, a non-empty
23731 // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
23732 // canonical `three_member_spec` `Replicated` fixture's
23733 // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
23734 //
23735 // Pins against a future silent detour that returned a fresh-
23736 // cloned `Placement` copy (which would type-check via a `Clone`
23737 // impl but silently break every downstream caller that relied on
23738 // the reference sharing the composite's backing identity), a
23739 // reference to an operator-resolved overlay (the future per-
23740 // cluster `:placement-overrides` slot MESH-COMPOSITION §V
23741 // acknowledges — its resolution must land at exactly this
23742 // accessor body, not silently divert the raw slot away from a
23743 // second consumer), or an axis-shuffled projection (a future
23744 // detour that swapped `clusters` and `affinity` through the
23745 // accessor would silently split the paired `validate_placement`
23746 // per-axis bracket-dispatch's traversal input from the peer
23747 // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
23748 // programs.yaml distribution-annotation emitter's fan-out input
23749 // from the peer `feira app graph` per-Aplicacao print line's
23750 // input).
23751 //
23752 // Peer of the sibling M3
23753 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
23754 // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
23755 // outer mesh-policy composite-reference axis, and of the sibling
23756 // slice-return `aplicacao_spec_membros_returns_membros_slice_
23757 // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
23758 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
23759 // across_permutations` (0dcc926) `&[WitContract]` pins — extends
23760 // the outer-accessor byte-equal-projection discipline onto the
23761 // outermost M3 mesh-slot type's per-Aplicacao distribution
23762 // composite-reference axis, the second `&Composite`-return
23763 // accessor on the outer [`AplicacaoSpec`] type.
23764 let fixtures: Vec<Placement> = vec![
23765 Placement::default(),
23766 Placement {
23767 estrategia: PlacementStrategy::SingleNode,
23768 clusters: vec!["rio".into()],
23769 affinity: None,
23770 shard_key: None,
23771 },
23772 Placement {
23773 estrategia: PlacementStrategy::Replicated,
23774 clusters: vec!["rio".into(), "mar".into()],
23775 affinity: None,
23776 shard_key: None,
23777 },
23778 Placement {
23779 estrategia: PlacementStrategy::Replicated,
23780 clusters: vec!["rio".into(), "mar".into()],
23781 affinity: Some("data-locality".into()),
23782 shard_key: None,
23783 },
23784 Placement {
23785 estrategia: PlacementStrategy::Sharded,
23786 clusters: vec!["rio".into(), "mar".into()],
23787 affinity: None,
23788 shard_key: Some("tenantId".into()),
23789 },
23790 Placement {
23791 estrategia: PlacementStrategy::Sharded,
23792 clusters: vec!["rio".into(), "mar".into(), "sol".into()],
23793 affinity: Some("low-latency".into()),
23794 shard_key: Some("metadata.tenantId".into()),
23795 },
23796 ];
23797 for placement in fixtures {
23798 let s = AplicacaoSpec {
23799 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23800 contratos: Vec::new(),
23801 politicas: MeshPolicy::default(),
23802 placement: placement.clone(),
23803 entrada: None,
23804 };
23805 assert_eq!(
23806 *s.placement(),
23807 placement,
23808 "AplicacaoSpec::placement must return :placement verbatim \
23809 (got {:?}, expected {:?})",
23810 s.placement(),
23811 placement,
23812 );
23813 assert!(
23814 std::ptr::eq(s.placement(), &s.placement),
23815 "AplicacaoSpec::placement accessor and &self.placement \
23816 field access must borrow the same backing storage — the \
23817 accessor is the substrate-primitive typed dispatch every \
23818 downstream distribution-composite consumer must route \
23819 through, and a reference-identity split would silently \
23820 break every consumer that relied on the borrow sharing \
23821 the composite's storage",
23822 );
23823 assert_eq!(
23824 s.placement().estrategia(),
23825 s.placement.estrategia,
23826 "AplicacaoSpec::placement().estrategia() must byte-equal \
23827 self.placement.estrategia — a strategy-drift would \
23828 silently split the paired `validate_placement` \
23829 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
23830 peer caixa-mesh programs.yaml `placement.estrategia` \
23831 emitter's key from the peer `feira app graph` printer's \
23832 strategy label",
23833 );
23834 assert_eq!(
23835 s.placement().clusters(),
23836 s.placement.clusters.as_slice(),
23837 "AplicacaoSpec::placement().clusters() must byte-equal \
23838 self.placement.clusters — a cluster-pool drift would \
23839 silently split the paired `validate_placement` \
23840 pre-flight `.is_empty()` refusal probe's traversal from \
23841 the peer caixa-mesh programs.yaml `placement.clusters` \
23842 emitter's fan-out from the peer `feira app graph` \
23843 printer's cluster list",
23844 );
23845 }
23846 }
23847
23848 #[test]
23849 fn validate_placement_reads_through_lifted_placement_accessor() {
23850 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
23851 // per-axis bracket-dispatch seed (`let p = self.placement();`,
23852 // followed by the per-axis fan-out `p.clusters()` /
23853 // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
23854 // lifted axis-level accessor family) must key off the lifted
23855 // outer accessor, so any future rebrand on the typed slot's
23856 // outer-composite reader shape lands at exactly one place. Pins
23857 // the multi-axis coherence by exercising each per-axis refusal
23858 // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
23859 // `:clusters` pool under the outer accessor's reference
23860 // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
23861 // strategy with a `None` `:shard-key` under the same projection,
23862 // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
23863 // with a `Some` `:shard-key` under the same projection, and
23864 // (4) the canonical `three_member_spec` `Replicated` fixture
23865 // passes `validate_placement` under the outer accessor's
23866 // reference projection — the accessor's reference-projection
23867 // reaches every per-axis branch (cluster-pool refusal, `Sharded`
23868 // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
23869 // without silently short-circuiting any.
23870 //
23871 // Peer of the sibling M3
23872 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23873 // (534dc21) multi-axis coherence pin on the per-`:politicas`
23874 // outer mesh-policy composite-reference axis — extends the
23875 // multi-consumer coherence discipline onto the outermost M3
23876 // mesh-slot type's per-Aplicacao distribution composite-
23877 // reference axis, the second `&Composite`-return accessor on
23878 // the outer [`AplicacaoSpec`] type.
23879
23880 // (1) `PlacementWithoutClusters` refusal under the outer
23881 // accessor's reference projection: an empty `:clusters` pool
23882 // must trip the pre-flight refusal probe. The bracket-dispatch's
23883 // first arm reads `p.clusters()` on the reference returned by
23884 // the outer accessor.
23885 let mut spec = three_member_spec();
23886 spec.placement.clusters = Vec::new();
23887 assert_eq!(
23888 spec.validate().unwrap_err(),
23889 AplicacaoError::PlacementWithoutClusters {
23890 estrategia: PlacementStrategy::Replicated,
23891 },
23892 );
23893 assert!(
23894 std::ptr::eq(spec.placement(), &spec.placement),
23895 "the `validate_placement` per-axis bracket-dispatch's \
23896 traversal input must be the same backing composite the \
23897 accessor's reference projection borrows from",
23898 );
23899
23900 // (2) `ShardedWithoutKey` refusal under the outer accessor's
23901 // reference projection: a `Sharded` strategy with a `None`
23902 // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
23903 // The bracket-dispatch's third arm reads `p.estrategia()` for
23904 // the match scrutinee then `p.shard_key()` for the cascade
23905 // scrutinee, both on the reference returned by the outer
23906 // accessor.
23907 let mut spec = three_member_spec();
23908 spec.placement.estrategia = PlacementStrategy::Sharded;
23909 spec.placement.shard_key = None;
23910 assert_eq!(
23911 spec.validate().unwrap_err(),
23912 AplicacaoError::ShardedWithoutKey,
23913 );
23914
23915 // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
23916 // reference projection: a non-`Sharded` strategy with a `Some`
23917 // `:shard-key` must trip the declared-but-inert refusal. The
23918 // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
23919 // + `p.estrategia()` for the diagnostic on the reference
23920 // returned by the outer accessor.
23921 let mut spec = three_member_spec();
23922 spec.placement.estrategia = PlacementStrategy::Replicated;
23923 spec.placement.shard_key = Some("tenantId".into());
23924 assert_eq!(
23925 spec.validate().unwrap_err(),
23926 AplicacaoError::ShardKeyOnNonSharded {
23927 estrategia: PlacementStrategy::Replicated,
23928 shard_key: "tenantId".into(),
23929 },
23930 );
23931
23932 // (4) Canonical `three_member_spec` `Replicated` fixture passes
23933 // `validate_placement` — every per-axis arm reaches the fall-
23934 // through `Ok(())` without any per-axis refusal firing under the
23935 // outer accessor's reference projection.
23936 let spec = three_member_spec();
23937 assert!(
23938 spec.validate().is_ok(),
23939 "the canonical Replicated placement fixture must pass \
23940 `validate_placement` — every per-axis arm short-circuits on \
23941 valid input under the outer accessor's reference projection",
23942 );
23943 assert_eq!(
23944 spec.placement().estrategia(),
23945 PlacementStrategy::Replicated,
23946 "the outer accessor's reference projection must be the \
23947 canonical Replicated fixture's strategy",
23948 );
23949 assert_eq!(
23950 spec.placement().clusters(),
23951 &["rio", "mar"],
23952 "the outer accessor's reference projection must be the \
23953 canonical Replicated fixture's cluster pool",
23954 );
23955 }
23956
23957 #[test]
23958 fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
23959 // The canonical per-`:entrada` outer-composite-optional-
23960 // reference-shape pin: [`AplicacaoSpec::entrada`] must return
23961 // the `:entrada` typed `Option<Entrada>` verbatim as an
23962 // `Option<&Entrada>` reference over the same backing storage
23963 // the raw `self.entrada.as_ref()` field access borrows from,
23964 // byte-equal across every representative fixture in the
23965 // accept-set — the author-omitted `None` shape (the
23966 // "internal-only mesh" partition every downstream external-
23967 // gateway emitter treats as "emit nothing"), the minimal
23968 // singleton `:entrada` composite (host + destination + empty
23969 // paths + default port), the paths-carrying composite (the
23970 // canonical `three_member_spec` fixture's ["/api" "/health"]
23971 // path-list shape every HTTPRoute per-rule fan-out emitter
23972 // reads), and the non-default port composite (the canonical
23973 // custom-port shape the port-fallback resolver reads).
23974 //
23975 // Pins against a future silent detour that returned a fresh-
23976 // cloned `Entrada` copy (which would type-check via a `Clone`
23977 // impl but silently break every downstream caller that
23978 // relied on the reference sharing the composite's backing
23979 // identity), a reference to an operator-resolved overlay
23980 // (the future per-cluster `:entrada-overrides` slot the
23981 // MESH-COMPOSITION §V federation roadmap acknowledges — its
23982 // resolution must land at exactly this accessor body, not
23983 // silently divert the raw slot away from a second consumer),
23984 // a `None` → `Some(Entrada::default)` cluster-default
23985 // projection (which would collapse the load-bearing
23986 // "author-omitted `:entrada` ⇒ internal-only mesh" partition
23987 // the peer `gateway_routes` early-return + `feira app graph`
23988 // internal-only-mesh partition both read), or an axis-
23989 // shuffled projection (a future detour that swapped
23990 // `host` and `para` through the accessor would silently
23991 // split the paired `validate` per-`:entrada` shape-and-
23992 // membership gate's traversal input from the peer
23993 // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
23994 // fan-out input from the peer `feira app graph` external-
23995 // gateway summary line).
23996 //
23997 // Peer of the sibling M3
23998 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
23999 // (534dc21) `&MeshPolicy` byte-equal pin on the per-
24000 // `:politicas` outer mesh-policy composite-reference axis
24001 // and of the sibling M3
24002 // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
24003 // (9abb8f0) `&Placement` byte-equal pin on the per-
24004 // `:placement` outer distribution-composite composite-
24005 // reference axis — extends the outer-accessor byte-equal-
24006 // projection discipline onto the last unlifted outermost M3
24007 // mesh-slot type's per-Aplicacao external-gateway composite-
24008 // reference axis, the third and final `&Composite`-return
24009 // accessor on the outer [`AplicacaoSpec`] type.
24010 let fixtures: Vec<Option<Entrada>> = vec![
24011 None,
24012 Some(Entrada {
24013 host: "checkout.quero.cloud".into(),
24014 para: "cart".into(),
24015 paths: Vec::new(),
24016 port: DEFAULT_SERVICO_PORT,
24017 }),
24018 Some(Entrada {
24019 host: "checkout.quero.cloud".into(),
24020 para: "cart".into(),
24021 paths: vec!["/api".into(), "/health".into()],
24022 port: DEFAULT_SERVICO_PORT,
24023 }),
24024 Some(Entrada {
24025 host: "checkout.quero.cloud".into(),
24026 para: "cart".into(),
24027 paths: vec!["/api".into()],
24028 port: 9443,
24029 }),
24030 ];
24031 for entrada in fixtures {
24032 let s = AplicacaoSpec {
24033 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24034 contratos: Vec::new(),
24035 politicas: MeshPolicy::default(),
24036 placement: Placement::default(),
24037 entrada: entrada.clone(),
24038 };
24039 assert_eq!(
24040 s.entrada(),
24041 entrada.as_ref(),
24042 "AplicacaoSpec::entrada must return :entrada verbatim \
24043 (got {:?}, expected {:?})",
24044 s.entrada(),
24045 entrada.as_ref(),
24046 );
24047 match (s.entrada(), s.entrada.as_ref()) {
24048 (Some(a), Some(b)) => assert!(
24049 std::ptr::eq(a, b),
24050 "AplicacaoSpec::entrada accessor and \
24051 self.entrada.as_ref() field access must borrow \
24052 the same backing storage — the accessor is the \
24053 substrate-primitive typed dispatch every \
24054 downstream external-gateway composite consumer \
24055 must route through, and a reference-identity \
24056 split would silently break every consumer that \
24057 relied on the borrow sharing the composite's \
24058 storage",
24059 ),
24060 (None, None) => {}
24061 _ => panic!(
24062 "AplicacaoSpec::entrada presence bit must byte-\
24063 equal self.entrada.is_some() — a presence-bit \
24064 drift would silently split the paired `validate` \
24065 per-`:entrada` shape-and-membership gate's \
24066 traversal head from the peer \
24067 caixa-mesh gateway_routes early-return partition \
24068 from the peer `feira app graph` internal-only-\
24069 mesh partition",
24070 ),
24071 }
24072 assert_eq!(
24073 s.entrada().is_some(),
24074 s.entrada.is_some(),
24075 "AplicacaoSpec::entrada().is_some() must byte-equal \
24076 self.entrada.is_some() — a presence-bit drift would \
24077 silently split every downstream `Option<&Entrada>` \
24078 consumer's partition on the internal-only-mesh arm",
24079 );
24080 }
24081 }
24082
24083 #[test]
24084 fn validate_reads_through_lifted_entrada_accessor() {
24085 // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
24086 // per-`:entrada` shape-and-membership gate (`if let Some(e) =
24087 // self.entrada() { … }`, followed by the per-axis fan-out
24088 // `validate_entrada_para(&e.para)` /
24089 // `EntradaMemberMissing` membership lookup /
24090 // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
24091 // per-`e.paths` `validate_entrada_path` traversal) must key
24092 // off the lifted outer accessor, so any future rebrand on
24093 // the typed slot's outer-composite reader shape lands at
24094 // exactly one place. Pins the multi-axis coherence by
24095 // exercising each per-axis refusal end-to-end: (1) the
24096 // author-omitted `None` shape short-circuits past every
24097 // per-`:entrada` refusal (the internal-only mesh partition
24098 // the accessor's `None` arm names), (2) `EntradaMemberMissing`
24099 // fires on a well-shaped but phantom `:para` under the outer
24100 // accessor's reference projection, and (3) the canonical
24101 // `three_member_spec` `:entrada` fixture passes `validate`
24102 // under the outer accessor's reference projection.
24103 //
24104 // Peer of the sibling M3
24105 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24106 // (534dc21) multi-axis coherence pin on the per-`:politicas`
24107 // outer mesh-policy composite-reference axis and the sibling
24108 // M3
24109 // [`validate_placement_reads_through_lifted_placement_accessor`]
24110 // (9abb8f0) multi-axis coherence pin on the per-`:placement`
24111 // outer distribution-composite composite-reference axis —
24112 // extends the multi-consumer coherence discipline onto the
24113 // last unlifted outermost M3 mesh-slot type's per-Aplicacao
24114 // external-gateway composite-reference axis, the third and
24115 // final `&Composite`-return accessor on the outer
24116 // [`AplicacaoSpec`] type.
24117
24118 // (1) `None` :entrada — the internal-only-mesh partition
24119 // short-circuits past every per-`:entrada` refusal. The outer
24120 // accessor's reference projection reaches the fall-through
24121 // `Ok(())` on the `None` arm without any per-axis refusal
24122 // firing.
24123 let mut spec = three_member_spec();
24124 spec.entrada = None;
24125 assert!(
24126 spec.validate().is_ok(),
24127 "an author-omitted `:entrada` must pass `validate` — the \
24128 internal-only-mesh partition short-circuits past every \
24129 per-`:entrada` refusal under the outer accessor's \
24130 reference projection",
24131 );
24132 assert!(
24133 spec.entrada().is_none(),
24134 "the outer accessor's reference projection must name the \
24135 internal-only-mesh partition per the `None` fixture",
24136 );
24137
24138 // (2) `EntradaMemberMissing` refusal under the outer accessor's
24139 // reference projection: a well-shaped but phantom `:para` must
24140 // trip the membership-lookup refusal. The gate's second arm
24141 // reads `e.para` on the reference returned by the outer
24142 // accessor.
24143 let mut spec = three_member_spec();
24144 if let Some(e) = spec.entrada.as_mut() {
24145 e.para = "phantom".into();
24146 }
24147 assert_eq!(
24148 spec.validate().unwrap_err(),
24149 AplicacaoError::EntradaMemberMissing {
24150 para: "phantom".into(),
24151 },
24152 );
24153 match (spec.entrada(), spec.entrada.as_ref()) {
24154 (Some(a), Some(b)) => assert!(
24155 std::ptr::eq(a, b),
24156 "the `validate` per-`:entrada` gate's traversal head \
24157 must be the same backing composite the accessor's \
24158 reference projection borrows from",
24159 ),
24160 _ => panic!("fixture must carry Some(:entrada)"),
24161 }
24162
24163 // (3) Canonical `three_member_spec` `:entrada` fixture passes
24164 // `validate` — every per-axis arm reaches the fall-through
24165 // `Ok(())` without any per-axis refusal firing under the
24166 // outer accessor's reference projection.
24167 let spec = three_member_spec();
24168 assert!(
24169 spec.validate().is_ok(),
24170 "the canonical `:entrada` fixture must pass `validate` — \
24171 every per-axis arm short-circuits on valid input under \
24172 the outer accessor's reference projection",
24173 );
24174 assert!(
24175 spec.entrada().is_some(),
24176 "the outer accessor's reference projection must be the \
24177 canonical `:entrada` fixture's composite",
24178 );
24179 }
24180
24181 #[test]
24182 fn port_for_destination_reads_through_lifted_entrada_accessor() {
24183 // Peer coherence pin: the
24184 // [`AplicacaoSpec::port_for_destination`] per-destination
24185 // L4-port fallback resolver's composite-projection seed
24186 // (`self.entrada().filter(…).map_or(…)`) must key off the
24187 // lifted outer accessor. Pins the coherence by exercising
24188 // the resolver end-to-end: (1) the `None` `:entrada` shape
24189 // falls through to `DEFAULT_SERVICO_PORT` under the outer
24190 // accessor's reference projection, (2) a non-matching
24191 // destination falls through to `DEFAULT_SERVICO_PORT` under
24192 // the outer accessor's reference projection, and (3) the
24193 // matching destination resolves to the `:entrada :port`
24194 // value under the outer accessor's reference projection.
24195 //
24196 // Peer of the sibling
24197 // [`validate_reads_through_lifted_entrada_accessor`] multi-
24198 // consumer coherence pin on the same per-`:entrada` outer-
24199 // composite axis — extends the multi-consumer coherence
24200 // discipline onto the second per-`:entrada` production
24201 // consumer, the L4-port fallback resolver.
24202
24203 // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
24204 // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
24205 // arm under the outer accessor's reference projection.
24206 let mut spec = three_member_spec();
24207 spec.entrada = None;
24208 assert_eq!(
24209 spec.port_for_destination("cart"),
24210 DEFAULT_SERVICO_PORT,
24211 "the port-fallback resolver must fall through to \
24212 DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
24213 under the outer accessor's reference projection",
24214 );
24215
24216 // (2) Non-matching destination — the resolver's `filter(…)`
24217 // arm rejects a mismatched destination and falls through
24218 // to `DEFAULT_SERVICO_PORT` under the outer accessor's
24219 // reference projection.
24220 let mut spec = three_member_spec();
24221 if let Some(e) = spec.entrada.as_mut() {
24222 e.para = "cart".into();
24223 e.port = 9443;
24224 }
24225 assert_eq!(
24226 spec.port_for_destination("catalog"),
24227 DEFAULT_SERVICO_PORT,
24228 "the port-fallback resolver must fall through to \
24229 DEFAULT_SERVICO_PORT on a non-matching destination \
24230 under the outer accessor's reference projection",
24231 );
24232
24233 // (3) Matching destination — the resolver's `map_or(…)` arm
24234 // returns the `:entrada :port` value under the outer
24235 // accessor's reference projection.
24236 let mut spec = three_member_spec();
24237 if let Some(e) = spec.entrada.as_mut() {
24238 e.para = "cart".into();
24239 e.port = 9443;
24240 }
24241 assert_eq!(
24242 spec.port_for_destination("cart"),
24243 9443,
24244 "the port-fallback resolver must return the \
24245 `:entrada :port` value on a matching destination \
24246 under the outer accessor's reference projection",
24247 );
24248 }
24249
24250 #[test]
24251 fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
24252 // The canonical per-`:politicas` `:mtls-required` mTLS-
24253 // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
24254 // must return the `:politicas :mtls-required` typed bool
24255 // verbatim as an `Option<bool>`, byte-equal to the raw field
24256 // access across every value in the three-way accept-set —
24257 // `None` (cluster default applies), `Some(true)` (mTLS
24258 // handshake enforced — the sandboxing-by-default arm the
24259 // MeshPolicy's docstring names), `Some(false)` (handshake
24260 // skipped — the explicit debug-edge opt-out).
24261 //
24262 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
24263 // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
24264 // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
24265 // shape — first `Option<Copy-T>`-return accessor on the M3
24266 // mesh-slot family. Pins against a future silent detour that
24267 // re-derived the toggle from a peer axis (an accidental
24268 // `.circuit_breaker.is_some()` collapse that assumed mTLS on
24269 // whenever a breaker is set), a `None` → `Some(false)` cluster-
24270 // default projection (the canonical `Option<bool>` → `bool`
24271 // collapse footgun the surrounding `is_empty()` predicate
24272 // guards on the peer emptiness axis), or a `Some(true)` /
24273 // `Some(false)` variant swap that landed on one consumer
24274 // without the other.
24275 for required in [None, Some(true), Some(false)] {
24276 let p = MeshPolicy {
24277 mtls_required: required,
24278 ..MeshPolicy::default()
24279 };
24280 assert_eq!(
24281 p.mtls_required(),
24282 required,
24283 "MeshPolicy::mtls_required must return :politicas \
24284 :mtls-required verbatim (got {:?}, expected {required:?})",
24285 p.mtls_required(),
24286 );
24287 assert_eq!(
24288 p.mtls_required(),
24289 p.mtls_required,
24290 "MeshPolicy::mtls_required must byte-equal the raw \
24291 .mtls_required field access across every value in the \
24292 three-way accept-set",
24293 );
24294 }
24295 }
24296
24297 #[test]
24298 fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
24299 // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
24300 // arm must key off [`MeshPolicy::mtls_required`], not the raw
24301 // `.mtls_required` field access. Structurally: toggling ONLY
24302 // the `mtls_required` slot on an otherwise-default MeshPolicy
24303 // must flip `is_empty()` from `true` (all-`None`) to `false`
24304 // (one axis carries a value); the flip must be observed for
24305 // both `Some(true)` and `Some(false)` since the emptiness
24306 // semantic reads "any axis carries a value" — not "any axis
24307 // carries a truthy value" — the same non-collapsing shape the
24308 // sibling M2 [`crate::LimitsSpec::is_empty`] /
24309 // [`crate::BehaviorSpec::is_empty`] predicates carry on their
24310 // peer `Option<T>`-typed slot surfaces.
24311 //
24312 // Pins against a future silent detour that re-derived the
24313 // emptiness predicate off a peer axis (an accidental
24314 // `.rate_limit.is_none()`-only chain that dropped the
24315 // `mtls_required` arm entirely), a `mtls_required == Some(_)`
24316 // collapse to a truthy-only check (which would silently
24317 // classify `Some(false)` as empty), or an accessor-side
24318 // detour that no longer names the substrate-primitive typed
24319 // dispatch (an accidental `self.mtls_required.unwrap_or(false)
24320 // == false` fallback in the accessor that would silently
24321 // classify both `None` and `Some(false)` as the same value).
24322 //
24323 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
24324 // (7cd2a28) accessor-composition pin on the sibling optional-
24325 // scalar axis — same "the emptiness / shape-gate predicate
24326 // must route through the substrate-primitive typed dispatch"
24327 // discipline extended onto the peer per-`:politicas` emptiness
24328 // predicate.
24329 let empty = MeshPolicy::default();
24330 assert!(
24331 empty.is_empty(),
24332 "MeshPolicy::default() must be is_empty() — every axis \
24333 defaults to None",
24334 );
24335 for required in [Some(true), Some(false)] {
24336 let p = MeshPolicy {
24337 mtls_required: required,
24338 ..MeshPolicy::default()
24339 };
24340 assert!(
24341 !p.is_empty(),
24342 "MeshPolicy::is_empty must return false when \
24343 :mtls-required is {required:?} — the emptiness \
24344 predicate reads \"any axis carries a value\", not \
24345 \"any axis carries a truthy value\"",
24346 );
24347 assert_eq!(
24348 p.mtls_required().is_none(),
24349 p.is_empty(),
24350 "when :mtls-required is the only set axis, \
24351 is_empty() must equal mtls_required().is_none() — \
24352 the accessor and the emptiness predicate must \
24353 route through the same substrate-primitive typed \
24354 dispatch on the :mtls-required arm",
24355 );
24356 }
24357 }
24358
24359 #[test]
24360 fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
24361 // The by-copy pin: [`MeshPolicy::mtls_required`] returns
24362 // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
24363 // accessor must return by value, not by reference. Peer of the
24364 // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
24365 // borrow-invariant pin on the sibling `Option<String>` slot,
24366 // but extended onto the peer `Option<bool>` copy-invariant
24367 // shape — the accessor's returned `Option<bool>` must outlive
24368 // `&self` (multiple calls must return equal values from a
24369 // dropped-`&self` copy, since the returned Option carries no
24370 // borrow), and calling the accessor twice on the same
24371 // MeshPolicy must yield the same `Option<bool>` verbatim
24372 // (idempotent, no side effects on `&self`).
24373 //
24374 // Pins against a future silent detour that returned
24375 // `Option<&bool>` (which would type-check but silently break
24376 // every downstream caller — [`single_field_overlay`]'s first
24377 // parameter is `Option<T: Clone>`, and `&bool` would fold to a
24378 // detached copy at the call site), an accidental
24379 // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
24380 // would also type-check but return `Option<&bool>`), or a
24381 // one-arm-only accessor that reads `Some(*b)` in the Some arm
24382 // but reads a fresh Default::default() in the None arm.
24383 for required in [None, Some(true), Some(false)] {
24384 let p = MeshPolicy {
24385 mtls_required: required,
24386 ..MeshPolicy::default()
24387 };
24388 let first = p.mtls_required();
24389 let second = p.mtls_required();
24390 assert_eq!(
24391 first, second,
24392 "MeshPolicy::mtls_required must be idempotent — two \
24393 successive calls on the same &self must return the \
24394 same Option<bool>",
24395 );
24396 assert_eq!(
24397 first, required,
24398 "MeshPolicy::mtls_required must return :politicas \
24399 :mtls-required verbatim by copy — got {first:?}, \
24400 expected {required:?}",
24401 );
24402 }
24403 }
24404
24405 #[test]
24406 fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
24407 // The canonical per-`:politicas` `:retries` transient-failure-
24408 // retry-budget scalar pin: [`MeshPolicy::retries`] must return
24409 // the `:politicas :retries` typed `u32` verbatim as an
24410 // `Option<u32>`, byte-equal to the raw field access across every
24411 // representative value in the accept-set — `None` (cluster
24412 // default applies — typically "no retries beyond a single
24413 // dispatch attempt" the caixa-mesh `retry_overlay` builder
24414 // documents), `Some(1)` (the lower boundary of the
24415 // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
24416 // `AplicacaoSpec::validate_politicas` gate carves out on the
24417 // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
24418 // (the upper boundary the same gate carves out on the sibling
24419 // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
24420 // past-the-guard sentinel that pins the accessor doesn't perform
24421 // a silent bounds-collapse at the return path).
24422 //
24423 // Sibling of the peer per-`:politicas`
24424 // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
24425 // sibling `Option<Copy-T>` optional-scalar axis, extended to the
24426 // peer per-`:politicas` `Option<u32>` shape — second
24427 // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
24428 // Pins against a future silent detour that re-derived the retry
24429 // cap from a peer axis (an accidental `.circuit_breaker
24430 // .as_ref().map(|b| b.max_failures)` collapse that read the
24431 // breaker's max-failure count as a retry budget), a
24432 // `None → Some(0)` cluster-default projection (which would
24433 // silently re-introduce the `PolicyRetriesZero` refusal case at
24434 // the emit boundary), or a bounds-collapsing accessor that
24435 // clamped the return through `POLICY_RETRIES_MAX` (the
24436 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
24437 // must ship the raw slot verbatim so a validate-time gate
24438 // regression surfaces at the emit boundary rather than being
24439 // silently absorbed).
24440 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
24441 let p = MeshPolicy {
24442 retries,
24443 ..MeshPolicy::default()
24444 };
24445 assert_eq!(
24446 p.retries(),
24447 retries,
24448 "MeshPolicy::retries must return :politicas :retries \
24449 verbatim (got {:?}, expected {retries:?})",
24450 p.retries(),
24451 );
24452 assert_eq!(
24453 p.retries(),
24454 p.retries,
24455 "MeshPolicy::retries must byte-equal the raw .retries \
24456 field access across every value in the accept-set",
24457 );
24458 }
24459 }
24460
24461 #[test]
24462 fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
24463 // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
24464 // must key off [`MeshPolicy::retries`], not the raw `.retries`
24465 // field access. Structurally: toggling ONLY the `retries` slot
24466 // on an otherwise-default MeshPolicy must flip `is_empty()`
24467 // from `true` (all-`None`) to `false` (one axis carries a
24468 // value); the flip must be observed for every value in the
24469 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
24470 // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
24471 // the emptiness semantic reads "any axis carries a value" —
24472 // not "any axis carries a value the validate gate accepts" —
24473 // the same non-collapsing shape the peer M2
24474 // [`crate::LimitsSpec::is_empty`] /
24475 // [`crate::BehaviorSpec::is_empty`] predicates carry.
24476 //
24477 // Pins against a future silent detour that re-derived the
24478 // emptiness predicate off a peer axis (an accidental
24479 // `.rate_limit.is_none()`-only chain that dropped the
24480 // `retries` arm entirely), a `retries == Some(_)` collapse
24481 // that key-off a validate-gate-clamped bounds check (which
24482 // would silently classify a past-the-guard `Some(u32::MAX)`
24483 // as empty because it fails the `1..=POLICY_RETRIES_MAX`
24484 // check), or an accessor-side detour that no longer names the
24485 // substrate-primitive typed dispatch.
24486 //
24487 // Sibling of the peer per-`:politicas`
24488 // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
24489 // pin on the sibling `Option<Copy-T>` optional-scalar axis —
24490 // same "the emptiness predicate must route through the
24491 // substrate-primitive typed dispatch" discipline extended onto
24492 // the peer per-`:politicas` `Option<u32>` axis.
24493 let empty = MeshPolicy::default();
24494 assert!(
24495 empty.is_empty(),
24496 "MeshPolicy::default() must be is_empty() — every axis \
24497 defaults to None",
24498 );
24499 for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
24500 let p = MeshPolicy {
24501 retries,
24502 ..MeshPolicy::default()
24503 };
24504 assert!(
24505 !p.is_empty(),
24506 "MeshPolicy::is_empty must return false when \
24507 :retries is {retries:?} — the emptiness \
24508 predicate reads \"any axis carries a value\", not \
24509 \"any axis carries a value the validate gate \
24510 accepts\"",
24511 );
24512 assert_eq!(
24513 p.retries().is_none(),
24514 p.is_empty(),
24515 "when :retries is the only set axis, is_empty() \
24516 must equal retries().is_none() — the accessor and \
24517 the emptiness predicate must route through the same \
24518 substrate-primitive typed dispatch on the :retries \
24519 arm",
24520 );
24521 }
24522 }
24523
24524 #[test]
24525 fn mesh_policy_retries_projects_option_u32_by_copy() {
24526 // The by-copy pin: [`MeshPolicy::retries`] returns
24527 // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
24528 // accessor must return by value, not by reference. Sibling of
24529 // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
24530 // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
24531 // extended onto the sibling `Option<u32>` copy-invariant
24532 // shape — the accessor's returned `Option<u32>` must outlive
24533 // `&self` (multiple calls must return equal values from a
24534 // dropped-`&self` copy, since the returned Option carries no
24535 // borrow), and calling the accessor twice on the same
24536 // MeshPolicy must yield the same `Option<u32>` verbatim
24537 // (idempotent, no side effects on `&self`).
24538 //
24539 // Pins against a future silent detour that returned
24540 // `Option<&u32>` (which would type-check but silently break
24541 // every downstream caller — [`crate::render::single_field_overlay`]'s
24542 // first parameter is `Option<T: Clone>`, and `&u32` would
24543 // fold to a detached copy at the call site), an accidental
24544 // `Option::as_ref()` projection (`self.retries.as_ref()` would
24545 // also type-check but return `Option<&u32>`), or a one-arm-
24546 // only accessor that reads `Some(*n)` in the Some arm but
24547 // reads a fresh `Default::default()` (`0_u32`) in the None
24548 // arm.
24549 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
24550 let p = MeshPolicy {
24551 retries,
24552 ..MeshPolicy::default()
24553 };
24554 let first = p.retries();
24555 let second = p.retries();
24556 assert_eq!(
24557 first, second,
24558 "MeshPolicy::retries must be idempotent — two \
24559 successive calls on the same &self must return the \
24560 same Option<u32>",
24561 );
24562 assert_eq!(
24563 first, retries,
24564 "MeshPolicy::retries must return :politicas :retries \
24565 verbatim by copy — got {first:?}, expected {retries:?}",
24566 );
24567 }
24568 }
24569
24570 #[test]
24571 fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
24572 // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
24573 // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
24574 // return the `:politicas :timeout` typed [`Duration`] verbatim
24575 // as an `Option<Duration>`, byte-equal to the raw field access
24576 // across every representative value in the accept-set — `None`
24577 // (cluster default applies — typically the gateway class's
24578 // implementation-side per-request wall-clock cap the caixa-mesh
24579 // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
24580 // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
24581 // set the surrounding `AplicacaoSpec::validate_politicas` gate
24582 // carves out on the sibling `PolicyTimeoutZero` /
24583 // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
24584 // (the upper boundary the same gate carves out on the sibling
24585 // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
24586 // (a past-the-guard sentinel that pins the accessor doesn't
24587 // perform a silent bounds-collapse into `None` on the zero-
24588 // Duration arm — validate rejects zero but the accessor must
24589 // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
24590 // past-the-guard sentinel that pins the accessor doesn't
24591 // perform a silent bounds-collapse at the return path).
24592 //
24593 // Sibling of the peer per-`:politicas`
24594 // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
24595 // `Option<u32>` optional-scalar axis and the peer per-
24596 // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
24597 // pin on the sibling `Option<bool>` optional-scalar axis,
24598 // extended onto the peer per-`:politicas` `Option<Duration>`
24599 // shape — third `Option<Copy-T>`-return accessor on the M3
24600 // mesh-slot family. Pins against a future silent detour that
24601 // re-derived the per-call cap from a peer axis (an accidental
24602 // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
24603 // read the breaker's rolling-window duration as a per-call
24604 // deadline), a `None → Some(Duration::MAX)` cluster-default
24605 // projection (which would silently re-introduce the
24606 // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
24607 // blocking" arm at the emit boundary), or a bounds-collapsing
24608 // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
24609 // (the `AplicacaoSpec::validate` gate owns the bounds; the
24610 // accessor must ship the raw slot verbatim so a validate-time
24611 // gate regression surfaces at the emit boundary rather than
24612 // being silently absorbed).
24613 for timeout in [
24614 None,
24615 Some(Duration::from_millis(1)),
24616 Some(POLICY_TIMEOUT_MAX),
24617 Some(Duration::ZERO),
24618 Some(Duration::MAX),
24619 ] {
24620 let p = MeshPolicy {
24621 timeout,
24622 ..MeshPolicy::default()
24623 };
24624 assert_eq!(
24625 p.timeout(),
24626 timeout,
24627 "MeshPolicy::timeout must return :politicas :timeout \
24628 verbatim (got {:?}, expected {timeout:?})",
24629 p.timeout(),
24630 );
24631 assert_eq!(
24632 p.timeout(),
24633 p.timeout,
24634 "MeshPolicy::timeout must byte-equal the raw .timeout \
24635 field access across every value in the accept-set",
24636 );
24637 }
24638 }
24639
24640 #[test]
24641 fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
24642 // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
24643 // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
24644 // field access. Structurally: toggling ONLY the `timeout` slot
24645 // on an otherwise-default MeshPolicy must flip `is_empty()`
24646 // from `true` (all-`None`) to `false` (one axis carries a
24647 // value); the flip must be observed for every value in the
24648 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
24649 // gate accepts (`Some(Duration::from_millis(1))`,
24650 // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
24651 // reads "any axis carries a value" — not "any axis carries a
24652 // value the validate gate accepts" — the same non-collapsing
24653 // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
24654 // [`crate::BehaviorSpec::is_empty`] predicates carry.
24655 //
24656 // Pins against a future silent detour that re-derived the
24657 // emptiness predicate off a peer axis (an accidental
24658 // `.rate_limit.is_none()`-only chain that dropped the
24659 // `timeout` arm entirely), a `timeout == Some(_)` collapse
24660 // that key-off a validate-gate-clamped bounds check (which
24661 // would silently classify a past-the-guard `Some(Duration::MAX)`
24662 // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
24663 // check), or an accessor-side detour that no longer names the
24664 // substrate-primitive typed dispatch.
24665 //
24666 // Sibling of the peer per-`:politicas`
24667 // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
24668 // the sibling `Option<u32>` optional-scalar axis and the peer
24669 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
24670 // accessor-composition pin on the sibling `Option<bool>`
24671 // optional-scalar axis — same "the emptiness predicate must
24672 // route through the substrate-primitive typed dispatch"
24673 // discipline extended onto the peer per-`:politicas`
24674 // `Option<Duration>` axis.
24675 let empty = MeshPolicy::default();
24676 assert!(
24677 empty.is_empty(),
24678 "MeshPolicy::default() must be is_empty() — every axis \
24679 defaults to None",
24680 );
24681 for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
24682 let p = MeshPolicy {
24683 timeout,
24684 ..MeshPolicy::default()
24685 };
24686 assert!(
24687 !p.is_empty(),
24688 "MeshPolicy::is_empty must return false when \
24689 :timeout is {timeout:?} — the emptiness \
24690 predicate reads \"any axis carries a value\", not \
24691 \"any axis carries a value the validate gate \
24692 accepts\"",
24693 );
24694 assert_eq!(
24695 p.timeout().is_none(),
24696 p.is_empty(),
24697 "when :timeout is the only set axis, is_empty() \
24698 must equal timeout().is_none() — the accessor and \
24699 the emptiness predicate must route through the same \
24700 substrate-primitive typed dispatch on the :timeout \
24701 arm",
24702 );
24703 }
24704 }
24705
24706 #[test]
24707 fn mesh_policy_timeout_projects_option_duration_by_copy() {
24708 // The by-copy pin: [`MeshPolicy::timeout`] returns
24709 // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
24710 // and the accessor must return by value, not by reference.
24711 // Sibling of the peer per-`:politicas`
24712 // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
24713 // sibling `Option<u32>` optional-scalar axis and the peer
24714 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
24715 // by-copy pin on the sibling `Option<bool>` optional-scalar
24716 // axis, extended onto the peer per-`:politicas`
24717 // `Option<Duration>` copy-invariant shape — the accessor's
24718 // returned `Option<Duration>` must outlive `&self` (multiple
24719 // calls must return equal values from a dropped-`&self`
24720 // copy, since the returned Option carries no borrow), and
24721 // calling the accessor twice on the same MeshPolicy must
24722 // yield the same `Option<Duration>` verbatim (idempotent, no
24723 // side effects on `&self`).
24724 //
24725 // Pins against a future silent detour that returned
24726 // `Option<&Duration>` (which would type-check but silently
24727 // break every downstream caller — [`crate::render::single_field_overlay`]'s
24728 // first parameter is `Option<T: Clone>`, and `&Duration`
24729 // would fold to a detached copy at the call site), an
24730 // accidental `Option::as_ref()` projection
24731 // (`self.timeout.as_ref()` would also type-check but return
24732 // `Option<&Duration>`), or a one-arm-only accessor that
24733 // reads `Some(*d)` in the Some arm but reads a fresh
24734 // `Default::default()` (`Duration::ZERO`) in the None arm
24735 // (which would silently re-classify every unset `:timeout`
24736 // as the `PolicyTimeoutZero`-refused zero-Duration value at
24737 // the accessor boundary).
24738 for timeout in [
24739 None,
24740 Some(Duration::from_millis(1)),
24741 Some(POLICY_TIMEOUT_MAX),
24742 Some(Duration::ZERO),
24743 Some(Duration::MAX),
24744 ] {
24745 let p = MeshPolicy {
24746 timeout,
24747 ..MeshPolicy::default()
24748 };
24749 let first = p.timeout();
24750 let second = p.timeout();
24751 assert_eq!(
24752 first, second,
24753 "MeshPolicy::timeout must be idempotent — two \
24754 successive calls on the same &self must return the \
24755 same Option<Duration>",
24756 );
24757 assert_eq!(
24758 first, timeout,
24759 "MeshPolicy::timeout must return :politicas :timeout \
24760 verbatim by copy — got {first:?}, expected {timeout:?}",
24761 );
24762 }
24763 }
24764
24765 #[test]
24766 fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
24767 // The canonical per-`:politicas` `:rate-limit` Envoy-
24768 // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
24769 // [`MeshPolicy::rate_limit`] must return the `:politicas
24770 // :rate-limit` typed [`RateLimit`] verbatim as an
24771 // `Option<RateLimit>`, byte-equal to the raw field access
24772 // across every representative value in the accept-set — `None`
24773 // (cluster default applies — no per-Aplicacao rate declaration,
24774 // the gateway-class per-listener default arm the future caixa-
24775 // mesh `local_rate_limit_overlay` emitter documents),
24776 // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
24777 // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
24778 // accept-set the surrounding
24779 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
24780 // sibling `PolicyRateLimitZero` refusal, paired with the
24781 // canonical-window "1 second" arm of the three-unit
24782 // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
24783 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
24784 // (the upper boundary the same gate carves out on the sibling
24785 // `PolicyRateLimitExceedsCap` refusal, paired with the
24786 // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
24787 // (a past-the-guard sentinel that pins the accessor doesn't
24788 // perform a silent bounds-collapse into `None` on the
24789 // zero-rate/zero-window arm — validate rejects zero but the
24790 // accessor must ship the raw slot verbatim so a validate-time
24791 // gate regression surfaces at the emit boundary rather than
24792 // being silently absorbed), and
24793 // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
24794 // (a past-the-guard sentinel that pins the accessor doesn't
24795 // perform a silent bounds-collapse at the return path).
24796 //
24797 // First `Option<Copy-composite-T>`-return accessor pin on the
24798 // M3 mesh-slot family (peer of the sibling per-`:politicas`
24799 // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
24800 // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
24801 // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
24802 // Copy accessor pins, extended onto the peer per-`:politicas`
24803 // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
24804 // and the accessor returns by value). Pins against a future
24805 // silent detour that re-derived the rate declaration from a
24806 // peer axis (an accidental
24807 // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
24808 // collapse that read the breaker's trip threshold + rolling
24809 // window as a rate declaration), a `None → Some(default())`
24810 // cluster-default projection (which would silently re-
24811 // introduce a "cluster default is 0/s" arm the emit boundary
24812 // would take as "declared but inert" — the canonical
24813 // declared-but-inert footgun the sibling
24814 // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
24815 // amplification-shape axis), a bounds-collapsing accessor
24816 // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
24817 // clamped `rl.window` through [`is_canonical_rate_limit_window`]
24818 // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
24819 // accessor must ship the raw slot verbatim), or a
24820 // by-reference detour (`Option<&RateLimit>`) that broke every
24821 // downstream consumer keying off `Option<RateLimit>` by-copy.
24822 for rl in [
24823 None,
24824 Some(RateLimit {
24825 rate: 1,
24826 window: Duration::from_secs(1),
24827 }),
24828 Some(RateLimit {
24829 rate: POLICY_RATE_LIMIT_MAX,
24830 window: Duration::from_secs(3600),
24831 }),
24832 Some(RateLimit {
24833 rate: 0,
24834 window: Duration::ZERO,
24835 }),
24836 Some(RateLimit {
24837 rate: u32::MAX,
24838 window: Duration::MAX,
24839 }),
24840 ] {
24841 let p = MeshPolicy {
24842 rate_limit: rl,
24843 ..MeshPolicy::default()
24844 };
24845 assert_eq!(
24846 p.rate_limit(),
24847 rl,
24848 "MeshPolicy::rate_limit must return :politicas :rate-limit \
24849 verbatim (got {:?}, expected {rl:?})",
24850 p.rate_limit(),
24851 );
24852 assert_eq!(
24853 p.rate_limit(),
24854 p.rate_limit,
24855 "MeshPolicy::rate_limit must byte-equal the raw \
24856 .rate_limit field access across every value in the \
24857 accept-set",
24858 );
24859 }
24860 }
24861
24862 #[test]
24863 fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
24864 // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
24865 // must key off [`MeshPolicy::rate_limit`], not the raw
24866 // `.rate_limit` field access. Structurally: toggling ONLY the
24867 // `rate_limit` slot on an otherwise-default MeshPolicy must
24868 // flip `is_empty()` from `true` (all-`None`) to `false` (one
24869 // axis carries a value); the flip must be observed for every
24870 // representative value in the accept-set the surrounding
24871 // [`AplicacaoSpec::validate_politicas`] gate accepts
24872 // (`Some(RateLimit { rate: 1, window: 1s })`,
24873 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
24874 // since the emptiness semantic reads "any axis carries a
24875 // value" — not "any axis carries a value the validate gate
24876 // accepts" — the same non-collapsing shape the peer M2
24877 // [`crate::LimitsSpec::is_empty`] /
24878 // [`crate::BehaviorSpec::is_empty`] predicates carry.
24879 //
24880 // Pins against a future silent detour that re-derived the
24881 // emptiness predicate off a peer axis (an accidental
24882 // `.timeout.is_none()`-only chain that dropped the
24883 // `rate_limit` arm entirely — the last unlifted inline field
24884 // access on `is_empty` before this lift), a `rate_limit ==
24885 // Some(_)` collapse that key-off a validate-gate-clamped
24886 // bounds check (which would silently classify a past-the-
24887 // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
24888 // because it fails the value-shape gate), or an accessor-
24889 // side detour that no longer names the substrate-primitive
24890 // typed dispatch.
24891 //
24892 // Fourth "the emptiness predicate must route through the
24893 // substrate-primitive typed dispatch" composition pin on the
24894 // M3 mesh-slot family — closes the last unlifted composition
24895 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
24896 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
24897 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
24898 // 7073d0f is_empty-composition pins on the sibling primitive-
24899 // Copy axes, extended onto the peer per-`:politicas`
24900 // composite-Copy `Option<RateLimit>` axis).
24901 let empty = MeshPolicy::default();
24902 assert!(
24903 empty.is_empty(),
24904 "MeshPolicy::default() must be is_empty() — every axis \
24905 defaults to None",
24906 );
24907 for rl in [
24908 RateLimit {
24909 rate: 1,
24910 window: Duration::from_secs(1),
24911 },
24912 RateLimit {
24913 rate: POLICY_RATE_LIMIT_MAX,
24914 window: Duration::from_secs(3600),
24915 },
24916 ] {
24917 let p = MeshPolicy {
24918 rate_limit: Some(rl),
24919 ..MeshPolicy::default()
24920 };
24921 assert!(
24922 !p.is_empty(),
24923 "MeshPolicy::is_empty must return false when \
24924 :rate-limit is {rl:?} — the emptiness predicate \
24925 reads \"any axis carries a value\", not \"any axis \
24926 carries a value the validate gate accepts\"",
24927 );
24928 assert_eq!(
24929 p.rate_limit().is_none(),
24930 p.is_empty(),
24931 "when :rate-limit is the only set axis, is_empty() \
24932 must equal rate_limit().is_none() — the accessor \
24933 and the emptiness predicate must route through the \
24934 same substrate-primitive typed dispatch on the \
24935 :rate-limit arm",
24936 );
24937 }
24938 }
24939
24940 #[test]
24941 fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
24942 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24943 // `:rate-limit` value-shape gate must key off
24944 // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
24945 // field bind. Structurally: a `MeshPolicy` whose only set
24946 // axis is a `Some(RateLimit { rate: 0, .. })` must surface
24947 // the `PolicyRateLimitZero` refusal exactly, and the same
24948 // MeshPolicy with the rate at the canonical lower boundary
24949 // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
24950 // The pair jointly pins the accessor + validate-gate
24951 // composition: any future silent detour that had the accessor
24952 // omit the `Some(RateLimit { rate: 0, .. })` arm (a
24953 // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
24954 // silently absorb the `PolicyRateLimitZero` refusal at the
24955 // accessor boundary — the composition pin catches that at
24956 // caixa-core build time.
24957 //
24958 // Sibling of the peer [`validate_politicas`]
24959 // `:mtls-required` / `:retries` / `:timeout` composition pins
24960 // on the sibling primitive-Copy optional-scalar axes — same
24961 // "the validate / shape-gate predicate must route through the
24962 // substrate-primitive typed dispatch" discipline extended
24963 // onto the peer per-`:politicas` composite-Copy
24964 // `Option<RateLimit>` axis. Second composition-with-accessor
24965 // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
24966 // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
24967 let mut spec = three_member_spec();
24968 spec.politicas = MeshPolicy {
24969 rate_limit: Some(RateLimit {
24970 rate: 0,
24971 window: Duration::from_secs(1),
24972 }),
24973 ..MeshPolicy::default()
24974 };
24975 assert!(
24976 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
24977 "validate_politicas must reject rate == 0 with \
24978 PolicyRateLimitZero — the accessor and the validate gate \
24979 must route through the same substrate-primitive typed \
24980 dispatch on the :rate-limit zero-floor arm",
24981 );
24982 spec.politicas = MeshPolicy {
24983 rate_limit: Some(RateLimit {
24984 rate: 1,
24985 window: Duration::from_secs(1),
24986 }),
24987 ..MeshPolicy::default()
24988 };
24989 assert!(
24990 spec.validate().is_ok(),
24991 "validate_politicas must accept rate == 1 (the canonical \
24992 lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
24993 set) with a canonical 1s window",
24994 );
24995 }
24996
24997 #[test]
24998 fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
24999 // The canonical per-`:politicas` `:circuit-breaker` Envoy-
25000 // `outlier_detection`-mesh consecutive-failure-ejection scalar
25001 // pin: [`MeshPolicy::circuit_breaker`] must return the
25002 // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
25003 // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
25004 // raw field access across every representative value in the
25005 // accept-set — `None` (cluster default applies — no
25006 // per-Aplicacao breaker declaration, the gateway-class per-
25007 // listener default arm the future caixa-mesh
25008 // `outlier_detection_overlay` emitter documents),
25009 // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
25010 // (the lower boundary of the accept-set the surrounding
25011 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25012 // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
25013 // refusals),
25014 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
25015 // (the upper boundary the same gate carves out on the sibling
25016 // `PolicyBreakerMaxFailuresExceedsCap` /
25017 // `PolicyBreakerWindowExceedsCap` refusals),
25018 // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
25019 // (a past-the-guard sentinel that pins the accessor doesn't
25020 // perform a silent bounds-collapse into `None` on the
25021 // zero-failures/zero-window arm — validate rejects zero but
25022 // the accessor must ship the raw slot verbatim so a validate-
25023 // time gate regression surfaces at the emit boundary rather
25024 // than being silently absorbed), and
25025 // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
25026 // (a past-the-guard sentinel that pins the accessor doesn't
25027 // perform a silent bounds-collapse at the return path).
25028 //
25029 // Second `Option<Copy-composite-T>`-return accessor pin on the
25030 // M3 mesh-slot family (peer of the sibling per-`:politicas`
25031 // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
25032 // composite-Copy accessor pin, and of the sibling per-
25033 // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
25034 // [`MeshPolicy::retries`] bdfb399 /
25035 // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
25036 // accessor pins). Pins against a future silent detour that
25037 // re-derived the breaker declaration from a peer axis (an
25038 // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
25039 // collapse that read the rate-limit's bucket capacity + refill
25040 // period as a breaker declaration), a `None → Some(default())`
25041 // cluster-default projection (which would silently re-
25042 // introduce the `PolicyBreakerZeroFailures` /
25043 // `PolicyBreakerZeroWindow` refusal cases at the emit
25044 // boundary), a bounds-collapsing accessor that clamped
25045 // `cb.max_failures` through
25046 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
25047 // through [`POLICY_BREAKER_WINDOW_MAX`] (the
25048 // [`AplicacaoSpec::validate`] gate owns the bounds; the
25049 // accessor must ship the raw slot verbatim), or a
25050 // by-reference detour (`Option<&CircuitBreaker>`) that broke
25051 // every downstream consumer keying off `Option<CircuitBreaker>`
25052 // by-copy.
25053 for cb in [
25054 None,
25055 Some(CircuitBreaker {
25056 max_failures: 1,
25057 window: Duration::from_millis(1),
25058 }),
25059 Some(CircuitBreaker {
25060 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25061 window: POLICY_BREAKER_WINDOW_MAX,
25062 }),
25063 Some(CircuitBreaker {
25064 max_failures: 0,
25065 window: Duration::ZERO,
25066 }),
25067 Some(CircuitBreaker {
25068 max_failures: u32::MAX,
25069 window: Duration::MAX,
25070 }),
25071 ] {
25072 let p = MeshPolicy {
25073 circuit_breaker: cb,
25074 ..MeshPolicy::default()
25075 };
25076 assert_eq!(
25077 p.circuit_breaker(),
25078 cb,
25079 "MeshPolicy::circuit_breaker must return :politicas \
25080 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
25081 p.circuit_breaker(),
25082 );
25083 assert_eq!(
25084 p.circuit_breaker(),
25085 p.circuit_breaker,
25086 "MeshPolicy::circuit_breaker must byte-equal the raw \
25087 .circuit_breaker field access across every value in \
25088 the accept-set",
25089 );
25090 }
25091 }
25092
25093 #[test]
25094 fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
25095 // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
25096 // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
25097 // `.circuit_breaker` field access. Structurally: toggling ONLY
25098 // the `circuit_breaker` slot on an otherwise-default MeshPolicy
25099 // must flip `is_empty()` from `true` (all-`None`) to `false`
25100 // (one axis carries a value); the flip must be observed for
25101 // every representative value in the accept-set the surrounding
25102 // [`AplicacaoSpec::validate_politicas`] gate accepts
25103 // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
25104 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
25105 // since the emptiness semantic reads "any axis carries a
25106 // value" — not "any axis carries a value the validate gate
25107 // accepts" — the same non-collapsing shape the peer M2
25108 // [`crate::LimitsSpec::is_empty`] /
25109 // [`crate::BehaviorSpec::is_empty`] predicates carry.
25110 //
25111 // Pins against a future silent detour that re-derived the
25112 // emptiness predicate off a peer axis (an accidental
25113 // `.rate_limit.is_none()`-only chain that dropped the
25114 // `circuit_breaker` arm entirely — the last unlifted inline
25115 // field access on `is_empty` before this lift), a
25116 // `circuit_breaker == Some(_)` collapse that key-off a
25117 // validate-gate-clamped bounds check (which would silently
25118 // classify a past-the-guard `Some(CircuitBreaker { max_failures:
25119 // 0, window: 0s })` as empty because it fails the value-shape
25120 // gate), or an accessor-side detour that no longer names the
25121 // substrate-primitive typed dispatch.
25122 //
25123 // Fifth "the emptiness predicate must route through the
25124 // substrate-primitive typed dispatch" composition pin on the
25125 // M3 mesh-slot family — closes the last unlifted composition
25126 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25127 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25128 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25129 // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
25130 // composition pins on the sibling primitive-Copy + composite-
25131 // Copy axes, extended onto the peer per-`:politicas`
25132 // composite-Copy `Option<CircuitBreaker>` axis).
25133 let empty = MeshPolicy::default();
25134 assert!(
25135 empty.is_empty(),
25136 "MeshPolicy::default() must be is_empty() — every axis \
25137 defaults to None",
25138 );
25139 for cb in [
25140 CircuitBreaker {
25141 max_failures: 1,
25142 window: Duration::from_millis(1),
25143 },
25144 CircuitBreaker {
25145 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25146 window: POLICY_BREAKER_WINDOW_MAX,
25147 },
25148 ] {
25149 let p = MeshPolicy {
25150 circuit_breaker: Some(cb),
25151 ..MeshPolicy::default()
25152 };
25153 assert!(
25154 !p.is_empty(),
25155 "MeshPolicy::is_empty must return false when \
25156 :circuit-breaker is {cb:?} — the emptiness predicate \
25157 reads \"any axis carries a value\", not \"any axis \
25158 carries a value the validate gate accepts\"",
25159 );
25160 assert_eq!(
25161 p.circuit_breaker().is_none(),
25162 p.is_empty(),
25163 "when :circuit-breaker is the only set axis, \
25164 is_empty() must equal circuit_breaker().is_none() — \
25165 the accessor and the emptiness predicate must route \
25166 through the same substrate-primitive typed dispatch \
25167 on the :circuit-breaker arm",
25168 );
25169 }
25170 }
25171
25172 #[test]
25173 fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
25174 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25175 // `:circuit-breaker` value-shape gate must key off
25176 // [`MeshPolicy::circuit_breaker`], not the raw
25177 // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
25178 // whose only set axis is a `Some(CircuitBreaker { max_failures:
25179 // 0, .. })` must surface the `PolicyBreakerZeroFailures`
25180 // refusal exactly, and the same MeshPolicy with the breaker at
25181 // the canonical lower boundary
25182 // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
25183 // pass validate. The pair jointly pins the accessor +
25184 // validate-gate composition: any future silent detour that had
25185 // the accessor omit the `Some(CircuitBreaker { max_failures:
25186 // 0, .. })` arm (a
25187 // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
25188 // collapse) would silently absorb the
25189 // `PolicyBreakerZeroFailures` refusal at the accessor
25190 // boundary — the composition pin catches that at caixa-core
25191 // build time.
25192 //
25193 // Sibling of the peer [`validate_politicas`]
25194 // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
25195 // composition pins on the sibling primitive-Copy + composite-
25196 // Copy optional-scalar axes — same "the validate / shape-gate
25197 // predicate must route through the substrate-primitive typed
25198 // dispatch" discipline extended onto the peer per-`:politicas`
25199 // composite-Copy `Option<CircuitBreaker>` axis. Second
25200 // composition-with-accessor pin on the M3 mesh-slot
25201 // `Option<CircuitBreaker>` arm alongside the
25202 // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
25203 let mut spec = three_member_spec();
25204 spec.politicas = MeshPolicy {
25205 circuit_breaker: Some(CircuitBreaker {
25206 max_failures: 0,
25207 window: Duration::from_millis(1),
25208 }),
25209 ..MeshPolicy::default()
25210 };
25211 assert!(
25212 matches!(
25213 spec.validate(),
25214 Err(AplicacaoError::PolicyBreakerZeroFailures)
25215 ),
25216 "validate_politicas must reject max_failures == 0 with \
25217 PolicyBreakerZeroFailures — the accessor and the validate \
25218 gate must route through the same substrate-primitive \
25219 typed dispatch on the :circuit-breaker zero-floor arm",
25220 );
25221 spec.politicas = MeshPolicy {
25222 circuit_breaker: Some(CircuitBreaker {
25223 max_failures: 1,
25224 window: Duration::from_millis(1),
25225 }),
25226 ..MeshPolicy::default()
25227 };
25228 assert!(
25229 spec.validate().is_ok(),
25230 "validate_politicas must accept a CircuitBreaker at the \
25231 canonical lower boundary (max_failures = 1, window = \
25232 1ms) — the accessor and the validate gate must route \
25233 through the same substrate-primitive typed dispatch on \
25234 the :circuit-breaker arm",
25235 );
25236 }
25237
25238 #[test]
25239 fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
25240 // The canonical per-`:politicas :circuit-breaker` `:max-failures`
25241 // Envoy-outlier-detection trip-threshold scalar pin:
25242 // [`CircuitBreaker::max_failures`] must return the
25243 // `:politicas :circuit-breaker :max-failures` typed `u32`
25244 // verbatim, byte-equal to the raw field access across every
25245 // representative value in the accept-set — `1` (the lower
25246 // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
25247 // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
25248 // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
25249 // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
25250 // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
25251 // refusal), `0` (a past-the-guard sentinel that pins the accessor
25252 // doesn't perform a silent bounds-collapse into `1` on the zero
25253 // arm — validate rejects zero but the accessor must ship the
25254 // raw slot verbatim so a validate-time gate regression surfaces
25255 // at the emit boundary rather than being silently absorbed),
25256 // `u32::MAX` (a past-the-guard sentinel that pins the accessor
25257 // doesn't perform a silent bounds-collapse through
25258 // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
25259 //
25260 // First sub-struct required-scalar accessor pin on the M3
25261 // mesh-slot family — sibling in shape to the peer per-`:membros`
25262 // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
25263 // (a40b0e3) required-`String`-carry accessor pins and the peer
25264 // per-`:contratos` [`WitContract::source`] /
25265 // [`WitContract::destination`] (7f0fd43) required-`String`-carry
25266 // accessor pins, extended onto the peer per-`CircuitBreaker`
25267 // required-`u32` scalar-value axis. Pins against a future silent
25268 // detour that re-derived the trip threshold from a peer axis (an
25269 // accidental `self.window.as_secs() as u32` collapse that read
25270 // the breaker's rolling-window duration as a failure count), a
25271 // `0 → 1` cluster-default projection (which would silently absorb
25272 // the `PolicyBreakerZeroFailures` refusal case at the accessor
25273 // boundary), or a bounds-collapsing accessor that clamped the
25274 // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
25275 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25276 // must ship the raw slot verbatim).
25277 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
25278 let cb = CircuitBreaker {
25279 max_failures,
25280 window: Duration::from_secs(60),
25281 };
25282 assert_eq!(
25283 cb.max_failures(),
25284 max_failures,
25285 "CircuitBreaker::max_failures must return :politicas \
25286 :circuit-breaker :max-failures verbatim (got {}, \
25287 expected {max_failures})",
25288 cb.max_failures(),
25289 );
25290 assert_eq!(
25291 cb.max_failures(),
25292 cb.max_failures,
25293 "CircuitBreaker::max_failures must byte-equal the raw \
25294 .max_failures field access across every value in the \
25295 u32 accept-set",
25296 );
25297 }
25298 }
25299
25300 #[test]
25301 fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
25302 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25303 // `:circuit-breaker :max-failures` zero-floor arm must key off
25304 // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
25305 // field access. Structurally: a `CircuitBreaker { max_failures:
25306 // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
25307 // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
25308 // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
25309 // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
25310 // pass validate. The pair jointly pins the accessor +
25311 // validate-gate composition: any future silent detour that had
25312 // the accessor return a fresh `1` on the zero arm (a
25313 // `.max_failures().max(1)` collapse) would silently absorb the
25314 // `PolicyBreakerZeroFailures` refusal at the accessor boundary
25315 // and the validate gate would accept a struct-literal
25316 // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
25317 // catches that at caixa-core build time.
25318 //
25319 // Peer of the sibling per-`:politicas`
25320 // [`MeshPolicy::mtls_required`] (c0110f1) /
25321 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
25322 // (7073d0f) accessor-composition pins on the sibling optional-
25323 // scalar axes — same "the validate / shape-gate predicate must
25324 // route through the substrate-primitive typed dispatch"
25325 // discipline extended onto the peer per-`CircuitBreaker`
25326 // required-scalar composition axis.
25327 let mut spec = three_member_spec();
25328 spec.politicas = MeshPolicy {
25329 circuit_breaker: Some(CircuitBreaker {
25330 max_failures: 0,
25331 window: Duration::from_secs(60),
25332 }),
25333 ..MeshPolicy::default()
25334 };
25335 assert!(
25336 matches!(
25337 spec.validate(),
25338 Err(AplicacaoError::PolicyBreakerZeroFailures)
25339 ),
25340 "validate_politicas must reject max_failures == 0 with \
25341 PolicyBreakerZeroFailures — the accessor and the validate \
25342 gate must route through the same substrate-primitive typed \
25343 dispatch on the :max-failures zero-floor arm",
25344 );
25345 spec.politicas = MeshPolicy {
25346 circuit_breaker: Some(CircuitBreaker {
25347 max_failures: 1,
25348 window: Duration::from_secs(60),
25349 }),
25350 ..MeshPolicy::default()
25351 };
25352 assert!(
25353 spec.validate().is_ok(),
25354 "validate_politicas must accept max_failures == 1 (the \
25355 lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
25356 accept-set)",
25357 );
25358 }
25359
25360 #[test]
25361 fn circuit_breaker_max_failures_projects_u32_by_copy() {
25362 // The by-copy pin: [`CircuitBreaker::max_failures`] returns
25363 // `u32` by copy — `u32` is `Copy` and the accessor must return
25364 // by value, not by reference. Peer of the sibling
25365 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
25366 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
25367 // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
25368 // optional-scalar axes, extended onto the peer
25369 // per-`CircuitBreaker` required-`u32` copy-invariant shape —
25370 // the accessor's returned `u32` must outlive `&self` (multiple
25371 // calls must return equal values from a dropped-`&self` copy,
25372 // since the returned scalar carries no borrow), and calling
25373 // the accessor twice on the same CircuitBreaker must yield the
25374 // same `u32` verbatim (idempotent, no side effects on `&self`).
25375 //
25376 // Pins against a future silent detour that returned `&u32`
25377 // (which would type-check but silently break every downstream
25378 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
25379 // first parameter is `u32`, and `&u32` would fold to a detached
25380 // copy at the call site with a `*` deref the sibling accessors
25381 // don't need), an accidental `.max_failures.wrapping_add(0)`
25382 // detour that returned a fresh copy through an arithmetic
25383 // no-op (breaking a future `const fn` regression), or a
25384 // one-arm-only accessor that returned a saturating value on
25385 // some sentinel input (breaking the pass-through invariant the
25386 // sibling required-scalar accessors carry).
25387 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
25388 let cb = CircuitBreaker {
25389 max_failures,
25390 window: Duration::from_secs(60),
25391 };
25392 let first = cb.max_failures();
25393 let second = cb.max_failures();
25394 assert_eq!(
25395 first, second,
25396 "CircuitBreaker::max_failures must be idempotent — two \
25397 successive calls on the same &self must return the \
25398 same u32",
25399 );
25400 assert_eq!(
25401 first, max_failures,
25402 "CircuitBreaker::max_failures must return :politicas \
25403 :circuit-breaker :max-failures verbatim by copy — \
25404 got {first}, expected {max_failures}",
25405 );
25406 }
25407 }
25408
25409 #[test]
25410 fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
25411 // The canonical per-`:politicas :circuit-breaker` `:window`
25412 // Envoy-outlier-detection rolling-observation-interval scalar
25413 // pin: [`CircuitBreaker::window`] must return the
25414 // `:politicas :circuit-breaker :window` typed `Duration`
25415 // verbatim, byte-equal to the raw field access across every
25416 // representative value in the accept-set — `Duration::from_millis(1)`
25417 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
25418 // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
25419 // gate carves out on the sibling `PolicyBreakerZeroWindow`
25420 // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
25421 // same gate carves out on the sibling
25422 // `PolicyBreakerWindowExceedsCap` refusal),
25423 // `Duration::ZERO` (a past-the-guard sentinel that pins the
25424 // accessor doesn't perform a silent bounds-collapse into
25425 // `Duration::from_millis(1)` on the zero arm — validate rejects
25426 // zero but the accessor must ship the raw slot verbatim so a
25427 // validate-time gate regression surfaces at the emit boundary
25428 // rather than being silently absorbed),
25429 // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
25430 // far above the 1h cap — that pins the accessor doesn't perform
25431 // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
25432 // at the return path).
25433 //
25434 // Second sub-struct required-scalar accessor pin on the M3
25435 // mesh-slot family — sibling in shape to the just-landed
25436 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
25437 // (3a74062) required-`u32` accessor pin on the peer
25438 // per-`CircuitBreaker` required-axis, extended onto the
25439 // per-sub-struct required-`Duration` axis. Pins against a
25440 // future silent detour that re-derived the observation window
25441 // from a peer axis (an accidental
25442 // `Duration::from_secs(self.max_failures as u64)` collapse that
25443 // read the breaker's trip count as an observation-interval
25444 // duration), a `Duration::ZERO → Duration::from_millis(1)`
25445 // cluster-default projection (which would silently absorb the
25446 // `PolicyBreakerZeroWindow` refusal case at the accessor
25447 // boundary), or a bounds-collapsing accessor that clamped the
25448 // return through `POLICY_BREAKER_WINDOW_MAX` (the
25449 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25450 // must ship the raw slot verbatim).
25451 for window in [
25452 Duration::from_millis(1),
25453 POLICY_BREAKER_WINDOW_MAX,
25454 Duration::ZERO,
25455 Duration::from_secs(86_400),
25456 ] {
25457 let cb = CircuitBreaker {
25458 max_failures: 5,
25459 window,
25460 };
25461 assert_eq!(
25462 cb.window(),
25463 window,
25464 "CircuitBreaker::window must return :politicas \
25465 :circuit-breaker :window verbatim (got {:?}, \
25466 expected {window:?})",
25467 cb.window(),
25468 );
25469 assert_eq!(
25470 cb.window(),
25471 cb.window,
25472 "CircuitBreaker::window must byte-equal the raw \
25473 .window field access across every value in the \
25474 Duration accept-set",
25475 );
25476 }
25477 }
25478
25479 #[test]
25480 fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
25481 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25482 // `:circuit-breaker :window` zero-floor arm must key off
25483 // [`CircuitBreaker::window`], not the raw `.window` field
25484 // access. Structurally: a `CircuitBreaker { window:
25485 // Duration::ZERO, .. }` embedded in a
25486 // `:politicas :circuit-breaker` slot must surface the
25487 // `PolicyBreakerZeroWindow` refusal exactly, and a
25488 // `CircuitBreaker { window: Duration::from_millis(1), .. }`
25489 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
25490 // accept-set) must pass validate. The pair jointly pins the
25491 // accessor + validate-gate composition: any future silent
25492 // detour that had the accessor return a fresh
25493 // `Duration::from_millis(1)` on the zero arm (a
25494 // `.window().max(Duration::from_millis(1))` collapse) would
25495 // silently absorb the `PolicyBreakerZeroWindow` refusal at the
25496 // accessor boundary and the validate gate would accept a
25497 // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
25498 // — the composition pin catches that at caixa-core build time.
25499 //
25500 // Peer of the sibling per-`CircuitBreaker`
25501 // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
25502 // pin on the peer required-scalar `:max-failures` axis — same
25503 // "the validate / shape-gate predicate must route through the
25504 // substrate-primitive typed dispatch" discipline extended onto
25505 // the peer per-`CircuitBreaker` required-`Duration` composition
25506 // axis.
25507 let mut spec = three_member_spec();
25508 spec.politicas = MeshPolicy {
25509 circuit_breaker: Some(CircuitBreaker {
25510 max_failures: 5,
25511 window: Duration::ZERO,
25512 }),
25513 ..MeshPolicy::default()
25514 };
25515 assert!(
25516 matches!(
25517 spec.validate(),
25518 Err(AplicacaoError::PolicyBreakerZeroWindow)
25519 ),
25520 "validate_politicas must reject window == Duration::ZERO \
25521 with PolicyBreakerZeroWindow — the accessor and the \
25522 validate gate must route through the same substrate-\
25523 primitive typed dispatch on the :window zero-floor arm",
25524 );
25525 spec.politicas = MeshPolicy {
25526 circuit_breaker: Some(CircuitBreaker {
25527 max_failures: 5,
25528 window: Duration::from_millis(1),
25529 }),
25530 ..MeshPolicy::default()
25531 };
25532 assert!(
25533 spec.validate().is_ok(),
25534 "validate_politicas must accept window == \
25535 Duration::from_millis(1) (the lower boundary of the \
25536 1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
25537 );
25538 }
25539
25540 #[test]
25541 fn circuit_breaker_window_projects_duration_by_copy() {
25542 // The by-copy pin: [`CircuitBreaker::window`] returns
25543 // `Duration` by copy — `Duration` is `Copy` and the accessor
25544 // must return by value, not by reference. Peer of the sibling
25545 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
25546 // (3a74062) by-copy pin on the peer required-scalar
25547 // `:max-failures` axis, extended onto the peer
25548 // per-`CircuitBreaker` required-`Duration` copy-invariant shape
25549 // — the accessor's returned `Duration` must outlive `&self`
25550 // (multiple calls must return equal values from a
25551 // dropped-`&self` copy, since the returned scalar carries no
25552 // borrow), and calling the accessor twice on the same
25553 // CircuitBreaker must yield the same `Duration` verbatim
25554 // (idempotent, no side effects on `&self`).
25555 //
25556 // Pins against a future silent detour that returned
25557 // `&Duration` (which would type-check but silently break every
25558 // downstream `Duration`-by-value consumer —
25559 // [`crate::render::require_positive_canonical_bounded_duration`]'s
25560 // first parameter is `Duration`, and `&Duration` would fold to
25561 // a detached copy at the call site with a `*` deref the sibling
25562 // accessors don't need), an accidental `.window + Duration::ZERO`
25563 // detour that returned a fresh copy through an arithmetic
25564 // no-op (breaking a future `const fn` regression), or a
25565 // one-arm-only accessor that returned a saturating value on
25566 // some sentinel input (breaking the pass-through invariant the
25567 // sibling required-scalar accessors carry).
25568 for window in [
25569 Duration::from_millis(1),
25570 POLICY_BREAKER_WINDOW_MAX,
25571 Duration::ZERO,
25572 Duration::from_secs(86_400),
25573 ] {
25574 let cb = CircuitBreaker {
25575 max_failures: 5,
25576 window,
25577 };
25578 let first = cb.window();
25579 let second = cb.window();
25580 assert_eq!(
25581 first, second,
25582 "CircuitBreaker::window must be idempotent — two \
25583 successive calls on the same &self must return the \
25584 same Duration",
25585 );
25586 assert_eq!(
25587 first, window,
25588 "CircuitBreaker::window must return :politicas \
25589 :circuit-breaker :window verbatim by copy — \
25590 got {first:?}, expected {window:?}",
25591 );
25592 }
25593 }
25594
25595 #[test]
25596 fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
25597 // Apex-identity pair-invariant pin composing both substrate-
25598 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
25599 // and [`WitContract::destination`] — at the emit-side call shape
25600 // every per-`(:de, :para)` CNP L4 port reader now takes. The
25601 // invariant, evaluated per-edge:
25602 //
25603 // spec.port_for_destination(c.destination()) == expected_port
25604 //
25605 // where `expected_port` is `entrada.port` when
25606 // `c.destination() == entrada.destination()` and
25607 // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
25608 // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
25609 // pin on the per-`:entrada` axis — that pin encodes the apex
25610 // ingress L4 identity via `entrada.destination()`; this pin
25611 // encodes the per-edge L4 identity via `c.destination()`, and
25612 // both compose on the same substrate-primitive resolver so a
25613 // future refactor that silently split either accessor's apex
25614 // behavior surfaces at caixa-core build time.
25615 let mut spec = three_member_spec();
25616 if let Some(e) = spec.entrada.as_mut() {
25617 e.para = "cart".into();
25618 e.port = 8443;
25619 }
25620 let apex_contract = WitContract {
25621 de: "checkout".into(),
25622 para: "cart".into(),
25623 wit: "wasi:http/proxy".into(),
25624 endpoint: Some("/hello".into()),
25625 subject: None,
25626 slot: None,
25627 };
25628 assert_eq!(
25629 spec.port_for_destination(apex_contract.destination()),
25630 8443,
25631 "`spec.port_for_destination(c.destination())` must equal \
25632 `entrada.port` when the contract callee names the ingress \
25633 apex — the CNP per-edge L4 port and the HTTPRoute apex \
25634 backendRef port share this substrate-primitive resolver.",
25635 );
25636 let non_apex_contract = WitContract {
25637 de: "cart".into(),
25638 para: "payment".into(),
25639 wit: "wasi:http/proxy".into(),
25640 endpoint: Some("/charge".into()),
25641 subject: None,
25642 slot: None,
25643 };
25644 assert_eq!(
25645 spec.port_for_destination(non_apex_contract.destination()),
25646 DEFAULT_SERVICO_PORT,
25647 "`spec.port_for_destination(c.destination())` must fall back \
25648 to the substrate-canonical port floor when the contract \
25649 callee is not the ingress apex — the resolver's non-apex \
25650 arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
25651 );
25652 }
25653
25654 #[test]
25655 fn membro_key_consts_are_lower_camel_case_shape() {
25656 // Shape-pin: every `MEMBRO_KEY_*` const must be a
25657 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25658 // `kebab-case` hyphens, no leading colon, no `PascalCase`
25659 // leading capital, no whitespace / dots) — the canonical shape
25660 // the `#[serde(rename_all = "camelCase")]` derive produces on
25661 // [`Membro`]. A future flip to a non-camelCase attribute at
25662 // the derive surfaces both here (this test fails on the
25663 // stale-constant shape) and at
25664 // `membro_serde_keys_match_lifted_membro_key_consts` (that test
25665 // fails on the mismatch between const and derive). Peer with
25666 // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
25667 // on the sibling `SupervisorSpec` top-level axis.
25668 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
25669 assert!(
25670 !key.is_empty(),
25671 "MEMBRO_KEY_* must be non-empty (got {key:?})"
25672 );
25673 let first = key.chars().next().unwrap();
25674 assert!(
25675 first.is_ascii_lowercase(),
25676 "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
25677 (got {key:?}, leads with {first:?})",
25678 );
25679 assert!(
25680 key.chars().all(|c| c.is_ascii_alphanumeric()),
25681 "MEMBRO_KEY_* must be ASCII-alphanumeric only \
25682 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25683 );
25684 }
25685 }
25686
25687 // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
25688
25689 #[test]
25690 fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
25691 // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
25692 // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
25693 // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
25694 // keys the `#[serde(rename_all = "camelCase")]` attribute on
25695 // [`WitContract`] emits for the required-triad. The three
25696 // sibling payload-arm keys already pin under
25697 // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
25698 // `STORE_FIELD_NAME` — pin all six alongside so a future
25699 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
25700 // verbatim-field-name flip at the derive attribute (any of which
25701 // would silently break every downstream JSON consumer that
25702 // reaches for one of the six via `Value::get(...)`) surfaces
25703 // here as a build-time test failure at `aplicacao.rs`, not as an
25704 // apply-time `.get(<stale-canonical-const>)` returning `None`
25705 // far from the derive-attr drift's commit. Peer with the sibling
25706 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
25707 // pin on the M3 `:membros` per-entry axis — same discipline the
25708 // `Membro` per-entry lift established, extended here to the
25709 // sibling M3 `WitContract` per-`:contratos` entry axis, the last
25710 // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
25711 // axis on the Aplicacao surface without a lifted serde-key peer.
25712 let c = WitContract {
25713 de: "cart".into(),
25714 para: "catalog".into(),
25715 wit: "wasi:http/proxy".into(),
25716 endpoint: Some("/lookup".into()),
25717 subject: None,
25718 slot: None,
25719 };
25720 let json = serde_json::to_string(&c).unwrap();
25721 for key in [
25722 crate::CONTRATO_KEY_DE,
25723 crate::CONTRATO_KEY_PARA,
25724 crate::CONTRATO_KEY_WIT,
25725 WitTarget::HTTP_FIELD_NAME,
25726 ] {
25727 let quoted = format!("\"{key}\"");
25728 assert!(
25729 json.contains("ed),
25730 "serialized WitContract must carry the lifted \
25731 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
25732 {quoted} verbatim in the JSON emission (got: {json})",
25733 );
25734 }
25735
25736 // Pin the two remaining payload-arm keys by round-tripping a
25737 // `WitContract` under each payload-shape (pub-sub, store) — the
25738 // required-triad appears on every emission but the payload arms
25739 // only surface when their `Option<String>` field is `Some`.
25740 let pubsub = WitContract {
25741 de: "cart".into(),
25742 para: "events".into(),
25743 wit: "nats:pub-sub".into(),
25744 endpoint: None,
25745 subject: Some("orders.placed".into()),
25746 slot: None,
25747 };
25748 let pubsub_json = serde_json::to_string(&pubsub).unwrap();
25749 let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
25750 assert!(
25751 pubsub_json.contains(&pubsub_quoted),
25752 "serialized pub-sub WitContract must carry the lifted \
25753 WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
25754 verbatim in the JSON emission (got: {pubsub_json})",
25755 );
25756 let store = WitContract {
25757 de: "cart".into(),
25758 para: "sessions".into(),
25759 wit: "wasi:keyvalue/store".into(),
25760 endpoint: None,
25761 subject: None,
25762 slot: Some("cart/$id".into()),
25763 };
25764 let store_json = serde_json::to_string(&store).unwrap();
25765 let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
25766 assert!(
25767 store_json.contains(&store_quoted),
25768 "serialized store WitContract must carry the lifted \
25769 WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
25770 verbatim in the JSON emission (got: {store_json})",
25771 );
25772 }
25773
25774 #[test]
25775 fn contrato_key_consts_are_pairwise_distinct() {
25776 // Cross-axis drift-detection pin: a future collapse of the six
25777 // canonical [`WitContract`] per-entry byte-strings onto the same
25778 // value (e.g. an accidental copy-paste flip of
25779 // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
25780 // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
25781 // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
25782 // every downstream probe on one axis onto the sibling axis's
25783 // overlay entry and pass every propagation-probe test that
25784 // expected only the stale axis's value. Peer of the sibling
25785 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
25786 // widened here to the six-way axis the `WitContract`
25787 // required-triad + `WitTarget` payload-triad jointly cover.
25788 let all = [
25789 crate::CONTRATO_KEY_DE,
25790 crate::CONTRATO_KEY_PARA,
25791 crate::CONTRATO_KEY_WIT,
25792 WitTarget::HTTP_FIELD_NAME,
25793 WitTarget::PUBSUB_FIELD_NAME,
25794 WitTarget::STORE_FIELD_NAME,
25795 ];
25796 for (i, a) in all.iter().enumerate() {
25797 for b in all.iter().skip(i + 1) {
25798 assert_ne!(
25799 a, b,
25800 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
25801 must be pairwise-distinct canonical byte-sequences \
25802 — got `{a}` == `{b}`",
25803 );
25804 }
25805 }
25806 }
25807
25808 #[test]
25809 fn contrato_key_consts_are_lower_camel_case_shape() {
25810 // Shape-pin: every `CONTRATO_KEY_*` (and every peer
25811 // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
25812 // byte-sequence (no `snake_case` underscores, no `kebab-case`
25813 // hyphens, no leading colon, no `PascalCase` leading capital, no
25814 // whitespace / dots) — the canonical shape the
25815 // `#[serde(rename_all = "camelCase")]` derive produces on
25816 // [`WitContract`]. A future flip to a non-camelCase attribute at
25817 // the derive surfaces both here (this test fails on the
25818 // stale-constant shape) and at
25819 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25820 // (that test fails on the mismatch between const and derive).
25821 // Peer with `membro_key_consts_are_lower_camel_case_shape`
25822 // (ce80ca0) on the sibling `Membro` per-entry axis.
25823 for key in [
25824 crate::CONTRATO_KEY_DE,
25825 crate::CONTRATO_KEY_PARA,
25826 crate::CONTRATO_KEY_WIT,
25827 WitTarget::HTTP_FIELD_NAME,
25828 WitTarget::PUBSUB_FIELD_NAME,
25829 WitTarget::STORE_FIELD_NAME,
25830 ] {
25831 assert!(
25832 !key.is_empty(),
25833 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
25834 non-empty (got {key:?})"
25835 );
25836 let first = key.chars().next().unwrap();
25837 assert!(
25838 first.is_ascii_lowercase(),
25839 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
25840 with an ASCII-lowercase byte (got {key:?}, leads with \
25841 {first:?})",
25842 );
25843 assert!(
25844 key.chars().all(|c| c.is_ascii_alphanumeric()),
25845 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
25846 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
25847 whitespace (got {key:?})",
25848 );
25849 }
25850 }
25851
25852 // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
25853
25854 #[test]
25855 fn entrada_serde_keys_match_lifted_entrada_key_consts() {
25856 // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
25857 // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
25858 // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
25859 // name the exact camelCase JSON keys the
25860 // `#[serde(rename_all = "camelCase")]` attribute on
25861 // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
25862 // pin that each canonical byte-sequence appears verbatim in the
25863 // JSON — a future accidental `rename_all = "snake_case"` /
25864 // `"kebab-case"` / verbatim-field-name flip at the derive
25865 // attribute (any of which would silently break every downstream
25866 // JSON consumer that reaches for one of the four consts via
25867 // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
25868 // emitter's per-Aplicacao hostname/paths/port projection, the
25869 // future `app-operator` reconciler's per-Aplicacao ingress
25870 // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
25871 // materializer's admission-time cross-check) surfaces here as
25872 // a build-time test failure at `aplicacao.rs`, not as an
25873 // apply-time `.get(<stale-canonical-const>)` returning `None`
25874 // far from the derive-attr drift's commit. Peer with the
25875 // sibling
25876 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25877 // (ca463a4) and
25878 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
25879 // pins on the M3 collection-slot atom axes — same discipline
25880 // both collection-slot lifts established, extended here to the
25881 // singleton `:entrada` mesh-slot atom axis, the last M3
25882 // typed-struct top-level `#[serde(rename_all = "camelCase")]`
25883 // axis on the Aplicacao surface without a lifted serde-key
25884 // peer.
25885 let e = Entrada {
25886 host: "checkout.quero.cloud".into(),
25887 para: "cart".into(),
25888 paths: vec!["/cart".into()],
25889 port: 8080,
25890 };
25891 let json = serde_json::to_string(&e).unwrap();
25892 for key in [
25893 crate::ENTRADA_KEY_HOST,
25894 crate::ENTRADA_KEY_PARA,
25895 crate::ENTRADA_KEY_PATHS,
25896 crate::ENTRADA_KEY_PORT,
25897 ] {
25898 let quoted = format!("\"{key}\"");
25899 assert!(
25900 json.contains("ed),
25901 "serialized Entrada must carry the lifted ENTRADA_KEY_* \
25902 byte-sequence {quoted} verbatim in the JSON emission \
25903 (got: {json})",
25904 );
25905 }
25906 }
25907
25908 #[test]
25909 fn entrada_key_consts_are_pairwise_distinct() {
25910 // Cross-axis drift-detection pin: a future collapse of the four
25911 // canonical [`Entrada`] singleton byte-strings onto the same
25912 // value (e.g. an accidental copy-paste flip of
25913 // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
25914 // silently reroute every downstream probe on one axis onto the
25915 // sibling axis's overlay entry and pass every propagation-probe
25916 // test that expected only the stale axis's value — the
25917 // Gateway/HTTPRoute emitter would read the hostname string
25918 // where the destination-Servico name was expected (or vice
25919 // versa), the admission-webhook cross-check would compare the
25920 // wrong pair of values, and the resulting Gateway resource
25921 // would either be admitted with garbage or rejected at the
25922 // controller far from the rebrand commit's source. Peer of the
25923 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
25924 // tetrad (40cc4e5), the two-way distinct pin on the
25925 // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
25926 // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
25927 // triad (ca463a4).
25928 let all = [
25929 crate::ENTRADA_KEY_HOST,
25930 crate::ENTRADA_KEY_PARA,
25931 crate::ENTRADA_KEY_PATHS,
25932 crate::ENTRADA_KEY_PORT,
25933 ];
25934 for (i, a) in all.iter().enumerate() {
25935 for b in all.iter().skip(i + 1) {
25936 assert_ne!(
25937 a, b,
25938 "ENTRADA_KEY_* consts must be pairwise-distinct \
25939 canonical byte-sequences — got `{a}` == `{b}`",
25940 );
25941 }
25942 }
25943 }
25944
25945 #[test]
25946 fn entrada_key_consts_are_lower_camel_case_shape() {
25947 // Shape-pin: every `ENTRADA_KEY_*` const must be a
25948 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25949 // `kebab-case` hyphens, no leading colon, no `PascalCase`
25950 // leading capital, no whitespace / dots) — the canonical shape
25951 // the `#[serde(rename_all = "camelCase")]` derive produces on
25952 // [`Entrada`]. A future flip to a non-camelCase attribute at
25953 // the derive surfaces both here (this test fails on the
25954 // stale-constant shape) and at
25955 // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
25956 // test fails on the mismatch between const and derive). Peer
25957 // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
25958 // and `contrato_key_consts_are_lower_camel_case_shape`
25959 // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
25960 // entry axes.
25961 for key in [
25962 crate::ENTRADA_KEY_HOST,
25963 crate::ENTRADA_KEY_PARA,
25964 crate::ENTRADA_KEY_PATHS,
25965 crate::ENTRADA_KEY_PORT,
25966 ] {
25967 assert!(
25968 !key.is_empty(),
25969 "ENTRADA_KEY_* must be non-empty (got {key:?})"
25970 );
25971 let first = key.chars().next().unwrap();
25972 assert!(
25973 first.is_ascii_lowercase(),
25974 "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
25975 (got {key:?}, leads with {first:?})",
25976 );
25977 assert!(
25978 key.chars().all(|c| c.is_ascii_alphanumeric()),
25979 "ENTRADA_KEY_* must be ASCII-alphanumeric only \
25980 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25981 );
25982 }
25983 }
25984
25985 // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
25986
25987 #[test]
25988 fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
25989 // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
25990 // ([`crate::POLITICAS_KEY_TIMEOUT`] /
25991 // [`crate::POLITICAS_KEY_RETRIES`] /
25992 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
25993 // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
25994 // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
25995 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
25996 // on [`MeshPolicy`] emits. Three of the five axes
25997 // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
25998 // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
25999 // camelCase transforms — the derive-attribute is load-bearing
26000 // on those, unlike the sibling `Entrada` / `Membro` /
26001 // `WitContract` structs whose fields are all lowercase-single-
26002 // word and where the derive is a no-op on every axis.
26003 // Serialize a fully-populated [`MeshPolicy`] (every axis
26004 // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
26005 // on none of the five slots) and pin that each canonical
26006 // byte-sequence appears verbatim in the JSON — a future
26007 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26008 // verbatim-field-name flip at the derive attribute (any of
26009 // which would silently break every downstream JSON consumer
26010 // that reaches for one of the five consts via
26011 // `Value::get(...)` — the future M4 per-edge `:politicas`
26012 // overlay projection onto Cilium `L7Rules` and Gateway API
26013 // `HTTPRoute` backend timeouts, the future
26014 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26015 // admission-time mesh-policy cross-check, the future
26016 // `feira lint` per-`:politicas` bound-check gate) surfaces here
26017 // as a build-time test failure at `aplicacao.rs`, not as an
26018 // apply-time `.get(<stale-canonical-const>)` returning `None`
26019 // far from the derive-attr drift's commit. Peer with the
26020 // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
26021 // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26022 // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
26023 // (ce80ca0) pins on the M3 collection-slot / singleton-slot
26024 // atom axes — same discipline every M3 sibling lift
26025 // established, extended here to the singleton `:politicas`
26026 // mesh-slot atom axis, closing the last M3 typed-struct
26027 // top-level `#[serde(rename_all = "camelCase")]` axis on the
26028 // Aplicacao surface without a lifted serde-key peer.
26029 let p = MeshPolicy {
26030 timeout: Some(Duration::from_secs(30)),
26031 retries: Some(3),
26032 circuit_breaker: Some(CircuitBreaker {
26033 max_failures: 5,
26034 window: Duration::from_secs(60),
26035 }),
26036 mtls_required: Some(true),
26037 rate_limit: Some(RateLimit {
26038 rate: 100,
26039 window: Duration::from_secs(1),
26040 }),
26041 };
26042 let json = serde_json::to_string(&p).unwrap();
26043 for key in [
26044 crate::POLITICAS_KEY_TIMEOUT,
26045 crate::POLITICAS_KEY_RETRIES,
26046 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26047 crate::POLITICAS_KEY_MTLS_REQUIRED,
26048 crate::POLITICAS_KEY_RATE_LIMIT,
26049 ] {
26050 let quoted = format!("\"{key}\"");
26051 assert!(
26052 json.contains("ed),
26053 "serialized MeshPolicy must carry the lifted \
26054 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
26055 JSON emission (got: {json})",
26056 );
26057 }
26058 }
26059
26060 #[test]
26061 fn politicas_key_consts_are_pairwise_distinct() {
26062 // Cross-axis drift-detection pin: a future collapse of the five
26063 // canonical [`MeshPolicy`] singleton byte-strings onto the same
26064 // value (e.g. an accidental copy-paste flip of
26065 // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
26066 // would silently reroute every downstream probe on one axis
26067 // onto the sibling axis's overlay entry and pass every
26068 // propagation-probe test that expected only the stale axis's
26069 // value — the M4 per-edge `:politicas` overlay projection would
26070 // read the retry-count string where the timeout duration was
26071 // expected (or vice versa), the CR materializer's admission
26072 // cross-check would compare the wrong pair of values, and the
26073 // resulting mesh reconciler would either bind the wrong axis
26074 // or reject the resource at reconcile far from the rebrand
26075 // commit's source. Peer of the sibling four-way distinct pin
26076 // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
26077 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26078 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
26079 // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26080 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26081 let all = [
26082 crate::POLITICAS_KEY_TIMEOUT,
26083 crate::POLITICAS_KEY_RETRIES,
26084 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26085 crate::POLITICAS_KEY_MTLS_REQUIRED,
26086 crate::POLITICAS_KEY_RATE_LIMIT,
26087 ];
26088 for (i, a) in all.iter().enumerate() {
26089 for b in all.iter().skip(i + 1) {
26090 assert_ne!(
26091 a, b,
26092 "POLITICAS_KEY_* consts must be pairwise-distinct \
26093 canonical byte-sequences — got `{a}` == `{b}`",
26094 );
26095 }
26096 }
26097 }
26098
26099 #[test]
26100 fn politicas_key_consts_are_lower_camel_case_shape() {
26101 // Shape-pin: every `POLITICAS_KEY_*` const must be a
26102 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26103 // `kebab-case` hyphens, no leading colon, no `PascalCase`
26104 // leading capital, no whitespace / dots) — the canonical shape
26105 // the `#[serde(rename_all = "camelCase")]` derive produces on
26106 // [`MeshPolicy`]. A future flip to a non-camelCase attribute
26107 // at the derive surfaces both here (this test fails on the
26108 // stale-constant shape) and at
26109 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26110 // (that test fails on the mismatch between const and derive).
26111 // Peer with `entrada_key_consts_are_lower_camel_case_shape`
26112 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26113 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26114 // (ca463a4) on the sibling M3 typed-struct axes.
26115 for key in [
26116 crate::POLITICAS_KEY_TIMEOUT,
26117 crate::POLITICAS_KEY_RETRIES,
26118 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26119 crate::POLITICAS_KEY_MTLS_REQUIRED,
26120 crate::POLITICAS_KEY_RATE_LIMIT,
26121 ] {
26122 assert!(
26123 !key.is_empty(),
26124 "POLITICAS_KEY_* must be non-empty (got {key:?})"
26125 );
26126 let first = key.chars().next().unwrap();
26127 assert!(
26128 first.is_ascii_lowercase(),
26129 "POLITICAS_KEY_* must lead with an ASCII-lowercase \
26130 byte (got {key:?}, leads with {first:?})",
26131 );
26132 assert!(
26133 key.chars().all(|c| c.is_ascii_alphanumeric()),
26134 "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
26135 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26136 );
26137 }
26138 }
26139
26140 // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
26141
26142 #[test]
26143 fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
26144 // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
26145 // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
26146 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
26147 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
26148 // [`CircuitBreaker`] emits inside the
26149 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
26150 // two axes (`max_failures` → `maxFailures`) is a non-trivial
26151 // camelCase transform — the derive-attribute is load-bearing on
26152 // that axis, unlike the sibling `window` field where the derive
26153 // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
26154 // pin that each canonical byte-sequence appears verbatim in the
26155 // JSON — a future accidental `rename_all = "snake_case"` /
26156 // `"kebab-case"` / verbatim-field-name flip at the derive
26157 // attribute (any of which would silently break every downstream
26158 // JSON consumer that reaches for one of the two consts via
26159 // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
26160 // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
26161 // per-edge `:politicas` overlay projection onto the mesh's
26162 // per-backend consecutive-failure-counter tripping threshold, the
26163 // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26164 // admission-time breaker cross-check, the future `feira lint`
26165 // per-`:politicas :circuit-breaker` bound-check gate) surfaces
26166 // here as a build-time test failure at `aplicacao.rs`, not as an
26167 // apply-time `.get(<stale-canonical-const>)` returning `None`
26168 // far from the derive-attr drift's commit. Peer with the sibling
26169 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26170 // (b55cca7) parent-axis pin — that test pins the outer
26171 // sub-block key the derive on [`MeshPolicy`] emits, this test
26172 // pins the inner keys the derive on the payload type emits, so
26173 // the two together lock the whole [`MeshPolicy`] breaker-tuning
26174 // shape end-to-end at build time.
26175 let cb = CircuitBreaker {
26176 max_failures: 5,
26177 window: Duration::from_secs(60),
26178 };
26179 let json = serde_json::to_string(&cb).unwrap();
26180 for key in [
26181 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26182 crate::CIRCUIT_BREAKER_KEY_WINDOW,
26183 ] {
26184 let quoted = format!("\"{key}\"");
26185 assert!(
26186 json.contains("ed),
26187 "serialized CircuitBreaker must carry the lifted \
26188 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
26189 in the JSON emission (got: {json})",
26190 );
26191 }
26192 }
26193
26194 #[test]
26195 fn circuit_breaker_key_consts_are_pairwise_distinct() {
26196 // Cross-axis drift-detection pin: a future collapse of the two
26197 // canonical [`CircuitBreaker`] sub-block byte-strings onto the
26198 // same value (e.g. an accidental copy-paste flip of
26199 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
26200 // `"maxFailures"`) would silently reroute every downstream
26201 // probe on one axis onto the sibling axis's overlay entry and
26202 // pass every propagation-probe test that expected only the
26203 // stale axis's value — the M4 per-edge `:politicas` overlay
26204 // projection would read the failure-count where the window
26205 // duration was expected (or vice versa), the CR materializer's
26206 // admission cross-check would compare the wrong pair of values,
26207 // and the resulting mesh reconciler would either bind the wrong
26208 // axis or reject the resource at reconcile far from the rebrand
26209 // commit's source. Peer of the sibling five-way distinct pin on
26210 // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
26211 // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
26212 // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
26213 // six-way distinct pin on the `CONTRATO_KEY_*` triad +
26214 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26215 let all = [
26216 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26217 crate::CIRCUIT_BREAKER_KEY_WINDOW,
26218 ];
26219 for (i, a) in all.iter().enumerate() {
26220 for b in all.iter().skip(i + 1) {
26221 assert_ne!(
26222 a, b,
26223 "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
26224 canonical byte-sequences — got `{a}` == `{b}`",
26225 );
26226 }
26227 }
26228 }
26229
26230 #[test]
26231 fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
26232 // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
26233 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26234 // `kebab-case` hyphens, no leading colon, no `PascalCase`
26235 // leading capital, no whitespace / dots) — the canonical shape
26236 // the `#[serde(rename_all = "camelCase")]` derive produces on
26237 // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
26238 // at the derive surfaces both here (this test fails on the
26239 // stale-constant shape) and at
26240 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
26241 // (that test fails on the mismatch between const and derive).
26242 // Peer with `politicas_key_consts_are_lower_camel_case_shape`
26243 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
26244 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26245 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26246 // (ca463a4) on the sibling M3 typed-struct axes.
26247 for key in [
26248 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26249 crate::CIRCUIT_BREAKER_KEY_WINDOW,
26250 ] {
26251 assert!(
26252 !key.is_empty(),
26253 "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
26254 );
26255 let first = key.chars().next().unwrap();
26256 assert!(
26257 first.is_ascii_lowercase(),
26258 "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
26259 byte (got {key:?}, leads with {first:?})",
26260 );
26261 assert!(
26262 key.chars().all(|c| c.is_ascii_alphanumeric()),
26263 "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
26264 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26265 );
26266 }
26267 }
26268
26269 // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
26270
26271 #[test]
26272 fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
26273 // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
26274 // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
26275 // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
26276 // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
26277 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
26278 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
26279 // [`Placement`] emits. One of the four axes (`shard_key` →
26280 // `shardKey`) is a non-trivial camelCase transform — the
26281 // derive-attribute is load-bearing on that axis, unlike the
26282 // sibling `estrategia` / `clusters` / `affinity` axes whose
26283 // source-side field names carry no `_` and where the derive is a
26284 // no-op. Serialize a fully-populated [`Placement`] (both
26285 // `Option`-carrying axes `Some(_)` so
26286 // `skip_serializing_if = "Option::is_none"` fires on neither of
26287 // the two optional slots) and pin that each canonical
26288 // byte-sequence appears verbatim in the JSON — a future
26289 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26290 // verbatim-field-name flip at the derive attribute (any of which
26291 // would silently break every downstream consumer that reaches
26292 // for one of the four consts via
26293 // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
26294 // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
26295 // aggregator's per-cluster fanout filter keying off
26296 // `placement.clusters`, the M3 shard-pool dispatch materializer
26297 // keying off `placement.shardKey`, the M3 Adaptive compression
26298 // pass weighting off `placement.affinity`, every downstream
26299 // dispatcher branching on `placement.estrategia`, the future
26300 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26301 // admission-time placement cross-check, the future `feira lint`
26302 // per-`:placement` bound-check gate) surfaces here as a
26303 // build-time test failure at `aplicacao.rs`, not as an
26304 // apply-time `.get(<stale-canonical-const>)` returning `None`
26305 // far from the derive-attr drift's commit. Peer with the sibling
26306 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26307 // (b55cca7),
26308 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
26309 // (468e959),
26310 // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
26311 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26312 // (ca463a4), and
26313 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26314 // pins on the M3 collection-slot / singleton-slot atom axes —
26315 // closes the last M3 typed-struct top-level
26316 // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
26317 // surface without a drift-detection pin.
26318 let p = Placement {
26319 estrategia: PlacementStrategy::Sharded,
26320 clusters: vec!["rio".into(), "mar".into()],
26321 affinity: Some("data-locality".into()),
26322 shard_key: Some("$tenantId".into()),
26323 };
26324 let json = serde_json::to_string(&p).unwrap();
26325 for key in [
26326 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26327 crate::M3_PLACEMENT_KEY_CLUSTERS,
26328 crate::M3_PLACEMENT_KEY_AFFINITY,
26329 crate::M3_PLACEMENT_KEY_SHARD_KEY,
26330 ] {
26331 let quoted = format!("\"{key}\"");
26332 assert!(
26333 json.contains("ed),
26334 "serialized Placement must carry the lifted \
26335 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
26336 the JSON emission (got: {json})",
26337 );
26338 }
26339 }
26340
26341 #[test]
26342 fn m3_placement_key_consts_are_pairwise_distinct() {
26343 // Cross-axis drift-detection pin: a future collapse of the four
26344 // canonical [`Placement`] sub-block byte-strings onto the same
26345 // value (e.g. an accidental copy-paste flip of
26346 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
26347 // `"affinity"`) would silently reroute every downstream probe on
26348 // one axis onto the sibling axis's overlay entry and pass every
26349 // propagation-probe test that expected only the stale axis's
26350 // value — the M3 shard-pool dispatch materializer would read the
26351 // affinity placement-hint where the shard-selection template was
26352 // expected (or vice versa), the M3 Adaptive compression pass's
26353 // cross-check would compare the wrong pair of values, and the
26354 // resulting placement engine would either bind the wrong axis or
26355 // reject the resource at reconcile far from the rebrand commit's
26356 // source. Peer of the sibling two-way distinct pin on the
26357 // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
26358 // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
26359 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26360 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
26361 // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26362 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26363 let all = [
26364 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26365 crate::M3_PLACEMENT_KEY_CLUSTERS,
26366 crate::M3_PLACEMENT_KEY_AFFINITY,
26367 crate::M3_PLACEMENT_KEY_SHARD_KEY,
26368 ];
26369 for (i, a) in all.iter().enumerate() {
26370 for b in all.iter().skip(i + 1) {
26371 assert_ne!(
26372 a, b,
26373 "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
26374 canonical byte-sequences — got `{a}` == `{b}`",
26375 );
26376 }
26377 }
26378 }
26379
26380 #[test]
26381 fn m3_placement_key_consts_are_lower_camel_case_shape() {
26382 // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
26383 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26384 // `kebab-case` hyphens, no leading colon, no `PascalCase`
26385 // leading capital, no whitespace / dots) — the canonical shape
26386 // the `#[serde(rename_all = "camelCase")]` derive produces on
26387 // [`Placement`]. A future flip to a non-camelCase attribute at
26388 // the derive surfaces both here (this test fails on the stale-
26389 // constant shape) and at
26390 // `placement_serde_keys_match_lifted_m3_placement_key_consts`
26391 // (that test fails on the mismatch between const and derive).
26392 // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
26393 // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
26394 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
26395 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26396 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26397 // (ca463a4) on the sibling M3 typed-struct axes.
26398 for key in [
26399 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26400 crate::M3_PLACEMENT_KEY_CLUSTERS,
26401 crate::M3_PLACEMENT_KEY_AFFINITY,
26402 crate::M3_PLACEMENT_KEY_SHARD_KEY,
26403 ] {
26404 assert!(
26405 !key.is_empty(),
26406 "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
26407 );
26408 let first = key.chars().next().unwrap();
26409 assert!(
26410 first.is_ascii_lowercase(),
26411 "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
26412 byte (got {key:?}, leads with {first:?})",
26413 );
26414 assert!(
26415 key.chars().all(|c| c.is_ascii_alphanumeric()),
26416 "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
26417 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26418 );
26419 }
26420 }
26421
26422 // ── AplicacaoSpec::port_for_destination — the substrate-canonical
26423 // destination-facing L4 port resolver every per-Aplicacao renderer
26424 // reaching for a per-destination Servico TCP port axis routes
26425 // through. The four pin tests below fix the four-way accept-set
26426 // the resolver must always honor: (:entrada-para-matches,
26427 // :entrada-para-mismatches, :entrada-none-so-fallback,
26428 // :entrada-port-non-default-honored) — drift on any arm surfaces
26429 // at caixa-core build time rather than at cluster-apply time.
26430
26431 #[test]
26432 fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
26433 // The typed `:entrada` block's `:para "cart"` matches the
26434 // queried destination, so the resolver returns the author-
26435 // declared `:port` scalar verbatim — the canonical "the
26436 // destination Servico IS the ingress apex, honor the typed
26437 // listener port" arm of the port-resolution dispatch.
26438 let mut spec = three_member_spec();
26439 if let Some(e) = spec.entrada.as_mut() {
26440 e.para = "cart".into();
26441 e.port = 9090;
26442 }
26443 assert_eq!(
26444 spec.port_for_destination("cart"),
26445 9090,
26446 "port_for_destination(entrada.para) must return entrada.port \
26447 verbatim, not the DEFAULT_SERVICO_PORT fallback"
26448 );
26449 }
26450
26451 #[test]
26452 fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
26453 // The typed `:entrada` block names `:para "cart"`, but the
26454 // queried destination is `"payment"` — a Servico that
26455 // participates in the mesh graph but is not the ingress apex.
26456 // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
26457 // canonical port floor, closing the "non-apex destination reads
26458 // the substrate default" arm. Same fixture the peer
26459 // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
26460 // pin at caixa-mesh exercises through the CNP emit-side path;
26461 // this pin exercises the shared underlying resolver directly.
26462 let spec = three_member_spec();
26463 assert_eq!(
26464 spec.port_for_destination("payment"),
26465 DEFAULT_SERVICO_PORT,
26466 "port_for_destination(non-apex-destination) must route \
26467 through the lifted DEFAULT_SERVICO_PORT canonical port floor"
26468 );
26469 }
26470
26471 #[test]
26472 fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
26473 // Internal-only Aplicacao — no `:entrada` block declared. Every
26474 // per-destination port query falls back to the lifted
26475 // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
26476 // the Aplicacao surface admits `:entrada None` (internal mesh
26477 // with no external gateway); every downstream renderer's per-
26478 // destination port axis must still resolve to a well-defined
26479 // scalar even without an ingress apex.
26480 let mut spec = three_member_spec();
26481 spec.entrada = None;
26482 assert_eq!(
26483 spec.port_for_destination("cart"),
26484 DEFAULT_SERVICO_PORT,
26485 "port_for_destination on an internal-only Aplicacao must \
26486 fall back to the lifted DEFAULT_SERVICO_PORT floor for \
26487 every destination"
26488 );
26489 assert_eq!(
26490 spec.port_for_destination("payment"),
26491 DEFAULT_SERVICO_PORT,
26492 "port_for_destination on an internal-only Aplicacao must \
26493 fall back uniformly across every destination — the fallback \
26494 is not entrada-shape-conditional"
26495 );
26496 }
26497
26498 #[test]
26499 fn port_for_destination_honors_non_default_entrada_port_verbatim() {
26500 // Structural pin against a hypothetical future refactor that
26501 // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
26502 // the resolver (a "normalize to the default when the author's
26503 // port matches the substrate default" collapse) — that would
26504 // break renderer sites that carry meaning on the emitted port
26505 // value beyond bare equality (a future per-cluster listener-
26506 // audit that keys off the author-declared port, not the
26507 // resolved-with-fallback port). Pin that a non-default
26508 // entrada.port is returned verbatim so drift here surfaces at
26509 // caixa-core build time.
26510 let mut spec = three_member_spec();
26511 if let Some(e) = spec.entrada.as_mut() {
26512 e.para = "cart".into();
26513 e.port = 8443;
26514 }
26515 assert_ne!(
26516 8443, DEFAULT_SERVICO_PORT,
26517 "test fixture must probe a port distinct from \
26518 DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
26519 );
26520 assert_eq!(
26521 spec.port_for_destination("cart"),
26522 8443,
26523 "port_for_destination(entrada.para) must return entrada.port \
26524 verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
26525 );
26526 }
26527
26528 #[test]
26529 fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
26530 // Apex-identity pair-invariant pin composing both substrate-
26531 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26532 // and [`Entrada::destination`] — at the emit-side call shape
26533 // every per-Aplicacao renderer's ingress-apex L4 port reader
26534 // now takes. The invariant:
26535 //
26536 // spec.port_for_destination(entrada.destination()) == entrada.port
26537 //
26538 // holds by construction under today's single-destination
26539 // `:entrada` slot (`destination()` returns `entrada.para`, and
26540 // the resolver's apex arm matches `para == destination` and
26541 // returns `entrada.port`), and every downstream consumer that
26542 // composes the two accessors at the ingress apex — the
26543 // `caixa_mesh::gateway_routes` HTTPRoute per-rule
26544 // `backendRefs[0].port` emit-site path, the peer future M4 CR
26545 // materializer's admission-webhook that promotes the scalar to
26546 // a per-CR override overlay, every future per-Aplicacao snapshot
26547 // renderer's apex-facing L4 port reader — reaches through the
26548 // same composition. Pin the identity across four permutations
26549 // (`:para` × `:port` including a non-default port to exercise
26550 // the honor-verbatim arm and a non-cart `:para` to exercise
26551 // destination-agnostic identity) so a future refactor that
26552 // silently split either accessor's apex behavior surfaces at
26553 // caixa-core build time — a subtle `destination()` renaming
26554 // that returned `entrada.host.as_str()` instead of
26555 // `entrada.para.as_str()` would blow this pin loudly, closing
26556 // the last quiet failure mode the two lifts admit in composition.
26557 //
26558 // Peer discipline with the sibling caixa-mesh cross-crate pin
26559 // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
26560 // on the two-renderer pair-invariant axis; this pin encodes the
26561 // same two-consumer coherence rule at the substrate-primitive
26562 // level so the invariant survives even if every renderer is
26563 // deleted.
26564 for (para, port) in [
26565 ("cart", DEFAULT_SERVICO_PORT),
26566 ("cart", 8443u16),
26567 ("payment", 9090u16),
26568 ("catalog", 443u16),
26569 ] {
26570 let mut spec = three_member_spec();
26571 if let Some(e) = spec.entrada.as_mut() {
26572 e.para = para.into();
26573 e.port = port;
26574 }
26575 let expected_port = spec
26576 .entrada()
26577 .expect("three_member_spec carries a typed `:entrada` block")
26578 .port();
26579 let composed_port = {
26580 let entrada = spec.entrada().expect("entrada present");
26581 spec.port_for_destination(entrada.destination())
26582 };
26583 assert_eq!(
26584 composed_port, expected_port,
26585 "`spec.port_for_destination(entrada.destination())` must \
26586 equal `entrada.port` under today's single-destination \
26587 `:entrada` slot — this is the apex-identity contract \
26588 every downstream ingress-apex L4 port reader relies on. \
26589 Input :entrada :para: {para:?}, :entrada :port: {port}"
26590 );
26591 }
26592 }
26593
26594 #[test]
26595 fn port_for_destination_apex_arm_routes_through_destination_accessor() {
26596 // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
26597 // per-`:entrada` apex-arm membership probe must key off
26598 // [`Entrada::destination`], not the raw `.para` field access.
26599 // Structurally: setting ONLY the `:entrada :para` field to a
26600 // fresh non-cart destination on an otherwise-well-formed
26601 // Aplicacao must (1) leave `e.destination()` byte-equal to
26602 // `e.para.as_str()` (the accessor is byte-projective by
26603 // definition), and (2) cause the resolver's apex arm to fire
26604 // and return `entrada.port` at exactly that new destination
26605 // while every other destination string falls through to
26606 // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
26607 // membership check. Pins against a future silent detour that
26608 // (a) re-derived the apex-arm membership probe off
26609 // `e.para == destination` in `port_for_destination` instead of
26610 // `e.destination() == destination`, silently disagreeing with
26611 // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
26612 // consumers (`entrada.destination()` at
26613 // caixa-mesh/src/lib.rs:3173, `c.destination()` at
26614 // caixa-mesh/src/lib.rs:2739) that already reach through the
26615 // accessor, (b) accessor-side introduced a per-tenant alias
26616 // arm the caller was unaware of, silently rewriting an
26617 // author-declared `:para "cart"` value to a canary-aliased
26618 // form — the raw-field-access resolver would fall through to
26619 // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
26620 // while the peer emit-site consumers landed on the aliased
26621 // destination, splitting the ingress-apex L4 port at
26622 // cluster-apply time.
26623 //
26624 // Peer of the sibling
26625 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
26626 // (d0de220) composition pin on the per-`:membros` refusal-arm
26627 // axis — same "the shape-gate predicate must route through the
26628 // substrate-primitive typed dispatch" discipline extended onto
26629 // the per-`:entrada` apex-arm membership-probe axis. Closes
26630 // the last unlifted `.para` production-code read site on
26631 // `Entrada` in `caixa-core` — after this converge every
26632 // `caixa-core` `.para` field access outside the accessor's own
26633 // body and outside the `WitContract` per-`:contratos` sibling
26634 // axis is either a test-side field-setter or a doc-comment
26635 // reference.
26636 for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
26637 let mut spec = three_member_spec();
26638 if let Some(e) = spec.entrada.as_mut() {
26639 e.para = para.into();
26640 e.port = port;
26641 }
26642 let e = spec
26643 .entrada
26644 .as_ref()
26645 .expect("three_member_spec carries a typed `:entrada` block");
26646 assert_eq!(
26647 e.destination(),
26648 e.para.as_str(),
26649 "Entrada::destination must byte-equal the .para field \
26650 access — an accessor-side detour that no longer \
26651 projects the raw field would silently split this \
26652 drift-detection test from the port_for_destination \
26653 apex-arm membership probe",
26654 );
26655 assert_eq!(
26656 spec.port_for_destination(para),
26657 port,
26658 "port_for_destination must key off the accessor-projected \
26659 destination and return `entrada.port` on the apex arm — \
26660 input :entrada :para: {para:?}, :entrada :port: {port}",
26661 );
26662 assert_eq!(
26663 spec.port_for_destination("ghost-destination-never-a-member"),
26664 DEFAULT_SERVICO_PORT,
26665 "port_for_destination must fall through to \
26666 DEFAULT_SERVICO_PORT on a non-matching destination \
26667 under the accessor-projected membership check — input \
26668 :entrada :para: {para:?}, :entrada :port: {port}",
26669 );
26670 }
26671 }
26672
26673 #[test]
26674 fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
26675 // The canonical per-`:politicas :rate-limit` `:rate`
26676 // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
26677 // [`RateLimit::rate`] must return the `:politicas :rate-limit`
26678 // typed `u32` verbatim, byte-equal to the raw field access
26679 // across every representative value in the accept-set — `1` (the
26680 // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
26681 // the surrounding [`AplicacaoSpec::validate_politicas`] gate
26682 // carves out on the sibling `PolicyRateLimitZero` refusal),
26683 // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
26684 // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
26685 // `0` (a past-the-guard sentinel that pins the accessor doesn't
26686 // perform a silent bounds-collapse into `1` on the zero arm —
26687 // validate rejects zero but the accessor must ship the raw slot
26688 // verbatim so a validate-time gate regression surfaces at the
26689 // emit boundary rather than being silently absorbed), `u32::MAX`
26690 // (a past-the-guard sentinel that pins the accessor doesn't
26691 // perform a silent bounds-collapse through
26692 // `POLICY_RATE_LIMIT_MAX` at the return path).
26693 //
26694 // First sub-struct required-scalar accessor pin on the
26695 // `RateLimit` axis — sibling in shape to the peer
26696 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
26697 // required-`u32` accessor pin on the peer per-sub-struct
26698 // required-axis. Pins against a future silent detour that
26699 // re-derived the token capacity from a peer axis (an accidental
26700 // `self.window.as_secs() as u32` collapse that read the
26701 // rate-limit window duration as a token count), a `0 → 1`
26702 // cluster-default projection (which would silently absorb the
26703 // `PolicyRateLimitZero` refusal case at the accessor boundary),
26704 // or a bounds-collapsing accessor that clamped the return
26705 // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
26706 // gate owns the bounds; the accessor must ship the raw slot
26707 // verbatim).
26708 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
26709 let rl = RateLimit {
26710 rate,
26711 window: Duration::from_secs(1),
26712 };
26713 assert_eq!(
26714 rl.rate(),
26715 rate,
26716 "RateLimit::rate must return :politicas :rate-limit :rate \
26717 verbatim (got {}, expected {rate})",
26718 rl.rate(),
26719 );
26720 assert_eq!(
26721 rl.rate(),
26722 rl.rate,
26723 "RateLimit::rate must byte-equal the raw .rate field \
26724 access across every value in the u32 accept-set",
26725 );
26726 }
26727 }
26728
26729 #[test]
26730 fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
26731 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26732 // `:rate-limit :rate` zero-floor arm must key off
26733 // [`RateLimit::rate`], not the raw `.rate` field access.
26734 // Structurally: a `RateLimit { rate: 0, window:
26735 // Duration::from_secs(1) }` embedded in a `:politicas
26736 // :rate-limit` slot must surface the `PolicyRateLimitZero`
26737 // refusal exactly, and a `RateLimit { rate: 1, window:
26738 // Duration::from_secs(1) }` (the lower boundary of the
26739 // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
26740 // The pair jointly pins the accessor + validate-gate composition:
26741 // any future silent detour that had the accessor return a fresh
26742 // `1` on the zero arm (a `.rate().max(1)` collapse) would
26743 // silently absorb the `PolicyRateLimitZero` refusal at the
26744 // accessor boundary and the validate gate would accept a
26745 // struct-literal `RateLimit { rate: 0, .. }` — the composition
26746 // pin catches that at caixa-core build time.
26747 //
26748 // Peer of the sibling per-`CircuitBreaker`
26749 // [`CircuitBreaker::max_failures`] (3a74062) /
26750 // [`CircuitBreaker::window`] (373957f) accessor-composition
26751 // pins on the peer required-scalar axes — same "the validate /
26752 // shape-gate predicate must route through the substrate-primitive
26753 // typed dispatch" discipline extended onto the peer
26754 // per-`RateLimit` required-`u32` composition axis.
26755 let mut spec = three_member_spec();
26756 spec.politicas = MeshPolicy {
26757 rate_limit: Some(RateLimit {
26758 rate: 0,
26759 window: Duration::from_secs(1),
26760 }),
26761 ..MeshPolicy::default()
26762 };
26763 assert!(
26764 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
26765 "validate_politicas must reject rate == 0 with \
26766 PolicyRateLimitZero — the accessor and the validate gate \
26767 must route through the same substrate-primitive typed \
26768 dispatch on the :rate zero-floor arm",
26769 );
26770 spec.politicas = MeshPolicy {
26771 rate_limit: Some(RateLimit {
26772 rate: 1,
26773 window: Duration::from_secs(1),
26774 }),
26775 ..MeshPolicy::default()
26776 };
26777 assert!(
26778 spec.validate().is_ok(),
26779 "validate_politicas must accept rate == 1 (the lower \
26780 boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
26781 );
26782 }
26783
26784 #[test]
26785 fn rate_limit_rate_projects_u32_by_copy() {
26786 // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
26787 // `u32` is `Copy` and the accessor must return by value, not by
26788 // reference. Peer of the sibling per-`CircuitBreaker`
26789 // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
26790 // peer required-scalar `:max-failures` axis, extended onto the
26791 // peer per-`RateLimit` required-`u32` copy-invariant shape —
26792 // the accessor's returned `u32` must outlive `&self` (multiple
26793 // calls must return equal values from a dropped-`&self` copy,
26794 // since the returned scalar carries no borrow), and calling the
26795 // accessor twice on the same RateLimit must yield the same
26796 // `u32` verbatim (idempotent, no side effects on `&self`).
26797 //
26798 // Pins against a future silent detour that returned `&u32`
26799 // (which would type-check but silently break every downstream
26800 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
26801 // first parameter is `u32`, and `&u32` would fold to a detached
26802 // copy at the call site with a `*` deref the sibling accessors
26803 // don't need), an accidental `.rate.wrapping_add(0)` detour that
26804 // returned a fresh copy through an arithmetic no-op (breaking a
26805 // future `const fn` regression), or a one-arm-only accessor
26806 // that returned a saturating value on some sentinel input
26807 // (breaking the pass-through invariant the sibling required-
26808 // scalar accessors carry).
26809 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
26810 let rl = RateLimit {
26811 rate,
26812 window: Duration::from_secs(1),
26813 };
26814 let first = rl.rate();
26815 let second = rl.rate();
26816 assert_eq!(
26817 first, second,
26818 "RateLimit::rate must be idempotent — two successive \
26819 calls on the same &self must return the same u32",
26820 );
26821 assert_eq!(
26822 first, rate,
26823 "RateLimit::rate must return :politicas :rate-limit :rate \
26824 verbatim by copy — got {first}, expected {rate}",
26825 );
26826 }
26827 }
26828
26829 #[test]
26830 fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
26831 // The canonical per-`:politicas :rate-limit` `:window`
26832 // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
26833 // pin: [`RateLimit::window`] must return the
26834 // `:politicas :rate-limit :window` typed `Duration` verbatim,
26835 // byte-equal to the raw field access across every
26836 // representative value in the accept-set — `Duration::from_secs(1)`
26837 // (the `"s"` canonical window, the lower row of
26838 // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
26839 // [`AplicacaoSpec::validate_politicas`] gate accepts via
26840 // [`is_canonical_rate_limit_window`]),
26841 // `Duration::from_secs(60)` (the `"m"` canonical window, the
26842 // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
26843 // window, the upper row), `Duration::ZERO` (a past-the-guard
26844 // sentinel that pins the accessor doesn't perform a silent
26845 // bounds-collapse into `Duration::from_secs(1)` on the zero
26846 // arm — validate rejects an off-set window through
26847 // `PolicyRateLimitWindowNotCanonical` but the accessor must
26848 // ship the raw slot verbatim so a validate-time gate
26849 // regression surfaces at the emit boundary rather than being
26850 // silently absorbed), `Duration::from_millis(500)` (a
26851 // sub-canonical past-the-guard sentinel that pins the accessor
26852 // doesn't silently normalize a non-canonical fractional
26853 // magnitude onto the nearest canonical row).
26854 //
26855 // Second sub-struct required-scalar accessor pin on the
26856 // `RateLimit` axis — sibling in shape to the just-landed
26857 // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
26858 // accessor pin on the peer per-sub-struct required-axis,
26859 // extended onto the per-`RateLimit` required-`Duration` axis.
26860 // Pins against a future silent detour that re-derived the
26861 // refill period from a peer axis (an accidental
26862 // `Duration::from_secs(self.rate as u64)` collapse that read
26863 // the rate-limit token capacity as a refill-interval
26864 // duration), a `Duration::ZERO → Duration::from_secs(1)`
26865 // canonical-default projection (which would silently absorb
26866 // the `PolicyRateLimitWindowNotCanonical` refusal case at the
26867 // accessor boundary), or a canonical-set-collapsing accessor
26868 // that clamped the return through [`rate_limit_window_unit`]
26869 // (the `AplicacaoSpec::validate` gate owns the canonical-set
26870 // membership; the accessor must ship the raw slot verbatim).
26871 for window in [
26872 Duration::from_secs(1),
26873 Duration::from_secs(60),
26874 Duration::from_secs(3600),
26875 Duration::ZERO,
26876 Duration::from_millis(500),
26877 ] {
26878 let rl = RateLimit { rate: 100, window };
26879 assert_eq!(
26880 rl.window(),
26881 window,
26882 "RateLimit::window must return :politicas :rate-limit :window \
26883 verbatim (got {:?}, expected {window:?})",
26884 rl.window(),
26885 );
26886 assert_eq!(
26887 rl.window(),
26888 rl.window,
26889 "RateLimit::window must byte-equal the raw .window field \
26890 access across every value in the Duration accept-set",
26891 );
26892 }
26893 }
26894
26895 #[test]
26896 fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
26897 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26898 // `:rate-limit :window` canonical-set arm must key off
26899 // [`RateLimit::window`], not the raw `.window` field access.
26900 // Structurally: a `RateLimit { window: Duration::from_millis(500),
26901 // .. }` embedded in a `:politicas :rate-limit` slot must
26902 // surface the `PolicyRateLimitWindowNotCanonical` refusal
26903 // exactly (with the sub-canonical `Duration::from_millis(500)`
26904 // magnitude carried through verbatim), and a `RateLimit
26905 // { window: Duration::from_secs(1), .. }` (the lower row of
26906 // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
26907 // The pair jointly pins the accessor + validate-gate
26908 // composition: any future silent detour that had the accessor
26909 // normalize the off-set window to the nearest canonical row
26910 // (a `.window().max(Duration::from_secs(1))` collapse, or a
26911 // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
26912 // collapse) would silently absorb the
26913 // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
26914 // boundary — including a drift in the error's `window` payload
26915 // (the emit-side diagnostic reader keys off the offending
26916 // magnitude verbatim, so a normalization at the accessor
26917 // boundary would silently pin the wrong magnitude in the
26918 // refusal). The composition pin catches that at caixa-core
26919 // build time.
26920 //
26921 // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
26922 // (7f81a60) accessor-composition pin on the peer required-
26923 // scalar `:rate` axis — same "the validate / shape-gate
26924 // predicate must route through the substrate-primitive typed
26925 // dispatch, and the error payload must project through the
26926 // same accessor" discipline extended onto the peer
26927 // per-`RateLimit` required-`Duration` composition axis.
26928 let mut spec = three_member_spec();
26929 spec.politicas = MeshPolicy {
26930 rate_limit: Some(RateLimit {
26931 rate: 100,
26932 window: Duration::from_millis(500),
26933 }),
26934 ..MeshPolicy::default()
26935 };
26936 match spec.validate() {
26937 Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
26938 assert_eq!(
26939 window,
26940 Duration::from_millis(500),
26941 "PolicyRateLimitWindowNotCanonical must carry the \
26942 offending :window magnitude verbatim through the \
26943 accessor — got {window:?}, expected 500ms",
26944 );
26945 }
26946 other => panic!(
26947 "validate_politicas must reject non-canonical :window \
26948 with PolicyRateLimitWindowNotCanonical — the accessor \
26949 and the validate gate must route through the same \
26950 substrate-primitive typed dispatch on the :window \
26951 canonical-set arm; got {other:?}",
26952 ),
26953 }
26954 spec.politicas = MeshPolicy {
26955 rate_limit: Some(RateLimit {
26956 rate: 100,
26957 window: Duration::from_secs(1),
26958 }),
26959 ..MeshPolicy::default()
26960 };
26961 assert!(
26962 spec.validate().is_ok(),
26963 "validate_politicas must accept window == Duration::from_secs(1) \
26964 (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
26965 );
26966 }
26967
26968 #[test]
26969 fn rate_limit_window_projects_duration_by_copy() {
26970 // The by-copy pin: [`RateLimit::window`] returns `Duration`
26971 // by copy — `Duration` is `Copy` and the accessor must return
26972 // by value, not by reference. Peer of the sibling per-`RateLimit`
26973 // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
26974 // required-scalar `:rate` axis, extended onto the peer
26975 // per-`RateLimit` required-`Duration` copy-invariant shape —
26976 // the accessor's returned `Duration` must outlive `&self`
26977 // (multiple calls must return equal values from a
26978 // dropped-`&self` copy, since the returned scalar carries no
26979 // borrow), and calling the accessor twice on the same
26980 // RateLimit must yield the same `Duration` verbatim
26981 // (idempotent, no side effects on `&self`).
26982 //
26983 // Pins against a future silent detour that returned
26984 // `&Duration` (which would type-check but silently break every
26985 // downstream `Duration`-by-value consumer —
26986 // [`is_canonical_rate_limit_window`]'s first parameter is
26987 // `Duration`, and `&Duration` would fold to a detached copy at
26988 // the call site with a `*` deref the sibling accessors don't
26989 // need), an accidental `.window + Duration::ZERO` detour that
26990 // returned a fresh copy through an arithmetic no-op (breaking
26991 // a future `const fn` regression), or a one-arm-only accessor
26992 // that returned a canonical fallback on some sentinel input
26993 // (breaking the pass-through invariant the sibling required-
26994 // scalar accessors carry).
26995 for window in [
26996 Duration::from_secs(1),
26997 Duration::from_secs(60),
26998 Duration::from_secs(3600),
26999 Duration::ZERO,
27000 Duration::from_millis(500),
27001 ] {
27002 let rl = RateLimit { rate: 100, window };
27003 let first = rl.window();
27004 let second = rl.window();
27005 assert_eq!(
27006 first, second,
27007 "RateLimit::window must be idempotent — two successive \
27008 calls on the same &self must return the same Duration",
27009 );
27010 assert_eq!(
27011 first, window,
27012 "RateLimit::window must return :politicas :rate-limit :window \
27013 verbatim by copy — got {first:?}, expected {window:?}",
27014 );
27015 }
27016 }
27017
27018 #[test]
27019 fn placement_estrategia_default_pins_m3_canonical_value() {
27020 // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
27021 // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
27022 // active-active-across-every-named-cluster arm, the closest
27023 // canonical M3 production reference the substrate carries and
27024 // the arm the caixa-mesh `programs.yaml` fan-out already keys off
27025 // for every un-`:placement`-declared Aplicacao. Pinning the arm
27026 // here surfaces a future rebrand of the M3-canonical
27027 // distribution default (a widening to `Sharded` once the
27028 // substrate discovers hash-keyed distribution as the more
27029 // common production shape, a tightening to `SingleNode` for
27030 // stateful Erlang/OTP distributed-app-takeover semantics
27031 // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
27032 // operator pins through a future `:placement-overrides` slot)
27033 // as a deliberate test edit, not a silent contract migration.
27034 // Peer of the sibling M2 per-supervisor value pins
27035 // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
27036 // /
27037 // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
27038 // extended onto the M3 mesh-primitive-defining `:placement
27039 // :estrategia` axis.
27040 assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
27041 }
27042
27043 #[test]
27044 fn placement_strategy_default_routes_through_lifted_default() {
27045 // Composition pin: the [`Default for PlacementStrategy`] impl's
27046 // return arm must route through the substrate-canonical
27047 // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
27048 // a raw `Self::Replicated` arm. Prior to the lift the impl
27049 // carried an inline `Self::Replicated` arm with no compile-time
27050 // link back to the shared M3-canonical `Replicated` arm the
27051 // paired [`Default for Placement`] impl's struct-literal
27052 // `estrategia` field, the serde-side `#[serde(default)]` on
27053 // [`Placement::estrategia`] that resolves an author-omitted
27054 // wire-form `:placement :estrategia` scalar through the impl,
27055 // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
27056 // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
27057 // routes through [`Placement::default`] which routes through the
27058 // strategy default) all key off — so a future rebrand of the
27059 // M3-canonical distribution default would have had to be threaded
27060 // through the `Default` impl and the three peer routes in
27061 // lockstep or the four consumers would silently split. Byte-
27062 // parity against the lifted constant closes the split. Peer of
27063 // the sibling
27064 // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
27065 // /
27066 // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
27067 // composition pins on the M2 per-supervisor axes.
27068 assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
27069 }
27070
27071 #[test]
27072 fn placement_default_estrategia_routes_through_lifted_default() {
27073 // Composition pin: the [`Default for Placement`] impl's
27074 // struct-literal `estrategia` field must route through the
27075 // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
27076 // `pub const` (either directly, or via the [`PlacementStrategy::default`]
27077 // impl that the sibling
27078 // `placement_strategy_default_routes_through_lifted_default` pin
27079 // already routes onto the constant). Structurally: every
27080 // `Placement::default()` call must yield an `estrategia` field
27081 // byte-equal to the lifted constant so the two paired defaults —
27082 // the [`Default for PlacementStrategy`] impl arm and the
27083 // struct-literal default arm here — cannot silently split on any
27084 // future M3-canonical distribution-default rebrand. Peer of the
27085 // sibling M2
27086 // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
27087 // byte-parity pin on the [`Default for SupervisorSpec`]
27088 // struct-literal `estrategia` field extended onto the M3
27089 // mesh-primitive-defining slot family.
27090 assert_eq!(
27091 Placement::default().estrategia,
27092 PLACEMENT_ESTRATEGIA_DEFAULT,
27093 );
27094 }
27095
27096 #[test]
27097 fn placement_serde_default_estrategia_routes_through_lifted_default() {
27098 // Composition pin: the serde-side `#[serde(default)]` on
27099 // [`Placement::estrategia`] — the wire-format author-omitted
27100 // `:placement :estrategia` arm — must resolve onto the substrate-
27101 // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
27102 // (via the [`Default for PlacementStrategy`] impl the sibling
27103 // `placement_strategy_default_routes_through_lifted_default` pin
27104 // already routes onto the constant). Structurally: a `Placement`
27105 // deserialized from a payload that omits the `estrategia` key
27106 // must yield an `estrategia` field byte-equal to the lifted
27107 // constant, so the wire-format author-omitted arm and the
27108 // [`PlacementStrategy::default`] impl arm cannot silently split
27109 // on any future M3-canonical distribution-default rebrand. Peer
27110 // of the sibling M2
27111 // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
27112 // byte-parity pin on the wire-format author-omitted `:children
27113 // :restart` scalar extended onto the M3 mesh-primitive-defining
27114 // slot family.
27115 let omitted: Placement = serde_json::from_str("{}")
27116 .expect("Placement must deserialize with the estrategia key omitted");
27117 assert_eq!(
27118 omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
27119 "an author-omitted :placement :estrategia slot must degrade onto \
27120 the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
27121 {:?}, expected {:?})",
27122 omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
27123 );
27124 }
27125}