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
181impl WitContract {
182 /// Substrate-canonical per-`:contratos` caller-Servico scalar
183 /// accessor every consumer that reads the edge's source endpoint
184 /// keys off — returns the author-declared `:contratos :de`
185 /// byte-string verbatim as a `&str`, borrowed from the typed slot's
186 /// own [`String`] storage.
187 ///
188 /// The `:contratos :de` slot names the caller-side member Servico
189 /// on a typed inter-Servico edge (validated by
190 /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
191 /// Aplicacao declares — a stray `:de` that doesn't name a member is
192 /// [`AplicacaoError::ContratoMemberMissing`], not a silent
193 /// caller-attachment miss at cluster-apply time). Peer of the
194 /// sibling [`WitContract::destination`] accessor on the same
195 /// per-`:contratos` entry — the pair `( source(), destination() )`
196 /// jointly names the typed edge every renderer that fans on the
197 /// caller-callee identity keys off (the
198 /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
199 /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
200 /// map, the per-edge dedup key, the per-edge membership-lookup
201 /// diagnostic).
202 ///
203 /// Prior to this lift the `.de` byte-string was accessed inline at
204 /// four caixa-core sites (the two validate-side membership lookups
205 /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
206 /// tuple's caller-arm at
207 /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
208 /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
209 /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
210 /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
211 /// — five open-coded `.de.as_str()` field-accesses that expressed
212 /// no compile-time link back to the typed slot. A future extension
213 /// of the `:contratos :de` axis to a richer author surface (a
214 /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
215 /// canary flow, a per-cluster caller-alias table the operator pins
216 /// through a future `:placement`-scoped slot, the M4
217 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
218 /// admission-webhook that promotes the scalar to a caller-set
219 /// projection) would have had to be threaded through every
220 /// open-coded copy in lockstep or one consumer would silently
221 /// disagree with the peers on which caller Servico a given edge
222 /// resolves to. Lifting the resolution rule to a typed method on
223 /// the substrate primitive means every downstream caller-facing
224 /// consumer reaches for one typed dispatch — the resolver's
225 /// accept-set migrates as a unit on any future axis addition.
226 ///
227 /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
228 /// (6db982c) accessor on the analogous per-ingress-Servico scalar
229 /// axis — same "one typed dispatch on the substrate primitive,
230 /// thin projections at each consumer" discipline extended onto the
231 /// per-`:contratos` caller-Servico byte-string axis.
232 #[must_use]
233 pub fn source(&self) -> &str {
234 self.de.as_str()
235 }
236
237 /// Substrate-canonical per-`:contratos` callee-Servico scalar
238 /// accessor every consumer that reads the edge's destination
239 /// endpoint keys off — returns the author-declared
240 /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
241 /// from the typed slot's own [`String`] storage.
242 ///
243 /// The `:contratos :para` slot names the callee-side member Servico
244 /// on a typed inter-Servico edge (validated by
245 /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
246 /// Aplicacao declares — a stray `:para` that doesn't name a member
247 /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
248 /// callee-attachment miss at cluster-apply time). Callee-side twin
249 /// of the sibling [`WitContract::source`] accessor — the pair
250 /// jointly names the typed edge every renderer that fans on the
251 /// caller-callee identity keys off, and this accessor is also the
252 /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
253 /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
254 /// composes with `destination()` at every emit site that projects a
255 /// per-edge destination Servico's L4 listener port.
256 ///
257 /// Prior to this lift the `.para` byte-string was accessed inline
258 /// at five sites — four caixa-core (the validate-side membership
259 /// lookup at `!names.contains(c.para.as_str())`, the per-edge
260 /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
261 /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
262 /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
263 /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
264 /// — with no compile-time link back to the typed slot. A future
265 /// extension of the `:contratos :para` axis to a richer author
266 /// surface (a multi-callee weighted-fan-out overlay for canary /
267 /// blue-green routing on typed edges, a per-cluster callee-alias
268 /// table the operator pins through a future `:placement`-scoped
269 /// slot, the M4 CR materializer's per-CR admission-webhook that
270 /// promotes the scalar to a callee-set projection) would have had
271 /// to be threaded through every open-coded copy in lockstep or one
272 /// consumer would silently disagree on which callee Servico a given
273 /// edge resolves to (a per-CNP `endpointSelector` that names a
274 /// different destination than its L4 port resolver reads for, a
275 /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
276 /// as distinct while the adjacency map collapses them, or vice
277 /// versa). Lifting to a typed method on the substrate primitive
278 /// means every downstream callee-facing consumer reaches for one
279 /// typed dispatch.
280 ///
281 /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
282 /// (6db982c) accessor — both name the "destination-Servico
283 /// byte-string" concept on their respective mesh-slot atoms (per-
284 /// ingress apex vs. per-typed-edge callee), and both extend the
285 /// substrate-primitive-owns-the-resolver discipline onto the
286 /// per-slot destination-Servico scalar axis. Composes with
287 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
288 /// emit-side per-edge L4 port reader — the composition
289 /// `spec.port_for_destination(c.destination())` pins the CNP per-
290 /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
291 /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
292 /// `spec.port_for_destination(entrada.destination())`.
293 #[must_use]
294 pub fn destination(&self) -> &str {
295 self.para.as_str()
296 }
297
298 /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
299 /// accessor every consumer that reads the edge's WIT world
300 /// discriminator keys off — returns the author-declared
301 /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
302 /// the typed slot's own [`String`] storage.
303 ///
304 /// The `:contratos :wit` slot names the WIT world the typed edge
305 /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
306 /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
307 /// be a well-shaped WIT world reference via
308 /// [`crate::render::is_wit_world_ref`] and by
309 /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
310 /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
311 /// [`WitContract::source`] / [`WitContract::destination`] accessors
312 /// on the same per-`:contratos` entry — the triple
313 /// `( source(), destination(), world_ref() )` jointly names the
314 /// typed edge every renderer that fans on the caller-callee-shape
315 /// identity keys off (the per-edge dedup key at
316 /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
317 /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
318 /// [`caixa_mesh::cilium_network_policies`], the
319 /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
320 /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
321 /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
322 ///
323 /// Prior to this lift the `.wit` byte-string was accessed inline at
324 /// five sites — three caixa-core (the `WitContract::is_*` shape-
325 /// dispatch predicates' `&self.wit` arg, the validate-side empty
326 /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
327 /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
328 /// printer's `{}` format-slot at `c.wit`) — five open-coded
329 /// `.wit` field-accesses that expressed no compile-time link back to
330 /// the typed slot. A future extension of the `:contratos :wit` axis
331 /// to a richer author surface (an M4 promotion from `String` to a
332 /// typed WIT-world enum once the WIT registry stabilizes in tatara-
333 /// lisp per this struct's own `:wit` field docstring, a per-cluster
334 /// WIT-alias table the operator pins through a future
335 /// `:placement`-scoped slot, a canonicalization pass that lowercases
336 /// `wasi:*` prefixes) would have had to be threaded through every
337 /// open-coded copy in lockstep or one consumer would silently
338 /// disagree with the peers on which WIT shape a given edge resolves
339 /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
340 /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
341 /// empty-check that missed a whitespace-only string a peer accessor
342 /// stripped, or vice versa). Lifting to a typed method on the
343 /// substrate primitive means every downstream WIT-shape-facing
344 /// consumer reaches for one typed dispatch — the resolver's
345 /// accept-set migrates as a unit on any future axis addition.
346 ///
347 /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
348 /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
349 /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
350 /// 6db982c), per-`:membros` [`Membro::nome`] /
351 /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
352 /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
353 /// on the substrate primitive, thin projections at each consumer"
354 /// discipline extended onto the last unlifted per-`:contratos`
355 /// scalar (the WIT-world-reference arm).
356 ///
357 /// [fag]: caixa-feira/src/cmd/app.rs
358 #[must_use]
359 pub fn world_ref(&self) -> &str {
360 self.wit.as_str()
361 }
362
363 /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
364 /// payload-target scalar accessor every consumer that reads the
365 /// edge's L7 HTTP request path payload keys off — returns the
366 /// author-declared `:contratos :endpoint` byte-string verbatim as
367 /// an `Option<&str>`, borrowed from the typed slot's own
368 /// `Option<String>` storage; `None` when the slot is absent (the
369 /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
370 /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
371 /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
372 /// [`WitTarget::Capability`] edge carries none of the three).
373 ///
374 /// The `:contratos :endpoint` slot carries the HTTP request path
375 /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
376 /// — same shape required of `:entrada :paths`, gated by the shared
377 /// [`crate::render::is_gateway_api_http_path`] predicate) that
378 /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
379 /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
380 /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
381 /// downstream consumer that reads the payload keys off this scalar
382 /// (the [`WitContract::target`] Http-arm payload extraction that
383 /// materializes [`WitTarget::Http { endpoint }`] under the paired
384 /// [`WitTarget::HTTP_FIELD_NAME`] label, the
385 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
386 /// key's endpoint arm that pins the payload as part of the six-tuple
387 /// dedup key alongside the sibling `:subject`/`:slot` arms, the
388 /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
389 /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
390 /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
391 /// emission path that lands the payload verbatim as a Cilium L7
392 /// `path:` rule).
393 ///
394 /// Prior to this lift the `.endpoint` field was accessed inline at
395 /// two production sites in `caixa-core/src/aplicacao.rs` — the
396 /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
397 /// self.endpoint.as_deref();` binding at the top of the method, and
398 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
399 /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
400 /// field-accesses that expressed no compile-time link back to the
401 /// typed slot. A future extension of the `:contratos :endpoint`
402 /// axis to a richer author surface (an M4 promotion from
403 /// `Option<String>` to a typed HTTP path-template enum once the
404 /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
405 /// this struct's own `:wit` field docstring, a per-cluster endpoint-
406 /// alias table the operator pins through a future `:placement`-
407 /// scoped slot, a canonicalization pass that percent-encodes non-
408 /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
409 /// materializer applies per-tenant) would have had to be threaded
410 /// through both open-coded copies in lockstep or the two consumers
411 /// would silently disagree on which HTTP path a given edge resolves
412 /// to — the [`WitContract::target`] payload-extraction reading
413 /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
414 /// the operator-resolved `"/tenant-a/lookup"` would silently split
415 /// the [`WitTarget::Http`]-arm rendered payload from the actual
416 /// dedup-key uniqueness axis, a two-consumer split at the validator
417 /// far from the source `caixa.lisp` with no field naming the
418 /// payload-drift root cause. Lifting the resolution rule to a typed
419 /// method on the substrate primitive means every downstream
420 /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
421 /// L7-payload surface reaches for exactly one typed dispatch — the
422 /// resolver's accept-set migrates as a unit on any future axis
423 /// addition.
424 ///
425 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
426 /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
427 /// accessors on the M3 mesh-slot family — same "one typed dispatch
428 /// on the substrate primitive, thin projections at each consumer"
429 /// discipline extended onto the per-`:contratos` HTTP-shaped
430 /// payload-carrier `Option<String>` optional-scalar axis. First
431 /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
432 /// atom — opens the "optional per-slot payload-carrier scalar"
433 /// projection pattern the sibling per-`:contratos` `:subject` /
434 /// `:slot` future lifts fold on, matching the closed
435 /// per-`:contratos` scalar-value accessor family
436 /// ([`WitContract::source`] / [`WitContract::destination`] /
437 /// [`WitContract::world_ref`]) already lifted onto the mandatory-
438 /// scalar `String` axes. Named `endpoint()` to match the storage
439 /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
440 /// author-facing label const; the accessor's identity name maps
441 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
442 /// docstring already carries.
443 #[must_use]
444 pub fn endpoint(&self) -> Option<&str> {
445 self.endpoint.as_deref()
446 }
447
448 /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
449 /// payload-target scalar accessor every consumer that reads the
450 /// edge's NATS / Kafka publish subject payload keys off — returns
451 /// the author-declared `:contratos :subject` byte-string verbatim
452 /// as an `Option<&str>`, borrowed from the typed slot's own
453 /// `Option<String>` storage; `None` when the slot is absent (the
454 /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
455 /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
456 /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
457 /// [`WitTarget::Capability`] edge carries none of the three).
458 ///
459 /// The `:contratos :subject` slot carries the NATS / Kafka publish
460 /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
461 /// per-edge target selector — `orders.paid`, `events.>`, whatever
462 /// subject namespace the author names on the pub-sub edge) that
463 /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
464 /// arm's `subject: &'a str` payload when the edge's `:wit` world
465 /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
466 /// downstream consumer that reads the payload keys off this scalar
467 /// (the [`WitContract::target`] PubSub-arm payload extraction that
468 /// materializes [`WitTarget::PubSub { subject }`] under the paired
469 /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
470 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
471 /// key's subject arm that pins the payload as part of the six-tuple
472 /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
473 /// future M4 per-edge WIT registry resolver's pub-sub-arm
474 /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
475 /// materializer's per-edge NATS admission webhook, the future
476 /// caixa-mesh L4 CNP emission path that lands the payload verbatim
477 /// as a NATS subject the operator pins per-CR).
478 ///
479 /// Prior to this lift the `.subject` field was accessed inline at
480 /// two production sites in `caixa-core/src/aplicacao.rs` — the
481 /// [`WitContract::target`] payload-shape dispatch's `let subject =
482 /// self.subject.as_deref();` binding at the top of the method, and
483 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
484 /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
485 /// field-accesses that expressed no compile-time link back to the
486 /// typed slot. A future extension of the `:contratos :subject` axis
487 /// to a richer author surface (an M4 promotion from `Option<String>`
488 /// to a typed NATS-subject-template enum once the WIT registry
489 /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
490 /// struct's own `:wit` field docstring, a per-cluster subject-alias
491 /// table the operator pins through a future `:placement`-scoped
492 /// slot, a canonicalization pass that lowercases / dedupes wildcard
493 /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
494 /// applies per-tenant) would have had to be threaded through both
495 /// open-coded copies in lockstep or the two consumers would silently
496 /// disagree on which NATS subject a given edge resolves to — the
497 /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
498 /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
499 /// resolved `"tenant-a.orders.paid"` would silently split the
500 /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
501 /// key uniqueness axis, a two-consumer split at the validator far
502 /// from the source `caixa.lisp` with no field naming the payload-
503 /// drift root cause. Lifting the resolution rule to a typed method
504 /// on the substrate primitive means every downstream pub-sub-payload-
505 /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
506 /// surface reaches for exactly one typed dispatch — the resolver's
507 /// accept-set migrates as a unit on any future axis addition.
508 ///
509 /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
510 /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
511 /// carrier axis — second `Option<&str>`-return accessor on the
512 /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
513 /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
514 /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
515 /// key/value-store arm as the last unlifted per-`:contratos`
516 /// `Option<String>` axis. Named `subject()` to match the storage
517 /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
518 /// author-facing label const; the accessor's identity name maps
519 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
520 /// docstring already carries.
521 #[must_use]
522 pub fn subject(&self) -> Option<&str> {
523 self.subject.as_deref()
524 }
525
526 /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
527 /// shaped payload-target scalar accessor every consumer that reads
528 /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
529 /// off — returns the author-declared `:contratos :slot` byte-string
530 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
531 /// own `Option<String>` storage; `None` when the slot is absent
532 /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
533 /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
534 /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
535 /// [`WitTarget::Capability`] edge carries none of the three).
536 ///
537 /// The `:contratos :slot` slot carries the key/value store
538 /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
539 /// arm's per-edge target selector — `carts/{cart_id}`,
540 /// `sessions/{tenant}/{sid}`, whatever key-template the author
541 /// names on the store edge) that [`WitContract::target`] projects
542 /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
543 /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
544 /// accept-set. Every downstream consumer that reads the payload
545 /// keys off this scalar (the [`WitContract::target`] Store-arm
546 /// payload extraction that materializes [`WitTarget::Store { slot }`]
547 /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
548 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
549 /// key's store arm that pins the payload as part of the six-tuple
550 /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
551 /// the future M4 per-edge WIT registry resolver's store-arm
552 /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
553 /// materializer's per-edge key/value admission webhook, the future
554 /// caixa-mesh L4 CNP emission path that lands the payload verbatim
555 /// as a key-template the operator pins per-CR).
556 ///
557 /// Prior to this lift the `.slot` field was accessed inline at two
558 /// production sites in `caixa-core/src/aplicacao.rs` — the
559 /// [`WitContract::target`] payload-shape dispatch's `let slot =
560 /// self.slot.as_deref();` binding at the top of the method, and
561 /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
562 /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
563 /// field-accesses that expressed no compile-time link back to the
564 /// typed slot. A future extension of the `:contratos :slot` axis
565 /// to a richer author surface (an M4 promotion from `Option<String>`
566 /// to a typed key-template enum once the WIT registry stabilizes
567 /// key-template parameter shapes in tatara-lisp per this struct's
568 /// own `:wit` field docstring, a per-cluster slot-alias table the
569 /// operator pins through a future `:placement`-scoped slot, a
570 /// canonicalization pass that lowercases the bucket prefix, a
571 /// per-CR fully-qualified rewrite the M4 CR materializer applies
572 /// per-tenant) would have had to be threaded through both
573 /// open-coded copies in lockstep or the two consumers would
574 /// silently disagree on which key-template a given edge resolves
575 /// to — the [`WitContract::target`] payload-extraction reading
576 /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
577 /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
578 /// would silently split the [`WitTarget::Store`]-arm rendered
579 /// payload from the actual dedup-key uniqueness axis, a
580 /// two-consumer split at the validator far from the source
581 /// `caixa.lisp` with no field naming the payload-drift root cause.
582 /// Lifting the resolution rule to a typed method on the substrate
583 /// primitive means every downstream store-payload-facing consumer
584 /// of the Aplicacao's per-`:contratos` payload surface reaches for
585 /// exactly one typed dispatch — the resolver's accept-set migrates
586 /// as a unit on any future axis addition.
587 ///
588 /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
589 /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
590 /// accessors on the M3 mesh-slot payload-carrier axis — third and
591 /// final `Option<&str>`-return accessor on the per-`:contratos`
592 /// mesh-slot atom, closes the last unlifted per-`:contratos`
593 /// `Option<String>` axis and completes the "optional per-slot
594 /// payload-carrier scalar" projection pattern the peer HTTP /
595 /// pub-sub arms established across the three payload-shape
596 /// dispatch arms. Named `slot()` to match the storage field's
597 /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
598 /// author-facing label const; the accessor's identity name maps
599 /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
600 /// docstring already carries.
601 #[must_use]
602 pub fn slot(&self) -> Option<&str> {
603 self.slot.as_deref()
604 }
605
606 /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
607 /// caller-callee-pair accessor every consumer that constructs an
608 /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
609 /// caller-callee pair keys off — returns the author-declared
610 /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
611 /// owned `(String, String)` tuple, projected through the lifted
612 /// [`WitContract::source`] / [`WitContract::destination`] scalar
613 /// accessors so any future rebrand on the caller-arm / callee-arm
614 /// projection axis (an M4 per-cluster caller-alias table the
615 /// operator pins through a future `:placement`-scoped slot, a
616 /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
617 /// a per-`:membros` alias overlay from the future `:membros
618 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
619 /// acknowledges) reaches every diagnostic-construction site by
620 /// construction.
621 ///
622 /// The `(de, para)` pair is the "typed-edge caller-callee identity in
623 /// owned form" primitive every per-`:contratos` diagnostic variant on
624 /// [`AplicacaoError`] carries alongside its payload-shape arm — the
625 /// nine variants [`AplicacaoError::EmptyWit`],
626 /// [`AplicacaoError::ContratoEndpointEmpty`],
627 /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
628 /// [`AplicacaoError::ContratoEndpointInvalid`],
629 /// [`AplicacaoError::ContratoSubjectEmpty`],
630 /// [`AplicacaoError::ContratoSubjectInvalid`],
631 /// [`AplicacaoError::ContratoSlotEmpty`],
632 /// [`AplicacaoError::ContratoSlotInvalid`], and
633 /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
634 /// para: String` field pair the constructor site reads verbatim off
635 /// the [`WitContract`] the diagnostic points at, so a diagnostic
636 /// whose `de:` and `para:` labels silently drift off the source
637 /// caller/callee — a per-cluster caller-alias rewrite that landed on
638 /// one variant's inline `de: c.de.clone()` field access but not on
639 /// its sibling variant's, an accidental swap of the `de:` and `para:`
640 /// arms in a copy-paste of the constructor block — would emit a
641 /// build-time error whose "which caixa is at fault" question the
642 /// operator answers wrongly, far from the source `caixa.lisp`.
643 ///
644 /// Prior to this lift the `(self.de.clone(), self.para.clone())`
645 /// pair was inlined at seven [`WitContract::target`] error-
646 /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
647 /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
648 /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
649 /// the [`AplicacaoError::ContratoSubjectEmpty`] /
650 /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
651 /// the [`AplicacaoError::ContratoSlotEmpty`] /
652 /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
653 /// two [`AplicacaoSpec::validate`] error-construction sites (the
654 /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
655 /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
656 /// insert-first-seen closure) — nine open-coded `.de.clone() +
657 /// .para.clone()` pairs that expressed no compile-time contract that
658 /// the caller-arm and callee-arm arms of the same diagnostic
659 /// construction reach for the same [`WitContract`] instance or that
660 /// the `de:` and `para:` label pair binds to the fields the author
661 /// declared. Any future rebrand on the axis — an M4 per-cluster
662 /// caller/callee-alias rewrite the operator pins through a future
663 /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
664 /// per-CR fully-qualified namespace prefix the M4
665 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
666 /// per-tenant, a canonicalization pass that lowercases the caller +
667 /// callee identifiers post-parse — would have had to be threaded
668 /// through every open-coded copy in lockstep or one variant's
669 /// diagnostic would silently name a different caller/callee pair
670 /// than its peer, silently degrading the "which caixa is at fault"
671 /// self-locating signal every operator-facing typed diagnostic
672 /// exists to carry. Lifting the pair to a typed method on the
673 /// substrate primitive means every downstream diagnostic-construction
674 /// site reaches for exactly one typed dispatch — the resolver's
675 /// projection migrates as a unit on any future axis addition.
676 ///
677 /// Peer of the sibling per-`:contratos` scalar accessor family
678 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
679 /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
680 /// scalar-value axes — first composite-projection accessor on the
681 /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
682 /// form `.clone()` field-accesses that pair the sibling
683 /// caller/callee accessors' `&str`-return borrowed-form outputs onto
684 /// one typed dispatch. Named `edge_pair()` to reflect the identity
685 /// name of the projected tuple (the typed-edge caller-callee pair,
686 /// distinct from the sibling triple-projection
687 /// [`WitContract::edge_triple`] accessor that folds the local `edge`
688 /// closure in [`WitContract::target`] + the paired
689 /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
690 /// site's `(de, para, wit)` triple onto one typed dispatch).
691 #[must_use]
692 pub fn edge_pair(&self) -> (String, String) {
693 (self.source().to_string(), self.destination().to_string())
694 }
695
696 /// Owned form of the `(:contratos :de, :contratos :para, :contratos
697 /// :wit)` triple every per-edge diagnostic constructor that names
698 /// all three axes threads verbatim into its `de:` / `para:` /
699 /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
700 /// / missing-target / invalid-wit / capability-with-payload arms
701 /// (eight sites all shape `let (de, para, wit) = edge();
702 /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
703 /// accessor landed) and the sibling
704 /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
705 /// constructor (which paired `edge_pair()` for the `(de, para)`
706 /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
707 /// typed-dispatch + raw-field-access shape the sibling accessor
708 /// family already flagged as a drift risk). Nine total call sites
709 /// collapse onto this helper.
710 ///
711 /// Lifted with the same one-source-of-truth discipline
712 /// [`WitContract::edge_pair`] carries on the paired
713 /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
714 /// arms compose through the lifted [`WitContract::source`] /
715 /// [`WitContract::destination`] / [`WitContract::world_ref`]
716 /// scalar accessors byte-for-byte (pinned by the paired
717 /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
718 /// composition-pin), so any future rebrand on the per-`:contratos`
719 /// caller / callee / world-ref axis (an M4 per-cluster
720 /// caller/callee-alias rewrite the operator pins through a future
721 /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
722 /// per-CR fully-qualified namespace prefix the M4
723 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
724 /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
725 /// on `source()` / `destination()`, a per-CR canonicalization pass
726 /// that lowercases the WIT world ref post-parse) migrates as a
727 /// single caixa-core edit rather than a coordinated rewrite of
728 /// nine open-coded triple-constructors.
729 ///
730 /// Peer of the sibling per-`:contratos` composite-projection
731 /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
732 /// composite-value axes — closes the last unlifted owned-form
733 /// composite-tuple axis on the per-`:contratos` diagnostic-
734 /// construction surface. Named `edge_triple()` to reflect the
735 /// identity name of the projected tuple (the typed-edge
736 /// caller-callee-wit triple, sibling to the caller-callee-only
737 /// pair `edge_pair()` returns).
738 #[must_use]
739 pub fn edge_triple(&self) -> (String, String, String) {
740 (
741 self.source().to_string(),
742 self.destination().to_string(),
743 self.world_ref().to_string(),
744 )
745 }
746
747 /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
748 /// dedups typed edges keys off — routes through the lifted
749 /// [`WitContract::source`] / [`WitContract::destination`] /
750 /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
751 /// [`WitContract::subject`] / [`WitContract::slot`] scalar
752 /// accessors so the tuple's six arms and the [`ContratoIdentity`]
753 /// type alias's six axes migrate as a unit on any future axis
754 /// addition (adding a seventh field to [`WitContract`] is one
755 /// [`ContratoIdentity`] alias edit + one accessor addition + one
756 /// arm here, not a coordinated rewrite of every open-coded
757 /// six-tuple builder that dedups on the identity axis).
758 ///
759 /// Sibling of [`WitContract::edge_pair`] /
760 /// [`WitContract::edge_triple`] on the composite-projection axis:
761 /// the pair projects the caller-callee axes, the triple extends it
762 /// with the world-ref, this method extends it with the three
763 /// payload-carrier axes. Every projection returns the same six
764 /// scalar accessors' outputs; the three methods differ only in
765 /// which arms they surface.
766 #[must_use]
767 pub fn identity(&self) -> ContratoIdentity<'_> {
768 (
769 self.source(),
770 self.destination(),
771 self.world_ref(),
772 self.endpoint(),
773 self.subject(),
774 self.slot(),
775 )
776 }
777
778 /// True when this contract targets an HTTP-shaped WIT world.
779 #[must_use]
780 pub fn is_http(&self) -> bool {
781 wit_shape_is_http(self.world_ref())
782 }
783
784 /// True when this contract targets a pub-sub-shaped WIT world.
785 #[must_use]
786 pub fn is_pubsub(&self) -> bool {
787 wit_shape_is_pubsub(self.world_ref())
788 }
789
790 /// True when this contract targets a key/value-shaped WIT world.
791 #[must_use]
792 pub fn is_store(&self) -> bool {
793 wit_shape_is_store(self.world_ref())
794 }
795
796 /// True when this contract's caller equals its callee — a
797 /// structurally degenerate typed edge that no `:contratos` entry can
798 /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
799 /// Servico B" is an *inter*-Servico contract between two distinct
800 /// graph nodes). A Servico contracting with itself resolves to an
801 /// in-process call the wasm-engine never routes through the mesh at
802 /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
803 /// per-edge policy can express the intended shape — the pub-sub
804 /// path silently rendered a self-allow rule that is a no-op (intra-
805 /// pod traffic bypasses the mesh entirely), and the synchronous
806 /// paths surfaced as a misleading `ContratoCycle` whose path was
807 /// `["cart", "cart"]` — framing a self-edge as a multi-node
808 /// deadlock. Every downstream consumer that must reject the shape
809 /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
810 /// gate at caixa-core/src/aplicacao.rs:5559, every future
811 /// per-`:contratos`-edge policy resolver on the M4 CR materializer
812 /// axis, every future adjacency-graph builder that must skip self-
813 /// edges rather than fold them into an incidental cycle) now keys
814 /// off exactly one typed dispatch on the substrate primitive, so
815 /// any future rebrand on the axis (an M4-typed-caller enum whose
816 /// identity comparison rule the accessor could route through, an
817 /// operator-side per-cluster caller/callee-alias table the
818 /// materializer resolves per-CR before the equality probe, a
819 /// promotion of the pointwise `==` to a set-membership check once
820 /// SimpleOneForOne-shaped dynamic replicas come into typed scope
821 /// so a per-replica self-edge is rejected under the same predicate)
822 /// migrates as a single caixa-core edit rather than a coordinated
823 /// rewrite of every downstream self-edge consumer. Composes
824 /// byte-for-byte through the lifted [`Self::source`] /
825 /// [`Self::destination`] scalar accessors — the accessor pair every
826 /// per-`:contratos` scalar-value axis already routes through — so
827 /// any future rebrand of the underlying `:de` / `:para` storage
828 /// (a lift from `String` to a typed `ServicoName(String)` newtype,
829 /// a per-Aplicacao interning arena the M4 CR materializer authors,
830 /// a `smol_str::SmolStr` inline-buffer swap) flows through the
831 /// same one body without a coordinated per-consumer rewrite.
832 ///
833 /// Sibling in shape to the peer per-`:contratos` shape-predicate
834 /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
835 /// on the `:wit` world-ref axis — extended onto the per-edge
836 /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
837 /// partition the WIT-shape-space; `is_self_loop` partitions the
838 /// caller-callee identity-space. Named `is_self_loop()` to reflect
839 /// the graph-theoretic identity of the shape (a loop from a graph
840 /// node to itself, distinct from the sibling multi-node
841 /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
842 /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
843 /// variant already carrying the term.
844 #[must_use]
845 pub fn is_self_loop(&self) -> bool {
846 self.source() == self.destination()
847 }
848
849 /// Typed view of the contract's payload target. Enforces that the
850 /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
851 /// fields agree, and that each carried value is itself
852 /// value-shape valid:
853 ///
854 /// - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
855 /// non-empty, leading-`/` (Cilium L7 `path` + Gateway API
856 /// `PathPrefix` invariant — same shape required of `:entrada
857 /// :paths`)
858 /// - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
859 /// non-empty (NATS / Kafka publish without a subject is a
860 /// no-op subscribe, never the author's intent)
861 /// - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
862 /// non-empty (an empty slot template addresses the bucket
863 /// root, defeating the per-key isolation the slot exists for)
864 /// - Anything else ⇒ none of the three; the contract is a pure
865 /// typed capability edge with no payload selector.
866 ///
867 /// Translates the Apollo Federation discipline ("conflicts are
868 /// errors at compile time, not warnings at runtime";
869 /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
870 /// a contract whose WIT shape disagrees with its target field, or
871 /// whose target field carries a value-shape-invalid string, is a
872 /// build error — not a silent renderer drop. The returned
873 /// [`WitTarget`] view's `&str` payload is therefore guaranteed
874 /// non-empty (and absolute, for `Http`); every downstream consumer
875 /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
876 /// the M4 per-edge policy resolver) can rely on that without
877 /// re-checking.
878 pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
879 // Route the HTTP-shaped payload-target extraction through the
880 // lifted [`WitContract::endpoint`] accessor rather than the raw
881 // `self.endpoint.as_deref()` field access — the two production
882 // consumers of the per-`:contratos :endpoint` HTTP-shaped
883 // payload-carrier scalar (this method's Http-arm payload
884 // extraction, the [`AplicacaoSpec::validate`] duplicate-
885 // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
886 // off exactly one typed dispatch on the substrate primitive, so
887 // any future rebrand on the axis (an M4 per-cluster endpoint-
888 // alias rewrite, a per-CR fully-qualified path prefix the M4
889 // materializer applies per-tenant, an M4 promotion from
890 // `Option<String>` to a typed HTTP path-template enum) migrates
891 // as a single caixa-core edit rather than a coordinated rewrite
892 // of the two call sites — peer of the sibling M3 per-`:placement`
893 // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
894 // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
895 // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
896 let endpoint = self.endpoint();
897 let subject = self.subject();
898 // Route the store-arm payload-carrier scalar through the
899 // lifted [`WitContract::slot`] accessor rather than the raw
900 // `self.slot.as_deref()` field access — the two production
901 // consumers of the per-`:contratos :slot` key/value-store-
902 // shaped payload-carrier scalar (this method's Store-arm
903 // payload extraction, the [`AplicacaoSpec::validate`]
904 // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
905 // arm) now key off exactly one typed dispatch on the substrate
906 // primitive. Closes the last unlifted per-`:contratos`
907 // `Option<String>` axis, completing the payload-carrier
908 // accessor family peer of the sibling per-`:contratos`
909 // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
910 // (90de675) lifts across the HTTP / pub-sub arms.
911 let slot = self.slot();
912 // Route the local `(de, para, wit)` triple-projection closure
913 // through the lifted [`WitContract::edge_triple`] typed accessor
914 // rather than re-inlining `(self.de.clone(), self.para.clone(),
915 // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
916 // triple-carrying diagnostic constructors below (wrong-target /
917 // missing-target on all three payload arms + capability-with-
918 // payload + invalid-wit) now key off exactly one typed dispatch
919 // on the substrate-primitive composite projection, sibling to
920 // the peer [`WitContract::edge_pair`]-routed
921 // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
922 // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
923 // diagnostic constructors on the same per-`:contratos`
924 // diagnostic-construction surface.
925 let edge = || self.edge_triple();
926
927 // The `:wit` value drives every downstream dispatch — the
928 // is_http/is_pubsub/is_store prefix matchers below, the
929 // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
930 // exclusion. Until this gate landed `target()` accepted any
931 // non-empty string and silently demoted unrecognized shapes to
932 // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
933 // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
934 // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
935 // package, the paste-from-binary footgun a multi-line blob
936 // accidentally landing in the slot, the un-percent-encoded
937 // non-ASCII byte) — the canonical "I thought I had L7 HTTP
938 // routing, got L4-only" footgun. Empty is still pre-checked at
939 // the [`AplicacaoSpec::validate`] call site via the narrower
940 // [`AplicacaoError::EmptyWit`] variant (and fires first at the
941 // validate layer); the value-shape gate here picks up the
942 // structurally-invalid non-empty cases the empty check misses,
943 // and remains correct under direct `target()` calls outside
944 // validate (the predicate's defensive empty arm returns a
945 // parser-shaped reason rather than silently falling through to
946 // the Capability arm). Same trajectory as c4213a4 (WitContract
947 // endpoint/subject/slot value-shape gates lifted into
948 // `target()`) on the peer payload axes.
949 if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
950 let (de, para, wit) = edge();
951 return Err(AplicacaoError::ContratoWitInvalid {
952 de,
953 para,
954 wit,
955 reason,
956 });
957 }
958
959 if self.is_http() {
960 if subject.is_some() || slot.is_some() {
961 let (de, para, wit) = edge();
962 return Err(AplicacaoError::ContratoWrongTarget {
963 de,
964 para,
965 wit,
966 expected: WitTarget::HTTP_FIELD_NAME,
967 });
968 }
969 let ep = endpoint.ok_or_else(|| {
970 let (de, para, wit) = edge();
971 AplicacaoError::ContratoMissingTarget {
972 de,
973 para,
974 wit,
975 expected: WitTarget::HTTP_FIELD_NAME,
976 }
977 })?;
978 if ep.is_empty() {
979 let (de, para) = self.edge_pair();
980 return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
981 }
982 if !ep.starts_with('/') {
983 let (de, para) = self.edge_pair();
984 return Err(AplicacaoError::ContratoEndpointNotAbsolute {
985 de,
986 para,
987 endpoint: ep.to_string(),
988 });
989 }
990 // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
991 // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
992 // API v1 HTTPPathMatch.value admission grammar with the
993 // sibling `:entrada :paths` axis. Until this gate landed
994 // `target()` only refused the empty string + the missing-
995 // leading-`/` form; a structurally invalid endpoint
996 // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
997 // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
998 // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
999 // path-traversal segment, the >1024-byte slug) silently
1000 // passed validate and the failure surfaced at apply time
1001 // as a Cilium policy rejection / silent traffic drop, far
1002 // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1003 // grammar `:entrada :paths` already gates (55410e4), now
1004 // shared with `:contratos :endpoint` through the lifted
1005 // `crate::render::is_gateway_api_http_path` predicate.
1006 if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1007 let (de, para) = self.edge_pair();
1008 return Err(AplicacaoError::ContratoEndpointInvalid {
1009 de,
1010 para,
1011 endpoint: ep.to_string(),
1012 reason,
1013 });
1014 }
1015 return Ok(WitTarget::Http { endpoint: ep });
1016 }
1017 if self.is_pubsub() {
1018 if endpoint.is_some() || slot.is_some() {
1019 let (de, para, wit) = edge();
1020 return Err(AplicacaoError::ContratoWrongTarget {
1021 de,
1022 para,
1023 wit,
1024 expected: WitTarget::PUBSUB_FIELD_NAME,
1025 });
1026 }
1027 let s = subject.ok_or_else(|| {
1028 let (de, para, wit) = edge();
1029 AplicacaoError::ContratoMissingTarget {
1030 de,
1031 para,
1032 wit,
1033 expected: WitTarget::PUBSUB_FIELD_NAME,
1034 }
1035 })?;
1036 if s.is_empty() {
1037 let (de, para) = self.edge_pair();
1038 return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1039 }
1040 // The `:subject` lands at runtime as the NATS subject the
1041 // producer publishes to and the consumer subscribes from.
1042 // Until this gate landed `target()` only refused the
1043 // empty string; a structurally invalid subject
1044 // (`"foo..bar"` — empty token between separators,
1045 // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1046 // server's subject parser rejects, `"foo bar"` —
1047 // un-percent-encoded whitespace, `"foo.café"` —
1048 // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1049 // empty leading/trailing tokens, the >256-byte
1050 // paste-from-binary slug) silently passed validate and
1051 // the failure surfaced at runtime as a NATS server-side
1052 // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1053 // a silent message drop, far from the source caixa.lisp.
1054 // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1055 // trajectory `:contratos :endpoint` (4f0390b) and
1056 // `:contratos :wit` (6226bf4) already gate, now shared
1057 // with `:contratos :subject` through the lifted
1058 // `crate::render::is_nats_subject` predicate.
1059 if let Err(reason) = crate::render::is_nats_subject(s) {
1060 let (de, para) = self.edge_pair();
1061 return Err(AplicacaoError::ContratoSubjectInvalid {
1062 de,
1063 para,
1064 subject: s.to_string(),
1065 reason,
1066 });
1067 }
1068 return Ok(WitTarget::PubSub { subject: s });
1069 }
1070 if self.is_store() {
1071 if endpoint.is_some() || subject.is_some() {
1072 let (de, para, wit) = edge();
1073 return Err(AplicacaoError::ContratoWrongTarget {
1074 de,
1075 para,
1076 wit,
1077 expected: WitTarget::STORE_FIELD_NAME,
1078 });
1079 }
1080 let sl = slot.ok_or_else(|| {
1081 let (de, para, wit) = edge();
1082 AplicacaoError::ContratoMissingTarget {
1083 de,
1084 para,
1085 wit,
1086 expected: WitTarget::STORE_FIELD_NAME,
1087 }
1088 })?;
1089 if sl.is_empty() {
1090 let (de, para) = self.edge_pair();
1091 return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1092 }
1093 // Value-shape gate on the third (and last) typed payload
1094 // axis the `WitContract::target` dispatch carries — the
1095 // peer of [`crate::render::is_gateway_api_http_path`] for
1096 // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1097 // for `:subject` (63e18a0). Until this gate landed
1098 // `target()` only refused the empty string; a structurally
1099 // invalid slot (`"check out/$order"` — un-percent-encoded
1100 // whitespace whose runtime behavior varies unpredictably
1101 // across kv backends, `"checkout/\x01order"` — control
1102 // character that Redis admits but corrupts on next read
1103 // and DynamoDB rejects outright, `"chéckout/$order"` —
1104 // un-percent-encoded non-ASCII byte each backend re-encodes
1105 // differently, `"checkout\n/$order"` — embedded newline,
1106 // the 513-byte paste-from-binary slug) silently passed
1107 // validate and surfaced at runtime as a per-backend kv
1108 // write rejection (DynamoDB / etcd) or as a silent
1109 // next-read corruption (Redis-via-RESP3), far from the
1110 // source caixa.lisp with no field naming which `:contratos`
1111 // edge carried the typo. The lifted predicate makes the
1112 // kv-backend intersection-floor a substrate-level
1113 // invariant at validate time, not a runtime "this passed
1114 // validate but the kv backend rejected on first write"
1115 // surprise — closes the typed payload-axis value-shape
1116 // trajectory across all three legs of the four
1117 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1118 // that caixa-mesh + the future kv emitters land in.
1119 if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1120 let (de, para) = self.edge_pair();
1121 return Err(AplicacaoError::ContratoSlotInvalid {
1122 de,
1123 para,
1124 slot: sl.to_string(),
1125 reason,
1126 });
1127 }
1128 return Ok(WitTarget::Store { slot: sl });
1129 }
1130
1131 // Unrecognized WIT world — must not carry any payload target.
1132 if endpoint.is_some() || subject.is_some() || slot.is_some() {
1133 let (de, para, wit) = edge();
1134 return Err(AplicacaoError::ContratoWrongTarget {
1135 de,
1136 para,
1137 wit,
1138 expected: WitTarget::CAPABILITY_EXPECTED,
1139 });
1140 }
1141 Ok(WitTarget::Capability)
1142 }
1143}
1144
1145/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1146/// gate (see [`AplicacaoSpec::validate`]): every field that
1147/// distinguishes one contract from another, in declaration order
1148/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1149/// with equal [`ContratoIdentity`]s are the same typed edge declared
1150/// twice — the graph-edge analogue of duplicate `:membros` /
1151/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1152/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1153/// clippy's `type_complexity` lint (and so a future axis added to
1154/// `WitContract` is one alias edit, not a coordinated rewrite of
1155/// every set instantiation).
1156pub type ContratoIdentity<'a> = (
1157 &'a str,
1158 &'a str,
1159 &'a str,
1160 Option<&'a str>,
1161 Option<&'a str>,
1162 Option<&'a str>,
1163);
1164
1165/// Typed view of a [`WitContract`]'s payload target. Each variant
1166/// carries the field its WIT shape requires; constructing a `Http`
1167/// view without an endpoint is impossible by the type system.
1168///
1169/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1170/// instead of probing `Option<String>` fields one by one — the
1171/// "which payload field is set?" question is answered once, at
1172/// validation time.
1173#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1174pub enum WitTarget<'a> {
1175 /// HTTP-shaped WIT world. Carries the configured request path.
1176 Http { endpoint: &'a str },
1177 /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1178 ///
1179 /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1180 /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1181 /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1182 /// method name byte-identical to the sibling
1183 /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1184 /// arm-discriminator that routes through
1185 /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1186 /// through `matches!` on the variant), so the two arm-discriminator
1187 /// axes — target-side variant-arm and shape-side ref-prefix — reach
1188 /// every downstream consumer through the same `is_pubsub()` name.
1189 #[is_variant(name = "pubsub")]
1190 PubSub { subject: &'a str },
1191 /// Key-value-shaped WIT world. Carries the slot template.
1192 Store { slot: &'a str },
1193 /// A typed capability edge with no payload selector — the WIT
1194 /// world stands on its own (rare; reserved for plain capability
1195 /// imports or M4-and-later WIT worlds we haven't shaped yet).
1196 Capability,
1197}
1198
1199impl<'a> WitTarget<'a> {
1200 /// Canonical author-facing `:contratos` payload field name for the
1201 /// HTTP-shaped arm — the `expected: &'static str` scalar the
1202 /// [`AplicacaoError::ContratoMissingTarget`] /
1203 /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1204 /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1205 /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1206 /// the `feira app graph` verb prints. Peer of
1207 /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1208 /// on the payload-field-name axis; declared as a peer const next
1209 /// to the [`WitTarget::Http`] variant so a future rename on the
1210 /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1211 /// :endpoint …)))` field lands in exactly one place, not scattered
1212 /// across the [`WitContract::target`] gate's six `expected:`
1213 /// literals, the label template, and every downstream consumer
1214 /// that prints a per-arm prefix. Same trajectory as the peer
1215 /// [`WitTarget::label`] lift (174e96a): a single source of truth
1216 /// for the arm's shape, next to the variant declaration.
1217 pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1218 /// Canonical author-facing `:contratos` payload field name for the
1219 /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1220 /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1221 /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1222 pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1223 /// Canonical author-facing `:contratos` payload field name for the
1224 /// key/value-store-shaped arm. Peer of
1225 /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1226 /// on the payload-field-name axis; see
1227 /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1228 pub const STORE_FIELD_NAME: &'static str = "slot";
1229
1230 /// Canonical stable human-readable label the payload-less
1231 /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1232 /// the byte-string every consumer that formats a payload-less
1233 /// typed capability edge as text lands on (the
1234 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1235 /// naming which identical edge was declared twice, the future
1236 /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1237 /// policy resolver's audit view, the operator's mesh-graph audit).
1238 /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1239 /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1240 /// author-facing label-scalar consts — the same
1241 /// "one canonical declaration per arm, next to the variant, so a
1242 /// future rename lands in one place" discipline extended to the
1243 /// payload-less arm. Until this lift landed the byte-string sat
1244 /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1245 /// match arm, once in the pin test asserting the label's
1246 /// [`WitTarget::Capability`] output — with no compile-time link
1247 /// between the two: a rebrand on either side (an operator-facing
1248 /// vocabulary shift, a per-consumer disambiguation like
1249 /// `"(capability — no payload; typed edge only)"`) would silently
1250 /// desynchronize until a downstream consumer surfaced the drift at
1251 /// runtime.
1252 pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1253
1254 /// Canonical `expected:` scalar the
1255 /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1256 /// through for the payload-less [`WitTarget::Capability`] arm — the
1257 /// byte-string authors read as "this WIT world's shape is not one
1258 /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1259 /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1260 /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1261 /// [`Self::STORE_FIELD_NAME`] consts on the
1262 /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1263 /// same "which payload field name goes in the diagnostic" dispatch
1264 /// the three payload-arm consts cover, extended to the payload-less
1265 /// arm. Until this lift landed the byte-string sat twice — once
1266 /// inline in the [`Self::target`] Capability-arm rejection at the
1267 /// production dispatch, once in the pin test asserting the
1268 /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1269 /// no compile-time link between the two: a rebrand on either side
1270 /// (an author-facing vocabulary shift to `"capability"` /
1271 /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1272 /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1273 /// [`WitTarget::Capability`] into per-shape peers) would silently
1274 /// desynchronize until a downstream consumer surfaced the drift at
1275 /// runtime. Same "one canonical declaration per arm, next to the
1276 /// variant, so a future rename lands in one place" discipline the
1277 /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1278 /// established for the payload-less arm's human-readable label
1279 /// axis; this lift extends it onto the peer diagnostic-scalar axis
1280 /// so both halves of the "how does the Capability arm surface at
1281 /// its two consumer axes (human-readable label, wrong-target
1282 /// diagnostic)" pipeline route through peer consts declared next
1283 /// to the variant.
1284 ///
1285 /// Pairwise-distinctness against the three payload-arm scalars
1286 /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1287 /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1288 /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1289 /// test — the 4-way closure of the 3-way
1290 /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1291 /// the `ContratoWrongTarget::expected` axis, matching the peer
1292 /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1293 /// scalar-value distinctness discipline the sibling M3 typed-enum
1294 /// discriminator axis already carries.
1295 pub const CAPABILITY_EXPECTED: &'static str = "none";
1296
1297 /// The `(author-facing field name, payload)` pair this typed target
1298 /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1299 /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1300 /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1301 /// [`Self::Store`], `None` for the payload-less
1302 /// [`Self::Capability`] arm.
1303 ///
1304 /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1305 /// (formats `":{field} {payload:?}"` on `Some`, falls to
1306 /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1307 /// (returns the first component) route through, so a future
1308 /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1309 /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1310 /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1311 /// exactly one new match-arm here (a compile-time exhaustiveness
1312 /// error otherwise), not a coordinated three-way rewrite of the
1313 /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1314 /// + every downstream consumer that reaches for the pair.
1315 ///
1316 /// Until this lift landed the three payload arms sat in
1317 /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1318 /// invocations (one per variant, each hand-quoting the paired
1319 /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1320 /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1321 /// "same shape, written N times" duplication THEORY.md §I.3.5
1322 /// ("Generation first, composition second, hand-authoring last;
1323 /// the duplication budget is zero") promotes to a build-time
1324 /// concern, with each per-arm site paired to its own const with no
1325 /// compile-time link between the format template and the arm's
1326 /// payload extraction.
1327 #[must_use]
1328 pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1329 match *self {
1330 WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1331 WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1332 WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1333 WitTarget::Capability => None,
1334 }
1335 }
1336
1337 /// The canonical author-facing `:contratos` payload field name
1338 /// this typed target arm carries (`Http` → `Some("endpoint")`,
1339 /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1340 /// `None` for the payload-less `Capability` arm.
1341 ///
1342 /// Routes through [`Self::payload_pair`] — the single 4-arm
1343 /// dispatch [`Self::label`] also reads — so a future variant
1344 /// addition is one match-arm edit at [`Self::payload_pair`], not a
1345 /// per-consumer rewrite. Same "exhaustive-match at one canonical
1346 /// dispatch, thin projections at each consumer" trajectory the
1347 /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1348 /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1349 #[must_use]
1350 pub const fn field_name(&self) -> Option<&'static str> {
1351 match self.payload_pair() {
1352 Some((f, _)) => Some(f),
1353 None => None,
1354 }
1355 }
1356
1357 /// Render this typed target as a stable human-readable label
1358 /// (`:endpoint "/charge"`, `:subject "events.x"`,
1359 /// `:slot "checkout/$order"`, or `(capability — no payload)` when
1360 /// the WIT world is a pure capability edge).
1361 ///
1362 /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
1363 /// gate so the diagnostic names *which* identical edge was
1364 /// declared twice (not just which `(de, para, wit)` triple).
1365 /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1366 /// on the payload-carrying arms (`Some((field, payload)) →
1367 /// format!(":{field} {payload:?}")`) and through the lifted
1368 /// [`Self::CAPABILITY_LABEL`] const on the payload-less
1369 /// [`Self::Capability`] arm — so a future variant addition (the
1370 /// M4-and-later per-edge WIT registry may split [`Self::Http`]
1371 /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1372 /// `Queue`-shaped peer) becomes a single new match-arm on
1373 /// [`Self::payload_pair`] rather than a rewrite of this template
1374 /// (and every downstream consumer that reaches for the label
1375 /// shape: the per-edge policy resolver in M4, the `feira app
1376 /// graph` view, the operator's mesh-graph audit). Until this
1377 /// lift landed the three payload arms carried three near-identical
1378 /// per-arm `format!(":{} {…:?}", …)` invocations, and the
1379 /// [`Self::Capability`] arm carried the payload-less byte-string
1380 /// twice (once inline here, once in the pin test) — closing the
1381 /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
1382 /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
1383 /// / 4a1e490) peer-const lifts already established for the
1384 /// payload-carrying arms.
1385 #[must_use]
1386 pub fn label(&self) -> String {
1387 match self.payload_pair() {
1388 Some((field, payload)) => format!(":{field} {payload:?}"),
1389 None => Self::CAPABILITY_LABEL.to_string(),
1390 }
1391 }
1392}
1393
1394/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
1395/// pretty-printed byte-string every consumer that formats a typed
1396/// payload target as user-facing text lands on (the
1397/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
1398/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
1399/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
1400/// graph` per-`:contratos`-edge payload column that reaches the graph
1401/// verb through `format!("{target}")`, the future M4 per-edge policy
1402/// resolver's per-edge audit-log line, the operator's mesh-graph
1403/// per-edge inspection view) reaches for the same lifted
1404/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
1405/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
1406/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
1407/// routes through — extending the three-path-convergence
1408/// (`Debug` for structural inspection, `Display` for user-facing text,
1409/// per-arm typed accessor for the canonical byte-string) discipline the
1410/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
1411/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
1412/// onto the fourth (and only remaining) typed-shape-discriminator axis
1413/// on the caixa surface.
1414///
1415/// Pre-lift the two paths were structurally independent — every consumer
1416/// reaching for a payload byte-string past the [`WitTarget::label`]
1417/// helper had to pick between three paths ([`WitTarget::label`],
1418/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
1419/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
1420/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
1421/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
1422/// that reached for `format!("{target}")` — the canonical shape every
1423/// user-facing pretty-print site on the sibling typed-enum axes already
1424/// uses — would silently land on the `Debug` derive's structural output
1425/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
1426/// than the `label()` helper's stable byte-string (`:endpoint
1427/// "/charge"` — the author-facing `:contratos` keyword form) the
1428/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
1429/// already threads through. The two spellings would diverge silently in
1430/// every downstream diagnostic / graph / audit line reached through
1431/// `format!` rather than through the `label()` helper. Routing
1432/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
1433/// path: every `format!("{v}")` call reaches the same
1434/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
1435/// and the duplicate-`:contratos` gate already route through, so a
1436/// future variant addition (the M4-and-later per-edge WIT registry may
1437/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
1438/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
1439/// consumer at exactly one place — the [`WitTarget::payload_pair`]
1440/// match — rather than fanning out through hand-rolled per-arm
1441/// [`std::fmt::Display`] arms.
1442///
1443/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
1444/// is the typed view returned by [`WitContract::target`], not a
1445/// closed-set discriminator enum with a gen-platform Discriminant
1446/// registration, so the `Debug` derive's structural output (which every
1447/// `{v:?}` consumer still reaches) stays distinct from the `Display`
1448/// helper's stable pretty-printed byte-string. `Debug` reveals variant
1449/// shape for structural inspection; `Display` (via `label`) reveals the
1450/// stable author-facing payload projection.
1451///
1452/// Pin tests
1453/// [`tests::wit_target_display_routes_through_label_helper`] and
1454/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
1455/// assert the two paths agree byte-for-byte on every variant, so a
1456/// future variant addition or `label()` reimplementation that hand-rolls
1457/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
1458/// build error visible at caixa-core test time, not a silent
1459/// per-consumer dispatch miss at diagnostic / audit / graph time.
1460impl std::fmt::Display for WitTarget<'_> {
1461 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1462 f.write_str(&self.label())
1463 }
1464}
1465
1466// ── one Aplicacao member ─────────────────────────────────────────────
1467
1468/// A Servico participating in the Aplicacao. Same shape as
1469/// `crate::supervisor::ChildSpec` but without a restart policy —
1470/// supervision is per-Servico (each member has its own
1471/// `:supervisor`), the Aplicacao orchestrates *placement*.
1472#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1473#[serde(rename_all = "camelCase")]
1474pub struct Membro {
1475 /// Member caixa's `:nome`. Resolves through the same dep
1476 /// resolution path as `crate::dep::Dep`.
1477 pub caixa: String,
1478
1479 /// Semver constraint.
1480 pub versao: String,
1481}
1482
1483impl Membro {
1484 /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
1485 /// accessor every consumer that reads the member's Servico identity
1486 /// keys off — returns the author-declared `:membros :caixa`
1487 /// byte-string verbatim as a `&str`, borrowed from the typed slot's
1488 /// own [`String`] storage.
1489 ///
1490 /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
1491 /// participating in the Aplicacao — validated by
1492 /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
1493 /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
1494 /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
1495 /// [`validate_no_self_membership`]) — and every downstream consumer
1496 /// that fans on the member's identity keys off this scalar (the
1497 /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
1498 /// lookup, the per-`:membros` duplicate gate's dedup key, the
1499 /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
1500 /// identity, the self-membership gate, the
1501 /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
1502 /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
1503 /// CR materializer's per-member resolver).
1504 ///
1505 /// Prior to this lift the `.caixa` byte-string was read inline at
1506 /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
1507 /// set collector at
1508 /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
1509 /// [`validate_membros`] validation-side member-caixa gate at
1510 /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
1511 /// per-member duplicate-gate dedup key at
1512 /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
1513 /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
1514 /// `adj.entry(m.caixa.as_str()).or_default()`, and the
1515 /// [`validate_no_self_membership`] self-loop gate at
1516 /// `m.caixa == parent_nome`) — five open-coded field-accesses that
1517 /// expressed no compile-time link back to the typed slot. Every
1518 /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
1519 /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
1520 /// `name:` axis, so a future extension of the `:membros :caixa`
1521 /// axis to a richer author surface — a per-cluster alias table the
1522 /// operator pins through a future `:placement`-scoped slot, a
1523 /// namespace-qualified rewrite the M4 CR materializer applies
1524 /// per-CR, a per-member overlay from the future `:membros
1525 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1526 /// acknowledges — would have had to be threaded through every
1527 /// open-coded copy in lockstep or one consumer would silently
1528 /// disagree with the peers on which caixa a given member resolves
1529 /// to. A member-set lookup that treated the name as `"cart"` while
1530 /// the peer adjacency map treated it as `"tenant-a/cart"` would
1531 /// silently split the `:contratos` membership-lookup diagnostic from
1532 /// the cycle-detector's node identity — a two-consumer split at the
1533 /// validator far from the source `caixa.lisp` with no field naming
1534 /// the identity-drift root cause. Lifting the resolution rule to a
1535 /// typed method on the substrate primitive means every downstream
1536 /// consumer of the Aplicacao's per-`:membros` identity surface
1537 /// reaches for exactly one typed dispatch — the resolver's
1538 /// accept-set migrates as a unit on any future axis addition.
1539 ///
1540 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1541 /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1542 /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1543 /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1544 /// destination-Servico scalar accessors — same "one typed dispatch
1545 /// on the substrate primitive, thin projections at each consumer"
1546 /// discipline extended onto the per-`:membros` member-caixa `:nome`
1547 /// byte-string axis. Named `nome()` to match the tatara-lisp
1548 /// author-surface term the field's docstring already reaches for
1549 /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
1550 /// [`crate::dep::Dep::nome`] field-name discipline the substrate
1551 /// already carries — the accessor's name maps directly onto the
1552 /// canonical caixa-identity vocabulary rather than shadowing the
1553 /// field's storage-side `caixa` label.
1554 #[must_use]
1555 pub fn nome(&self) -> &str {
1556 self.caixa.as_str()
1557 }
1558
1559 /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
1560 /// requirement scalar accessor every consumer that reads the
1561 /// member's version pin keys off — returns the author-declared
1562 /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
1563 /// from the typed slot's own [`String`] storage.
1564 ///
1565 /// The `:membros :versao` slot carries the Cargo-shaped semver
1566 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
1567 /// pins which release of the member-caixa the Aplicacao composes
1568 /// against — the same requirement grammar the peer `:deps :versao`
1569 /// / `:children :versao` axes carry, resolved through the shared
1570 /// [`crate::render::require_valid_versao_requirement`] cascade and
1571 /// the shared [`crate::version::parse_requirement`] parser. Every
1572 /// downstream consumer that fans on the member's version pin keys
1573 /// off this scalar (the [`validate_membros`] per-member requirement
1574 /// gate at `require_valid_versao_requirement(m.versao_requirement(),
1575 /// …)`, the [`feira app graph`] per-member `println!(" - {} {}",
1576 /// m.nome(), m.versao_requirement())` line, every future per-cluster
1577 /// version-lock overlay the operator pins through a future
1578 /// `:placement`-scoped slot, the future
1579 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
1580 /// version resolver, the future `feira app deploy` pipeline's
1581 /// per-member lacre BLAKE3-closure lookup).
1582 ///
1583 /// Prior to this lift the `.versao` byte-string was accessed inline
1584 /// at two `&str`-shaped sites — the [`validate_membros`]
1585 /// requirement-gate call `require_valid_versao_requirement(&m.versao,
1586 /// …)` and the `feira app graph` per-member printer's `println!(
1587 /// " - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
1588 /// prior to this lift) — two open-coded field-accesses that expressed
1589 /// no compile-time link back to the typed slot. A future extension of
1590 /// the `:membros :versao` axis to a richer author surface (a
1591 /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1592 /// flow, a lacre-projected concrete-version rewrite the operator
1593 /// materializes at CR-admission time, a future `:membros :versao-lock`
1594 /// per-cluster override slot) would have had to be threaded through
1595 /// every open-coded copy in lockstep or one consumer would silently
1596 /// disagree with the peers on which release constraint a given
1597 /// member resolves to. Lifting the resolution rule to a typed method
1598 /// on the substrate primitive means every downstream requirement-
1599 /// facing consumer reaches for exactly one typed dispatch — the
1600 /// resolver's accept-set migrates as a unit on any future axis
1601 /// addition.
1602 ///
1603 /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
1604 /// member-caixa `:nome` scalar accessor — the pair
1605 /// `(nome(), versao_requirement())` jointly projects the
1606 /// `(caixa, versao)` field pair every renderer that fans on
1607 /// per-member identity + version pin keys off, closing the last
1608 /// unlifted per-`:membros` scalar axis so every downstream
1609 /// per-`:membros` reader now routes through a typed dispatch on the
1610 /// substrate primitive. Named `versao_requirement()` rather than
1611 /// `versao()` because the field's storage-side `.versao` label is
1612 /// already the author-surface term (`:versao`); the accessor's name
1613 /// carries the semantic role — the semver *requirement* string the
1614 /// shared [`crate::version::parse_requirement`] entry-point consumes
1615 /// — so a raw field access and a typed dispatch read differently at
1616 /// every consumer site.
1617 ///
1618 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1619 /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1620 /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1621 /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1622 /// destination-Servico scalar accessors — same "one typed dispatch
1623 /// on the substrate primitive, thin projections at each consumer"
1624 /// discipline extended onto the per-`:membros` member-`:versao`
1625 /// semver-requirement byte-string axis.
1626 #[must_use]
1627 pub fn versao_requirement(&self) -> &str {
1628 self.versao.as_str()
1629 }
1630}
1631
1632// ── mesh-level policies ──────────────────────────────────────────────
1633
1634/// Mesh policies that apply to every `:contratos` edge unless
1635/// overridden per-edge in M4. V0 is a single global policy block.
1636#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
1637#[serde(rename_all = "camelCase")]
1638pub struct MeshPolicy {
1639 /// Per-call timeout. Authored as a duration string (`"30s"`).
1640 #[serde(
1641 default,
1642 skip_serializing_if = "Option::is_none",
1643 with = "supervisor::duration_codec"
1644 )]
1645 pub timeout: Option<Duration>,
1646
1647 /// Number of retries on transient failure. None = no retries.
1648 #[serde(default, skip_serializing_if = "Option::is_none")]
1649 pub retries: Option<u32>,
1650
1651 /// Circuit breaker config. Trips after N failures within W
1652 /// duration; closes after a cooldown.
1653 #[serde(default, skip_serializing_if = "Option::is_none")]
1654 pub circuit_breaker: Option<CircuitBreaker>,
1655
1656 /// Whether mTLS is required for every contrato. Default: true
1657 /// (sandboxing-by-default; explicit opt-out only).
1658 #[serde(default, skip_serializing_if = "Option::is_none")]
1659 pub mtls_required: Option<bool>,
1660
1661 /// Token-bucket rate limit. Authored as `"100/s"` or
1662 /// `"5000/m"`; stored as `(rate, window)`.
1663 #[serde(
1664 default,
1665 skip_serializing_if = "Option::is_none",
1666 with = "rate_limit_codec"
1667 )]
1668 pub rate_limit: Option<RateLimit>,
1669}
1670
1671impl MeshPolicy {
1672 /// True when no `:politicas` axis carries a value — every field is
1673 /// `None`. The same emptiness contract every other M2/M3 typed
1674 /// surface carries ([`crate::LimitsSpec::is_empty`],
1675 /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
1676 /// typed slot onto a cluster artifact key off this predicate to
1677 /// decide "emit the slot" vs "skip the slot entirely", so an
1678 /// authored-but-unset `:politicas (())` round-trips to a rendered
1679 /// artifact that's structurally identical to one that omits the
1680 /// slot. Lifted as a typed predicate (rather than per-renderer
1681 /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
1682 /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
1683 /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
1684 /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
1685 /// not a coordinated rewrite of every consumer that's reaching
1686 /// for the emptiness semantic.
1687 #[must_use]
1688 pub const fn is_empty(&self) -> bool {
1689 self.timeout().is_none()
1690 && self.retries().is_none()
1691 && self.circuit_breaker().is_none()
1692 && self.mtls_required().is_none()
1693 && self.rate_limit().is_none()
1694 }
1695
1696 /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
1697 /// per-call-deadline scalar accessor every consumer of the
1698 /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
1699 /// returns the author-declared `:politicas :timeout` typed
1700 /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
1701 /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
1702 /// is `Copy`, so the accessor returns by value; no borrow of
1703 /// `&self` past the call). `None` when the slot is absent (the
1704 /// "cluster default applies — typically the gateway class's
1705 /// implementation-side per-request wall-clock cap" arm caixa-mesh's
1706 /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
1707 /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
1708 /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
1709 /// round-trips to a rendered `HTTPRoute` structurally identical to
1710 /// one that omits the slot).
1711 ///
1712 /// The `:politicas :timeout` slot carries the "no infinite blocking"
1713 /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
1714 /// the typed slot's `Option<Duration>` accept-set (zero-floor
1715 /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
1716 /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
1717 /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
1718 /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
1719 /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
1720 /// Every downstream consumer that reads the per-call cap keys off
1721 /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
1722 /// renderers key off to decide "emit :politicas overlay" vs "skip
1723 /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
1724 /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
1725 /// fans the deadline into every rule via
1726 /// [`crate::render::single_field_overlay`], the future M4 per-
1727 /// Aplicacao Gateway API reconciler materialization pass, the
1728 /// future per-`:contratos`-edge timeout-override overlay the
1729 /// MESH-COMPOSITION §III.2 roadmap acknowledges).
1730 ///
1731 /// Prior to this lift the `.timeout` field was accessed inline at
1732 /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
1733 /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
1734 /// …)` call — two open-coded field-accesses that expressed no
1735 /// compile-time link back to the typed slot. A future extension of
1736 /// the `:politicas :timeout` axis to a richer author surface — a
1737 /// per-`:contratos`-edge timeout override the operator pins through
1738 /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
1739 /// roadmap acknowledges, a per-cluster timeout-default overlay the
1740 /// M4 CR materializer resolves per-CR, a split of the single
1741 /// per-call `Duration` into a richer `{request, backendRequest}`
1742 /// pair once the Gateway API's per-rule `timeouts` block grows the
1743 /// upstream-facing backendRequest arm alongside the client-facing
1744 /// request arm — would have had to be threaded through both open-
1745 /// coded copies in lockstep or the emptiness predicate and the
1746 /// caixa-mesh emit path would silently disagree on which per-call
1747 /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
1748 /// whose only axis is a `Some :timeout` would satisfy `is_empty()
1749 /// == false` while the renderer's overlay-emit path silently read
1750 /// a drifted other value, or vice versa: an author's `:timeout
1751 /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
1752 /// the emptiness predicate still classified the policy as non-
1753 /// empty, and every `kubectl -n tatara-system get httproute -o yaml
1754 /// | grep -A2 timeouts` audit would land on a route whose author's
1755 /// typed slot value silently vanished at the renderer layer).
1756 /// Lifting the resolution to a typed method on the substrate
1757 /// primitive means every downstream consumer of the Aplicacao's
1758 /// per-`:politicas` deadline surface reaches for exactly one typed
1759 /// dispatch — the resolver's accept-set migrates as a unit on any
1760 /// future axis addition.
1761 ///
1762 /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
1763 /// family (sibling of the peer per-`:politicas`
1764 /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
1765 /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
1766 /// `Option<bool>` accessor — same "one typed dispatch on the
1767 /// substrate primitive, thin projections at each consumer"
1768 /// discipline extended onto the peer per-`:politicas` typed-
1769 /// [`Duration`] optional-scalar axis; closes the "optional per-slot
1770 /// numeric-Copy-T scalar" projection pattern the sibling
1771 /// `Option<u32>` / `Option<bool>` lifts opened, since every
1772 /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
1773 /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
1774 /// than a scalar). Named `timeout()` to match the storage field's
1775 /// name; the accessor's identity maps onto the canonical MESH-
1776 /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
1777 #[must_use]
1778 pub const fn timeout(&self) -> Option<Duration> {
1779 self.timeout
1780 }
1781
1782 /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
1783 /// retry-budget scalar accessor every consumer of the Aplicacao's
1784 /// Gateway API v1.x per-rule retry-cap keys off — returns the
1785 /// author-declared `:politicas :retries` typed `u32` verbatim as an
1786 /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
1787 /// storage (`Option<u32>` is `Copy`, so the accessor returns by
1788 /// value; no borrow of `&self` past the call). `None` when the slot
1789 /// is absent (the "cluster default applies — typically 'no retries
1790 /// beyond a single dispatch attempt'" arm the caixa-mesh
1791 /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
1792 /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
1793 /// this predicate too, so an authored-but-unset `:politicas
1794 /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
1795 /// identical to one that omits the slot).
1796 ///
1797 /// The `:politicas :retries` slot carries the "transient failure
1798 /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
1799 /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
1800 /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
1801 /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
1802 /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
1803 /// count scalar the caixa-mesh `retry_overlay` builder writes.
1804 /// Every downstream consumer that reads the retry cap keys off this
1805 /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
1806 /// renderers key off to decide "emit :politicas overlay" vs "skip
1807 /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
1808 /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
1809 /// the value into every rule via [`crate::render::single_field_overlay`],
1810 /// the future M4 per-Aplicacao Gateway API reconciler
1811 /// materialization pass, the future per-`:contratos`-edge retry-
1812 /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
1813 /// acknowledges).
1814 ///
1815 /// Prior to this lift the `.retries` field was accessed inline at
1816 /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
1817 /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
1818 /// …)` call — two open-coded field-accesses that expressed no
1819 /// compile-time link back to the typed slot. A future extension of
1820 /// the `:politicas :retries` axis to a richer author surface — a
1821 /// per-`:contratos`-edge retry override the operator pins through a
1822 /// future `:contratos :retries` slot, a per-cluster retry-default
1823 /// overlay the M4 CR materializer resolves per-CR, a promotion of
1824 /// the plain `u32` attempt-count to a richer `{attempts, codes,
1825 /// backoff}` sub-block once the Gateway API grows the peer
1826 /// `retry.codes` / `retry.backoff` axes — would have had to be
1827 /// threaded through both open-coded copies in lockstep or the
1828 /// emptiness predicate and the caixa-mesh emit path would silently
1829 /// disagree on which retry budget a given [`MeshPolicy`] resolves to
1830 /// (a `:politicas` block whose only axis is a `Some :retries` would
1831 /// satisfy `is_empty() == false` while the renderer's overlay-emit
1832 /// path silently read a drifted other value, or vice versa: an
1833 /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
1834 /// block while the emptiness predicate still classified the policy
1835 /// as non-empty). Lifting the resolution to a typed method on the
1836 /// substrate primitive means every downstream consumer of the
1837 /// Aplicacao's per-`:politicas` retry surface reaches for exactly
1838 /// one typed dispatch — the resolver's accept-set migrates as a
1839 /// unit on any future axis addition.
1840 ///
1841 /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
1842 /// family (sibling of the peer per-`:politicas`
1843 /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
1844 /// same "one typed dispatch on the substrate primitive, thin
1845 /// projections at each consumer" discipline extended onto the
1846 /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
1847 /// the "optional per-slot numeric-Copy-T scalar" projection pattern
1848 /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
1849 /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
1850 /// fold on). Named `retries()` to match the storage field's name;
1851 /// the accessor's identity maps onto the canonical MESH-COMPOSITION
1852 /// §III.2 vocabulary the slot's docstring already carries.
1853 #[must_use]
1854 pub const fn retries(&self) -> Option<u32> {
1855 self.retries
1856 }
1857
1858 /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
1859 /// enforcement-toggle scalar accessor every consumer of the
1860 /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
1861 /// — returns the author-declared `:politicas :mtls-required` typed
1862 /// bool verbatim as an `Option<bool>`, copied out of the typed
1863 /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
1864 /// the accessor returns by value; no borrow of `&self` past the
1865 /// call). `None` when the slot is absent (the "cluster default
1866 /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
1867 /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
1868 /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
1869 /// this predicate too, so an authored-but-unset `:politicas
1870 /// (:mtls-required ())` round-trips to a rendered
1871 /// `CiliumNetworkPolicy` structurally identical to one that omits
1872 /// the slot).
1873 ///
1874 /// The `:politicas :mtls-required` slot carries the "explicit opt-
1875 /// out only, sandboxing-by-default" mTLS-enforcement toggle
1876 /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
1877 /// `{None, Some(true), Some(false)}` accept-set maps onto the
1878 /// Cilium `authentication.mode` bijection through
1879 /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
1880 /// handshake enforced), `Some(false) → "disabled"` (handshake
1881 /// skipped — the debug-edge opt-out), `None` → omit the block
1882 /// (cluster default applies). Every downstream consumer that
1883 /// reads the toggle keys off this scalar (the
1884 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
1885 /// off to decide "emit :politicas overlay" vs "skip entirely", the
1886 /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
1887 /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
1888 /// ingress rule via [`crate::render::single_field_overlay`], the
1889 /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
1890 /// materialization pass, the future per-`:contratos`-edge mTLS
1891 /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
1892 ///
1893 /// Prior to this lift the `.mtls_required` field was accessed
1894 /// inline at two sites — [`MeshPolicy::is_empty`]'s
1895 /// `self.mtls_required.is_none()` arm and caixa-mesh's
1896 /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
1897 /// two open-coded field-accesses that expressed no compile-time
1898 /// link back to the typed slot. A future extension of the
1899 /// `:politicas :mtls-required` axis to a richer author surface —
1900 /// a per-`:contratos`-edge mTLS override the operator pins through
1901 /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
1902 /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
1903 /// M4 CR materializer resolves per-CR, a three-valued
1904 /// `{None, Some(true), Some(false), Some(Optional)}` promotion
1905 /// once Cilium's `authentication.mode` grows an `"optional"` arm —
1906 /// would have had to be threaded through both open-coded copies in
1907 /// lockstep or the emptiness predicate and the caixa-mesh emit
1908 /// path would silently disagree on which toggle a given
1909 /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
1910 /// axis is a `Some`
1911 /// `:mtls-required` would satisfy `is_empty() == false` while the
1912 /// renderer's overlay-emit path silently read a drifted other
1913 /// value, or vice versa). Lifting the resolution to a typed method
1914 /// on the substrate primitive means every downstream consumer of
1915 /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
1916 /// for exactly one typed dispatch — the resolver's accept-set
1917 /// migrates as a unit on any future axis addition.
1918 ///
1919 /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
1920 /// family (peer of the sibling per-`:placement`
1921 /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
1922 /// same "one typed dispatch on the substrate primitive, thin
1923 /// projections at each consumer" discipline extended onto the
1924 /// peer per-`:politicas` typed-bool optional-scalar axis; opens
1925 /// the "optional per-slot Copy-T scalar" projection pattern the
1926 /// sibling per-`:politicas` `:retries` (Option<u32>) /
1927 /// `:timeout` (Option<Duration>) future lifts fold on). Named
1928 /// `mtls_required()` to match the storage field's name; the
1929 /// accessor's identity maps onto the canonical MESH-COMPOSITION
1930 /// §III.2 vocabulary the slot's docstring already carries.
1931 #[must_use]
1932 pub const fn mtls_required(&self) -> Option<bool> {
1933 self.mtls_required
1934 }
1935
1936 /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
1937 /// `local_rate_limit`-mesh token-bucket-declaration scalar
1938 /// accessor every consumer of the Aplicacao's per-`:politicas`
1939 /// per-`(rate, window)` rate-limit surface keys off — returns the
1940 /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
1941 /// verbatim as an `Option<RateLimit>`, copied out of the typed
1942 /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
1943 /// `Copy`, so the accessor returns by value; no borrow of `&self`
1944 /// past the call). `None` when the slot is absent (the "cluster
1945 /// default applies — typically 'no per-Aplicacao rate declaration,
1946 /// gateway-class per-listener default applies'" arm the future
1947 /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
1948 /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
1949 /// `rate_limit().is_none()` arm reads this predicate too, so an
1950 /// authored-but-unset `:politicas (:rate-limit ())` round-trips
1951 /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
1952 /// identical to one that omits the slot).
1953 ///
1954 /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
1955 /// token-bucket rate declaration" contract (MESH-COMPOSITION
1956 /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
1957 /// (rate lower-bounded by 1 through
1958 /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
1959 /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
1960 /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
1961 /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
1962 /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
1963 /// bijection the future `CiliumClusterwideEnvoyConfig` per-
1964 /// `:politicas` overlay emits. Every downstream consumer that
1965 /// reads the rate declaration keys off this scalar (the
1966 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
1967 /// off to decide "emit :politicas overlay" vs "skip entirely", the
1968 /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
1969 /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
1970 /// `rl.window` against [`is_canonical_rate_limit_window`], the
1971 /// future M4 per-Aplicacao Envoy reconciler materialization pass,
1972 /// the future per-`:contratos`-edge rate-limit override the
1973 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
1974 ///
1975 /// Prior to this lift the `.rate_limit` field was accessed inline
1976 /// at two sites — [`MeshPolicy::is_empty`]'s
1977 /// `self.rate_limit.is_none()` arm and the `validate_politicas`
1978 /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
1979 /// field-accesses that expressed no compile-time link back to the
1980 /// typed slot. A future extension of the `:politicas :rate-limit`
1981 /// axis to a richer author surface — a per-`:contratos`-edge
1982 /// rate-limit override the operator pins through a future
1983 /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
1984 /// roadmap acknowledges, a per-cluster rate-limit-default overlay
1985 /// the M4 CR materializer resolves per-CR, a promotion of the
1986 /// plain `(rate, window)` scalar pair to a richer
1987 /// `{rate, window, burst, key}` sub-block once Envoy's
1988 /// `local_rate_limit` grows the peer `burst_size` /
1989 /// `descriptor_key` axes — would have had to be threaded through
1990 /// both open-coded copies in lockstep or the emptiness predicate
1991 /// and the validate gate would silently disagree on which rate
1992 /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
1993 /// block whose only axis is a `Some :rate-limit` would satisfy
1994 /// `is_empty() == false` while the validate path silently read a
1995 /// drifted other value, or vice versa: an author's
1996 /// `:rate-limit "100/s"` would omit the value-shape gate while the
1997 /// emptiness predicate still classified the policy as non-empty).
1998 /// Lifting the resolution to a typed method on the substrate
1999 /// primitive means every downstream consumer of the Aplicacao's
2000 /// per-`:politicas` rate-limit surface reaches for exactly one
2001 /// typed dispatch — the resolver's accept-set migrates as a unit
2002 /// on any future axis addition.
2003 ///
2004 /// First `Option<Copy-composite-T>`-return accessor on the M3
2005 /// mesh-slot family — closes the last un-lifted per-`:politicas`
2006 /// scalar-value axis. Peer of the sibling per-`:politicas`
2007 /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2008 /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2009 /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2010 /// "one typed dispatch on the substrate primitive, thin
2011 /// projections at each consumer" discipline extended onto the
2012 /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2013 /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2014 /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2015 /// sub-accessors rather than a top-level accessor because
2016 /// consumers reach for the axes not the aggregate). Named
2017 /// `rate_limit()` to match the storage field's name; the
2018 /// accessor's identity maps onto the canonical MESH-COMPOSITION
2019 /// §III.2 vocabulary the slot's docstring already carries.
2020 #[must_use]
2021 pub const fn rate_limit(&self) -> Option<RateLimit> {
2022 self.rate_limit
2023 }
2024
2025 /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2026 /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2027 /// declaration scalar accessor every consumer of the Aplicacao's
2028 /// per-`:politicas` breaker declaration keys off — returns the
2029 /// author-declared `:politicas :circuit-breaker` typed
2030 /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2031 /// copied out of the typed slot's own `Option<CircuitBreaker>`
2032 /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2033 /// by value; no borrow of `&self` past the call). `None` when the
2034 /// slot is absent (the "cluster default applies — typically 'no
2035 /// per-Aplicacao breaker declaration, gateway-class per-listener
2036 /// default applies'" arm the future caixa-mesh
2037 /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2038 /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2039 /// arm reads this predicate too, so an authored-but-unset
2040 /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2041 /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2042 /// that omits the slot).
2043 ///
2044 /// The `:politicas :circuit-breaker` slot carries the
2045 /// "per-Aplicacao consecutive-transient-failure trip declaration"
2046 /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2047 /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2048 /// zero-floor rejected through
2049 /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2050 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2051 /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2052 /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2053 /// canonical-form pinned through
2054 /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2055 /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2056 /// bijection the future `CiliumClusterwideEnvoyConfig`
2057 /// per-`:politicas` overlay emits. Every downstream consumer that
2058 /// reads the breaker declaration keys off this scalar (the
2059 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2060 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2061 /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2062 /// that brackets `cb.max_failures()` against
2063 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2064 /// [`POLICY_BREAKER_WINDOW_MAX`] via
2065 /// [`crate::render::require_positive_canonical_bounded_duration`],
2066 /// the future M4 per-Aplicacao Envoy reconciler materialization
2067 /// pass, the future per-`:contratos`-edge breaker override the
2068 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2069 ///
2070 /// Prior to this lift the `.circuit_breaker` field was accessed
2071 /// inline at two sites — [`MeshPolicy::is_empty`]'s
2072 /// `self.circuit_breaker.is_none()` arm and the
2073 /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2074 /// bind — two open-coded field-accesses that expressed no
2075 /// compile-time link back to the typed slot. A future extension of
2076 /// the `:politicas :circuit-breaker` axis to a richer author
2077 /// surface — a per-`:contratos`-edge breaker override the operator
2078 /// pins through a future `:contratos :circuit-breaker` slot the
2079 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2080 /// breaker-default overlay the M4 CR materializer resolves per-CR,
2081 /// a promotion of the plain `(max_failures, window)` scalar pair to
2082 /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2083 /// sub-block once Envoy's `outlier_detection` grows the peer
2084 /// ejection-percentage / ejection-time axes — would have had to be
2085 /// threaded through both open-coded copies in lockstep or the
2086 /// emptiness predicate and the validate gate would silently
2087 /// disagree on which breaker declaration a given [`MeshPolicy`]
2088 /// resolves to (a `:politicas` block whose only axis is a
2089 /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2090 /// the validate path silently read a drifted other value, or vice
2091 /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2092 /// "60s"))` would omit the value-shape gate while the emptiness
2093 /// predicate still classified the policy as non-empty). Lifting
2094 /// the resolution to a typed method on the substrate primitive
2095 /// means every downstream consumer of the Aplicacao's
2096 /// per-`:politicas` breaker surface reaches for exactly one typed
2097 /// dispatch — the resolver's accept-set migrates as a unit on any
2098 /// future axis addition.
2099 ///
2100 /// Second `Option<Copy-composite-T>`-return accessor on the M3
2101 /// mesh-slot family (sibling of the peer per-`:politicas`
2102 /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2103 /// on the same composite-Copy shape, and of the sibling per-
2104 /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2105 /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2106 /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2107 /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2108 /// same "one typed dispatch on the substrate primitive, thin
2109 /// projections at each consumer" discipline extended onto the last
2110 /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2111 /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2112 /// match the storage field's name; the accessor's identity maps
2113 /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2114 /// docstring already carries. Closes the last unlifted
2115 /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2116 /// reader now routes through a typed dispatch on the substrate
2117 /// primitive.
2118 #[must_use]
2119 pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2120 self.circuit_breaker
2121 }
2122}
2123
2124#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2125#[serde(rename_all = "camelCase")]
2126pub struct CircuitBreaker {
2127 pub max_failures: u32,
2128 #[serde(with = "supervisor::duration_codec_required")]
2129 pub window: Duration,
2130}
2131
2132impl CircuitBreaker {
2133 /// Substrate-canonical per-`:politicas :circuit-breaker`
2134 /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2135 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2136 /// breaker trip-count keys off — returns the author-declared
2137 /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2138 /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2139 /// so the accessor returns by value; no borrow of `&self` past the
2140 /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2141 /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2142 /// axis; a `CircuitBreaker` past pattern-match is definitionally
2143 /// present, and its `:max-failures` field carries the trip count as a
2144 /// required-axis scalar).
2145 ///
2146 /// The `:politicas :circuit-breaker :max-failures` axis carries the
2147 /// "consecutive-transient-failure trip threshold" contract
2148 /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2149 /// (zero-floor rejected through
2150 /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2151 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2152 /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2153 /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2154 /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2155 /// Every downstream consumer that reads the trip threshold keys off
2156 /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2157 /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2158 /// canonical `require_positive_bounded_u32` helper, the future M4
2159 /// per-Aplicacao Envoy config reconciler materialization pass, the
2160 /// future per-`:contratos`-edge breaker-override overlay the
2161 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2162 ///
2163 /// Prior to this lift the `.max_failures` field was accessed inline
2164 /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2165 /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2166 /// open-coded field-access that expressed no compile-time link back
2167 /// to the typed sub-struct axis. A future extension of the
2168 /// `:max-failures` axis to a richer author surface — a
2169 /// per-`:contratos`-edge breaker override the operator pins through a
2170 /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2171 /// #3 roadmap acknowledges, a per-cluster max-failures-default
2172 /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2173 /// plain `u32` trip count to a richer
2174 /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2175 /// tuple once Envoy's `outlier_detection` block's peer axes come into
2176 /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2177 /// count arms — would have had to be threaded through every open-
2178 /// coded copy in lockstep or the validate gate and the future M4
2179 /// emit path would silently disagree on which trip threshold a given
2180 /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2181 /// would satisfy validate while the emit path silently read a drifted
2182 /// other value, or vice versa: a validated typed slot would land at
2183 /// the emit boundary as a no-op breaker whose trip threshold is
2184 /// structurally never reached). Lifting the resolution to a typed
2185 /// method on the substrate primitive means every downstream consumer
2186 /// of the Aplicacao's per-`:politicas :circuit-breaker`
2187 /// trip-threshold surface reaches for exactly one typed dispatch —
2188 /// the resolver's accept-set migrates as a unit on any future axis
2189 /// addition.
2190 ///
2191 /// First sub-struct scalar accessor on the M3 mesh-slot family
2192 /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2193 /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2194 /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2195 /// closes the last unlifted per-`:politicas` scalar-value axis after
2196 /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
2197 /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
2198 /// Same "one typed dispatch on the substrate primitive, thin
2199 /// projections at each consumer" discipline the peer
2200 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2201 /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2202 /// [`Membro::versao_requirement`] (a40b0e3),
2203 /// [`Entrada::destination`] (6db982c) accessors carry on their
2204 /// respective per-mesh-slot-atom scalar-value axes, extended onto the
2205 /// per-sub-struct required-`u32` axis. Named `max_failures()` to
2206 /// match the storage field's name; the accessor's identity maps onto
2207 /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2208 /// docstring already carries.
2209 #[must_use]
2210 pub const fn max_failures(&self) -> u32 {
2211 self.max_failures
2212 }
2213
2214 /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
2215 /// Envoy-outlier-detection rolling-observation-interval scalar
2216 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2217 /// breaker rolling-window duration keys off — returns the
2218 /// author-declared `:politicas :circuit-breaker :window` typed
2219 /// `Duration` verbatim, copied out of the typed slot's own
2220 /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
2221 /// by value; no borrow of `&self` past the call). Non-optional (the
2222 /// surrounding `Option<CircuitBreaker>` is the "slot present?"
2223 /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
2224 /// `CircuitBreaker` past pattern-match is definitionally present,
2225 /// and its `:window` field carries the rolling-observation interval
2226 /// as a required-axis scalar).
2227 ///
2228 /// The `:politicas :circuit-breaker :window` axis carries the
2229 /// "consecutive-transient-failure rolling-observation interval"
2230 /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2231 /// `Duration` accept-set (zero-floor rejected through
2232 /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
2233 /// residue rejected through
2234 /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
2235 /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
2236 /// Envoy `outlier_detection.interval` per-cluster
2237 /// ejection-observation-interval scalar (equivalently the future
2238 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2239 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2240 /// consumer that reads the rolling-observation interval keys off
2241 /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2242 /// integer-millisecond canonical-form + cap bracket at
2243 /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
2244 /// [`crate::render::require_positive_canonical_bounded_duration`]
2245 /// helper, the future M4 per-Aplicacao Envoy config reconciler
2246 /// materialization pass, the future per-`:contratos`-edge
2247 /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2248 /// acknowledges).
2249 ///
2250 /// Prior to this lift the `.window` field was accessed inline at
2251 /// one production site — [`AplicacaoSpec::validate_politicas`]'s
2252 /// `require_positive_canonical_bounded_duration(cb.window, …)`
2253 /// call — one open-coded field-access that expressed no compile-
2254 /// time link back to the typed sub-struct axis. A future extension
2255 /// of the `:window` axis to a richer author surface — a
2256 /// per-`:contratos`-edge window override the operator pins through
2257 /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
2258 /// #3 roadmap acknowledges, a per-cluster window-default overlay
2259 /// the M4 CR materializer resolves per-CR, a promotion of the plain
2260 /// `Duration` observation interval to a richer
2261 /// `{interval, base_ejection_time, max_ejection_percent}` tuple
2262 /// once Envoy's `outlier_detection` block's peer axes come into
2263 /// scope, a per-Envoy-cluster minimum-request-volume gate before
2264 /// the window arms — would have had to be threaded through every
2265 /// open-coded copy in lockstep or the validate gate and the future
2266 /// M4 emit path would silently disagree on which observation
2267 /// interval a given [`CircuitBreaker`] resolves to (an author's
2268 /// `:window "60s"` would satisfy validate while the emit path
2269 /// silently read a drifted other value, or vice versa: a validated
2270 /// typed slot would land at the emit boundary as a breaker whose
2271 /// observation window is structurally so wide that no realistic
2272 /// failure-rate shape can trip it). Lifting the resolution to a
2273 /// typed method on the substrate primitive means every downstream
2274 /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
2275 /// observation-window surface reaches for exactly one typed
2276 /// dispatch — the resolver's accept-set migrates as a unit on any
2277 /// future axis addition.
2278 ///
2279 /// Second sub-struct scalar accessor on the M3 mesh-slot family —
2280 /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
2281 /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
2282 /// required-axis, extended onto the per-sub-struct required-`Duration`
2283 /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
2284 /// axis. Same "one typed dispatch on the substrate primitive, thin
2285 /// projections at each consumer" discipline the peer
2286 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2287 /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2288 /// [`Membro::versao_requirement`] (a40b0e3),
2289 /// [`Entrada::destination`] (6db982c) accessors carry on their
2290 /// respective per-mesh-slot-atom scalar-value axes, extended onto
2291 /// the per-sub-struct required-`Duration` axis. Named `window()` to
2292 /// match the storage field's name; the accessor's identity maps onto
2293 /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2294 /// docstring already carries.
2295 #[must_use]
2296 pub const fn window(&self) -> Duration {
2297 self.window
2298 }
2299}
2300
2301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2302pub struct RateLimit {
2303 /// Requests per window.
2304 pub rate: u32,
2305 /// Window duration.
2306 pub window: Duration,
2307}
2308
2309impl RateLimit {
2310 /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
2311 /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
2312 /// every consumer of the Aplicacao's per-`:contratos`-edge
2313 /// rate-limit-bucket capacity keys off — returns the author-declared
2314 /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
2315 /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
2316 /// returns by value; no borrow of `&self` past the call). Non-optional
2317 /// (the surrounding `Option<RateLimit>` is the "slot present?"
2318 /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
2319 /// `RateLimit` past pattern-match is definitionally present, and its
2320 /// `:rate` field carries the token-bucket capacity as a required-axis
2321 /// scalar).
2322 ///
2323 /// The `:politicas :rate-limit` `:rate` axis carries the
2324 /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
2325 /// the typed slot's `u32` accept-set (zero-floor rejected through
2326 /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
2327 /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
2328 /// `local_rate_limit.token_bucket.max_tokens` per-cluster
2329 /// token-bucket-capacity scalar (equivalently the future
2330 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2331 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2332 /// consumer that reads the token-bucket capacity keys off this
2333 /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2334 /// cap bracket that gates on the canonical
2335 /// [`crate::render::require_positive_bounded_u32`] helper, the
2336 /// [`rate_limit_codec::render`] `Duration → unit` projection that
2337 /// emits the `<n>/<s|m|h>` author surface, the future M4
2338 /// per-Aplicacao Envoy config reconciler materialization pass, the
2339 /// future per-`:contratos`-edge rate-limit-override overlay the
2340 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2341 ///
2342 /// Prior to this lift the `.rate` field was accessed inline at three
2343 /// production sites — [`AplicacaoSpec::validate_politicas`]'s
2344 /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
2345 /// [`rate_limit_codec::render`] format-arm arms (canonical-window
2346 /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
2347 /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
2348 /// field-accesses that expressed no compile-time link back to the
2349 /// typed sub-struct axis. A future extension of the `:rate` axis
2350 /// to a richer author surface — a per-`:contratos`-edge rate
2351 /// override the operator pins through a future `:contratos :rate`
2352 /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
2353 /// per-cluster rate-default overlay the M4 CR materializer resolves
2354 /// per-CR, a promotion of the plain `u32` token capacity to a
2355 /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
2356 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2357 /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
2358 /// before the token arms — would have had to be threaded through
2359 /// every open-coded copy in lockstep or the validate gate, the
2360 /// codec's render path, and the future M4 emit path would silently
2361 /// disagree on which token capacity a given [`RateLimit`] resolves
2362 /// to (an author's `:rate-limit "100/s"` would satisfy validate
2363 /// while the render / emit paths silently read a drifted other
2364 /// value, or vice versa: a validated typed slot would land at the
2365 /// emit boundary as a no-op limiter whose token capacity is
2366 /// structurally so high that no realistic per-edge traffic shape
2367 /// can drain it). Lifting the resolution to a typed method on the
2368 /// substrate primitive means every downstream consumer of the
2369 /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
2370 /// reaches for exactly one typed dispatch — the resolver's
2371 /// accept-set migrates as a unit on any future axis addition.
2372 ///
2373 /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
2374 /// in shape to the peer per-`CircuitBreaker`
2375 /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
2376 /// on the peer per-sub-struct required-axis, extended onto the
2377 /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
2378 /// required-axis scalar" projection pattern the sibling
2379 /// [`RateLimit::window`] future lift folds on. Same "one typed
2380 /// dispatch on the substrate primitive, thin projections at each
2381 /// consumer" discipline the peer [`WitContract::source`] /
2382 /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
2383 /// (0804823), [`Membro::nome`] (4a32abf),
2384 /// [`Membro::versao_requirement`] (a40b0e3),
2385 /// [`Entrada::destination`] (6db982c),
2386 /// [`CircuitBreaker::max_failures`] (3a74062),
2387 /// [`CircuitBreaker::window`] (373957f) accessors carry on their
2388 /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
2389 /// to match the storage field's name; the accessor's identity maps
2390 /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2391 /// docstring already carries.
2392 #[must_use]
2393 pub const fn rate(&self) -> u32 {
2394 self.rate
2395 }
2396
2397 /// Substrate-canonical per-`:politicas :rate-limit` `:window`
2398 /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
2399 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2400 /// rate-limit-bucket refill period keys off — returns the
2401 /// author-declared `:politicas :rate-limit` typed `Duration`
2402 /// verbatim, copied out of the typed slot's own `Duration` storage
2403 /// (`Duration` is `Copy`, so the accessor returns by value; no
2404 /// borrow of `&self` past the call). Non-optional (the surrounding
2405 /// `Option<RateLimit>` is the "slot present?" projection at the
2406 /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
2407 /// pattern-match is definitionally present, and its `:window`
2408 /// field carries the token-bucket refill period as a required-axis
2409 /// scalar).
2410 ///
2411 /// The `:politicas :rate-limit` `:window` axis carries the
2412 /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
2413 /// — the typed slot's `Duration` accept-set (constrained to the
2414 /// three canonical windows `{1s, 60s, 3600s}` the
2415 /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
2416 /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
2417 /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
2418 /// per-cluster token-bucket-refill-period scalar (equivalently the
2419 /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2420 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2421 /// consumer that reads the token-bucket refill period keys off
2422 /// this scalar (the [`AplicacaoSpec::validate_politicas`]
2423 /// canonical-window gate that keys off
2424 /// [`is_canonical_rate_limit_window`], the
2425 /// [`rate_limit_codec::render`] `Duration → unit` projection that
2426 /// emits the `<n>/<s|m|h>` author surface — canonical arm via
2427 /// [`rate_limit_window_unit`] and non-canonical fallback via
2428 /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
2429 /// reconciler materialization pass, the future per-`:contratos`-
2430 /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
2431 /// roadmap acknowledges).
2432 ///
2433 /// Prior to this lift the `.window` field was accessed inline at
2434 /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
2435 /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
2436 /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
2437 /// error-payload construction on refusal, and the two
2438 /// [`rate_limit_codec::render`] arms
2439 /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
2440 /// and non-canonical-window `rl.window.as_secs()` fallback). Three
2441 /// open-coded field-accesses that expressed no compile-time link
2442 /// back to the typed sub-struct axis. A future extension of the
2443 /// `:window` axis to a richer author surface — a per-`:contratos`-
2444 /// edge window override the operator pins through a future
2445 /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
2446 /// acknowledges, a per-cluster window-default overlay the M4 CR
2447 /// materializer resolves per-CR, a promotion of the plain
2448 /// `Duration` refill period to a richer
2449 /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
2450 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2451 /// axis comes into scope, an addition of a `"d"` day suffix once
2452 /// Envoy's `rate_limit_action` grows daily-bucket support — would
2453 /// have had to be threaded through every open-coded copy in
2454 /// lockstep or the validate gate, the codec's render path, and
2455 /// the future M4 emit path would silently disagree on which
2456 /// refill period a given [`RateLimit`] resolves to (an author's
2457 /// `:rate-limit "100/s"` would satisfy validate while the render
2458 /// / emit paths silently read a drifted other value, or vice
2459 /// versa: a validated typed slot would land at the emit boundary
2460 /// as a limiter whose refill period is structurally so long that
2461 /// no realistic per-edge traffic shape stays inside the token
2462 /// budget). Lifting the resolution to a typed method on the
2463 /// substrate primitive means every downstream consumer of the
2464 /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
2465 /// reaches for exactly one typed dispatch — the resolver's
2466 /// accept-set migrates as a unit on any future axis addition.
2467 ///
2468 /// Second sub-struct scalar accessor on the `RateLimit` axis —
2469 /// sibling in shape to the just-landed [`RateLimit::rate`]
2470 /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
2471 /// required-axis, extended onto the per-sub-struct
2472 /// required-`Duration` axis; closes the last unlifted
2473 /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
2474 /// per-sub-struct accessor coverage is now complete across both
2475 /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
2476 /// the substrate primitive, thin projections at each consumer"
2477 /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
2478 /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
2479 /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
2480 /// (7f0fd43), [`WitContract::world_ref`] (0804823),
2481 /// [`Membro::nome`] (4a32abf),
2482 /// [`Membro::versao_requirement`] (a40b0e3),
2483 /// [`Entrada::destination`] (6db982c) accessors carry on their
2484 /// respective per-mesh-slot-atom scalar-value axes. Named
2485 /// `window()` to match the storage field's name; the accessor's
2486 /// identity maps onto the canonical MESH-COMPOSITION §III.2
2487 /// vocabulary the slot's docstring already carries.
2488 #[must_use]
2489 pub const fn window(&self) -> Duration {
2490 self.window
2491 }
2492
2493 /// Recognize this rate-limit's `:window` as a canonical
2494 /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
2495 /// exactly matches one of the three closed-set arm-Durations
2496 /// (`1s` / `60s` / `3600s`), `None` when the window carries a
2497 /// non-canonical magnitude the codec's round-trip would break on
2498 /// (sub-second residue, or a second-magnitude outside the set
2499 /// [`RateLimitUnit::ALL`] enumerates).
2500 ///
2501 /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
2502 /// returns `Some` here — the validate gate's
2503 /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
2504 /// rejects every window this accessor returns `None` on. Downstream
2505 /// consumers past validate (the codec's [`rate_limit_codec::render`]
2506 /// path, the future M4 per-Aplicacao Envoy config reconciler's
2507 /// materialization pass, the future per-`:contratos`-edge rate-limit-
2508 /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2509 /// acknowledges) that read the typed unit off a validated slot can
2510 /// pattern-match on the returned `Some` without re-checking
2511 /// canonicality at the consumer layer — the typed enum surface is
2512 /// the load-bearing carrier of the canonicality invariant.
2513 ///
2514 /// Preferred over the free [`is_canonical_rate_limit_window`]
2515 /// module-private helper at any call site that has the typed
2516 /// [`RateLimit`] in hand (the codec's `render` arm at
2517 /// [`rate_limit_codec::render`], the validate gate's canonical-form
2518 /// arm in [`AplicacaoSpec::validate_politicas`], any future
2519 /// per-`:contratos` edge-override overlay resolver): those consumers
2520 /// reach for the typed enum without going through the
2521 /// `.window()` scalar-projection layer, and get the enum value
2522 /// directly (which the codec's render arm can then format via
2523 /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
2524 /// "typed sub-struct scalar accessor, one dispatch on the substrate
2525 /// primitive" discipline the sibling [`RateLimit::rate`] and
2526 /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
2527 /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
2528 /// projection axis (the third scalar accessor on the [`RateLimit`]
2529 /// axis, first typed-enum-return projection).
2530 #[must_use]
2531 pub fn canonical_unit(&self) -> Option<RateLimitUnit> {
2532 RateLimitUnit::from_window(self.window)
2533 }
2534}
2535
2536/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
2537/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
2538/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
2539///
2540/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
2541/// the `:politicas :rate-limit` unit surface reads from
2542/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
2543/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
2544/// [`is_canonical_rate_limit_window`] predicate the
2545/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
2546/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
2547/// projection) now lives inside this typed enum's `match self` arms — a
2548/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
2549/// `rate_limit_action` grows daily-bucket support) is one new variant
2550/// plus the exhaustiveness arms on the four methods, so every consumer
2551/// picks it up by compile-time construction rather than a runtime
2552/// table-scan miss.
2553///
2554/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
2555/// scanned via `find_map` at every projection call — an untyped runtime
2556/// walk that carried no compile-time link between the parse arm's
2557/// accepted suffixes, the render arm's emitted suffixes, and the
2558/// validate gate's accepted windows. A future rate-limit-unit addition
2559/// that landed one row without threading through the other consumers
2560/// (or a copy-paste flip that collapsed two rows onto one suffix) would
2561/// silently split the accepted-set across the three consumers — the
2562/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
2563/// for a 24h window that parse can't round-trip, the validate gate
2564/// misses one canonical window. Lifting the pairs onto a typed
2565/// closed-set enum with exhaustive `match` arms makes any such
2566/// half-landed extension a caixa-core build error (the compiler enforces
2567/// arm coverage on every method), not a silent per-consumer drift
2568/// surfacing at apply time. Same "closed-set typed-enum discriminator"
2569/// discipline the sibling [`PlacementStrategy`] (cc8f749),
2570/// [`crate::supervisor::RestartStrategy`],
2571/// [`crate::supervisor::RestartPolicy`],
2572/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
2573/// closed-set typed enums carry on their respective closed-set axes —
2574/// extended onto the seventh closed-set typed-enum discriminator axis
2575/// on the caixa typed surface (the `:politicas :rate-limit :window`
2576/// canonical-unit axis).
2577#[derive(
2578 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
2579)]
2580pub enum RateLimitUnit {
2581 /// 1-second window — canonical author-surface suffix `"s"`
2582 /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2583 /// with a 1s magnitude.
2584 Second,
2585 /// 1-minute window — canonical author-surface suffix `"m"`
2586 /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2587 /// with a 60s magnitude.
2588 Minute,
2589 /// 1-hour window — canonical author-surface suffix `"h"`
2590 /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
2591 /// with a 3600s magnitude.
2592 Hour,
2593}
2594
2595impl RateLimitUnit {
2596 /// Exhaustive iteration surface for every consumer that reads the
2597 /// full canonical-unit set (the byte-parity witness against the
2598 /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
2599 /// webhook's accepted-suffix listing in its rejection body, any
2600 /// future round-trip fuzz harness). A future variant addition to
2601 /// [`RateLimitUnit`] extends this slice as a single edit and every
2602 /// consumer picks up the new entry by construction — the compiler-
2603 /// checked exhaustiveness on the sibling method `match` arms is the
2604 /// build-time guarantee that no arm forgets to grow.
2605 pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
2606
2607 /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
2608 /// string every `<n>/<unit>` rate-limit shape carries after its
2609 /// `/` separator. The single source of truth the codec's parse and
2610 /// render arms both dispatch on: the parse arm matches an incoming
2611 /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
2612 /// output; the render arm emits the entry's `as_suffix` verbatim
2613 /// after the rate magnitude.
2614 #[must_use]
2615 pub const fn as_suffix(self) -> &'static str {
2616 match self {
2617 Self::Second => "s",
2618 Self::Minute => "m",
2619 Self::Hour => "h",
2620 }
2621 }
2622
2623 /// Canonical `Duration` for this unit — the token-bucket refill
2624 /// period the [`RateLimit::window`] axis carries when the surrounding
2625 /// slot's `:rate-limit` author surface named this unit.
2626 #[must_use]
2627 pub const fn window(self) -> Duration {
2628 Duration::from_secs(match self {
2629 Self::Second => 1,
2630 Self::Minute => 60,
2631 Self::Hour => 3_600,
2632 })
2633 }
2634
2635 /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
2636 /// `None` when `suffix` is outside the closed-set arm-string set
2637 /// [`Self::as_suffix`] emits. The single `str → Self` projection
2638 /// [`rate_limit_codec::parse`] consumes.
2639 #[must_use]
2640 pub fn from_suffix(suffix: &str) -> Option<Self> {
2641 Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
2642 }
2643
2644 /// Recognize a canonical rate-limit `Duration` as one of the three
2645 /// arms, or `None` when `window` carries sub-second residue or a
2646 /// second-magnitude outside the closed-set arm-window set
2647 /// [`Self::window`] emits. The single `Duration → Self` projection
2648 /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
2649 /// both consume.
2650 #[must_use]
2651 pub fn from_window(window: Duration) -> Option<Self> {
2652 if window.subsec_nanos() != 0 {
2653 return None;
2654 }
2655 Self::ALL.iter().copied().find(|u| u.window() == window)
2656 }
2657
2658 /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
2659 /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
2660 /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
2661 /// single `&str → Duration` projection [`rate_limit_codec::parse`]
2662 /// consumes.
2663 ///
2664 /// The peer `Duration → &'static str` axis folded onto the substrate
2665 /// primitive [`RateLimit::canonical_unit`] typed accessor once both
2666 /// production consumers ([`rate_limit_codec::render`] and
2667 /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
2668 /// migrated (61421a6): the free helper's `Duration → &str` projection
2669 /// is now the two-step composition
2670 /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
2671 /// reads through the typed accessor. This lift closes the peer
2672 /// `&str → Duration` axis by folding the vestigial module-private
2673 /// `rate_limit_window_from_unit` delegate onto this associated method
2674 /// — the codec's parse arm and every future wire-side consumer of the
2675 /// `&str → Duration` projection (a future admission-webhook that
2676 /// reads a `:rate-limit` shape off a CR spec's `raw string` value
2677 /// before it's promoted to a validated typed slot, a future
2678 /// `feira lint` shape-probe that reads the author-surface bytes
2679 /// verbatim) now reach for exactly one typed dispatch on the
2680 /// substrate primitive.
2681 ///
2682 /// Same "closed-set typed-enum discriminator with canonical
2683 /// projections per axis" discipline the sibling [`Self::as_suffix`]
2684 /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
2685 /// methods carry — this associated method closes the fifth (and last
2686 /// unlifted) projection axis on the arm-table, so the closed-set enum
2687 /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
2688 /// consumer of the `:politicas :rate-limit :window` axis reaches
2689 /// through. A future rate-limit-unit addition (a `"d"` day suffix
2690 /// once Envoy's `rate_limit_action` grows daily-bucket support, a
2691 /// `"ms"` sub-second window once high-throughput per-edge policies
2692 /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
2693 /// variant plus one arm per method — the compiler enforces
2694 /// exhaustiveness on every consumer's `match self` arms and picks
2695 /// the new unit up by construction across all five projections.
2696 #[must_use]
2697 pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
2698 Self::from_suffix(suffix).map(Self::window)
2699 }
2700}
2701
2702/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
2703/// every consumer that formats a canonical rate-limit unit as user-
2704/// facing text (future M4 admission-webhook rejection bodies naming
2705/// the accepted-suffix set, future `feira app graph` per-`:politicas`
2706/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
2707/// codec's parse arm accepts and the render arm emits. Same
2708/// as_str-through-Display convergence discipline the sibling
2709/// [`PlacementStrategy`], [`crate::CaixaKind`],
2710/// [`crate::supervisor::RestartStrategy`], and
2711/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
2712impl std::fmt::Display for RateLimitUnit {
2713 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2714 f.write_str(self.as_suffix())
2715 }
2716}
2717
2718/// Upper-bound ceiling on the `:politicas :timeout` axis — every
2719/// validated [`MeshPolicy::timeout`] past
2720/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
2721/// (inclusive on both ends, integer-millisecond magnitudes by the
2722/// canonical-form gate immediately preceding).
2723///
2724/// The typed field is `Option<Duration>` (the zero-floor arm
2725/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
2726/// `Duration::ZERO`, and the canonical-form arm
2727/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
2728/// sub-millisecond residue), so a programmatic struct literal
2729/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
2730/// 24h) and the equivalent author-surface form
2731/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
2732/// integer-hour magnitude) both round-trip cleanly through serde — a
2733/// structurally unbounded `Duration` ceiling. A `:timeout` value far
2734/// above the documented production-playbook band (Envoy default `15s`,
2735/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
2736/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
2737/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
2738/// at `~3600s`) silently degenerates the mesh-policy contract: the
2739/// per-call deadline is structurally so long that no realistic
2740/// synchronous-`:contratos` traversal can reach it, so the typed slot
2741/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
2742/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
2743/// blocking" degenerates to a nominal-only contract on the
2744/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
2745/// the sibling `:politicas :retries` axis and the
2746/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
2747/// `:politicas :circuit-breaker :max-failures` axis — all three close
2748/// the "structurally unbounded ceiling on a typed `:politicas` axis"
2749/// footgun the prior zero-floor-and-canonical-form-only checks left
2750/// open.
2751///
2752/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
2753/// shared duration codec emits (`"<n>h"` for any integer-hour
2754/// magnitude) — every value in the canonical authoring form's
2755/// `<integer><unit>` grammar at or below this cap renders to a clean
2756/// canonical string. The cap sits an order of magnitude above every
2757/// documented production-playbook recommendation band (Envoy default
2758/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
2759/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
2760/// configured maximum (`proxy_read_timeout` typical max `3600s`),
2761/// below the clearly-pathological "effectively no timeout" floor
2762/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
2763/// want for a long-running synchronous workflow, but a hard wall above
2764/// which the mesh-level deadline is structurally a non-deadline.
2765/// Lifted as a typed `pub const` so the bound has exactly one source
2766/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2767/// materializer's admission webhook and the caixa-mesh-side
2768/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2769/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
2770/// other typed upper bound in this crate carries
2771/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
2772/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2773/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2774/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2775pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
2776
2777/// Upper-bound ceiling on the `:politicas :retries` axis — every
2778/// validated [`MeshPolicy::retries`] past
2779/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
2780///
2781/// The typed slot is `Option<u32>` (`None` = no retries on transient
2782/// failure; `Some(0)` already rejected by the
2783/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
2784/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
2785/// .. }`) and the equivalent author-surface form
2786/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
2787/// serde / the codec — a structurally unbounded `u32` ceiling. The
2788/// runtime substrate that consumes the value (Envoy's
2789/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
2790/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
2791/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
2792/// admission cap is 10) translates a four-billion-retry policy into a
2793/// thundering-herd amplification vector on transient failure — the
2794/// caller's one request fans out to `retries` server-side calls per
2795/// edge per traversal, multiplying load by `(retries+1)^depth` across
2796/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
2797/// invariant "no infinite blocking" pairs with a no-runaway-amplification
2798/// invariant on the retry axis; both belong at the typed-slot layer.
2799///
2800/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
2801/// upstream mesh-policy schema that documents one) and sits above the
2802/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
2803/// every documented production playbook): a value the author can
2804/// plausibly want, but a hard wall above which the policy is
2805/// structurally a footgun. Lifted as a typed `pub const` so the bound
2806/// has exactly one source of truth — a future axis reaching for the
2807/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2808/// materializer's admission webhook, the caixa-mesh-side
2809/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
2810/// one place. Same shape every other typed upper bound in this crate
2811/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2812/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2813/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
2814/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2815pub const POLICY_RETRIES_MAX: u32 = 10;
2816
2817/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
2818/// axis — every validated [`CircuitBreaker::max_failures`] past
2819/// [`AplicacaoSpec::validate_politicas`] lies in
2820/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
2821///
2822/// The typed field is `u32` (the zero-floor arm
2823/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
2824/// `0` — a breaker that trips on the first call), so a programmatic
2825/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
2826/// and the equivalent author-surface form
2827/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
2828/// cleanly through serde — a structurally unbounded `u32` ceiling. A
2829/// `max_failures` value far above the documented production-playbook
2830/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
2831/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
2832/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
2833/// typical 5–50) silently disables the breaker's protection role:
2834/// the threshold is structurally so high that no realistic
2835/// failures-per-`:window` traffic shape can reach it, so the breaker
2836/// never trips and the typed slot becomes a no-op carried on every
2837/// emitted Envoy / Cilium L7 overlay. Pairs with the
2838/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
2839/// axis — both close the "structurally unbounded `u32` ceiling on a
2840/// typed policy axis" footgun the prior zero-floor-only checks left
2841/// open.
2842///
2843/// The `1000` ceiling sits an order of magnitude above every
2844/// documented upstream production-playbook recommendation band (the
2845/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
2846/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
2847/// the clearly-pathological "effectively no protection"
2848/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
2849/// plausibly want at hyperscale, but a hard wall above which the
2850/// policy is structurally a no-op. Lifted as a typed `pub const` so
2851/// the bound has exactly one source of truth — the future M4
2852/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2853/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
2854/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
2855/// one place. Same shape every other typed upper bound in this crate
2856/// carries ([`POLICY_RETRIES_MAX`],
2857/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2858/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2859/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2860pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
2861
2862/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
2863/// every validated [`CircuitBreaker::window`] past
2864/// [`AplicacaoSpec::validate_politicas`] lies in
2865/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
2866/// integer-millisecond magnitudes by the canonical-form gate
2867/// immediately preceding).
2868///
2869/// The typed field is `Duration` (the zero-floor arm
2870/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
2871/// `Duration::ZERO`, and the canonical-form arm
2872/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
2873/// sub-millisecond residue), so a programmatic struct literal
2874/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
2875/// and the equivalent author-surface form
2876/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
2877/// integer-hour magnitude) both round-trip cleanly through serde — a
2878/// structurally unbounded `Duration` ceiling. A `:window` value far
2879/// above the documented production-playbook band (Hystrix
2880/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
2881/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
2882/// Istio `outlierDetection.interval` default `10s`, Envoy
2883/// `outlier_detection.interval` default `10s`, AWS App Mesh
2884/// circuit-breaker time-window typical `30s..=300s`) degenerates the
2885/// breaker's role: a rolling-window failure counter whose window is
2886/// hours long is operationally a lifetime counter, the breaker's
2887/// "recent failures" memory is structurally so long that transient
2888/// failures are never forgotten, and the typed slot becomes a no-op
2889/// trigger that trips once and stays tripped for the lifetime of the
2890/// component carried on every emitted Envoy / Cilium L7 overlay.
2891///
2892/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
2893/// shared duration codec emits (`"<n>h"` for any integer-hour
2894/// magnitude) — every value in the canonical authoring form's
2895/// `<integer><unit>` grammar at or below this cap renders to a clean
2896/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
2897/// cap on the first typed-`Duration` `:politicas` axis: the two
2898/// duration-typed `:politicas` axes now share a single uniform top
2899/// edge so the next typed-slot wiring (the future caixa-mesh
2900/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
2901/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
2902/// admission webhook) reaches for either field knowing the value is
2903/// in `1ms..=1h` without re-validating at the renderer layer. The cap
2904/// sits two orders of magnitude above every documented upstream
2905/// production-playbook recommendation band (Hystrix / resilience4j /
2906/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
2907/// and below the clearly-pathological "rolling window degenerates to
2908/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
2909/// author can plausibly want for a very-low-traffic long-tail
2910/// failure-detection window, but a hard wall above which the breaker's
2911/// rolling-window contract is structurally a lifetime-counter contract.
2912/// Lifted as a typed `pub const` so the bound has exactly one source
2913/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2914/// materializer's admission webhook and the caixa-mesh-side
2915/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2916/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
2917/// other typed upper bound in this crate carries
2918/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
2919/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
2920/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2921/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2922/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2923pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
2924
2925/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
2926/// every validated [`RateLimit::rate`] past
2927/// [`AplicacaoSpec::validate_politicas`] lies in
2928/// `1..=POLICY_RATE_LIMIT_MAX`.
2929///
2930/// The typed field is `u32` (the zero-floor arm
2931/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
2932/// zero-rate limit denies every request, the canonical "I forgot
2933/// that 0 means deny-everything" footgun), so a programmatic struct
2934/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
2935/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
2936/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
2937/// round-trip cleanly through serde — a structurally unbounded `u32`
2938/// ceiling. The runtime substrate consuming the value (Envoy's
2939/// `local_rate_limit.token_bucket.max_tokens`, the future
2940/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2941/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
2942/// rate-limit into a no-op rate-limiter: the bucket capacity is
2943/// structurally so high no realistic per-edge traffic shape can
2944/// drain it, the limiter never trips, and the typed slot becomes a
2945/// "rate-limit declared, no enforcement" footgun — the canonical
2946/// declared-but-inert shape every other `:politicas` cap arm
2947/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
2948/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
2949///
2950/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
2951/// above every documented upstream production-playbook recommendation
2952/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
2953/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
2954/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
2955/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
2956/// `limit_req_zone` typical `1..=1_000` RPS) and below the
2957/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
2958/// `u32::MAX`): a value the author can plausibly want at hyperscale
2959/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
2960/// /h-window arm), but a hard wall above which the policy is
2961/// structurally a no-op carried verbatim on every emitted Envoy /
2962/// Cilium L7 overlay. The cap brackets all three canonical windows
2963/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
2964/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
2965/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
2966/// per-endpoint API band). Lifted as a typed `pub const` so the bound
2967/// has exactly one source of truth — the future M4
2968/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2969/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
2970/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
2971/// one place. Same shape every other typed upper bound in this crate
2972/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
2973/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
2974/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2975/// [`crate::LIMITS_WALL_CLOCK_MAX`],
2976/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2977/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2978pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
2979
2980// `:entrada :host` total-length and per-label cap axes route through
2981// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
2982// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
2983// pair of aplicacao-private aliases the previous `validate_entrada_host`
2984// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
2985// = 63`) were structurally the same K8s Gateway API v1 Hostname
2986// admission-schema bounds — the total-length cap on the OpenAPI
2987// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
2988// same regex — that the peer axes at the caixa-core::render level pin,
2989// so hoisting both readers onto the shared lifted constants closes the
2990// third-occurrence duplication threshold structurally: the M4
2991// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
2992// label validator, the future per-`Certificate` SAN emitter, and every
2993// other per-Gateway-API-Hostname landing site reach the same one place
2994// as the `:entrada :host` gate does — no per-axis alias drift surface
2995// between them, by construction.
2996
2997/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
2998/// extractor expression — the upper bound `validate_placement_shard_key`
2999/// enforces on every well-shaped shard-key past validate. The realistic
3000/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3001/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3002/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3003/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3004/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3005/// in `:shard-key`" footgun at validate time rather than at the future
3006/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3007const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3008
3009/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3010/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3011/// that maps the shared parser-shaped reason into the
3012/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3013/// is self-locating (the offending `caixa:` is named verbatim) and
3014/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3015/// fix it in one edit. Same diagnostic shape as
3016/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3017/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3018fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3019 // Empty is already gated by `MembroCaixaEmpty` at the call site;
3020 // re-checking here keeps the predicate usable from any future
3021 // call site (the M4 CR materializer) without an empty-check
3022 // footgun. The shared
3023 // [`crate::render::require_valid_dns_1123_label`] helper brackets
3024 // the empty-first + shape cascade every peer name axis
3025 // (`:placement :clusters`, `:placement :affinity`, `:contratos
3026 // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3027 // `:upgrade-from :module`) routes through, so drift between the
3028 // eight axes' accepted DNS-1123-label sets is structurally
3029 // impossible.
3030 crate::render::require_valid_dns_1123_label(
3031 caixa,
3032 || AplicacaoError::MembroCaixaEmpty,
3033 |reason| AplicacaoError::MembroCaixaInvalid {
3034 caixa: caixa.to_string(),
3035 reason,
3036 },
3037 )
3038}
3039
3040/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3041/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3042/// that maps the shared parser-shaped reason into the
3043/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3044///
3045/// Cluster names land in DNS-1123-label territory across every consumer:
3046/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3047/// the `lareira-fleet-programs` aggregator applies to scope programs to
3048/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3049/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3050/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3051/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3052/// side schema enforces the DNS-1123 label rule on admission; a
3053/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3054/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3055/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3056/// only gate and the failure surfaces as a no-match at filter time —
3057/// the workload doesn't land in the named cluster, with no diagnostic
3058/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3059/// build time mirrors the `:membros :caixa` value-shape trajectory
3060/// (3f9d7a0) on the peer name axis.
3061///
3062/// The diagnostic carries the offending `cluster:` verbatim plus a
3063/// parser-shaped `reason:` naming the specific violation, so the
3064/// author can grep their caixa.lisp for `:clusters` and fix it in
3065/// one edit. Same diagnostic shape as
3066/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3067fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3068 // Empty is already gated by `PlacementClusterEmpty` at the call
3069 // site; re-checking here keeps the predicate usable from any
3070 // future call site (the M4 CR materializer's per-cluster validator)
3071 // without an empty-check footgun. Routes through the shared
3072 // [`crate::render::require_valid_dns_1123_label`] gate the peer
3073 // name axes each land on.
3074 crate::render::require_valid_dns_1123_label(
3075 cluster,
3076 || AplicacaoError::PlacementClusterEmpty,
3077 |reason| AplicacaoError::PlacementClusterInvalid {
3078 cluster: cluster.to_string(),
3079 reason,
3080 },
3081 )
3082}
3083
3084/// Reject `:placement :affinity` hints whose shape can never legitimately
3085/// land in any downstream selector or label-keyed routing axis. Thin
3086/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3087/// shared parser-shaped reason into the
3088/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3089/// diagnostic is self-locating (the offending `:affinity` is named
3090/// verbatim) and the author can grep their caixa.lisp for
3091/// `:affinity "<hint>"` and fix it in one edit.
3092///
3093/// The `:affinity` slot carries a placement-engine hint — canonical
3094/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3095/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3096/// compression overlay and the future M4 placement-engine's per-hint
3097/// routing axis. Each downstream consumer (caixa-mesh's
3098/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3099/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3100/// `spec.placement.affinity` admission rule, the future M4 per-hint
3101/// node-affinity / pod-affinity rule generator keying off the same
3102/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3103/// selector) requires the value to be a DNS-1123 label — K8s label
3104/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3105/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3106/// admission rule the apiserver enforces.
3107///
3108/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3109/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3110/// Python-module-name leak), `:affinity "data.locality"` (the
3111/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3112/// `:affinity "data-locality-"` (boundary-hyphen violation),
3113/// `:affinity "data locality"` (paste-from-doc whitespace),
3114/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3115/// 64-byte over-cap slug silently passed the empty-only check and the
3116/// failure surfaced as a no-match at the M3 Adaptive compression
3117/// overlay's filter time (`placement.affinity` carried a malformed
3118/// value, no node matched, the workload landed on the default
3119/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3120/// the empty-:affinity / empty-shard-key / zero-:politicas /
3121/// empty-:contratos-target gates already close on every other
3122/// declare-but-no-opinion axis. Lifting the rejection to a build-time
3123/// gate closes the fifth typed slot on the Aplicacao surface to land
3124/// on the canonical DNS-1123 label floor (after the four Servico-name
3125/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
3126/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
3127/// b0e8748).
3128///
3129/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
3130/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
3131/// validated values are guaranteed-accepted by the apiserver without
3132/// re-validation at any downstream renderer or admission layer.
3133fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
3134 // Empty is gated separately at the call site for a self-locating
3135 // diagnostic; re-checking here keeps the predicate usable from any
3136 // future call site (the M4 CR materializer's per-affinity
3137 // validator) without an empty-check footgun. Routes through the
3138 // shared [`crate::render::require_valid_dns_1123_label`] gate the
3139 // peer name axes each land on.
3140 crate::render::require_valid_dns_1123_label(
3141 affinity,
3142 || AplicacaoError::PlacementAffinityEmpty,
3143 |reason| AplicacaoError::PlacementAffinityInvalid {
3144 affinity: affinity.to_string(),
3145 reason,
3146 },
3147 )
3148}
3149
3150/// Reject `:placement :shard-key` extractor expressions whose shape can
3151/// never legitimately drive the future M4 Akka-style cluster-sharding
3152/// reconciler's hash-extractor pass. Maps the per-byte / length checks
3153/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
3154/// diagnostic is self-locating (the offending `:shard-key` value is
3155/// named verbatim alongside the parser-shaped reason) and the author can
3156/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
3157/// edit.
3158///
3159/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
3160/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
3161/// expression naming the message property to hash on. The realistic
3162/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
3163/// property name; `$tenantId` — Akka entity-id placeholder;
3164/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
3165/// `${tenant}` — interpolation-style template) all sit in the printable
3166/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
3167/// multi-line blob landing in `:shard-key`, an embedded space from a
3168/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
3169/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
3170/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
3171/// check and the failure surfaces at the future M4 reconciler's hash
3172/// pass as a runtime extractor-evaluation error far from the source
3173/// `caixa.lisp`, with no field naming which member's `:shard-key`
3174/// carried the offending value.
3175///
3176/// The contract — the printable ASCII single-token intersection-floor
3177/// every Akka-style entity-id extractor implementation admits:
3178///
3179/// - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
3180/// peer DNS-1123-label-shaped `:placement :affinity` /
3181/// `:placement :clusters` identifier axes; realistic shard-keys sit
3182/// well under 32 bytes, the cap surfaces paste-from-doc multi-line
3183/// blob footguns at validate time;
3184/// - every byte in the printable ASCII range `0x21..=0x7E` —
3185/// rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
3186/// `"$tenantId\n"` from paste-from-aligned-doc /
3187/// paste-from-shell-heredoc), control characters (`\x00..\x1F`,
3188/// `\x7F` — the canonical "embedded null from a copy-paste-binary
3189/// footgun"), and non-ASCII bytes (`"$tenàntId"` —
3190/// un-Punycode-encoded IDN that round-trips inconsistently across
3191/// NFC/NFD normalization).
3192///
3193/// The accepted set is broader than the DNS-1123 label floor the peer
3194/// `:placement :clusters` / `:placement :affinity` axes use because the
3195/// `:shard-key` value is not a K8s `metadata.name` / label-selector
3196/// landing site; it's an extractor expression the future Akka-style
3197/// reconciler reads as a property reference. The realistic forms
3198/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
3199/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
3200/// but every Akka-style entity-id extractor parses. The
3201/// printable-ASCII-token floor accepts every shape any such extractor
3202/// would accept while rejecting the cross-implementation footguns
3203/// (whitespace breaks token boundaries; non-ASCII round-trips
3204/// inconsistently across YAML emitters and NFC/NFD normalization;
3205/// control characters silently corrupt the next read).
3206///
3207/// Until this gate landed `validate_placement` only refused the
3208/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
3209/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
3210/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
3211/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
3212/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
3213/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
3214/// control character from paste-from-binary, the 64-byte over-cap
3215/// paste-from-doc multi-line slug) silently passed validate. The future
3216/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
3217/// would then surface the malformed value either as a runtime
3218/// extractor-evaluation error (whitespace breaks the extractor's token
3219/// boundary, no match) or as a silently-different shard assignment
3220/// across YAML emitters (non-ASCII normalizes differently between the
3221/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
3222/// parser, the same entity ID maps to two distinct shards on a
3223/// re-render). Lifting the shape gate to caixa-build time makes the
3224/// extractor-floor invariant a structural property of every validated
3225/// `Placement`: every `Sharded` placement past `validate_placement` has
3226/// a `:shard-key` the future M4 reconciler can hash without
3227/// re-validating at the runtime layer.
3228///
3229/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
3230/// [`AplicacaoError::ContratoSubjectInvalid`] /
3231/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
3232/// on the peer `:contratos` payload axes — each lifts the
3233/// runtime-side parser's intersection-floor to a caixa-build-time gate,
3234/// closing the canonical "this passed validate but the runtime parser
3235/// rejected it" surprise.
3236fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
3237 // Empty is gated separately at the call site via the more
3238 // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
3239 // re-checking here keeps the predicate usable from any future call
3240 // site (the M4 CR materializer's per-shard-key validator) without
3241 // an empty-check footgun.
3242 if key.is_empty() {
3243 return Err(AplicacaoError::ShardedKeyEmpty);
3244 }
3245 if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
3246 return Err(AplicacaoError::ShardKeyInvalid {
3247 shard_key: key.to_string(),
3248 reason: format!(
3249 "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
3250 (got {} bytes; realistic Akka-style entity-id extractor expressions \
3251 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
3252 well under 32 bytes, this length suggests a paste-from-doc \
3253 multi-line blob landed in `:shard-key` instead of a single-token \
3254 extractor expression)",
3255 key.len()
3256 ),
3257 });
3258 }
3259 for &b in key.as_bytes() {
3260 if (0x21..=0x7E).contains(&b) {
3261 continue;
3262 }
3263 let reason = if b == b' ' {
3264 "contains a space (Akka-style entity-id extractor expressions are \
3265 single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
3266 whitespace breaks the extractor's token boundary at the runtime layer, \
3267 and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
3268 a multi-token blob in one `:shard-key` slot)"
3269 .to_string()
3270 } else if b == b'\t' {
3271 "contains a tab character (paste-from-aligned-doc footgun; the \
3272 Akka-style entity-id extractor reads `:shard-key` as a single-token \
3273 reference, embedded whitespace breaks the token boundary at the \
3274 runtime hash-extractor pass)"
3275 .to_string()
3276 } else if b == b'\n' || b == b'\r' {
3277 format!(
3278 "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
3279 paste-from-multiline-doc footgun; the Akka-style entity-id \
3280 extractor reads `:shard-key` as a single-token reference, embedded \
3281 newlines either truncate the value at the YAML emitter layer or \
3282 break the token boundary at the runtime hash-extractor pass)"
3283 )
3284 } else if b < 0x20 || b == 0x7F {
3285 format!(
3286 "contains control character 0x{b:02x} (the canonical \
3287 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
3288 control characters silently corrupt round-trip serialization \
3289 across YAML emitters and break the runtime hash-extractor's \
3290 single-token parser)"
3291 )
3292 } else {
3293 format!(
3294 "contains non-ASCII byte 0x{b:02x} (the canonical \
3295 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
3296 inconsistently across NFC/NFD normalization on APFS / ext4 / \
3297 across YAML emitter implementations — the same entity ID can \
3298 silently map to two distinct shards on a re-render. Use a \
3299 printable-ASCII extractor expression like `tenantId`, \
3300 `$tenantId`, or `metadata.tenantId`)"
3301 )
3302 };
3303 return Err(AplicacaoError::ShardKeyInvalid {
3304 shard_key: key.to_string(),
3305 reason,
3306 });
3307 }
3308 Ok(())
3309}
3310
3311/// Reject `:contratos :de` / `:contratos :para` values whose shape
3312/// can never legitimately match a validated `:membros :caixa`. Thin
3313/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3314/// shared parser-shaped reason into the
3315/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
3316/// diagnostic is self-locating (which slot — `:de` or `:para` — and
3317/// the offending value verbatim) and the author can grep their
3318/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
3319/// one edit.
3320///
3321/// Until this gate landed an empty or DNS-1123-malformed `:de` /
3322/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
3323/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
3324/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
3325/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
3326/// un-Punycode-encoded IDN) silently passed the per-axis check and
3327/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
3328/// membership lookup — diagnostic-framed as "this caixa is not in
3329/// `:membros`" when the root cause is "this `:de` value is not a
3330/// well-shaped Servico-name identifier and could never legitimately
3331/// match any validated member". Because every `:membros :caixa` is
3332/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
3333/// `names` HashSet structurally never contains an empty / malformed
3334/// string, so the membership lookup arm misframes every empty /
3335/// malformed input. Lifting the shape arm ahead of the lookup
3336/// preserves the legitimate `ContratoMemberMissing` arm (a
3337/// well-shaped `:de` that simply isn't in `:membros` — a phantom
3338/// reference) while routing every structurally-impossible-to-match
3339/// input through the narrower self-locating shape diagnostic.
3340///
3341/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3342/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
3343/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
3344/// to land on the canonical [`crate::render::is_dns_1123_label`]
3345/// floor. The `slot: &'static str` field carries the kebab-case
3346/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
3347/// per-callback-slot diagnostic shape and the
3348/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
3349/// (85f102c) cross-list-tag pattern.
3350fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
3351 // Routes through the shared
3352 // [`crate::render::require_valid_dns_1123_label`] gate the peer
3353 // name axes each land on. The `slot: &'static str` field flows
3354 // through both error variants so the diagnostic names which
3355 // per-edge axis (`:de` vs `:para`) the offending value came from.
3356 crate::render::require_valid_dns_1123_label(
3357 caixa,
3358 || AplicacaoError::ContratoCaixaEmpty { slot },
3359 |reason| AplicacaoError::ContratoCaixaInvalid {
3360 slot,
3361 caixa: caixa.to_string(),
3362 reason,
3363 },
3364 )
3365}
3366
3367/// Reject `:entrada :para` values whose shape can never legitimately
3368/// match a validated `:membros :caixa`. Thin wrapper around
3369/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
3370/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
3371/// variant, so the diagnostic is self-locating (the offending
3372/// `:entrada :para` value is named verbatim) and the author can grep
3373/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
3374///
3375/// Until this gate landed an empty or DNS-1123-malformed `:entrada
3376/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
3377/// ADR typo, `:para "my_cart"` the Python-module-name leak,
3378/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
3379/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
3380/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
3381/// silently passed the per-axis check and surfaced as
3382/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
3383/// — diagnostic-framed as "this caixa is not in `:membros`" when the
3384/// root cause is "this `:entrada :para` value is not a well-shaped
3385/// Servico-name identifier and could never legitimately match any
3386/// validated member". Because every `:membros :caixa` is shape-
3387/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
3388/// `HashSet` structurally never contains an empty / malformed string,
3389/// so the membership lookup arm misframes every empty / malformed
3390/// input. Lifting the shape arm ahead of the lookup preserves the
3391/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
3392/// simply isn't in `:membros` — a phantom reference) while routing
3393/// every structurally-impossible-to-match input through the narrower
3394/// self-locating shape diagnostic.
3395///
3396/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3397/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
3398/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
3399/// fourth and last Aplicacao-level Servico-name reference axis to
3400/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
3401/// No `slot: &'static str` field because there is only one axis
3402/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
3403/// the simpler shape mirrors [`validate_membro_caixa`] and
3404/// [`validate_placement_cluster`].
3405fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
3406 // Empty is gated separately at the call site for a self-locating
3407 // diagnostic; re-checking here keeps the predicate usable from any
3408 // future call site (the M4 CR materializer's per-`:entrada`
3409 // validator) without an empty-check footgun. Routes through the
3410 // shared [`crate::render::require_valid_dns_1123_label`] gate the
3411 // peer name axes each land on.
3412 crate::render::require_valid_dns_1123_label(
3413 para,
3414 || AplicacaoError::EntradaParaEmpty,
3415 |reason| AplicacaoError::EntradaParaInvalid {
3416 para: para.to_string(),
3417 reason,
3418 },
3419 )
3420}
3421
3422/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
3423/// would refuse at admission time. The contract — exactly the regex
3424/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
3425/// and `HTTPRoute.spec.hostnames[]`,
3426/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
3427/// (max length 253; per-label max length 63):
3428///
3429/// - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
3430/// uppercase, no underscore, no Unicode/IDN — IDN must be
3431/// pre-encoded as Punycode `xn--…` by the author);
3432/// - exactly one optional leading wildcard label (`*.`); a wildcard
3433/// in any non-leading label position is rejected;
3434/// - each `.`-separated label is 1..=63 bytes, with non-hyphen
3435/// alphanumeric at both boundaries (no `-foo`, no `foo-`);
3436/// - total length 1..=253 bytes;
3437/// - no IPv4 literal (Gateway API forbids IP literals);
3438/// - no scheme (`https://`, `http://`), no port (`:8080`), no
3439/// whitespace, no path (`/`).
3440///
3441/// Lifted as a typed gate (rather than an inline cascade in
3442/// `validate()`) so the contract lives in one place — every future
3443/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3444/// materializer's host validator, the future per-`:entrada` SAN
3445/// emission for cert-manager Certificates, the multi-`:entrada`
3446/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
3447/// for the same predicate, not its own. Same compounding shape as
3448/// `is_canonical_rate_limit_window` (808017c) and
3449/// [`WitTarget::label`] (previously the free `contrato_target_label`
3450/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
3451/// per-variant label match is compiler-checked-exhaustive).
3452///
3453/// The diagnostic carries the offending `host:` verbatim plus a
3454/// parser-shaped `reason:` naming the specific violation, so the
3455/// author can grep their caixa.lisp for `:host "<host>"` and fix it
3456/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
3457/// (9888b13).
3458fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
3459 // Empty is already gated by `EmptyEntradaHost` at the call site;
3460 // re-checking here keeps the predicate usable from any future
3461 // call site (M4 CR materializer) without an empty-check footgun.
3462 if host.is_empty() {
3463 return Err(AplicacaoError::EmptyEntradaHost);
3464 }
3465 if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
3466 return Err(AplicacaoError::EntradaHostInvalid {
3467 host: host.to_string(),
3468 reason: format!(
3469 "exceeds Gateway API v1 Hostname max length of {cap} bytes \
3470 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
3471 host.len(),
3472 cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
3473 ),
3474 });
3475 }
3476 if host.contains("://") {
3477 return Err(AplicacaoError::EntradaHostInvalid {
3478 host: host.to_string(),
3479 reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
3480 Gateway API takes the bare hostname)"
3481 .to_string(),
3482 });
3483 }
3484 if host.contains('/') {
3485 return Err(AplicacaoError::EntradaHostInvalid {
3486 host: host.to_string(),
3487 reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
3488 matching is in `:entrada :paths`)"
3489 .to_string(),
3490 });
3491 }
3492 // After the `://` scheme-prefix and `/` path arms have ruled out the
3493 // two `:`-bearing shapes the Gateway API actively rejects with
3494 // location-shaped diagnostics, any remaining `:` in the host body is
3495 // either the canonical "I put the port in the `:host` slot"
3496 // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
3497 // slot lives one axis away on the same `:entrada` block) or an
3498 // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
3499 // Hostname forbids identically to the IPv4-literal arm below. Both
3500 // shapes silently fell through the `://` and `/` arms before this
3501 // lift and surfaced as a deep `label "<rest>:<port>" contains
3502 // invalid character ':'` diagnostic from the per-byte loop near the
3503 // bottom of this predicate, which named the offending byte but not
3504 // the canonical authoring fix — for the port case the author has to
3505 // know the `:entrada` block carries a separate `:port u16` slot
3506 // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
3507 // move the value over; for the IPv6 case the author has to know
3508 // Gateway API v1 forbids IP literals across the board. The contract
3509 // doc-comment above already promises "no port (`:8080`)" verbatim
3510 // in the rejected-shape enumeration but the predicate's
3511 // implementation refused the `:` only as a side-effect of the
3512 // per-label `[a-z0-9-]` character-class loop; this arm brings the
3513 // implementation in line with the documented contract by surfacing
3514 // the canonical fix at the top-level shape gate, peer with how the
3515 // `://` arm names the scheme prefix and the `/` arm names the
3516 // `:entrada :paths` axis. Same compounding trajectory the recent
3517 // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
3518 // — the typed slot's rejected set matches the apiserver's rejected
3519 // set, structurally, with a self-locating diagnostic at the
3520 // offending axis instead of a deep parser-shape leak.
3521 if host.contains(':') {
3522 return Err(AplicacaoError::EntradaHostInvalid {
3523 host: host.to_string(),
3524 reason: "must not contain `:` (the port belongs in the `:entrada :port` \
3525 slot — a separate `u16` axis on the same `:entrada` block, \
3526 defaulting to 8080 — not in the host body; drop the `:<port>` \
3527 suffix and author the bare hostname. If you intended an IPv6 \
3528 literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
3529 Hostname forbids IP literals identically to the IPv4-literal \
3530 arm — use a DNS name)"
3531 .to_string(),
3532 });
3533 }
3534 // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
3535 // predicate — the same single source of truth every peer
3536 // ASCII-whitespace scan in caixa-core flows through: the four
3537 // typed-magnitude codec sites (`limits::parse_byte_size` backing
3538 // `:limits :memory`, `limits::parse_duration` backing `:limits
3539 // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
3540 // `aplicacao::rate_limit_codec::parse` backing `:politicas
3541 // :rate-limit`) and the shared duration codec
3542 // (`supervisor::duration_codec::parse`) backing `:supervisor
3543 // :restart-window` / `:politicas :timeout` / `:politicas
3544 // :circuit-breaker :window`. This landing closes the last string-typed
3545 // slot in caixa-core still calling `.bytes().any(|b|
3546 // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
3547 // across every typed slot now shares one predicate, so a future
3548 // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
3549 // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
3550 // deliberately excluded from the peer non-ASCII predicate) can
3551 // extend at this shared site in one edit rather than seven
3552 // independent scans diverging over time. Naming the offending byte
3553 // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
3554 // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
3555 // the offending byte verbatim" discipline every peer codec site
3556 // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
3557 // / `supervisor.rs:823` / `aplicacao.rs:1640`).
3558 if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
3559 return Err(AplicacaoError::EntradaHostInvalid {
3560 host: host.to_string(),
3561 reason: format!(
3562 "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
3563 Hostname is a single-token DNS name — leading, trailing, \
3564 or embedded whitespace breaks the K8s apiserver's Hostname \
3565 regex at admission time; the paste-from-aligned-doc / \
3566 paste-from-shell-history / paste-from-CSV footgun silently \
3567 lands a multi-token blob in `:entrada :host`. Strip every \
3568 whitespace byte and author the bare hostname — space \
3569 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
3570 refuse identically)"
3571 ),
3572 });
3573 }
3574 // Peer of the ASCII-whitespace scan above: route the non-ASCII
3575 // subset of Unicode `White_Space` through the shared
3576 // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
3577 // single source of truth every peer non-ASCII-whitespace scan in
3578 // caixa-core flows through: `limits::parse_byte_size` (`:limits
3579 // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
3580 // `limits::parse_millicores` (`:limits :cpu`),
3581 // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
3582 // and `supervisor::duration_codec::parse` (`:supervisor
3583 // :restart-window` / `:politicas :timeout` / `:politicas
3584 // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
3585 // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
3586 // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
3587 // paste-from-web-doc), or an EM-SPACE-split host
3588 // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
3589 // survived this predicate's ASCII byte-scan (none of the UTF-8
3590 // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
3591 // `u8::is_ascii_whitespace`), then landed on the per-label
3592 // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
3593 // predicate with the generic `label "…" must start and end with an
3594 // alphanumeric` diagnostic — a "far from source at build-time"
3595 // leak that names the label-shape violation but not the
3596 // paste-from-typography origin the author actually needs to fix.
3597 // Peer with the four codec sites the 1b75b38 landing pinned: the
3598 // typed slot's diagnostic axis names the offending codepoint
3599 // (`U+XXXX`) verbatim rather than laundering the value through a
3600 // downstream label-shape arm, so the author can grep their
3601 // caixa.lisp for the invisible codepoint at the surfaced position
3602 // rather than eyeball a multi-byte host for embedded NBSP / LINE
3603 // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
3604 // discipline the peer ASCII-whitespace arm (720ac3b) carries:
3605 // drift between any two typed-slot sites' non-ASCII-whitespace
3606 // rejection set becomes a single-edit fix at the shared predicate
3607 // rather than N independent inline scans diverging over time, and
3608 // a future stricter classification (BOM `\u{FEFF}` / ZWSP
3609 // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
3610 // `char::is_whitespace`" class the peer non-ASCII predicate's
3611 // doc-comment names as the follow-up trajectory) extends at the
3612 // shared predicate in one edit rather than seven.
3613 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
3614 return Err(AplicacaoError::EntradaHostInvalid {
3615 host: host.to_string(),
3616 reason: format!(
3617 "contains non-ASCII Unicode whitespace character {ch:?} \
3618 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
3619 single-token DNS name limited to `[a-z0-9-]` labels; \
3620 the paste-from-typography footgun silently lands an \
3621 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
3622 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
3623 `U+3000`, and every other member of the Unicode \
3624 `White_Space` property outside the ASCII byte range) \
3625 in `:entrada :host`, which the K8s apiserver's \
3626 Hostname regex refuses at admission time far from the \
3627 caixa.lisp source line. Strip every non-ASCII \
3628 whitespace character and author the bare hostname \
3629 with only ASCII bytes (write \"checkout.quero.cloud\" \
3630 verbatim)",
3631 codepoint = ch as u32,
3632 ),
3633 });
3634 }
3635
3636 // Strip the optional single leading wildcard label *before* the
3637 // trailing-dot check so the bare `"*."` form surfaces the more
3638 // self-locating "wildcard without domain" diagnostic instead of
3639 // the generic "trailing dot" one.
3640 let (had_wildcard, rest) = match host.strip_prefix("*.") {
3641 Some(r) => (true, r),
3642 None => (false, host),
3643 };
3644 if had_wildcard && rest.is_empty() {
3645 return Err(AplicacaoError::EntradaHostInvalid {
3646 host: host.to_string(),
3647 reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
3648 });
3649 }
3650 if rest.contains('*') {
3651 return Err(AplicacaoError::EntradaHostInvalid {
3652 host: host.to_string(),
3653 reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
3654 no inner or trailing `*` labels"
3655 .to_string(),
3656 });
3657 }
3658 if rest.ends_with('.') {
3659 return Err(AplicacaoError::EntradaHostInvalid {
3660 host: host.to_string(),
3661 reason: "must not have a trailing `.` (Gateway API hostnames are not \
3662 fully-qualified with a root dot; the apiserver regex rejects \
3663 trailing dots)"
3664 .to_string(),
3665 });
3666 }
3667
3668 // Reject pure IPv4 literals: four dot-separated labels, every
3669 // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
3670 // literals as Hostnames.
3671 let labels: Vec<&str> = rest.split('.').collect();
3672 if labels.len() == 4
3673 && labels
3674 .iter()
3675 .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
3676 {
3677 return Err(AplicacaoError::EntradaHostInvalid {
3678 host: host.to_string(),
3679 reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
3680 literals; use a DNS name)"
3681 .to_string(),
3682 });
3683 }
3684
3685 // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
3686 // hyphen, with non-hyphen at both boundaries.
3687 for label in &labels {
3688 if label.is_empty() {
3689 return Err(AplicacaoError::EntradaHostInvalid {
3690 host: host.to_string(),
3691 reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
3692 });
3693 }
3694 if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
3695 return Err(AplicacaoError::EntradaHostInvalid {
3696 host: host.to_string(),
3697 reason: format!(
3698 "label {label:?} exceeds DNS-1123 label max length of \
3699 {cap} bytes (got {} bytes)",
3700 label.len(),
3701 cap = crate::render::DNS_1123_LABEL_MAX_LEN,
3702 ),
3703 });
3704 }
3705 let bytes = label.as_bytes();
3706 if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
3707 return Err(AplicacaoError::EntradaHostInvalid {
3708 host: host.to_string(),
3709 reason: format!(
3710 "label {label:?} must start and end with an alphanumeric \
3711 (no leading or trailing `-`)"
3712 ),
3713 });
3714 }
3715 for &b in bytes {
3716 let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
3717 if !valid {
3718 let msg = if b.is_ascii_uppercase() {
3719 format!(
3720 "label {label:?} contains uppercase character {ch:?} \
3721 (Gateway API hostnames are lowercase-only; use {lower:?})",
3722 ch = b as char,
3723 lower = label.to_ascii_lowercase()
3724 )
3725 } else if b == b'_' {
3726 format!(
3727 "label {label:?} contains `_` (Gateway API hostnames \
3728 allow only `[a-z0-9-]`; use `-` instead)"
3729 )
3730 } else {
3731 format!(
3732 "label {label:?} contains invalid character {ch:?} \
3733 (Gateway API hostnames allow only `[a-z0-9-]`)",
3734 ch = b as char
3735 )
3736 };
3737 return Err(AplicacaoError::EntradaHostInvalid {
3738 host: host.to_string(),
3739 reason: msg,
3740 });
3741 }
3742 }
3743 }
3744 Ok(())
3745}
3746
3747/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
3748/// would refuse at admission time. Thin wrapper around
3749/// [`crate::render::is_gateway_api_http_path`] that maps the shared
3750/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
3751/// variant, preserving the more self-locating
3752/// [`AplicacaoError::EntradaPathEmpty`] /
3753/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
3754/// path fails those narrower invariants first.
3755///
3756/// The contract is the canonical HTTP-path grammar — `1..=
3757/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
3758/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
3759/// whitespace/control/non-ASCII bytes — shared with the
3760/// `:contratos :endpoint` axis through the lifted predicate so drift
3761/// between either landing site and the K8s apiserver-side
3762/// HTTPPathMatch.value OpenAPI schema is a build error visible at
3763/// the predicate, not a per-renderer "this passed validate but failed
3764/// admission" surprise. The diagnostic carries the offending `path:`
3765/// verbatim plus a parser-shaped `reason:` naming the specific
3766/// violation, so the author can grep their caixa.lisp for `:paths`
3767/// and fix it in one edit. Same diagnostic shape as
3768/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
3769/// axis.
3770fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
3771 // Empty and missing-leading-`/` are already gated at the call
3772 // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
3773 // checking here keeps the per-axis narrower diagnostics in force
3774 // when the predicate is reached directly (and `is_gateway_api_http_path`
3775 // itself defends against `bytes[0]`-style indexing on empty
3776 // input).
3777 if path.is_empty() {
3778 return Err(AplicacaoError::EntradaPathEmpty);
3779 }
3780 if !path.starts_with('/') {
3781 return Err(AplicacaoError::EntradaPathNotAbsolute {
3782 path: path.to_string(),
3783 });
3784 }
3785 crate::render::is_gateway_api_http_path(path).map_err(|reason| {
3786 AplicacaoError::EntradaPathInvalid {
3787 path: path.to_string(),
3788 reason,
3789 }
3790 })
3791}
3792
3793mod rate_limit_codec {
3794 // `Duration` is no longer named here — the codec routes through
3795 // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
3796 // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
3797 // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
3798 // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
3799 // closed-set enum's arm-table rather than through vestigial free-helper
3800 // delegates.
3801 use super::{RateLimit, RateLimitUnit};
3802 use serde::{Deserialize, Deserializer, Serializer};
3803
3804 pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
3805 match v {
3806 Some(rl) => s.serialize_str(&render(*rl)),
3807 None => s.serialize_none(),
3808 }
3809 }
3810
3811 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
3812 let opt: Option<String> = Option::deserialize(d)?;
3813 match opt {
3814 None => Ok(None),
3815 Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
3816 }
3817 }
3818
3819 fn parse(s: &str) -> Result<RateLimit, String> {
3820 // Whitespace-rejection arm — peer with the leading-`+`
3821 // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
3822 // same canonical-form render-determinism axis. Until this gate
3823 // landed the parser silently tolerated leading / trailing /
3824 // internal whitespace via the top-level `s.trim()` and the
3825 // per-part `rate_str.trim()` / `unit.trim()` calls, so every
3826 // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
3827 // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
3828 // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
3829 // serde silently round-tripped to `"100/s"` on the next emit
3830 // (a *different* canonical string) — breaking the THEORY.md
3831 // Part V render-determinism contract on the same
3832 // canonical-form-drift axis the leading-`+` arm below (the
3833 // 4eeae98 predecessor) and the leading-zero arm below (the
3834 // 4f46830 predecessor) already close.
3835 //
3836 // The canonical author shape is `<integer>/<s|m|h>` with no
3837 // whitespace bytes anywhere — every string [`render`] emits
3838 // carries none, so the parser's accepted set must match for
3839 // serialize / deserialize to round-trip losslessly. This gate
3840 // makes the pre-existing `s.trim()` / `rate_str.trim()` /
3841 // `unit.trim()` calls below strict no-ops on the accepted set
3842 // (every byte-position match they would perform is now already
3843 // trimmed away by the accepted set itself), while the arm
3844 // surfaces every rejected whitespace-carrying shape with a
3845 // self-locating diagnostic naming the offending byte and the
3846 // canonical form the author intended, peer with every prior
3847 // canonical-form-drift arm on this codec.
3848 //
3849 // Routed through the lifted
3850 // [`crate::render::find_ascii_whitespace_byte`] predicate — the
3851 // same source of truth the four peer typed-magnitude codec
3852 // sites (`limits::parse_byte_size`, `limits::parse_duration`,
3853 // `limits::parse_millicores`, `supervisor::duration_codec`)
3854 // share. `u8::is_ascii_whitespace()` at the predicate covers
3855 // the five WhatWG-conformant ASCII whitespace bytes (space,
3856 // tab, LF, FF, CR); the "single lifted predicate" discipline
3857 // the peer non-ASCII arm below carries on the strictly-
3858 // complementary Unicode `White_Space` class extends here to
3859 // the ASCII byte set as well.
3860 if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
3861 return Err(format!(
3862 "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3863 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
3864 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
3865 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
3866 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
3867 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
3868 on first serialize — breaking the THEORY.md Part V render-determinism \
3869 contract every typed slot carries. Strip every whitespace byte (write \
3870 `\"100/s\"` verbatim)"
3871 ));
3872 }
3873 // Non-ASCII Unicode `White_Space` arm — the strictly-
3874 // complementary class the ASCII arm above cannot see.
3875 // `str::trim` at the top of every peer codec uses
3876 // `char::is_whitespace` (Unicode `White_Space`, strictly
3877 // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
3878 // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
3879 // survives the byte-scan (its UTF-8 bytes are not in
3880 // `is_ascii_whitespace`), gets silently stripped by the
3881 // top-level `s.trim()` below, and the value round-trips
3882 // through `render` to a *different* canonical form
3883 // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
3884 // render-determinism contract every typed slot carries.
3885 // Closed here (`:politicas :rate-limit`) and at the three
3886 // peer codec sites (`limits::parse_byte_size`,
3887 // `limits::parse_duration`, `supervisor::duration_codec`)
3888 // through the shared
3889 // [`crate::render::find_non_ascii_whitespace_char`] predicate
3890 // — the "single lifted predicate across all four codec sites
3891 // in one follow-up run" the 24a8ad4 commit body's `Forward
3892 // compounding` bullet named as the next compounding step.
3893 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
3894 return Err(format!(
3895 "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
3896 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
3897 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
3898 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
3899 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
3900 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
3901 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
3902 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
3903 silently strips it at parse entry, and the value round-trips through \
3904 `render` to a *different* canonical form (`\"100/s\"`) on first \
3905 serialize — breaking the THEORY.md Part V render-determinism contract \
3906 every typed slot carries. Strip every non-ASCII whitespace character \
3907 (write `\"100/s\"` verbatim with only ASCII bytes)",
3908 cp = ch as u32
3909 ));
3910 }
3911 let s = s.trim();
3912 let (rate_str, unit) = s
3913 .split_once('/')
3914 .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
3915 let rate_trim = rate_str.trim();
3916 // The canonical authoring form for `:politicas :rate-limit` is
3917 // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
3918 // non-negative integer with no decimal point and no leading
3919 // sign, so the parser's accepted set must match for
3920 // serialize/deserialize to round-trip without canonical-form
3921 // drift. Until this gate landed the parser accepted any
3922 // `u32::from_str`-shaped magnitude — and current Rust
3923 // `u32::from_str` permissively accepts a leading `+` (`"+100"`
3924 // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
3925 // serde silently round-tripped to `"100/s"` on the next emit
3926 // (a *different* canonical string) — breaking the THEORY.md
3927 // Part V render-determinism contract on the fifth typed-codec
3928 // surface in caixa-core (peer with the four duration codecs the
3929 // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
3930 // already covered: `supervisor::duration_codec` backing three
3931 // typed-duration slots, `limits::parse_duration` backing
3932 // `:limits :wall-clock`, `limits::parse_byte_size` backing
3933 // `:limits :memory`). The fractional / decimal-shaped sibling
3934 // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
3935 // existing rejection arm, but the diagnostic is value-laundered
3936 // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
3937 // doesn't name the canonical-form remediation or the round-trip
3938 // drift the next emit would produce); this gate lifts the
3939 // fractional arm onto the same canonical-form diagnostic the
3940 // peer codecs carry.
3941 //
3942 // Strict canonical form: every byte of the magnitude is an
3943 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3944 // inputs the gate distinguishes "non-canonical-but-numeric"
3945 // (parses as f64 or i64 — surfaced with a self-locating
3946 // diagnostic naming the canonical authoring form and the
3947 // round-trip drift the rejected shape would produce on first
3948 // serialize) from "garbage" (parses as neither — surfaced with
3949 // the existing narrower `"not a u32"` wording so its
3950 // diagnostic shape remains stable for the parser-shape footgun
3951 // case).
3952 //
3953 // Routed through the lifted
3954 // [`crate::render::is_digit_only_magnitude`] predicate — the
3955 // same source of truth the four peer typed-magnitude codec
3956 // sites share.
3957 let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
3958 if !digit_only {
3959 let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
3960 if numeric {
3961 return Err(format!(
3962 "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
3963 canonical authoring form for `:politicas :rate-limit` is \
3964 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
3965 with no decimal point and no leading `+` / `-` sign. A fractional / \
3966 signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
3967 through `render` to a *different* canonical form (`\"1/s\"`, \
3968 `\"100/s\"`, parser-reject) on first serialize — breaking the \
3969 THEORY.md Part V render-determinism contract every typed slot \
3970 carries. Pick an integer rate that fits the desired window \
3971 (write `\"6000/m\"` instead of `\"1.66/s\"`)"
3972 ));
3973 }
3974 return Err(format!("rate-limit rate {rate_str:?} not a u32"));
3975 }
3976 // Leading-zero arm — peer with the prior `"+100/s"` arm above
3977 // (4eeae98's predecessor) on the same canonical-form
3978 // render-determinism axis. The digit-only gate accepts
3979 // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
3980 // them losslessly (= 100, 0, 7), but `render` emits the
3981 // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
3982 // a *different* canonical string on the next emit, breaking
3983 // the THEORY.md Part V render-determinism contract the same
3984 // way `"+100/s"` did before the leading-`+` arm landed. The
3985 // single-byte magnitude `"0"` itself round-trips losslessly
3986 // through `render` (`render(0)` emits `"0/s"`) — the
3987 // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
3988 // what refuses rate-zero authoring, so `"0/s"` stays in the
3989 // accepted set at this codec layer and the diagnostic
3990 // partitioning between canonical-form drift (this arm) and
3991 // semantic-zero (the downstream gate) remains stable.
3992 // Peer with the future leading-zero arms on the three peer
3993 // typed-magnitude codecs the trajectory acknowledges:
3994 // `supervisor::duration_codec`, `limits::parse_duration`,
3995 // `limits::parse_byte_size` — each carries the same
3996 // canonical-form-drift class today; this gate lands the
3997 // discipline on the fourth typed-magnitude codec in
3998 // caixa-core first because the peer `"+100/s"` arm above is
3999 // the closest predecessor on the trajectory.
4000 //
4001 // Routed through the lifted
4002 // [`crate::render::is_leading_zero_padded_magnitude`]
4003 // predicate — the same source of truth the four peer
4004 // typed-magnitude codec sites share.
4005 if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4006 return Err(format!(
4007 "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4008 canonical authoring form for `:politicas :rate-limit` is \
4009 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4010 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4011 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4012 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4013 first serialize — breaking the THEORY.md Part V render-determinism \
4014 contract every typed slot carries. Strip the leading zeros (write \
4015 `\"100/s\"` instead of `\"0100/s\"`)"
4016 ));
4017 }
4018 // The digit-only gate guarantees every byte is `[0-9]`, and
4019 // the leading-zero arm above guarantees the magnitude is
4020 // either the single byte `"0"` or starts with `[1-9]`, so
4021 // the only way `u32::from_str` can fail here is overflow
4022 // (the magnitude exceeds `u32::MAX`). Surface that with an
4023 // overflow-shaped wording so the diagnostic names the
4024 // offending magnitude verbatim rather than collapsing onto
4025 // the non-canonical arm. Same shape
4026 // `supervisor::duration_codec` (1c55a2a) carries on the peer
4027 // duration-codec axis.
4028 let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4029 format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4030 })?;
4031 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4032 // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4033 // arm reads the `&str → Duration` projection through the
4034 // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4035 // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4036 // with [`super::RateLimitUnit::window`]) rather than the vestigial
4037 // module-private `rate_limit_window_from_unit` free helper the
4038 // predecessor 61421a6 left as the last unlifted delegate on this
4039 // axis. One typed dispatch on the substrate primitive instead of
4040 // one runtime call through the free-helper delegate; the sole
4041 // production consumer of the `&str → Duration` axis (this parse
4042 // arm) now reaches for exactly one typed method on the closed-set
4043 // enum, sibling to the codec's render arm's
4044 // [`super::RateLimit::canonical_unit`] dispatch on the paired
4045 // `Duration → RateLimitUnit` axis and to the validate gate's
4046 // [`super::RateLimit::canonical_unit`] shape-probe on the
4047 // canonical-window axis. A future rate-limit-unit addition (a
4048 // `"d"` day suffix once Envoy's `rate_limit_action` grows
4049 // daily-bucket support, a `"ms"` sub-second window once
4050 // high-throughput per-edge policies come into scope per
4051 // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4052 // on the closed-set enum, and the compiler enforces exhaustiveness
4053 // on every consumer's `match self` arms — this parse arm's
4054 // accepted-suffix set, the render arm's emitted-suffix set, the
4055 // validate gate's canonical-window set, and every future
4056 // per-`:contratos`-edge rate-limit-override overlay all pick it up
4057 // by construction.
4058 let unit = unit.trim();
4059 let window = RateLimitUnit::window_from_suffix(unit)
4060 .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4061 Ok(RateLimit { rate, window })
4062 }
4063
4064 fn render(rl: RateLimit) -> String {
4065 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4066 // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4067 // this render arm reads the `Duration → RateLimitUnit` projection
4068 // through the substrate primitive [`super::RateLimit::canonical_unit`]
4069 // (returns `None` on every non-canonical window — the sub-second /
4070 // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4071 // formats the returned typed enum through its
4072 // [`std::fmt::Display`] impl (which routes through
4073 // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4074 // the substrate primitive instead of one runtime `find_map`
4075 // walk through the free-helper delegate chain
4076 // [`super::rate_limit_window_unit`] (the vestigial free helper's
4077 // sole production consumer was this arm; every other consumer of
4078 // the `Duration → unit` axis — the validate gate below and the
4079 // future M4 per-Aplicacao Envoy config reconciler — now reads
4080 // the same typed method).
4081 //
4082 // A future rate-limit-unit addition (a `"d"` day suffix once
4083 // Envoy's `rate_limit_action` grows daily-bucket support) is
4084 // one variant + one arm per method on the closed-set enum, and
4085 // the compiler enforces exhaustiveness on every consumer's
4086 // `match self` arms — the codec's `parse` accepted-suffix set,
4087 // this render arm's emitted-suffix set, the validate gate's
4088 // canonical-window set, and every future per-`:contratos`-edge
4089 // rate-limit-override overlay all pick it up by construction.
4090 if let Some(unit) = rl.canonical_unit() {
4091 format!("{}/{unit}", rl.rate())
4092 } else {
4093 // Defensive fallback for non-canonical windows. Note:
4094 // [`AplicacaoSpec::validate_politicas`] rejects any
4095 // non-canonical `:rate-limit :window` via
4096 // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4097 // a validated `RateLimit` never reaches this branch. The
4098 // emitted `<n>/<k>s` form is *not* round-trippable through
4099 // [`parse`] (which accepts only the closed-set
4100 // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4101 // explicit count) — the validate gate is what makes the
4102 // round-trip a structural property; this branch exists only
4103 // so a programmatic non-validated serialize doesn't panic.
4104 format!("{}/{}s", rl.rate(), rl.window().as_secs())
4105 }
4106 }
4107}
4108
4109// ── placement strategy ───────────────────────────────────────────────
4110
4111/// How the Aplicacao distributes across clusters. Three options:
4112///
4113/// - `SingleNode` — one cluster runs the app at a time; takeover on
4114/// death (Erlang/OTP distributed-app semantics).
4115/// - `Replicated` — every named cluster runs an instance (active-active).
4116/// - `Sharded` — entities distribute by hash key across clusters
4117/// (Akka cluster sharding).
4118#[derive(
4119 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4120)]
4121pub enum PlacementStrategy {
4122 SingleNode,
4123 Replicated,
4124 Sharded,
4125}
4126
4127impl Default for PlacementStrategy {
4128 fn default() -> Self {
4129 Self::Replicated
4130 }
4131}
4132
4133impl PlacementStrategy {
4134 /// Exhaustive iteration surface for every consumer that reads the
4135 /// full closed-set (the future M4 admission-webhook's accepted-
4136 /// strategy listing in its rejection body, a future `feira app
4137 /// placement --list` CLI-side surfacing of the accepted arm-set,
4138 /// any future round-trip fuzz harness). A future variant addition
4139 /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
4140 /// names as a trajectory item) extends this slice as a single edit
4141 /// and every consumer picks up the new entry by construction — the
4142 /// compiler-checked exhaustiveness on the sibling method `match`
4143 /// arms is the build-time guarantee that no arm forgets to grow.
4144 /// Same shape as the sibling closed-set typed enums'
4145 /// [`RateLimitUnit::ALL`] (6bce03d) and
4146 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
4147 /// surfaces — the third closed-set typed enum on the caixa surface
4148 /// to converge onto the same discipline.
4149 pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
4150
4151 /// Canonical camelCase-schema discriminator scalar this variant
4152 /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
4153 /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
4154 /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4155 /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
4156 /// every substrate consumer that dispatches on the strategy (the
4157 /// `lareira-fleet-programs` aggregator, the future `app-operator`
4158 /// reconciler, the M3 Adaptive compression pass) reads the same
4159 /// byte-string the `Serialize` derive emits — the pin test in
4160 /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
4161 /// asserts the two paths agree.
4162 #[must_use]
4163 pub const fn as_str(self) -> &'static str {
4164 match self {
4165 Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
4166 Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
4167 Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
4168 }
4169 }
4170
4171 /// Substrate-canonical reverse projection on the `:placement
4172 /// :estrategia` closed-set axis — parses the camelCase-schema
4173 /// discriminator scalar back to the typed variant, or `None` when
4174 /// `s` is outside the closed-set arm-string set [`Self::as_str`]
4175 /// emits. Dispatches on the same lifted
4176 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4177 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4178 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
4179 /// [`Self::as_str`] emitter walks, so the parse and emit halves of
4180 /// the round-trip migrate through one caixa-core edit on any future
4181 /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
4182 /// §II.5 hint names as a trajectory item lands one variant + one
4183 /// arm per method and the compiler enforces exhaustiveness on every
4184 /// consumer's `match self` arms).
4185 ///
4186 /// Prior to this lift the substrate carried only the forward
4187 /// `Self → &str` projection (the [`Self::as_str`] emitter, the
4188 /// [`std::fmt::Display`] impl routed through it, the `Serialize`
4189 /// derive that emits the same byte-string under
4190 /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
4191 /// consumer that wanted to parse a wire-form strategy scalar had to
4192 /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
4193 /// => …, "Sharded" => …, _ => … }` cascade that expressed no
4194 /// compile-time link back to the typed variant's canonical lifted
4195 /// constant. A future variant rename or a per-arm serde-attribute
4196 /// drift would silently split the wire byte-string one non-serde
4197 /// consumer parsed from the one the emitter wrote, with the
4198 /// failure surfacing at parse time far from the rebrand commit.
4199 ///
4200 /// Same closed-set-reverse-projection discipline the sibling
4201 /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
4202 /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
4203 /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
4204 /// defining `:placement :estrategia` closed-set axis, the third
4205 /// substrate-side closed-set typed enum to converge on the two-way
4206 /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
4207 /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
4208 /// and side-step the [`std::str::FromStr`]-collision clippy
4209 /// (`clippy::should_implement_trait`) the plain `from_str` name
4210 /// carries; a future explicit [`std::str::FromStr`] impl can layer
4211 /// on top by delegating to this canonical arm-dispatch method.
4212 ///
4213 /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
4214 /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
4215 /// picks the diagnostic form appropriate for its use site — a
4216 /// future `feira app placement --set` CLI-side arg-parse that wants
4217 /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
4218 /// Sharded)"` diagnostic builds one on top by iterating
4219 /// [`Self::ALL`], while the future M4 admission-webhook's rejection
4220 /// path folds `None` onto its per-CR structured refusal body.
4221 #[must_use]
4222 pub fn from_wire(s: &str) -> Option<Self> {
4223 match s {
4224 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
4225 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
4226 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
4227 _ => None,
4228 }
4229 }
4230}
4231
4232/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
4233/// the pretty-printed byte-string every consumer that formats the strategy
4234/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
4235/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
4236/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
4237/// per-Aplicacao strategy line, the future M4 CR materializer's per-
4238/// admission-webhook rejection body) reaches for the same lifted
4239/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4240/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4241/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
4242/// `Serialize` derive already emits under
4243/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
4244/// [`PlacementStrategy::as_str`] helper already returns.
4245///
4246/// Until this lift landed the sibling OTP-shape typed enums —
4247/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
4248/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
4249/// so [`std::fmt::Display`] routes through the same discriminant string
4250/// the wire format emits) — carried a stable [`std::fmt::Display`]
4251/// surface but [`PlacementStrategy`] did not; every consumer reaching
4252/// for a strategy byte-string past the wire format had to pick between
4253/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
4254/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
4255/// derive), any two of which a future variant rename or
4256/// `#[serde(rename_all = "kebab-case")]` attribute would silently
4257/// desynchronize — with the failure surfacing as a downstream renderer /
4258/// operator's per-strategy dispatch reading one spelling while the wire
4259/// format emitted another, far from the source rebrand commit and with
4260/// no field naming the drift. Routing `Display` through
4261/// [`PlacementStrategy::as_str`] makes the three paths
4262/// (`Debug` for structural inspection, `Display` for user-facing text,
4263/// `Serialize` for the wire format) converge on the same lifted
4264/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
4265/// the diagnostic byte-string, and the pretty-printed byte-string move
4266/// as a single unit through one canonical declaration each, by
4267/// construction. Same trajectory as [`PlacementStrategy::as_str`]
4268/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
4269/// closes the third path.
4270///
4271/// Pin tests
4272/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
4273/// and
4274/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
4275/// assert the three paths agree byte-for-byte on every variant, so a
4276/// future variant rename or per-arm serde attribute drift is a build
4277/// error visible at caixa-core test time, not a silent per-consumer
4278/// dispatch miss at apply / reconcile time.
4279impl std::fmt::Display for PlacementStrategy {
4280 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4281 f.write_str(self.as_str())
4282 }
4283}
4284
4285/// Where the Aplicacao runs.
4286#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4287#[serde(rename_all = "camelCase")]
4288pub struct Placement {
4289 /// Distribution strategy.
4290 #[serde(default)]
4291 pub estrategia: PlacementStrategy,
4292
4293 /// Named clusters that host this Aplicacao. Required for
4294 /// `Replicated` and `SingleNode`; for `Sharded` declares the
4295 /// shard pool.
4296 #[serde(default)]
4297 pub clusters: Vec<String>,
4298
4299 /// Optional hint to the placement engine: `"data-locality"`,
4300 /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
4301 #[serde(default, skip_serializing_if = "Option::is_none")]
4302 pub affinity: Option<String>,
4303
4304 /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
4305 #[serde(default, skip_serializing_if = "Option::is_none")]
4306 pub shard_key: Option<String>,
4307}
4308
4309impl Placement {
4310 /// Substrate-canonical per-`:placement` Akka-cluster-sharding
4311 /// `:shard-key` extractor-expression scalar accessor every consumer
4312 /// of the Aplicacao's hash-keyed distribution routing keys off —
4313 /// returns the author-declared `:placement :shard-key` byte-string
4314 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
4315 /// own `Option<String>` storage; `None` when the slot is absent
4316 /// (the canonical shape under `:estrategia Replicated` /
4317 /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
4318 /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
4319 /// partition — `validate` refuses any `Placement` past this call
4320 /// that lands `Some` on a non-`Sharded` strategy or `None` on
4321 /// `Sharded`).
4322 ///
4323 /// The `:placement :shard-key` slot carries the Akka-style
4324 /// cluster-sharding entity-id extractor expression
4325 /// (MESH-COMPOSITION §II.4) — validated by
4326 /// [`validate_placement_shard_key`] to be a non-empty printable-
4327 /// ASCII single-token reference (`tenantId`, `$tenantId`,
4328 /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
4329 /// future M4 Akka-style cluster-sharding reconciler hashes without
4330 /// re-validating at the runtime layer), and every downstream
4331 /// consumer that reads the key keys off this scalar (the
4332 /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
4333 /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4334 /// declared-but-inert refusal diagnostic, the caixa-mesh
4335 /// per-Aplicacao `placement.shardKey` emit path the substrate
4336 /// operator's per-entity hash-routing reader consumes, the future
4337 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4338 /// per-shard-key resolver).
4339 ///
4340 /// Prior to this lift the `.shard_key` field was accessed inline at
4341 /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
4342 /// `Sharded` arm's `match &self.placement.shard_key { None => …,
4343 /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
4344 /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
4345 /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
4346 /// — two open-coded field-accesses that expressed no compile-time
4347 /// link back to the typed slot. A future extension of the
4348 /// `:placement :shard-key` axis to a richer author surface — a
4349 /// per-cluster override the operator pins through a future
4350 /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
4351 /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
4352 /// alias table the M4 CR materializer resolves per-CR, a
4353 /// per-Aplicacao dynamic `:shard-key` derivation the future
4354 /// adaptive placement engine computes from `:affinity` weights —
4355 /// would have had to be threaded through both open-coded copies in
4356 /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
4357 /// arm refusal would silently disagree on which extractor
4358 /// expression a given Placement resolves to. Lifting the resolution
4359 /// rule to a typed method on the substrate primitive means every
4360 /// downstream consumer of the Aplicacao's per-`:placement`
4361 /// hash-key surface reaches for exactly one typed dispatch — the
4362 /// resolver's accept-set migrates as a unit on any future axis
4363 /// addition.
4364 ///
4365 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
4366 /// [`WitContract::destination`] / [`WitContract::world_ref`]
4367 /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
4368 /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
4369 /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
4370 /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
4371 /// typed dispatch on the substrate primitive, thin projections at
4372 /// each consumer" discipline extended onto the per-`:placement`
4373 /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
4374 /// First `Option<&str>`-return accessor on the M3 mesh-slot family
4375 /// — opens the "optional per-slot scalar" projection pattern the
4376 /// sibling per-`:placement` `:affinity`, per-`:politicas`
4377 /// `:rate-limit` future lifts fold on. Named `shard_key()` to
4378 /// match the storage field's name; the accessor's identity name
4379 /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
4380 /// slot's docstring already carries.
4381 #[must_use]
4382 pub fn shard_key(&self) -> Option<&str> {
4383 self.shard_key.as_deref()
4384 }
4385
4386 /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
4387 /// compression-hint scalar accessor every weighting-consumer of the
4388 /// Aplicacao's per-hint routing surface keys off — returns the
4389 /// author-declared `:placement :affinity` byte-string verbatim as
4390 /// an `Option<&str>`, borrowed from the typed slot's own
4391 /// `Option<String>` storage; `None` when the slot is absent (the
4392 /// canonical shape of an Aplicacao that leaves the compression
4393 /// weighting up to the placement engine's cluster-default arm — no
4394 /// author-authored `data-locality` / `low-latency` / etc. hint
4395 /// biases the routing).
4396 ///
4397 /// The `:placement :affinity` slot carries the M3 Adaptive-
4398 /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
4399 /// by [`validate_placement_affinity`] to be a DNS-1123 label
4400 /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
4401 /// K8s-conformant label-selector shape every apiserver-side pod-
4402 /// affinity / node-affinity materializer already gates on
4403 /// admission), and every downstream consumer that reads the hint
4404 /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
4405 /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
4406 /// `placement.affinity` overlay emit path the substrate operator's
4407 /// per-hint weighting-consumer reads, the future M4
4408 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
4409 /// pod-affinity / node-affinity selector resolver).
4410 ///
4411 /// Prior to this lift the `.affinity` field was accessed inline at
4412 /// the sole caixa-core site — the
4413 /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
4414 /// `if let Some(a) = &self.placement.affinity { …
4415 /// validate_placement_affinity(a)? … }` cascade — one open-coded
4416 /// field-access that expressed no compile-time link back to the
4417 /// typed slot. A future extension of the `:placement :affinity`
4418 /// axis to a richer author surface — a per-cluster override the
4419 /// operator pins through a future `:placement :affinity-overrides`
4420 /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
4421 /// tenant hint alias table the M4 CR materializer resolves per-CR,
4422 /// a per-Aplicacao dynamic `:affinity` derivation the future
4423 /// adaptive placement engine computes from `:clusters` topology —
4424 /// would have had to be threaded through the open-coded copy in
4425 /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
4426 /// materializer reader that landed on the axis, or the per-hint
4427 /// value-shape gate and its downstream weighting consumers would
4428 /// silently disagree on which hint a given Placement resolves to.
4429 /// Lifting the resolution rule to a typed method on the substrate
4430 /// primitive means every downstream consumer of the Aplicacao's
4431 /// per-`:placement` compression-hint surface reaches for exactly
4432 /// one typed dispatch — the resolver's accept-set migrates as a
4433 /// unit on any future axis addition.
4434 ///
4435 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
4436 /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
4437 /// optional-scalar axis — same "one typed dispatch on the substrate
4438 /// primitive, thin projections at each consumer" discipline extended
4439 /// onto the per-`:placement` M3-Adaptive-compression-hint
4440 /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
4441 /// return accessor on the M3 mesh-slot family; closes the last
4442 /// un-lifted per-`:placement` `Option<String>` axis. Named
4443 /// `affinity()` to match the storage field's name; the accessor's
4444 /// identity name maps onto the canonical MESH-COMPOSITION §II.4
4445 /// vocabulary the slot's docstring already carries.
4446 #[must_use]
4447 pub fn affinity(&self) -> Option<&str> {
4448 self.affinity.as_deref()
4449 }
4450
4451 /// Substrate-canonical per-`:placement` `:estrategia` distribution-
4452 /// strategy scalar accessor every consumer that dispatches on the
4453 /// Aplicacao's per-cluster distribution shape keys off — returns the
4454 /// author-declared `:placement :estrategia` variant verbatim as a
4455 /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
4456 /// `PlacementStrategy` storage.
4457 ///
4458 /// The `:placement :estrategia` slot carries the closed-set
4459 /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
4460 /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
4461 /// `Replicated` — active-active across every named cluster; `Sharded`
4462 /// — Akka-style hash-keyed entity distribution across the cluster pool
4463 /// per §II.4) that every downstream consumer of the Aplicacao's
4464 /// per-cluster fan-out shape keys off. Validated by
4465 /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
4466 /// the sibling `:shard-key` axis (`shard_key.is_some() ==
4467 /// matches!(estrategia, Sharded)` — the cross-slot partition the
4468 /// [`Placement::shard_key`] accessor's docstring pins), and every
4469 /// downstream consumer that reads the strategy keys off this scalar
4470 /// (the [`AplicacaoSpec::validate_placement`]
4471 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
4472 /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
4473 /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
4474 /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4475 /// declared-but-inert refusal's
4476 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
4477 /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
4478 /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
4479 /// emit path the substrate operator's per-strategy fan-out reader
4480 /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4481 /// materializer's per-strategy admission-webhook resolver).
4482 ///
4483 /// Prior to this lift the `.estrategia` field was accessed inline at
4484 /// four sites — the [`AplicacaoSpec::validate_placement`]
4485 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
4486 /// `estrategia: self.placement.estrategia`, the same method's
4487 /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
4488 /// partition dispatch, the non-`Sharded`-arm
4489 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
4490 /// `estrategia: self.placement.estrategia`, and the `feira app graph`
4491 /// per-Aplicacao strategy print line at
4492 /// `println!("… {} …", spec.placement.estrategia, …)`
4493 /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
4494 /// expressed no compile-time link back to the typed slot. A future
4495 /// extension of the `:placement :estrategia` axis to a richer author
4496 /// surface (a per-cluster override the operator pins through a future
4497 /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
4498 /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
4499 /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
4500 /// derivation the future adaptive placement engine computes from
4501 /// `:affinity` + `:clusters` topology) would have had to be threaded
4502 /// through every open-coded copy in lockstep — one consumer reading
4503 /// the raw variant while a peer read the operator-resolved variant
4504 /// would silently split the `PlacementWithoutClusters` /
4505 /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
4506 /// partition-dispatch input, a two-consumer split at the validator
4507 /// far from the source `caixa.lisp` with no field naming the
4508 /// strategy-drift root cause. Lifting the resolution rule to a typed
4509 /// method on the substrate primitive means every downstream consumer
4510 /// of the Aplicacao's per-`:placement` distribution-strategy surface
4511 /// reaches for exactly one typed dispatch — the resolver's accept-set
4512 /// migrates as a unit on any future axis addition.
4513 ///
4514 /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
4515 /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
4516 /// same "one typed dispatch on the substrate primitive, thin
4517 /// projections at each consumer" discipline extended onto the
4518 /// per-`:placement` distribution-strategy `Copy`-composite-enum
4519 /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
4520 /// family; first `Copy`-return accessor on the M3 mesh-slot
4521 /// `Placement` type — companion to the sibling per-`:placement`
4522 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4523 /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
4524 /// optional-scalar axes, closing the last unlifted per-`:placement`
4525 /// scalar-value axis (the closed-set `PlacementStrategy`
4526 /// distribution-strategy discriminator) so every downstream
4527 /// per-`:placement` reader now routes through a typed dispatch on
4528 /// the substrate primitive. Named `estrategia()` to match the storage
4529 /// field's name; the accessor's identity name maps onto the
4530 /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
4531 /// already carries.
4532 #[must_use]
4533 pub fn estrategia(&self) -> PlacementStrategy {
4534 self.estrategia
4535 }
4536
4537 /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
4538 /// per-cluster distribution-target slice accessor every consumer that
4539 /// walks the Aplicacao's declared cluster-pool keys off — returns the
4540 /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
4541 /// `&[String]` slice-view, borrowed from the typed slot's own
4542 /// `Vec<String>` storage (a zero-copy slice-view over the same
4543 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
4544 /// through). Non-optional: the empty slice is the load-bearing
4545 /// pre-validation sentinel every downstream consumer of the paired
4546 /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
4547 /// off — every strategy in the closed
4548 /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
4549 /// requires a non-empty list (`SingleNode` / `Replicated` use the
4550 /// list as hosting / takeover candidates per Erlang/OTP distributed-
4551 /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
4552 /// shard pool per Akka cluster-sharding convention, §II.4), so the
4553 /// `.is_empty()` probe is the shared pre-condition every
4554 /// [`AplicacaoSpec::validate_placement`] arm heads on.
4555 ///
4556 /// The `:placement :clusters` slot carries the K8s-conformant DNS-
4557 /// 1123-label per-cluster distribution-target list — the same
4558 /// set-not-multiset shape the sibling `:membros :caixa` /
4559 /// `:children :caixa` axes carry (`validate_placement`'s per-entry
4560 /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
4561 /// pins the shape). Every downstream consumer that fans on the list
4562 /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
4563 /// pre-flight `.is_empty()` probe that trips
4564 /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
4565 /// per-cluster value-shape + duplicate-detection fan-out loop, the
4566 /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
4567 /// that materializes the list verbatim onto every
4568 /// programs.yaml entry the substrate operator's per-cluster
4569 /// `placement.clusters | contains .Values.cluster` filter reads,
4570 /// the `feira app graph` per-Aplicacao cluster print line, the
4571 /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4572 /// per-cluster admission-webhook fan-out, the future M5 adaptive-
4573 /// placement engine's cluster-topology reader).
4574 ///
4575 /// Prior to this lift the `.clusters` `Vec<String>` was accessed
4576 /// inline at three production sites — the
4577 /// [`AplicacaoSpec::validate_placement`] pre-flight
4578 /// `self.placement.clusters.is_empty()` refusal probe, the same
4579 /// method's per-cluster validate loop's
4580 /// `for c in &self.placement.clusters` traversal head, and the
4581 /// `feira app graph` per-Aplicacao print line's
4582 /// `spec.placement.clusters` `{:?}` formatter argument
4583 /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
4584 /// that expressed no compile-time link back to the typed slot. A
4585 /// future extension of the `:placement :clusters` axis to a richer
4586 /// author surface (a per-tenant cluster-pool overlay the operator
4587 /// pins through a future `:placement :clusters-overrides` slot the
4588 /// MESH-COMPOSITION §V cross-cluster-federation roadmap
4589 /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
4590 /// the future M5 adaptive-placement engine computes from
4591 /// `:affinity` weights + live cluster-topology probes, a promotion
4592 /// of the plain `Vec<String>` to a richer `{static, dynamic}`
4593 /// partition once the substrate operator's cluster-membership
4594 /// reconciler comes into typed scope) would have had to be threaded
4595 /// through all three open-coded copies in lockstep or one consumer
4596 /// would silently disagree with the peers on which cluster-pool a
4597 /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
4598 /// reading the raw slot while the peer per-cluster validate loop
4599 /// read an operator-resolved slot would silently split the paired
4600 /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
4601 /// `PlacementClusterDuplicate` refusal cascade's actual traversal
4602 /// input from the pre-flight input, a three-consumer split at the
4603 /// validator and formatter far from the source `caixa.lisp` with
4604 /// no field naming the cluster-pool-drift root cause. Lifting the
4605 /// resolution rule to a typed method on the substrate primitive
4606 /// means every downstream consumer of the Aplicacao's
4607 /// per-`:placement` cluster-pool surface reaches for exactly one
4608 /// typed dispatch — the resolver's accept-set migrates as a unit
4609 /// on any future axis addition.
4610 ///
4611 /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
4612 /// slot — sibling to the seed M2
4613 /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
4614 /// slice-return accessor on the peer per-`:supervisor` static-
4615 /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
4616 /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
4617 /// primitive, thin projections at each consumer" discipline. The
4618 /// three peer `Vec`-carry axes still unlifted at the time of this
4619 /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
4620 /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
4621 /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
4622 /// [`crate::UpgradeFromEntry::instructions`]
4623 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4624 /// — inherit this accessor's discipline as future compounding runs
4625 /// migrate their consumers onto the shared slice-return shape.
4626 /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
4627 /// type, sibling to the two `Option<&str>`-return
4628 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4629 /// (74ec2d3) accessors and the `Copy`-return
4630 /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
4631 /// unlifted per-`:placement` field axis (the `Vec<String>`
4632 /// distribution-target-list carrier) so every downstream
4633 /// per-`:placement` reader now routes through a typed dispatch on
4634 /// the substrate primitive. Named `clusters()` to match the storage
4635 /// field's name verbatim and the tatara-lisp author-surface term
4636 /// (`:clusters`) the field's own docstring already carries; the
4637 /// accessor's identity maps onto the canonical MESH-COMPOSITION
4638 /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
4639 /// for. Returns `&[String]` (not `&Vec<String>`) because every
4640 /// downstream consumer of the cluster list treats it as a read-only
4641 /// sequence — the slice-view is the narrowest borrow that supports
4642 /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
4643 /// `.len()`) without leaking the backing `Vec`'s
4644 /// grow/push/reserve surface that no consumer of the typed view
4645 /// reaches for (the storage-side `Vec` remains reachable through
4646 /// the `pub clusters` field for the mutation-carrying serde
4647 /// round-trip and per-test fixture-mutation paths).
4648 #[must_use]
4649 pub fn clusters(&self) -> &[String] {
4650 self.clusters.as_slice()
4651 }
4652}
4653
4654impl Default for Placement {
4655 fn default() -> Self {
4656 Self {
4657 estrategia: PlacementStrategy::default(),
4658 clusters: Vec::new(),
4659 affinity: None,
4660 shard_key: None,
4661 }
4662 }
4663}
4664
4665// ── external entry point ─────────────────────────────────────────────
4666
4667/// External entry point — what an outside caller sees. Renders to a
4668/// Gateway / Ingress + a route to the named member Servico.
4669#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4670#[serde(rename_all = "camelCase")]
4671pub struct Entrada {
4672 /// Public hostname (e.g. `"checkout.quero.cloud"`).
4673 pub host: String,
4674
4675 /// Member Servico the gateway routes to. Must be in `:membros`.
4676 pub para: String,
4677
4678 /// Optional path filter — if set, only matching paths route to
4679 /// this Aplicacao (the rest fall through to other route rules).
4680 #[serde(default)]
4681 pub paths: Vec<String>,
4682
4683 /// Default port on the destination Servico (the trigger.service.port).
4684 #[serde(default = "default_port")]
4685 pub port: u16,
4686}
4687
4688impl Entrada {
4689 /// Substrate-canonical per-`:entrada` URL-path fallback resolver
4690 /// every HTTPRoute-aware renderer keys off — returns the author-
4691 /// declared `:entrada :paths` list verbatim when non-empty, and the
4692 /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
4693 /// all fallback otherwise (so an Aplicacao author who declares an
4694 /// external `:entrada` block but no per-path rule surface still
4695 /// gets a route whose sole `HTTPPathMatch` matches every incoming
4696 /// request under the paired
4697 /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
4698 ///
4699 /// Prior to this lift the "if `:entrada :paths` is empty use the
4700 /// substrate catch-all; else return each declared path verbatim"
4701 /// cascade lived inline at
4702 /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
4703 /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
4704 /// per-Aplicacao HTTPRoute per-rule path-list emit site the
4705 /// substrate ships today, with no typed method on the substrate
4706 /// primitive that named the rule. A future path-resolution axis
4707 /// addition — a per-cluster `:entrada :default-path` override the
4708 /// operator pins through a future `:placement`-scoped slot, an
4709 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
4710 /// admission-webhook floor that materializes the catch-all before
4711 /// the CR lands, a future per-`:entrada :paths` overlay from a
4712 /// per-cluster policy the future `feira app deploy` pipeline
4713 /// consumes — would have to be threaded through every renderer's
4714 /// inline copy of the cascade in lockstep or one consumer would
4715 /// silently disagree with the peers on which path list a given
4716 /// `:entrada` block resolves to. Lifting the rule to a typed
4717 /// method on the substrate primitive means every downstream
4718 /// HTTPRoute-aware consumer (the M4 CR materializer, the future
4719 /// per-cluster overlay resolver, every future per-Aplicacao
4720 /// snapshot renderer) reaches for exactly one typed dispatch —
4721 /// the resolver's accept-set moves as a unit on any future axis
4722 /// addition.
4723 ///
4724 /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
4725 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
4726 /// per-`:entrada` scalar-value axes — extends the "one typed
4727 /// dispatch on the substrate primitive, thin projections at each
4728 /// consumer" discipline onto the per-`:entrada` path-list
4729 /// resolution axis every HTTPRoute-aware renderer consumes. Same
4730 /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
4731 /// sibling `:politicas` primitive — one typed method on the
4732 /// substrate primitive that names the cascade every renderer
4733 /// otherwise re-inlines.
4734 #[must_use]
4735 pub fn resolved_paths(&self) -> Vec<&str> {
4736 // Route the internal cascade-head + per-entry projection reads
4737 // through the lifted [`Self::paths`] slice accessor rather than
4738 // the raw `self.paths` field access — the substrate-primitive
4739 // per-`:entrada` path-list resolver's two internal reads now
4740 // key off the canonical raw-slot surface every downstream
4741 // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
4742 // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
4743 // entrada summary line's `{:?}` Debug print) routes through, so
4744 // any future rebrand on the typed slot's raw-slot reader lands
4745 // at exactly one place. Same two-consumer coherence discipline
4746 // the sibling `Placement::clusters` (a6e18d7) accessor pins on
4747 // the peer M3 mesh-slot `Vec<String>`-carry axis.
4748 if self.paths().is_empty() {
4749 vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
4750 } else {
4751 self.paths().iter().map(String::as_str).collect()
4752 }
4753 }
4754
4755 /// Substrate-canonical per-`:entrada` DNS-hostname singular
4756 /// accessor every Gateway-API `Listener.hostname` reader keys off
4757 /// — returns the author-declared `:entrada :host` byte-string
4758 /// verbatim as a `&str`, borrowed from the typed slot's own
4759 /// [`String`] storage.
4760 ///
4761 /// Named the "singular" half of the DNS-hostname resolver pair on
4762 /// the substrate primitive: the parent-Gateway per-listener
4763 /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
4764 /// (`Listener.hostname: Option<PreciseHostname>` — at most one
4765 /// hostname per listener), and this accessor is the typed dispatch
4766 /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
4767 /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
4768 /// the per-HTTPRoute `spec.hostnames[]` list axis the same
4769 /// per-Aplicacao ingress-hostname surface projects onto.
4770 ///
4771 /// Prior to this lift the `entrada.host.clone()` byte-string was
4772 /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
4773 /// per-listener singular `hostname:` axis
4774 /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
4775 /// per-HTTPRoute plural `spec.hostnames[]` axis
4776 /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
4777 /// consumers read the same `entrada.host` field but the two-site
4778 /// duplication expressed no compile-time contract that the singular
4779 /// Gateway-listener filter and the plural `HTTPRoute` filter list
4780 /// stay in lockstep on future extensions of the `:entrada` slot to
4781 /// a multi-hostname author surface (an `:entrada :alt-hosts` list
4782 /// overlay, a per-cluster SNI fan-out the operator pins through a
4783 /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
4784 /// Aplicacao` CR materializer's per-listener virtual-host filter
4785 /// admission-webhook overlay). Any such extension would have to be
4786 /// threaded through every renderer's inline copy of the resolution
4787 /// in lockstep or the Gateway listener's `hostname:` filter would
4788 /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
4789 /// — a Gateway-API-conformance divergence whose apply-time symptom
4790 /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
4791 /// `NoMatchingParent` — the API server rejects the route because
4792 /// its `hostnames[]` filter doesn't intersect the parent listener's
4793 /// `hostname` filter) is far from the source `caixa.lisp` and never
4794 /// surfaces in the emitted YAML. Lifting the singular and plural
4795 /// resolvers to typed methods on the substrate primitive means
4796 /// every consumer of the Aplicacao's ingress-hostname surface
4797 /// reaches for exactly one typed dispatch, and the pair-invariant
4798 /// `hostnames() == vec![hostname()]` pinned by the sibling
4799 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
4800 /// keeps the two axes in lockstep by construction.
4801 ///
4802 /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
4803 /// (1449891) path-list resolver on the per-HTTPRoute per-rule
4804 /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
4805 /// the substrate primitive, thin projections at each consumer"
4806 /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
4807 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
4808 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
4809 /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
4810 /// `:entrada` scalar-value + list-value axes.
4811 #[must_use]
4812 pub fn hostname(&self) -> &str {
4813 self.host.as_str()
4814 }
4815
4816 /// Substrate-canonical per-`:entrada` DNS-hostname plural
4817 /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
4818 /// keys off — returns the singleton `[hostname()]` list under
4819 /// today's single-hostname-per-Aplicacao author surface, and the
4820 /// authoritative multi-hostname list under a future
4821 /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
4822 ///
4823 /// Plural half of the DNS-hostname resolver pair — see the
4824 /// companion [`Entrada::hostname`] docstring for the two-consumer
4825 /// lift + pair-invariant discipline (`hostnames() ==
4826 /// vec![hostname()]`, pinned load-bearing by the sibling
4827 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
4828 /// test).
4829 ///
4830 /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
4831 /// per-`:entrada` plural-list resolver on the per-HTTPRoute
4832 /// per-rule path-list axis — same `Vec<&str>` shape, same
4833 /// substrate-primitive-owns-the-resolver discipline extended to
4834 /// the per-HTTPRoute virtual-host filter-list axis.
4835 #[must_use]
4836 pub fn hostnames(&self) -> Vec<&str> {
4837 vec![self.hostname()]
4838 }
4839
4840 /// Substrate-canonical per-`:entrada` destination-Servico scalar
4841 /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
4842 /// the author-declared `:entrada :para` byte-string verbatim as a
4843 /// `&str`, borrowed from the typed slot's own [`String`] storage.
4844 ///
4845 /// The `:entrada :para` slot names the single member Servico the
4846 /// external Gateway routes to (validated by
4847 /// [`AplicacaoSpec::validate`] to be a
4848 /// [`Membro::caixa`] the Aplicacao declares — a stray
4849 /// `:para` that doesn't name a member is
4850 /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
4851 /// backend-attachment miss at cluster-apply time). Under today's
4852 /// single-destination author surface `:entrada :para` is the ingress
4853 /// apex Servico's canonical identity; under a hypothetical
4854 /// future multi-backend author surface (a `:entrada
4855 /// :split :backends` weighted-fan-out overlay for canary /
4856 /// blue-green traffic-split rollouts, per-path override for
4857 /// path-based per-Servico routing beyond the single-apex model,
4858 /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4859 /// per-CR admission-webhook that promotes the scalar to a
4860 /// weighted list) this accessor is the substrate primitive's typed
4861 /// dispatch every downstream `HTTPRoute`-aware consumer routes
4862 /// through, so the resolution shape migrates as a unit on one
4863 /// caixa-core edit rather than a coordinated rewrite across every
4864 /// renderer's inline field-access.
4865 ///
4866 /// Prior to this lift the `entrada.para` byte-string was accessed
4867 /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
4868 /// `metadata.name` composer's per-destination discriminator arg
4869 /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
4870 /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
4871 /// per-HTTPRoute per-rule `backendRefs[0].name` axis
4872 /// (`entrada.para.clone()`,
4873 /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
4874 /// consumers read the same `entrada.para` field but the two-site
4875 /// duplication expressed no compile-time contract that the HTTPRoute
4876 /// name-discriminator and the per-rule backend name stay in
4877 /// lockstep on future extensions of the `:entrada` slot to a
4878 /// multi-destination author surface. Any such extension would have
4879 /// to be threaded through every renderer's inline copy of the
4880 /// destination projection in lockstep or the HTTPRoute
4881 /// `metadata.name` would silently reference a different destination
4882 /// than its own `backendRefs[]` — an operator-side
4883 /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
4884 /// grep-by-name lookup would land on a route whose `backendRefs[]`
4885 /// silently point at a peer Servico, dropping every external
4886 /// `:entrada` flow at the gateway with the destination-drift root
4887 /// cause invisible in the emitted YAML.
4888 ///
4889 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
4890 /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
4891 /// the per-listener singular / per-HTTPRoute plural filter axes and
4892 /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
4893 /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
4894 /// typed dispatch on the substrate primitive, thin projections at
4895 /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
4896 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
4897 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
4898 /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
4899 /// sibling per-`:entrada` scalar-value + list-value axes — this
4900 /// accessor closes the last unlifted per-`:entrada` scalar axis
4901 /// (the destination-Servico byte-string) so every downstream
4902 /// per-`:entrada` reader now routes through a typed dispatch on
4903 /// the substrate primitive.
4904 #[must_use]
4905 pub fn destination(&self) -> &str {
4906 self.para.as_str()
4907 }
4908
4909 /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
4910 /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
4911 /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
4912 /// reader keys off — returns the author-declared `:entrada :port`
4913 /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
4914 /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
4915 /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
4916 /// [`AplicacaoError::EntradaPortZero`], not a silent
4917 /// admission-webhook rejection at cluster-apply time).
4918 ///
4919 /// The `:entrada :port` slot carries the destination Servico's
4920 /// canonical in-cluster L4 listener port (`trigger.service.port` on
4921 /// the `pleme-computeunit` library chart), and every downstream
4922 /// consumer that reads the port keys off this scalar (the
4923 /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
4924 /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
4925 /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
4926 /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4927 /// CR materializer's per-Aplicacao gateway port resolver).
4928 ///
4929 /// Prior to this lift the `.port` field was accessed inline at two
4930 /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
4931 /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
4932 /// the [`AplicacaoSpec::port_for_destination`] resolver's
4933 /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
4934 /// open-coded field-accesses that expressed no compile-time link
4935 /// back to the typed slot. A future extension of the `:entrada :port`
4936 /// axis to a richer author surface — a per-cluster override the
4937 /// operator pins through a future `:placement :default-port` slot the
4938 /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
4939 /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
4940 /// heterogeneous listener ports, an M4
4941 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
4942 /// admission-webhook floor that promotes the scalar to a
4943 /// per-destination map — would have had to be threaded through both
4944 /// open-coded copies in lockstep or the structural-floor validator
4945 /// and the [`AplicacaoSpec::port_for_destination`] resolver would
4946 /// silently disagree on which port a given [`Entrada`] resolves to.
4947 /// Lifting the resolution rule to a typed method on the substrate
4948 /// primitive means every downstream consumer of the Aplicacao's
4949 /// per-`:entrada` L4-port surface reaches for exactly one typed
4950 /// dispatch — the resolver's accept-set migrates as a unit on any
4951 /// future axis addition.
4952 ///
4953 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
4954 /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
4955 /// accessors on the per-`:entrada` scalar-value axis — same "one
4956 /// typed dispatch on the substrate primitive, thin projections at
4957 /// each consumer" discipline extended onto the per-`:entrada`
4958 /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
4959 /// the M3 mesh-slot `Entrada` type — closes the last unlifted
4960 /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
4961 /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
4962 /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
4963 /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
4964 /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
4965 /// storage field's name; the accessor's identity name maps onto the
4966 /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
4967 /// already carries.
4968 #[must_use]
4969 pub fn port(&self) -> u16 {
4970 self.port
4971 }
4972
4973 /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
4974 /// slice accessor every HTTPRoute-aware renderer keys off when it
4975 /// wants the raw author-declared path-list (not the fallback-
4976 /// applied projection [`Self::resolved_paths`] returns) — returns
4977 /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
4978 /// borrowed from the typed slot's own [`Vec<String>`] storage.
4979 ///
4980 /// Named the "raw slot" half of the per-`:entrada` path-list resolver
4981 /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
4982 /// (1449891) closes the fallback-applying arm every per-Aplicacao
4983 /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
4984 /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
4985 /// catch-all; non-empty slot → per-entry verbatim projection); this
4986 /// accessor closes the raw-slot arm every consumer that must see the
4987 /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
4988 /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
4989 /// not `Err(EntradaPathEmpty)`, so it cannot route through the
4990 /// fallback-applying sibling; the `feira app graph` per-Aplicacao
4991 /// external-gateway summary line's `{:?}` Debug print — which must
4992 /// name the author's declaration, not the substrate's fallback, so
4993 /// an author reading their graph output can grep their caixa.lisp
4994 /// for the exact list they authored) routes through.
4995 ///
4996 /// Prior to this lift the `.paths` field was accessed inline at four
4997 /// production sites: the two internal reads in [`Self::resolved_paths`]
4998 /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
4999 /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
5000 /// value-shape gate's `for p in &e.paths` traversal head, and the
5001 /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
5002 /// Debug print — four open-coded field-accesses that expressed no
5003 /// compile-time link back to the typed slot. A future extension of
5004 /// the `:entrada :paths` axis to a richer author surface — a
5005 /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
5006 /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
5007 /// spec supports through `matches[].method`), a per-path per-header
5008 /// filter overlay (`matches[].headers[]`), a per-cluster override
5009 /// the operator pins through a future `:placement :path-overlay`
5010 /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5011 /// per-CR admission-webhook that normalized the list at admission
5012 /// time — would have had to be threaded through every open-coded
5013 /// copy in lockstep or the validator's per-entry gate would silently
5014 /// disagree with the renderer's per-entry emit on which list a given
5015 /// `:entrada` block resolves to. Lifting the resolution to a typed
5016 /// method on the substrate primitive means every downstream consumer
5017 /// of the Aplicacao's per-`:entrada` path-list surface reaches for
5018 /// exactly one typed dispatch — the resolver's accept-set migrates
5019 /// as a unit on any future axis addition.
5020 ///
5021 /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
5022 /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
5023 /// carry axis — same "one typed dispatch on the substrate primitive,
5024 /// thin projections at each consumer" discipline extended onto the
5025 /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
5026 /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
5027 /// carrier) so every downstream per-`:entrada` reader now routes
5028 /// through a typed dispatch on the substrate primitive. Returns
5029 /// `&[String]` (not `&Vec<String>`) because every downstream consumer
5030 /// treats the list as a read-only sequence — the slice-view is the
5031 /// narrowest borrow that supports every present + roadmapped consumer
5032 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
5033 /// `Vec`'s grow/push/reserve surface that no consumer of the typed
5034 /// view reaches for (the storage-side `Vec` remains reachable through
5035 /// the `pub paths` field for the mutation-carrying serde round-trip
5036 /// and per-test fixture-mutation paths).
5037 #[must_use]
5038 pub fn paths(&self) -> &[String] {
5039 self.paths.as_slice()
5040 }
5041}
5042
5043/// Canonical default L4 port every typed Servico exposes on its
5044/// in-cluster K8s Service (the `trigger.service.port` axis the
5045/// `pleme-computeunit` library chart emits, the `:entrada :port` author
5046/// surface defaults to when the author omits the slot, and the
5047/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
5048/// `:entrada` block matches the per-`:contratos` destination Servico).
5049/// The single source of truth all three typed-port consumers reach for:
5050///
5051/// - [`Entrada::port`]'s serde default (via the
5052/// [`default_port`] helper this constant feeds); the author surface
5053/// `(:entrada (:host … :para …))` without an explicit `:port` slot
5054/// reads back as a typed [`Entrada`] carrying this exact value;
5055/// - the
5056/// [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
5057/// emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
5058/// fallback, fired when the typed `:entrada` block doesn't name
5059/// the per-`:contratos` destination Servico — the typed
5060/// `:contratos` graph carries no per-destination port axis (the
5061/// destination port is the destination Servico's
5062/// `lareira-<nome>` chart's `trigger.service.port`, which the
5063/// Aplicacao-level renderer has no visibility into without a
5064/// resolver round-trip), so the renderer falls back to the
5065/// substrate's canonical Servico-port assumption — by
5066/// construction the same value the destination's own
5067/// `pleme-computeunit` chart emits, the same value the
5068/// destination's own typed `:entrada :port` slot defaults to;
5069/// - every future per-Servico renderer the absorption-roadmap
5070/// acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5071/// CR materializer's per-edge port resolver, the future
5072/// per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
5073/// emitter's per-route bucket key, the future caixa-otel
5074/// collector-pipeline emitter's per-Servico scrape port).
5075///
5076/// Until this lift landed the value `8080` lived at two production-code
5077/// call-sites: the [`default_port`] helper at
5078/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
5079/// and the `.unwrap_or(8080)` literal at
5080/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
5081/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
5082/// resolver). A future Servico-port rebrand — the substrate moving the
5083/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
5084/// gateway grows direct `:80` listeners, to `8443` once the substrate
5085/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
5086/// override the operator pins through a future
5087/// `:placement :default-port` slot — without a coordinated edit on
5088/// both sides would silently emit Servicos listening on one port and
5089/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
5090/// The CNP's apply-time symptom (the policy is admitted but every L4
5091/// flow on the destination Servico's actual port silently drops because
5092/// it doesn't match the whitelisted port) is far from the rebrand
5093/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
5094/// in hubble traces, not in `kubectl describe`. Lifting the literal to
5095/// a shared constant closes the drift footgun structurally — both
5096/// consumers read from the same `u16`, so any rebrand reaches both
5097/// sites by construction.
5098///
5099/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
5100/// per-renderer canonical-K8s-axis constant — the namespace string
5101/// and the canonical Servico port both lived as duplicated literals
5102/// across caixa-core / caixa-mesh / caixa-flux before their respective
5103/// lifts. Same "the typed constant lives in one place" discipline the
5104/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
5105/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
5106/// shared-string axes.
5107///
5108/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
5109pub const DEFAULT_SERVICO_PORT: u16 = 8080;
5110
5111/// Structural floor for the typed `:entrada :port` axis — every
5112/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
5113/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
5114///
5115/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
5116/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
5117/// interprets as "let the kernel pick a free port at bind time", not a
5118/// well-defined destination the substrate's per-`:entrada` Gateway API
5119/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
5120/// carrying `port: 0` degenerates to a nominal-only routing target: the
5121/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
5122/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
5123/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
5124/// at build time rather than at `kubectl apply` time), and the
5125/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
5126/// (caixa-mesh/src/lib.rs:2657 through
5127/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
5128/// [`Entrada::port`] typed value — silently emits a policy whose
5129/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
5130/// actual listener, dropping every L4 flow at the eBPF data plane far
5131/// from the source caixa.lisp with no field naming the port-zero-drift
5132/// root cause.
5133///
5134/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
5135/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
5136/// on the top edge (unlike the peer capped-`u32` `:politicas` /
5137/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
5138/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
5139/// well below `u32::MAX` and therefore need explicit typed caps).
5140///
5141/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
5142/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
5143/// scalar every `(:entrada (:host … :para …))` slot without an explicit
5144/// `:port` inherits through the serde default hook; this constant names
5145/// the accept-set floor every declared port must satisfy. The pair is
5146/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
5147/// substrate's default must satisfy its own accept-set floor by
5148/// construction) — a future rebrand that accidentally moved
5149/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
5150/// negative-cast typo, a per-cluster override the operator pins through
5151/// a future `:placement :default-port` slot that lands out-of-range)
5152/// would silently invalidate the serde-default emission at every
5153/// author-side `(:entrada (:host … :para …))` slot — the compile-time
5154/// invariant pin
5155/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
5156/// closes the drift footgun at caixa-core build time.
5157///
5158/// Lifted as a typed `pub const` (rather than an inline `0` literal at
5159/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
5160/// has exactly one source of truth — the future M4
5161/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
5162/// gateway resolver, the future per-Servico
5163/// `computeunit.trigger.service.port` renderer's per-CR port-value
5164/// validator, and every downstream test-fixture navigator asserting
5165/// the accept-set floor all read from one place. Same shape every
5166/// other typed bracket-floor / bracket-ceiling in this crate carries
5167/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5168/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
5169/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5170/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
5171/// [`POLICY_RATE_LIMIT_MAX`]).
5172pub const SERVICO_PORT_MIN: u16 = 1;
5173
5174const fn default_port() -> u16 {
5175 DEFAULT_SERVICO_PORT
5176}
5177
5178// ── the typed view ───────────────────────────────────────────────────
5179
5180/// Typed composition view of the flat Aplicacao slots on
5181/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
5182/// validation + downstream renderer consumption.
5183#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5184#[serde(rename_all = "camelCase")]
5185pub struct AplicacaoSpec {
5186 pub membros: Vec<Membro>,
5187 pub contratos: Vec<WitContract>,
5188 pub politicas: MeshPolicy,
5189 pub placement: Placement,
5190 pub entrada: Option<Entrada>,
5191}
5192
5193impl AplicacaoSpec {
5194 /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
5195 /// per-Aplicacao member-list slice-return accessor every
5196 /// per-Aplicacao member-list reader keys off — returns the author-
5197 /// declared `:membros` list verbatim as a `&[Membro]` slice-view
5198 /// over the same backing buffer the raw `self.membros.as_slice()`
5199 /// field access borrows from.
5200 ///
5201 /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
5202 /// member list — the load-bearing identity of the application graph
5203 /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
5204 /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
5205 /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
5206 /// accessor) with a `:versao` semver-requirement string (through
5207 /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
5208 /// and every downstream consumer that fans on the member-set keys
5209 /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
5210 /// membership-lookup `HashSet<&str>` seed's collect input, the
5211 /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
5212 /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
5213 /// per-member DNS-1123 / semver-requirement / duplicate-detection
5214 /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
5215 /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
5216 /// programs.yaml per-`:membros` fan-out emitter's per-entry
5217 /// mapping-composition loop, the `feira app graph` per-Aplicacao
5218 /// member-count print line and per-member tree traversal,
5219 /// every future wasm-operator (M4) per-Aplicacao CR materializer's
5220 /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
5221 /// placement engine's per-member weight-topology reader).
5222 ///
5223 /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
5224 /// inline at six production sites — the [`AplicacaoSpec::validate`]
5225 /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
5226 /// [`AplicacaoSpec::validate_membros`]'s pre-flight
5227 /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
5228 /// probe, the same method's per-member `for m in &self.membros`
5229 /// validate-loop traversal head, the
5230 /// [`AplicacaoSpec::detect_sync_cycles`]'s
5231 /// `for m in &self.membros` adjacency-list seed, the
5232 /// [`caixa_mesh::programs_for_aplicacao`] emitter's
5233 /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
5234 /// paired with the peer `for m in &spec.membros` per-entry fan-out
5235 /// loop, and the `feira app graph` per-Aplicacao print line's
5236 /// `spec.membros.len()` count formatter argument paired with the
5237 /// peer `for m in &spec.membros` per-member tree traversal — six
5238 /// open-coded field-accesses that expressed no compile-time link
5239 /// back to the typed slot. A future extension of the `:membros`
5240 /// axis to a richer author surface (a per-cluster member-set
5241 /// overlay the operator pins through a future
5242 /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
5243 /// roadmap acknowledges, a per-tenant member-alias table the M4
5244 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
5245 /// CR at admission time, a per-Aplicacao dynamic member-set
5246 /// derivation the future adaptive-placement engine computes from
5247 /// weighted membership topology, a promotion of the plain
5248 /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
5249 /// Orleans-style virtual-actor dynamic-membership comes into typed
5250 /// scope) would have had to be threaded through all six open-coded
5251 /// copies in lockstep or one consumer would silently disagree with
5252 /// the peers on which member-set a given Aplicacao resolves to —
5253 /// the `HashSet<&str>` name-set seed reading the raw slot while
5254 /// the peer `.is_empty()` refusal probe read an operator-resolved
5255 /// slot would silently split the `:contratos` membership-lookup
5256 /// input from the pre-flight-refusal input, a six-consumer split
5257 /// at the validator + programs.yaml emitter + graph printer far
5258 /// from the source `caixa.lisp` with no field naming the member-
5259 /// set-drift root cause. Lifting the resolution rule to a typed
5260 /// method on the substrate primitive means every downstream
5261 /// consumer of the Aplicacao's per-`:membros` member-list surface
5262 /// reaches for exactly one typed dispatch — the resolver's accept-
5263 /// set migrates as a unit on any future axis addition.
5264 ///
5265 /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
5266 /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5267 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5268 /// static-child-list `Vec`-carry axis, and to the M3
5269 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5270 /// on the peer per-`:placement` distribution-target-list `Vec`-
5271 /// carry axis. Same "one typed dispatch on the substrate primitive,
5272 /// thin projections at each consumer" discipline. The two peer
5273 /// `Vec`-carry axes still unlifted at the time of this lift —
5274 /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
5275 /// WIT-typed edge list) and
5276 /// [`crate::UpgradeFromEntry::instructions`]
5277 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5278 /// — inherit this accessor's discipline as future compounding runs
5279 /// migrate their consumers onto the shared slice-return shape.
5280 /// First `&[T]`-return accessor on the top-level M3 mesh-slot
5281 /// `AplicacaoSpec` type itself, extending the discipline beyond
5282 /// the inner per-slot types ([`crate::Placement`],
5283 /// [`crate::SupervisorSpec`]) onto the outermost typed composition
5284 /// view every renderer consumes. Named `membros()` to match the
5285 /// storage field's name verbatim and the tatara-lisp author-
5286 /// surface term (`:membros`) the field's own docstring already
5287 /// carries; the accessor's identity maps onto the canonical
5288 /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
5289 /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
5290 /// every downstream consumer of the member list treats it as a
5291 /// read-only sequence — the slice-view is the narrowest borrow
5292 /// that supports every present + roadmapped consumer
5293 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5294 /// backing `Vec`'s grow/push/reserve surface that no consumer of
5295 /// the typed view reaches for (the storage-side `Vec` remains
5296 /// reachable through the `pub membros` field for the mutation-
5297 /// carrying serde round-trip and per-test fixture-mutation paths).
5298 #[must_use]
5299 pub fn membros(&self) -> &[Membro] {
5300 self.membros.as_slice()
5301 }
5302
5303 /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
5304 /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
5305 /// accessor every per-Aplicacao contract-list reader keys off —
5306 /// returns the author-declared `:contratos` list verbatim as a
5307 /// `&[WitContract]` slice-view over the same backing buffer the raw
5308 /// `self.contratos.as_slice()` field access borrows from.
5309 ///
5310 /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
5311 /// WIT-typed edge list — the load-bearing set of directed edges
5312 /// on the application graph whose nodes are the `:membros` entries
5313 /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
5314 /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
5315 /// six-tuple is the edge identity every downstream duplicate gate
5316 /// keys off). Every per-`:contratos` entry pairs a `:de` source-
5317 /// Servico caller name + a `:para` destination-Servico callee name
5318 /// (through the lifted [`WitContract::source`] +
5319 /// [`WitContract::destination`] (7f0fd43) accessor pair on the
5320 /// caller/callee-Servico axis) with a `:wit` world-reference
5321 /// (through the lifted [`WitContract::world_ref`] (0804823)
5322 /// accessor) and the target-shape-appropriate payload-carrier
5323 /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
5324 /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
5325 /// (ed22b66) accessor on the per-target-shape payload-carrier
5326 /// axis). Every downstream consumer that fans on the edge-set
5327 /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
5328 /// name-set / self-edge / target-shape / dedup fan-out loop, the
5329 /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
5330 /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
5331 /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
5332 /// grouping loop, the `feira app graph` per-Aplicacao contract-
5333 /// count print line and per-contract tree traversal, every future
5334 /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
5335 /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
5336 /// mesh-policy overlay resolver's per-contract typed-edge weight
5337 /// reader).
5338 ///
5339 /// Prior to this lift the `.contratos` `Vec<WitContract>` was
5340 /// accessed inline at four production sites — the
5341 /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
5342 /// per-edge validate-loop traversal head (which drives every
5343 /// per-edge name-set membership lookup, self-edge check,
5344 /// target-shape dispatch, and dedup `HashSet` insert), the
5345 /// [`AplicacaoSpec::detect_sync_cycles`]'s
5346 /// `for c in &self.contratos` adjacency-list seed head (which
5347 /// drives every per-edge sync-vs-pub-sub partition and per-edge
5348 /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
5349 /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
5350 /// `BTreeMap` grouping loop head (which drives every per-CNP
5351 /// fan-out emit), and the `feira app graph` per-Aplicacao print
5352 /// line's `spec.contratos.len()` count formatter argument paired
5353 /// with the peer `for c in &spec.contratos` per-contract tree
5354 /// traversal — four open-coded field-accesses that expressed no
5355 /// compile-time link back to the typed slot. A future extension
5356 /// of the `:contratos` axis to a richer author surface (a
5357 /// per-cluster contract overlay the operator pins through a
5358 /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
5359 /// federation roadmap acknowledges, a per-tenant edge-policy
5360 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5361 /// materializer resolves per-CR at admission time, a per-edge
5362 /// weight scalar the future adaptive-placement engine reads to
5363 /// bias sync-subgraph routing, a promotion of the plain
5364 /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
5365 /// once virtual-actor-style dynamic-edge composition comes into
5366 /// typed scope) would have had to be threaded through all four
5367 /// open-coded copies in lockstep or one consumer would silently
5368 /// disagree with the peers on which edge-set a given Aplicacao
5369 /// resolves to — the validator's per-edge dedup `HashSet` seed
5370 /// reading the raw slot while the peer sync-cycle adjacency-list
5371 /// seed read an operator-resolved slot would silently split the
5372 /// build-time edge-set gate from the runtime deadlock-detection
5373 /// gate, a four-consumer split at the validator, the cycle
5374 /// detector, the CNP emitter, and the graph printer far from
5375 /// the source `caixa.lisp` with no field naming the edge-set-
5376 /// drift root cause. Lifting the resolution rule to a typed method on the
5377 /// substrate primitive means every downstream consumer of the
5378 /// Aplicacao's per-`:contratos` edge-list surface reaches for
5379 /// exactly one typed dispatch — the resolver's accept-set
5380 /// migrates as a unit on any future axis addition.
5381 ///
5382 /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
5383 /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5384 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5385 /// static-child-list `Vec`-carry axis, to the M3
5386 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5387 /// on the peer per-`:placement` distribution-target-list `Vec`-
5388 /// carry axis, and to the immediately-adjacent sibling M3
5389 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
5390 /// the peer per-`:membros` node-list `Vec`-carry axis — the
5391 /// per-`:contratos` edge-list accessor is the natural pair of
5392 /// the per-`:membros` node-list accessor (graph edges over graph
5393 /// nodes; every graph-shaped consumer reads both). Same "one
5394 /// typed dispatch on the substrate primitive, thin projections
5395 /// at each consumer" discipline. The last remaining `Vec`-carry
5396 /// axis still unlifted at the time of this lift —
5397 /// [`crate::UpgradeFromEntry::instructions`]
5398 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
5399 /// list) — inherits this accessor's discipline as future
5400 /// compounding runs migrate its consumers onto the shared slice-
5401 /// return shape. Second `&[T]`-return accessor on the top-level
5402 /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
5403 /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
5404 /// `:contratos` are the two `Vec` fields on the outer typed
5405 /// composition view — `:politicas`, `:placement`, `:entrada` are
5406 /// scalar/option-shaped and already route through their per-slot
5407 /// accessor families). Named `contratos()` to match the storage
5408 /// field's name verbatim and the tatara-lisp author-surface term
5409 /// (`:contratos`) the field's own docstring already carries; the
5410 /// accessor's identity maps onto the canonical MESH-COMPOSITION
5411 /// §III.1 vocabulary the slot's docstring already reaches for.
5412 /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
5413 /// every downstream consumer of the contract list treats it as a
5414 /// read-only sequence — the slice-view is the narrowest borrow
5415 /// that supports every present + roadmapped consumer
5416 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5417 /// backing `Vec`'s grow/push/reserve surface that no consumer of
5418 /// the typed view reaches for (the storage-side `Vec` remains
5419 /// reachable through the `pub contratos` field for the mutation-
5420 /// carrying serde round-trip and per-test fixture-mutation paths).
5421 #[must_use]
5422 pub fn contratos(&self) -> &[WitContract] {
5423 self.contratos.as_slice()
5424 }
5425
5426 /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
5427 /// per-Aplicacao mesh-policy composite-reference accessor every
5428 /// per-Aplicacao policy-block reader keys off — returns the author-
5429 /// declared `:politicas` composite verbatim as a `&MeshPolicy`
5430 /// reference over the same backing storage the raw `&self.politicas`
5431 /// field access borrows from.
5432 ///
5433 /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
5434 /// mesh-policy composite — the load-bearing container of every
5435 /// mesh-level operational-policy axis every downstream mesh-artifact
5436 /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
5437 /// mesh-policy overlay is the single typed surface a
5438 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
5439 /// from). Every per-`:politicas` axis threads through a lifted
5440 /// per-slot accessor on the [`MeshPolicy`] type: the
5441 /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
5442 /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
5443 /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
5444 /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
5445 /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
5446 /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
5447 /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
5448 /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
5449 /// accessor. Every downstream consumer that reaches for a policy
5450 /// axis first passes through this outer accessor onto the composite
5451 /// and then dispatches onto the per-axis accessor — the two-level
5452 /// dispatch means every per-`:politicas` reader now routes through
5453 /// a typed dispatch on the substrate primitive at both altitudes.
5454 ///
5455 /// Prior to this lift the `.politicas` `MeshPolicy` composite was
5456 /// accessed inline at four production sites — the
5457 /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
5458 /// &self.politicas;` traversal seed (which drives every per-axis
5459 /// zero-floor + upper-cap + canonical-form bracket dispatch through
5460 /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
5461 /// `p.rate_limit()` on the axis-level lifted accessors), the
5462 /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
5463 /// emitter's `spec.politicas.mtls_required()` field-then-accessor
5464 /// chain (which drives every per-`(:de, :para)` CNP
5465 /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
5466 /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
5467 /// timeout + retry overlay emitter's paired
5468 /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
5469 /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
5470 /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
5471 /// open-coded outer-field accesses that expressed no compile-time
5472 /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
5473 /// future extension of the `:politicas` outer axis to a richer
5474 /// author surface (a per-cluster policy overlay the operator pins
5475 /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
5476 /// §V federation roadmap acknowledges, a per-tenant policy-alias
5477 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5478 /// resolves per-CR at admission time, a per-Aplicacao dynamic
5479 /// policy-composite derivation the future adaptive-placement engine
5480 /// computes from a per-cluster load-topology reader, a promotion of
5481 /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
5482 /// partition once virtual-actor-style dynamic-mesh-policy
5483 /// composition comes into typed scope) would have had to be threaded
5484 /// through all four open-coded copies in lockstep or one consumer
5485 /// would silently disagree with the peers on which mesh-policy
5486 /// composite a given Aplicacao resolves to — the validator's
5487 /// per-axis bracket-dispatch seed reading the raw slot while the
5488 /// peer CNP mTLS-overlay emitter read an operator-resolved slot
5489 /// would silently split the build-time policy-shape gate from the
5490 /// runtime CNP-emission gate, a four-consumer split at the
5491 /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
5492 /// the source `caixa.lisp` with no field naming the policy-drift
5493 /// root cause. Lifting the resolution rule to a typed method on the
5494 /// substrate primitive means every downstream consumer of the
5495 /// Aplicacao's per-`:politicas` mesh-policy composite surface
5496 /// reaches for exactly one typed dispatch — the resolver's accept-
5497 /// set migrates as a unit on any future axis addition.
5498 ///
5499 /// First `&Composite`-return accessor on the top-level M3 mesh-slot
5500 /// `AplicacaoSpec` type itself — sibling to the seed slice-return
5501 /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5502 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
5503 /// close the two `Vec`-carry axes on the outer typed composition
5504 /// view; the outer `:politicas` composite-reference axis is the
5505 /// natural pair to the paired outer `Vec`-carry accessors on the
5506 /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
5507 /// emitter reads all four axes as one unit (graph nodes + graph
5508 /// edges + mesh policy + placement pool). Peer to the same
5509 /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
5510 /// slot: every M2 `SupervisorSpec`-scoped composite reader
5511 /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
5512 /// `restart_window`, `children`) already routes through the M2
5513 /// `SupervisorSpec` accessor family — this lift extends the same
5514 /// "one typed dispatch on the substrate primitive at the outer
5515 /// composition altitude" discipline to the M3 mesh-slot
5516 /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
5517 /// remaining peer outer-composite axes still unlifted at the time
5518 /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
5519 /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
5520 /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
5521 /// inherit this accessor's discipline as future compounding runs
5522 /// migrate their consumers onto the shared reference-return shape.
5523 /// Named `politicas()` to match the storage field's name verbatim
5524 /// and the tatara-lisp author-surface term (`:politicas`) the
5525 /// field's own docstring already carries; the accessor's identity
5526 /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
5527 /// slot's docstring already reaches for. Returns `&MeshPolicy`
5528 /// (not the owning composite by copy or clone) because every
5529 /// downstream consumer of the mesh-policy composite treats it as a
5530 /// read-only per-axis dispatch source — the reference-view is the
5531 /// narrowest borrow that supports every present + roadmapped
5532 /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
5533 /// emptiness probe) without cloning the composite through every
5534 /// consumer's fast path.
5535 #[must_use]
5536 pub fn politicas(&self) -> &MeshPolicy {
5537 &self.politicas
5538 }
5539
5540 /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
5541 /// per-Aplicacao distribution-composite composite-reference accessor
5542 /// every per-Aplicacao placement-block reader keys off — returns the
5543 /// author-declared `:placement` composite verbatim as a `&Placement`
5544 /// reference over the same backing storage the raw `&self.placement`
5545 /// field access borrows from.
5546 ///
5547 /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
5548 /// distribution composite — the load-bearing container of every
5549 /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
5550 /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
5551 /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
5552 /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
5553 /// hosting-pool identity, §V for the `M3-Adaptive`-compression
5554 /// `:affinity` hint). Every per-`:placement` axis threads through a
5555 /// lifted per-slot accessor on the [`Placement`] type: the
5556 /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
5557 /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
5558 /// per-cluster distribution-target slice-return accessor, the
5559 /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
5560 /// optional-scalar accessor, and the [`Placement::shard_key`]
5561 /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
5562 /// downstream consumer that reaches for a placement axis first passes
5563 /// through this outer accessor onto the composite and then dispatches
5564 /// onto the per-axis accessor — the two-level dispatch means every
5565 /// per-`:placement` reader now routes through a typed dispatch on the
5566 /// substrate primitive at both altitudes.
5567 ///
5568 /// Prior to this lift the `.placement` `Placement` composite was
5569 /// accessed inline at three production sites — the
5570 /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
5571 /// seed (six `self.placement.<axis>()` field-then-inner-accessor
5572 /// chains: the pre-flight `.clusters().is_empty()` refusal probe
5573 /// paired with the `.estrategia()` diagnostic-carry copy, the per-
5574 /// cluster `.clusters()` validate-loop traversal head, the per-
5575 /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
5576 /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
5577 /// paired with the shape-gate cascade's `.shard_key()` /
5578 /// `.estrategia()` diagnostic-carry pair), the
5579 /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
5580 /// per-entry placement-block emitter's outer
5581 /// `serde_yaml::to_value(&spec.placement)` composite-serialization
5582 /// seed (which fans onto every per-cluster `programs[]` entry as a
5583 /// self-describing distribution overlay the aggregator filters by),
5584 /// and the `feira app graph` per-Aplicacao print line's paired
5585 /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
5586 /// then-inner-accessor chains (which drive the human-readable
5587 /// distribution summary of the typed Aplicacao view) — three open-
5588 /// coded outer-field accesses that expressed no compile-time link
5589 /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
5590 /// extension of the `:placement` outer axis to a richer author surface
5591 /// (a per-cluster placement overlay the operator pins through a
5592 /// future `:placement-overrides` slot the MESH-COMPOSITION §V
5593 /// federation roadmap acknowledges, a per-tenant placement-alias
5594 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5595 /// resolves per-CR at admission time, a per-Aplicacao dynamic
5596 /// placement-composite derivation the future M5 adaptive-placement
5597 /// engine computes from a per-cluster load-topology reader, a
5598 /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
5599 /// partition once Orleans-style virtual-actor dynamic-placement comes
5600 /// into typed scope) would have had to be threaded through all three
5601 /// open-coded copies in lockstep or one consumer would silently
5602 /// disagree with the peers on which placement composite a given
5603 /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
5604 /// seed reading the raw slot while the peer
5605 /// `programs_for_aplicacao` emitter read an operator-resolved slot
5606 /// would silently split the build-time distribution-shape gate from
5607 /// the runtime programs.yaml distribution-annotation gate, a three-
5608 /// consumer split at the validator, the programs.yaml emitter, and
5609 /// the `feira app graph` printer far from the source `caixa.lisp`
5610 /// with no field naming the placement-drift root cause. Lifting the
5611 /// resolution rule to a typed method on the substrate primitive
5612 /// means every downstream consumer of the Aplicacao's per-
5613 /// `:placement` distribution composite surface reaches for exactly
5614 /// one typed dispatch — the resolver's accept-set migrates as a unit
5615 /// on any future axis addition.
5616 ///
5617 /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
5618 /// `AplicacaoSpec` type itself — sibling to the seed
5619 /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
5620 /// composite-reference accessor on the peer per-`:politicas` outer-
5621 /// composite axis, and to the paired slice-return accessors
5622 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5623 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
5624 /// the two `Vec`-carry axes on the outer typed composition view; the
5625 /// outer `:placement` composite-reference axis is the natural pair
5626 /// to the peer `:politicas` composite-reference axis on the two
5627 /// operationally-symmetric M3 mesh slots (`:politicas` carries the
5628 /// how-to-run policy overlay, `:placement` carries the where-to-run
5629 /// distribution composite — every whole-Aplicacao mesh-artifact
5630 /// emitter reads both as one unit). Same "one typed dispatch on the
5631 /// substrate primitive, thin projections at each consumer"
5632 /// discipline the peer per-`:politicas` composite-reference axis
5633 /// already routes through. The one remaining outer-composite axis
5634 /// still unlifted at the time of this lift —
5635 /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
5636 /// external-gateway composite) — inherits this accessor's discipline
5637 /// as the next compounding run migrates its consumers onto the shared
5638 /// reference-return shape, closing the outer-composite altitude on
5639 /// every M3 mesh-slot axis. Named `placement()` to match the storage
5640 /// field's name verbatim and the tatara-lisp author-surface term
5641 /// (`:placement`) the field's own docstring already carries; the
5642 /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
5643 /// vocabulary the slot's docstring already reaches for. Returns
5644 /// `&Placement` (not the owning composite by copy or clone) because
5645 /// every downstream consumer of the placement composite treats it as
5646 /// a read-only per-axis dispatch source — the reference-view is the
5647 /// narrowest borrow that supports every present + roadmapped consumer
5648 /// (per-axis accessor dispatch, serde composite-serialization) without
5649 /// cloning the composite through every consumer's fast path.
5650 #[must_use]
5651 pub fn placement(&self) -> &Placement {
5652 &self.placement
5653 }
5654
5655 /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
5656 /// per-Aplicacao external-gateway composite optional-composite-
5657 /// reference accessor every per-Aplicacao gateway-block reader
5658 /// keys off — returns the author-declared `:entrada` composite
5659 /// verbatim as an `Option<&Entrada>` reference over the same
5660 /// backing storage the raw `self.entrada.as_ref()` field access
5661 /// borrows from, with `None` naming the internal-only mesh shape
5662 /// (the author-omitted `:entrada` slot the K8s Gateway API v1
5663 /// gateway_routes emitter treats as "emit nothing" and the peer
5664 /// `feira app graph` printer treats as "internal-only mesh").
5665 ///
5666 /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
5667 /// external-gateway composite — the load-bearing container of
5668 /// every does-this-Aplicacao-expose-a-public-endpoint axis every
5669 /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
5670 /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
5671 /// hostname axis, §III.4 for the `:para` destination-Servico
5672 /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
5673 /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
5674 /// axis threads through a lifted per-slot accessor on the
5675 /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
5676 /// Gateway-API `Listener.hostname` scalar accessor, the paired
5677 /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
5678 /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
5679 /// backendRefs destination-Servico scalar accessor, the
5680 /// [`Entrada::resolved_paths`] path-fallback resolver, and the
5681 /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
5682 /// scalar accessor. Every downstream consumer that reaches for
5683 /// an entrada axis first passes through this outer accessor onto
5684 /// the composite and then dispatches onto the per-axis accessor
5685 /// — the two-level dispatch means every per-`:entrada` reader
5686 /// now routes through a typed dispatch on the substrate primitive
5687 /// at both altitudes.
5688 ///
5689 /// Prior to this lift the `.entrada` `Option<Entrada>` composite
5690 /// was accessed inline at four production sites — the
5691 /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
5692 /// gate's `if let Some(e) = &self.entrada { … }` traversal head
5693 /// (which drives every per-axis refusal on the composite: the
5694 /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
5695 /// `EntradaMemberMissing` membership lookup against the
5696 /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
5697 /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
5698 /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
5699 /// per-path shape gate on each entry of `e.paths`), the
5700 /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
5701 /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
5702 /// composite-projection seed (which drives the destination-
5703 /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
5704 /// backendRefs port emitter fans on), the
5705 /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
5706 /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
5707 /// early-return seed (which drives the "no `:entrada` ⇒ no
5708 /// external artifacts" partition on the whole-Aplicacao Gateway-
5709 /// API emitter's fan-out), and the `feira app graph` per-
5710 /// Aplicacao print line's `if let Some(e) = &spec.entrada`
5711 /// external-gateway summary emitter (which drives the human-
5712 /// readable `entrada: host → para (paths=…, port=…)` /
5713 /// `entrada: (internal-only mesh)` partition on the typed
5714 /// Aplicacao view) — four open-coded outer-field accesses that
5715 /// expressed no compile-time link back to the typed slot at the
5716 /// [`AplicacaoSpec`] altitude. A future extension of the
5717 /// `:entrada` outer axis to a richer author surface (a
5718 /// multi-`:entrada` list the M4 CR materializer resolves per-CR
5719 /// at admission time so an Aplicacao can expose a public-web +
5720 /// admin-web pair, a per-cluster `:entrada-overrides` slot the
5721 /// MESH-COMPOSITION §V federation roadmap acknowledges so an
5722 /// operator can pin a per-cluster hostname override without
5723 /// re-authoring the `caixa.lisp`, a promotion of the plain
5724 /// `Option<Entrada>` to a richer `{single, multi}` partition once
5725 /// the multi-`:entrada` roadmap lands) would have had to be
5726 /// threaded through all four open-coded copies in lockstep or one
5727 /// consumer would silently disagree with the peers on which
5728 /// entrada composite a given Aplicacao resolves to — the
5729 /// validator's per-axis bracket-dispatch seed reading the raw
5730 /// slot while the peer `gateway_routes` emitter read an
5731 /// operator-resolved slot would silently split the build-time
5732 /// gateway-shape gate from the runtime Gateway + HTTPRoute
5733 /// emission gate, a four-consumer split at the validator, the
5734 /// `port_for_destination` L4-port resolver, the `gateway_routes`
5735 /// emitter, and the `feira app graph` printer far from the
5736 /// source `caixa.lisp` with no field naming the entrada-drift
5737 /// root cause. Lifting the resolution rule to a typed method on
5738 /// the substrate primitive means every downstream consumer of
5739 /// the Aplicacao's per-`:entrada` external-gateway composite
5740 /// surface reaches for exactly one typed dispatch — the
5741 /// resolver's accept-set migrates as a unit on any future axis
5742 /// addition.
5743 ///
5744 /// Third and final `&Composite`-return accessor on the top-level
5745 /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
5746 /// unlifted outer-composite axis on the outer typed composition
5747 /// view, sibling to the seed [`AplicacaoSpec::politicas`]
5748 /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
5749 /// accessor on the per-`:politicas` outer-composite axis and to
5750 /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
5751 /// distribution-composite composite-reference accessor on the
5752 /// per-`:placement` outer-composite axis; extends the outer-
5753 /// composite reference-return discipline the two peers already
5754 /// route through onto the last unlifted per-`AplicacaoSpec`
5755 /// outer-composite axis. The `:entrada` outer-composite axis is
5756 /// the natural pair to the two peer outer-composite axes on the
5757 /// three operationally-symmetric M3 mesh-slot outer composites
5758 /// (`:politicas` carries the how-to-run policy overlay,
5759 /// `:placement` carries the where-to-run distribution composite,
5760 /// `:entrada` carries the who-can-reach-it external-gateway
5761 /// composite — every whole-Aplicacao mesh-artifact emitter reads
5762 /// all three as one unit). Same "one typed dispatch on the
5763 /// substrate primitive, thin projections at each consumer"
5764 /// discipline the peer outer-composite axes already route through.
5765 /// Named `entrada()` to match the storage field's name verbatim
5766 /// and the tatara-lisp author-surface term (`:entrada`) the
5767 /// field's own docstring already carries; the accessor's
5768 /// identity maps onto the canonical MESH-COMPOSITION §III.4
5769 /// vocabulary the slot's docstring already reaches for. Returns
5770 /// `Option<&Entrada>` (not the owning composite by copy or
5771 /// clone) because every downstream consumer of the entrada
5772 /// composite treats it as a read-only per-axis dispatch source
5773 /// — the reference-view is the narrowest borrow that supports
5774 /// every present + roadmapped consumer (per-axis accessor
5775 /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
5776 /// port-fallback projection, early-return partition on the
5777 /// `None` arm) without cloning the composite through every
5778 /// consumer's fast path. The `Option` half of the return-type
5779 /// preserves the load-bearing "author-omitted `:entrada` ⇒
5780 /// internal-only mesh" partition (not a default composite the
5781 /// downstream must reject on emptiness) — the accessor projects
5782 /// the raw `Option<Entrada>` slot's presence bit through the
5783 /// reference-return unchanged.
5784 #[must_use]
5785 pub fn entrada(&self) -> Option<&Entrada> {
5786 self.entrada.as_ref()
5787 }
5788
5789 /// Validate the typed shape:
5790 /// - `:membros` is non-empty; every entry has a non-empty `:caixa`
5791 /// and a non-empty `:versao`; no two entries share the same
5792 /// `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
5793 /// not a multiset)
5794 /// - every `:contratos` :de + :para must be in `:membros`
5795 /// - no `:contratos` edge is a self-edge (`:de == :para`) — a
5796 /// contract is an inter-Servico edge, so a Servico contracting
5797 /// with itself is a build error under every WIT shape
5798 /// (MESH-COMPOSITION §III.1)
5799 /// - no two `:contratos` entries agree on
5800 /// `(de, para, wit, endpoint, subject, slot)` — the typed-graph
5801 /// edges are a set, not a multiset (peer of the `:membros` /
5802 /// `:placement :clusters` / `:entrada :paths` duplicate gates)
5803 /// - `:entrada :para` must be in `:membros`
5804 /// - `:placement Sharded` must declare `:shard-key` (non-empty);
5805 /// `:placement Replicated`/`SingleNode` must NOT declare
5806 /// `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
5807 /// consumes it (MESH-COMPOSITION §II.4), and the typed partition
5808 /// between strategy and shard-key is symmetric: every validated
5809 /// `Placement` has `shard_key.is_some()` iff `estrategia ==
5810 /// Sharded`
5811 /// - every `:placement` strategy must declare ≥1 `:clusters` entry —
5812 /// `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
5813 /// the shard pool (MESH-COMPOSITION §III.1)
5814 /// - every `:clusters` entry is non-empty and unique
5815 /// - `:placement :affinity`, when set, is non-empty
5816 /// - the synchronous-`:contratos` subgraph is acyclic
5817 /// (MESH-COMPOSITION §III.3)
5818 /// - every declared `:politicas` value is operationally meaningful
5819 /// (zero timeout, zero retries, zero breaker thresholds, zero rate
5820 /// limit are all build errors — MESH-COMPOSITION §V CSE invariants;
5821 /// omit the field instead to express "no policy on this axis")
5822 pub fn validate(&self) -> Result<(), AplicacaoError> {
5823 self.validate_membros()?;
5824 let names: std::collections::HashSet<&str> =
5825 self.membros().iter().map(Membro::nome).collect();
5826
5827 // Identity key for the typed-edge duplicate gate below: every
5828 // field that distinguishes one contract from another. Two
5829 // entries that agree on all six are *the same edge declared
5830 // twice*, the typed-graph analogue of duplicate `:membros` /
5831 // `:placement :clusters` / `:entrada :paths` entries (which
5832 // are already build errors at this layer). Rejecting it at the
5833 // validate gate closes a renderer-side footgun: caixa-mesh's
5834 // `cilium_network_policies` keys each emitted policy by
5835 // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
5836 // (de, para) and identical payload would land as two K8s
5837 // objects with colliding `metadata.name`, rejected at apply
5838 // time far from the source caixa.lisp.
5839 let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
5840 std::collections::HashSet::new();
5841 for c in self.contratos() {
5842 // Per-axis value-shape gate on every `:contratos` name
5843 // reference, before any graph-membership lookup. Empty +
5844 // DNS-1123-malformed `:de`/`:para` values silently fell
5845 // through to `ContratoMemberMissing` at the lookup arm
5846 // because every `:membros :caixa` is shape-validated
5847 // (3f9d7a0), so the `names` set structurally cannot contain
5848 // an empty / malformed string and the membership-lookup
5849 // diagnostic always misframed the root cause as
5850 // "this caixa is not in `:membros`". The shape gate runs
5851 // ahead of the lookup so structurally-impossible-to-match
5852 // inputs route through the narrower self-locating
5853 // diagnostic, preserving the legitimate "well-shaped
5854 // phantom reference" arm. `:de` runs before `:para` per
5855 // the canonical edge-direction order the existing
5856 // membership lookup, self-edge check, target dispatch,
5857 // and diagnostic strings already use.
5858 // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
5859 // + the paired [`AplicacaoError::ContratoMemberMissing`]
5860 // diagnostic's `caixa:` carrier through the lifted
5861 // [`WitContract::source`] / [`WitContract::destination`]
5862 // scalar accessors rather than the raw `&c.de` / `&c.para`
5863 // `&String`-borrow arg site + the raw `c.de.clone()` /
5864 // `c.para.clone()` field-access `String`-carry sites — the
5865 // last unlifted per-`:contratos` raw-field-access sites in
5866 // the M3 mesh-slot validator's per-edge per-arm shape-gate
5867 // arg + phantom-name diagnostic wrap-envelope emit surface.
5868 // `c.source()` is byte-identical to `&c.de` (pinned by the
5869 // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
5870 // + `wit_contract_source_borrows_from_de_storage` accessor
5871 // tests) and `c.destination()` is byte-identical to `&c.para`
5872 // (pinned by the sibling
5873 // `wit_contract_destination_returns_para_byte_equal_across_permutations`
5874 // + `wit_contract_destination_borrows_from_para_storage`
5875 // accessor tests) — so a future rebrand of either underlying
5876 // storage flows through the accessor's one body without a
5877 // coordinated per-consumer rewrite across the M3 mesh
5878 // validator's per-edge shape-gate + phantom-name refusal
5879 // arms. Peer of the sibling per-`:contratos` self-loop
5880 // arm's `.source().to_string()` / `.world_ref().to_string()`
5881 // `String`-carry sites the earlier convergence lifted onto
5882 // the same accessor pair.
5883 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
5884 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
5885 if !names.contains(c.source()) {
5886 return Err(AplicacaoError::ContratoMemberMissing {
5887 caixa: c.source().to_string(),
5888 });
5889 }
5890 if !names.contains(c.destination()) {
5891 return Err(AplicacaoError::ContratoMemberMissing {
5892 caixa: c.destination().to_string(),
5893 });
5894 }
5895 // A `:contratos` entry is an *inter*-Servico contract
5896 // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
5897 // typed edge between two distinct graph nodes. An edge whose
5898 // `:de` equals its `:para` is a Servico contracting with
5899 // itself — a degenerate edge under every WIT shape. The
5900 // synchronous shapes were caught only incidentally, and with
5901 // a misleading diagnostic: `detect_sync_cycles` reported
5902 // `cart → cart` as a `ContratoCycle` whose path is
5903 // `["cart", "cart"]` — framing a self-edge as a multi-node
5904 // deadlock. The pub-sub shape slipped through entirely
5905 // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
5906 // `nats:pub-sub` edge from a member to itself silently
5907 // validated, then rendered a `CiliumNetworkPolicy` whose
5908 // endpointSelector and fromEndpoints both name the same
5909 // program — a self-allow rule that is a no-op, since
5910 // intra-pod traffic never traverses the mesh). A self-edge's
5911 // runtime meaning is an in-process call, which doesn't go
5912 // through the mesh at all, so no `:contratos` edge can carry
5913 // it. Firing the gate before the `:wit`/`target()` shape
5914 // checks means the structural "this edge can't exist" error
5915 // precedes the narrower payload-shape diagnostics, and shape-
5916 // agnostically covers all four `WitTarget` arms (HTTP / Store
5917 // / Capability / PubSub) at one point — closing the pub-sub
5918 // hole and replacing the misleading cycle diagnostic in one
5919 // gate. Peer of the duplicate-`:contratos` / duplicate-
5920 // `:membros` set gates: both reject a structurally
5921 // ill-formed graph at the typed surface, before the renderer
5922 // emits a K8s object that fails or no-ops far from the source
5923 // caixa.lisp.
5924 // Route the per-`:contratos` structural self-edge probe
5925 // through the lifted [`WitContract::is_self_loop`] typed
5926 // predicate rather than the raw `c.de == c.para` field-
5927 // equality check — the one production consumer of the per-
5928 // `:contratos` caller-equals-callee endpoint-equality axis
5929 // now keys off exactly one typed dispatch on the substrate
5930 // primitive, so any future rebrand of the axis (an M4-typed-
5931 // caller enum whose identity comparison rule the predicate
5932 // could route through, a per-cluster caller/callee-alias
5933 // table the M4 CR materializer resolves per-CR before the
5934 // equality probe) migrates as a single caixa-core edit
5935 // rather than a coordinated rewrite of the gate + every
5936 // downstream self-edge consumer. Peer of the sibling
5937 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
5938 // [`WitContract::is_store`] shape-predicate routing on the
5939 // `:wit` world-ref axis, extended onto the per-edge
5940 // endpoint-equality axis.
5941 //
5942 // Route the paired [`AplicacaoError::ContratoSelfLoop`]
5943 // diagnostic's `caixa:` / `wit:` carriers through the
5944 // lifted [`WitContract::source`] / [`WitContract::world_ref`]
5945 // scalar accessors rather than the raw `c.de.clone()` /
5946 // `c.wit.clone()` field-access `String`-carry sites — the
5947 // last unlifted per-`:contratos` raw-field-access
5948 // `.clone()` sites in the M3 mesh-slot validator's self-
5949 // edge refusal arm. `.source().to_string()` is byte-
5950 // identical to `.de.clone()` (pinned by the sibling
5951 // `source_returns_de_byte_equal_across_permutations` accessor
5952 // test), and `.world_ref().to_string()` is byte-identical
5953 // to `.wit.clone()` (pinned by the sibling
5954 // `world_ref_returns_wit_byte_equal_across_permutations`
5955 // accessor test) — so a future rebrand of either underlying
5956 // storage flows through the accessor's one body without a
5957 // coordinated per-consumer rewrite across the M3 mesh
5958 // validator.
5959 if c.is_self_loop() {
5960 return Err(AplicacaoError::ContratoSelfLoop {
5961 caixa: c.source().to_string(),
5962 wit: c.world_ref().to_string(),
5963 });
5964 }
5965 if c.world_ref().is_empty() {
5966 let (de, para) = c.edge_pair();
5967 return Err(AplicacaoError::EmptyWit { de, para });
5968 }
5969 // Shape ↔ target consistency — surfaces "HTTP wit without
5970 // :endpoint", "NATS wit with :endpoint set", etc. as named
5971 // build errors instead of silent renderer drops. Threaded
5972 // through the duplicate-edge diagnostic below (via
5973 // [`WitTarget::label`]) so the "which typed target arm did
5974 // the duplicate carry" question is answered by the typed
5975 // enum's variant discriminator, not by re-probing the raw
5976 // `Option<String>` payload fields.
5977 let target_view = c.target()?;
5978 // Contract identity: (de, para, wit, endpoint, subject, slot).
5979 // Two contracts that match on all six are the same typed edge
5980 // declared twice — author error, not a legitimate variant of
5981 // "same caller-callee pair, different payload" (e.g.
5982 // cart→catalog at /products vs /search), which keeps distinct
5983 // identity keys via the differing endpoint payloads.
5984 //
5985 // Route the six-axis dedup key through the lifted
5986 // [`WitContract::identity`] composite-projection accessor
5987 // rather than the inline six-tuple builder — the two
5988 // substrate primitives on the per-`:contratos` identity axis
5989 // (the [`ContratoIdentity`] type alias's six axes, this
5990 // dedup-key's six tuple arms) now migrate as a unit on any
5991 // future axis addition. Peer of the sibling per-`:contratos`
5992 // composite-projection [`WitContract::edge_pair`] /
5993 // [`WitContract::edge_triple`] accessors on the
5994 // caller-callee / caller-callee-wit prefix axes; extends
5995 // the discipline onto the full-identity axis that carries
5996 // the three payload-shape arms too.
5997 let key = c.identity();
5998 crate::render::insert_first_seen(&mut seen_contracts, key, || {
5999 // Route the per-`:contratos` duplicate-gate diagnostic's
6000 // `(de, para, wit)` triple through the lifted
6001 // [`WitContract::edge_triple`] typed accessor rather
6002 // than pairing `edge_pair()` for the `(de, para)` prefix
6003 // with a raw `c.wit.clone()` for the `wit:` tail — the
6004 // paired-with-raw-field-access shape was the last
6005 // per-`:contratos` diagnostic constructor bypassing the
6006 // substrate-primitive composite projection, sibling to
6007 // the eight [`AplicacaoError::Contrato*`] triple-
6008 // carrying constructors [`WitContract::target`]'s edge
6009 // closure feeds through the same accessor.
6010 let (de, para, wit) = c.edge_triple();
6011 AplicacaoError::ContratoDuplicate {
6012 de,
6013 para,
6014 wit,
6015 target: target_view.label(),
6016 }
6017 })?;
6018 }
6019
6020 // Cycles in the synchronous-edge subgraph are build errors
6021 // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
6022 // are "acyclic by construction" because the publisher fires
6023 // and forgets, so no caller blocks on a downstream that loops
6024 // back to it.
6025 self.detect_sync_cycles()?;
6026
6027 if let Some(e) = self.entrada() {
6028 // Route the per-`:entrada` composite-reference read
6029 // through the lifted [`AplicacaoSpec::entrada`] accessor
6030 // rather than the raw `&self.entrada` field access — the
6031 // shape-and-membership gate's traversal head is now the
6032 // canonical read-side surface every per-Aplicacao entrada
6033 // consumer routes through, closing the fourth of four
6034 // open-coded outer-field accesses on the per-`:entrada`
6035 // outer-composite axis.
6036 //
6037 // Shape gate on `:entrada :para` runs ahead of the
6038 // membership lookup. Every `:membros :caixa` past
6039 // `validate_membro_caixa` is a valid DNS-1123 label
6040 // (3f9d7a0), so the `names` set structurally cannot
6041 // contain an empty / malformed string and the membership-
6042 // lookup diagnostic always misframed the root cause as
6043 // "this caixa is not in `:membros`". The shape gate
6044 // routes structurally-impossible-to-match inputs through
6045 // the narrower self-locating diagnostic, preserving the
6046 // legitimate "well-shaped phantom reference" arm — the
6047 // same trajectory the peer `:membros :caixa` (3f9d7a0),
6048 // `:placement :clusters` (6c8c00b), and `:contratos :de`
6049 // / `:para` (8d5af6b) axes already follow. This closes
6050 // the fourth and last Aplicacao-level Servico-name
6051 // reference axis on the canonical DNS-1123 floor.
6052 // Route the per-`:entrada :para` byte-string reads through
6053 // the lifted [`Entrada::destination`] accessor rather than
6054 // the raw `e.para` field access — the three
6055 // per-`AplicacaoSpec::validate` `:entrada :para` consumers
6056 // (shape-gate `validate_entrada_para` arg, membership
6057 // lookup, `EntradaMemberMissing` diagnostic carry) now key
6058 // off exactly one typed dispatch on the substrate
6059 // primitive, closing the last unlifted per-`:entrada :para`
6060 // raw-field-access axis on the M3 mesh-slot validator.
6061 // The `.destination().to_string()` at the diagnostic site
6062 // is byte-identical to `.para.clone()` — pinned by the
6063 // sibling `destination_returns_entrada_para_byte_equal` +
6064 // `destination_borrows_from_entrada_para_storage` accessor
6065 // tests — so a future rebrand of the underlying `:para`
6066 // storage (a lift from `String` to a typed
6067 // `ServicoName(String)` newtype, a per-Aplicacao interning
6068 // arena the M4 CR materializer authors, a
6069 // `smol_str::SmolStr` inline-buffer swap) flows through
6070 // the accessor's one body without a coordinated
6071 // per-consumer rewrite across the M3 mesh validator.
6072 validate_entrada_para(e.destination())?;
6073 if !names.contains(e.destination()) {
6074 return Err(AplicacaoError::EntradaMemberMissing {
6075 para: e.destination().to_string(),
6076 });
6077 }
6078 // Route the per-`:entrada :host` byte-string reads through
6079 // the lifted [`Entrada::hostname`] accessor rather than
6080 // the raw `e.host` field access — the emptiness gate and
6081 // the shape-gate `validate_entrada_host` arg now key off
6082 // exactly one typed dispatch on the substrate primitive,
6083 // closing the last unlifted per-`:entrada :host` raw-
6084 // field-access axis on the M3 mesh-slot validator. Peer
6085 // of the sibling per-`:entrada :para` convergence above
6086 // and pinned by the existing
6087 // `hostname_returns_entrada_host_byte_equal` +
6088 // `hostnames_returns_singleton_of_hostname_accessor`
6089 // accessor tests, so any future
6090 // Gateway-API-shaped host renormalization (a wildcard-
6091 // label lift, a trailing-`.` FQDN substitution, an IDNA
6092 // Punycode round-trip the SNI fan-out overlay authors)
6093 // flows through the accessor's one body without a
6094 // coordinated per-consumer rewrite across the M3 mesh
6095 // validator.
6096 if e.hostname().is_empty() {
6097 return Err(AplicacaoError::EmptyEntradaHost);
6098 }
6099 // The `:host` lands verbatim as a K8s Gateway API v1
6100 // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
6101 // both apiserver-validated against the same restrictive
6102 // pattern: lowercase RFC 1123 DNS subdomain, optional
6103 // single leading wildcard label (`*.`), max length 253,
6104 // per-label max length 63, no IP literals, no scheme,
6105 // no port. Until this gate landed `validate()` only
6106 // refused the empty string (`EmptyEntradaHost`); a
6107 // structurally invalid hostname (`"https://example.com"`,
6108 // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
6109 // `"_underscored.example.com"`, `"FOO.example.com"`,
6110 // `"checkout.quero.cloud."`) silently passed validate
6111 // and the apiserver `field is invalid` error surfaced at
6112 // `kubectl apply` time, far from the source caixa.lisp.
6113 // Lifting the gate to caixa-build time mirrors the
6114 // `:entrada :paths` value-shape trajectory (eb3456d) and
6115 // closes the last unstructured `:entrada` axis.
6116 validate_entrada_host(e.hostname())?;
6117 // Structural-floor gate on `:entrada :port`: every
6118 // validated `Entrada::port` past this gate lies in
6119 // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
6120 // type-inferred ceiling closes the top edge, so no companion
6121 // upper-cap arm is needed here — unlike the peer capped-
6122 // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
6123 // `require_positive_bounded_u32` bracket covers both edges).
6124 // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
6125 // accept-set-floor const rather than the prior inline
6126 // `if e.port == 0` byte-check so a future rebrand of the
6127 // accept-set floor (a hypothetical unprivileged-only
6128 // migration lifting the floor to `1024`, a per-cluster
6129 // scoping the operator pins through a future
6130 // `:placement :port-floor` slot as the M4 typed-slot
6131 // trajectory adds it, the future
6132 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6133 // per-Aplicacao gateway resolver reaching for the same
6134 // floor) is a one-line edit on the canonical
6135 // [`SERVICO_PORT_MIN`] declaration, not a coordinated
6136 // rewrite across the emit site + the pin test + every
6137 // future per-target renderer the substrate adds.
6138 if e.port() < SERVICO_PORT_MIN {
6139 return Err(AplicacaoError::EntradaPortZero);
6140 }
6141 // Each `:entrada :paths` entry becomes a K8s Gateway API
6142 // HTTPRoute `matches[].path.value`. The Gateway API rejects
6143 // values that don't start with `/` for `type: PathPrefix`,
6144 // and an empty value is meaningless. Surface those as build
6145 // errors (MESH-COMPOSITION §III.3) rather than apply-time
6146 // failures. Empty `:paths` itself is fine — caixa-mesh
6147 // falls back to a single `/` catch-all.
6148 let mut seen = std::collections::HashSet::new();
6149 // Route the per-entry value-shape gate's traversal head
6150 // through the lifted [`Entrada::paths`] slice accessor
6151 // rather than the raw `&e.paths` field access — the
6152 // per-Aplicacao `:entrada :paths` validate loop now keys
6153 // off the canonical raw-slot surface every downstream
6154 // per-`:entrada` path-list consumer (the sibling
6155 // [`Entrada::resolved_paths`] fallback-applying resolver
6156 // internal reads, `feira app graph`'s per-Aplicacao entrada
6157 // summary line's `{:?}` Debug print) routes through, so any
6158 // future rebrand on the typed slot's raw-slot reader lands
6159 // at exactly one place. Same convergence discipline as the
6160 // sibling [`Placement::clusters`] (a6e18d7) reader-site
6161 // convergences on the peer M3 mesh-slot `Vec<String>`-carry
6162 // axis.
6163 for p in e.paths() {
6164 if p.is_empty() {
6165 return Err(AplicacaoError::EntradaPathEmpty);
6166 }
6167 if !p.starts_with('/') {
6168 return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
6169 }
6170 // Per-entry value-shape gate: the path lands verbatim
6171 // as a K8s Gateway API HTTPRoute `matches[].path.value`
6172 // (caixa-mesh/src/lib.rs:498), apiserver-validated
6173 // against `maxLength: 1024` + the Gateway API webhook's
6174 // path-grammar rules (no `//`, no `/./`, no `/../`, no
6175 // query/fragment separators, no whitespace, no control
6176 // characters, no non-ASCII bytes). Until this gate
6177 // landed `validate` only refused the empty string and
6178 // missing-leading-slash (eb3456d); a structurally
6179 // invalid path (`"/api?q=1"`, `"/api#frag"`,
6180 // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
6181 // 1025-byte URL-shaped slug) silently passed validate
6182 // and the failure surfaced at `kubectl apply` time as
6183 // a Gateway API webhook rejection, far from the source
6184 // caixa.lisp, with no field naming the offending
6185 // `:paths` entry. Lifting the gate to caixa-build time
6186 // mirrors the `:entrada :host` value-shape trajectory
6187 // (c7d05ec) on the sibling axis — every author surface
6188 // that emits a Gateway API field now matches the
6189 // apiserver's accepted set at validate time.
6190 validate_entrada_path(p)?;
6191 crate::render::insert_first_seen(&mut seen, p.as_str(), || {
6192 AplicacaoError::EntradaPathDuplicate { path: p.clone() }
6193 })?;
6194 }
6195 }
6196
6197 self.validate_placement()?;
6198
6199 self.validate_politicas()?;
6200
6201 Ok(())
6202 }
6203
6204 /// Reject `:membros` values that are operationally meaningless. The
6205 /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
6206 /// every entry names a Servico that participates in the Aplicacao,
6207 /// and the rendered programs.yaml fan-out emits one entry per
6208 /// `:membros`. Three authoring footguns are closed here:
6209 ///
6210 /// - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
6211 /// a `programs:` entry whose `name:` is the empty string, which
6212 /// downstream `lareira-fleet-programs` rejects at template time
6213 /// with a non-localized error;
6214 /// - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
6215 /// an empty semver constraint, so the failure surfaces far from
6216 /// the source caixa.lisp;
6217 /// - duplicate `:caixa` names — two entries with the same name
6218 /// produce duplicate programs.yaml entries (one silently
6219 /// overwrites the other in the cluster's HelmRelease values), and
6220 /// contract membership lookups against `:contratos` collapse the
6221 /// two onto one node, masking authoring mistakes.
6222 ///
6223 /// Same value-shape discipline as `:placement :clusters` (where empty
6224 /// + duplicate cluster names are rejected) and `:entrada :paths`
6225 /// (where empty + duplicate path entries are rejected). Lifting these
6226 /// invariants to the typed surface mirrors the MESH-COMPOSITION
6227 /// §III.3 promise that the `:membros` set — the load-bearing identity
6228 /// of the application graph — is well-formed by construction.
6229 fn validate_membros(&self) -> Result<(), AplicacaoError> {
6230 if self.membros().is_empty() {
6231 return Err(AplicacaoError::NoMembros);
6232 }
6233 let mut seen = std::collections::HashSet::new();
6234 for m in self.membros() {
6235 // Route the `MembroCaixaEmpty` refusal-arm's per-member
6236 // empty-`:caixa` shape-gate through the typed
6237 // [`Membro::nome`] accessor rather than the raw `.caixa`
6238 // field access — the last un-lifted `.caixa` production-
6239 // code read site on the per-`:membros` member-caixa `:nome`
6240 // axis, sibling to the six caixa-core validator read sites
6241 // (member-set collector, per-member value-shape gate,
6242 // duplicate dedup key, cycle-detector adjacency-map seed,
6243 // self-loop gate) the 4a32abf lift already routed through
6244 // the accessor and the peer 54bf2f3 caixa-mesh emit-side
6245 // per-`programs[]` entry-`name:` `String`-carry converge.
6246 // Prior to this converge the `MembroCaixaEmpty` refusal
6247 // arm was the solitary consumer bypassing the typed
6248 // dispatch — the same-loop iteration's very next call
6249 // `validate_membro_caixa(m.nome())` already routed through
6250 // the accessor, so an author landing an empty-`:caixa`
6251 // entry hit the accessor on the shape-gate line but
6252 // bypassed it on the emptiness line one line above. A
6253 // future extension of the `:membros :caixa` axis to a
6254 // richer author surface (a per-cluster alias table pinned
6255 // through a future `:placement`-scoped slot, a namespace-
6256 // qualified rewrite the M4 CR materializer applies per-CR,
6257 // a per-member overlay from the future `:membros
6258 // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
6259 // that lands on the accessor would silently disagree
6260 // between the emptiness gate and every peer consumer —
6261 // an author-declared `:caixa "checkout"` value the
6262 // accessor rewrote to `""` under a future alias arm would
6263 // pass the raw `.is_empty()` gate here while the peer
6264 // `validate_membro_caixa(m.nome())` call one line below
6265 // (and every downstream emit-side consumer routing through
6266 // the accessor) tripped on the empty-value shape far from
6267 // this diagnostic. Pinned by the drift-detection test
6268 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
6269 // below.
6270 if m.nome().is_empty() {
6271 return Err(AplicacaoError::MembroCaixaEmpty);
6272 }
6273 // Every emitted cluster artifact's `metadata.name` derives
6274 // from a `:membros :caixa` value verbatim — the rendered
6275 // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
6276 // the [`crate::LABEL_PROGRAM`] label value on every CNP
6277 // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
6278 // 272), the composed `CiliumNetworkPolicy` `metadata.name`
6279 // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
6280 // `metadata.name` when the member is the `:entrada :para`
6281 // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
6282 // schema enforces the DNS-1123 label rule on admission;
6283 // a structurally invalid member name (`"Cart"`, `"my_cart"`,
6284 // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
6285 // mistaken-identity slug) silently passes the prior empty-/
6286 // duplicate-only gate and the failure surfaces at `kubectl
6287 // apply` time as a `metadata.name: Invalid value` rejection,
6288 // far from the source caixa.lisp, with no field naming the
6289 // offending `:membros` entry. Lifting the gate to caixa-build
6290 // time mirrors the `:entrada :host` value-shape trajectory
6291 // (c7d05ec) on the peer axis — every author surface that
6292 // emits a K8s name now matches the apiserver's accepted set
6293 // at validate time.
6294 validate_membro_caixa(m.nome())?;
6295 // The author surface for `:versao` is the same Cargo-shaped
6296 // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
6297 // `"*"`) every `:deps` entry carries — and the lacre pipeline
6298 // resolves both axes through the same
6299 // [`crate::version::parse_requirement`] entry-point. The
6300 // shared [`crate::render::require_valid_versao_requirement`]
6301 // helper brackets the empty-first + parse cascade both peer
6302 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
6303 // [`crate::SupervisorSpec::validate`] on `:children :versao`)
6304 // route through, so drift between the three axes' accepted
6305 // requirement sets is structurally impossible and the parse-
6306 // side no-op the empty-first arm closes (semver's empty
6307 // parse yields an implicit `*`) lives in exactly one
6308 // predicate.
6309 crate::render::require_valid_versao_requirement(
6310 m.versao_requirement(),
6311 || AplicacaoError::MembroVersaoEmpty {
6312 caixa: m.nome().to_string(),
6313 },
6314 |reason| AplicacaoError::MembroVersaoInvalid {
6315 caixa: m.nome().to_string(),
6316 versao: m.versao_requirement().to_string(),
6317 reason,
6318 },
6319 )?;
6320 crate::render::insert_first_seen(&mut seen, m.nome(), || {
6321 AplicacaoError::MembroDuplicate {
6322 caixa: m.nome().to_string(),
6323 }
6324 })?;
6325 }
6326 Ok(())
6327 }
6328
6329 /// Reject `:placement` values that are operationally meaningless or
6330 /// internally contradictory. Each strategy variant has the same
6331 /// invariants on `:clusters` (non-empty list, non-empty unique
6332 /// entries) — the §III.1 author surface is uniform on this axis,
6333 /// even though the *meaning* of the list differs by strategy
6334 /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
6335 /// shard pool).
6336 ///
6337 /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
6338 /// are the same authoring footgun closed for `:politicas` zero
6339 /// values and `:entrada` empty paths: the field is *declared* but
6340 /// carries no meaning, so downstream renderers either skip it
6341 /// silently (cluster-fanout drops the empty entry, no diagnostic)
6342 /// or apply it literally and fail at admission time. Lifting both
6343 /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
6344 /// violation is a build error" promise.
6345 ///
6346 /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
6347 /// is required exactly when `:estrategia Sharded` (hash-keyed
6348 /// distribution, Akka cluster-sharding convention, §II.4) and
6349 /// refused on `:estrategia Replicated`/`SingleNode` (where no
6350 /// hash-keyed routing axis consumes it). The partition closes the
6351 /// "I think I configured sharding" footgun where an author writes
6352 /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
6353 /// the typed slot's value silently vanishes at the renderer layer
6354 /// — every validated `Placement` past this call satisfies
6355 /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
6356 fn validate_placement(&self) -> Result<(), AplicacaoError> {
6357 // Every strategy needs at least one named cluster: `Replicated`
6358 // and `SingleNode` use the list as hosting/takeover candidates
6359 // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
6360 // §II.1), while `Sharded` uses it as the shard pool
6361 // (Akka cluster-sharding convention — §II.4). An empty list is
6362 // meaningless under any of the three.
6363 //
6364 // Route the paired pre-flight `.is_empty()` refusal probe and
6365 // the per-cluster validate loop's traversal head through the
6366 // lifted [`Placement::clusters`] slice-return accessor rather
6367 // than the raw `self.placement.clusters` field access — the
6368 // two production consumers of the per-`:placement` cluster-
6369 // pool `Vec`-carry now key off exactly one typed dispatch on
6370 // the substrate primitive, so any future rebrand on the axis
6371 // (a per-tenant cluster-pool overlay the operator pins through
6372 // a future `:placement :clusters-overrides` slot, a per-
6373 // Aplicacao dynamic cluster-pool derivation the future M5
6374 // adaptive-placement engine computes from `:affinity` weights)
6375 // migrates as a single caixa-core edit rather than a
6376 // coordinated rewrite of the paired arms — sibling of the
6377 // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
6378 // arm migration on the per-`:supervisor` static-child-list
6379 // `Vec`-carry axis.
6380 //
6381 // Route the per-`:placement` outer-composite reference read
6382 // through the lifted [`AplicacaoSpec::placement`] outer accessor
6383 // rather than the raw `&self.placement` field access — the
6384 // per-axis bracket-dispatch fan-out below (`p.clusters()`,
6385 // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
6386 // axis-level lifted accessor family) now routes through the
6387 // substrate-primitive typed dispatch at the outer composition
6388 // altitude, the same shape the peer caixa-mesh
6389 // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
6390 // and the sibling `feira app graph` per-Aplicacao print line
6391 // now key off after this accessor lift.
6392 let p = self.placement();
6393 if p.clusters().is_empty() {
6394 return Err(AplicacaoError::PlacementWithoutClusters {
6395 estrategia: p.estrategia(),
6396 });
6397 }
6398 let mut seen = std::collections::HashSet::new();
6399 for c in p.clusters() {
6400 // Per-entry value-shape gate: the cluster name lands in
6401 // every K8s context / `lareira-fleet-programs` aggregator
6402 // filter / future M4 CR materializer's per-cluster axis
6403 // a validated `:clusters` entry passes through, each
6404 // enforcing the DNS-1123 label rule on admission. Same
6405 // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
6406 // on the peer name axis — both axes' validated values
6407 // are guaranteed-accepted by the apiserver without
6408 // re-validation at any downstream renderer or admission
6409 // layer.
6410 validate_placement_cluster(c)?;
6411 crate::render::insert_first_seen(&mut seen, c.as_str(), || {
6412 AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
6413 })?;
6414 }
6415 // Route the per-`:placement :affinity` per-hint value-shape
6416 // gate through the typed [`Placement::affinity`] accessor rather
6417 // than the raw `&self.placement.affinity` field access — the
6418 // sole open-coded field-access site on the per-`:placement`
6419 // M3-Adaptive-compression-hint axis the accessor lift now owns.
6420 // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
6421 // the accessor's `Option<&str>` return type;
6422 // [`validate_placement_affinity`]'s `&str` parameter accepts
6423 // the narrower borrow without a re-allocation, so the routing
6424 // change is byte-for-byte in the pass arm and remains
6425 // byte-for-byte in every failure diagnostic
6426 // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
6427 // String` field is populated inside
6428 // [`validate_placement_affinity`] via the peer `.to_string()`
6429 // path on the same borrowed slice). Peer of the sibling
6430 // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
6431 // routing through [`Placement::shard_key`] at the caixa-core
6432 // site above — extends the "read `:placement` optional-scalars
6433 // through the typed accessor" discipline to the second
6434 // `Option<String>`-shape slot on the M3 mesh-slot family.
6435 //
6436 // Per-hint value-shape gate: the `:affinity` value lands
6437 // verbatim in the M3 Adaptive compression overlay
6438 // (caixa-mesh's `placement.affinity` emission) and every
6439 // future M4 placement-engine routing axis keying off the
6440 // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
6441 // selector — each enforces the DNS-1123 label rule on
6442 // admission. Same typed-shape trajectory as `:placement
6443 // :clusters` (6c8c00b) on the sibling slot and the four
6444 // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
6445 // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
6446 // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
6447 // on the Aplicacao surface to land on the canonical
6448 // [`crate::render::is_dns_1123_label`] floor.
6449 if let Some(a) = p.affinity() {
6450 validate_placement_affinity(a)?;
6451 }
6452 match p.estrategia() {
6453 // Route the `Sharded`-arm shape-gate cascade through the
6454 // typed [`Placement::shard_key`] accessor rather than the
6455 // raw `&self.placement.shard_key` field access — one of the
6456 // two open-coded field-access sites on the per-`:placement`
6457 // Akka-cluster-sharding-key axis the accessor lift now
6458 // owns. The `Some(k)`-bound `k` narrows from `&String` to
6459 // `&str` under the accessor's `Option<&str>` return type;
6460 // `str::is_empty` and [`validate_placement_shard_key`]'s
6461 // `&str` parameter both accept the narrower borrow without
6462 // a re-allocation.
6463 PlacementStrategy::Sharded => match p.shard_key() {
6464 None => return Err(AplicacaoError::ShardedWithoutKey),
6465 Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
6466 // Per-axis value-shape gate on the Akka-cluster-sharding
6467 // `:shard-key` extractor expression. The shape gate runs
6468 // after the more self-locating `ShardedKeyEmpty` arm so
6469 // a `:shard-key ""` surfaces the narrower empty
6470 // diagnostic first; every non-empty `:shard-key` past
6471 // this call is guaranteed to be a printable-ASCII
6472 // single-token reference the future M4 Akka-style
6473 // cluster-sharding reconciler can hash without
6474 // re-validating at the runtime layer. Mirrors the
6475 // payload-axis shape gates on the peer `:contratos`
6476 // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
6477 // 63e18a0 / c4213a4) — each lifts the runtime parser's
6478 // intersection-floor to a caixa-build-time gate.
6479 Some(k) => validate_placement_shard_key(k)?,
6480 },
6481 // `:shard-key` is the Akka-cluster-sharding axis
6482 // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
6483 // across the cluster pool. `Replicated` (active-active across
6484 // every named cluster) and `SingleNode` (Erlang/OTP
6485 // distributed-app takeover/failover, §II.1) have no hash-keyed
6486 // routing axis to consume the slot; downstream renderers
6487 // (caixa-mesh's `placement.shardKey` overlay at
6488 // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
6489 // sharding reconciler) ignore `:shard-key` outside the
6490 // `Sharded` arm by construction. Until this gate landed an
6491 // author who wrote `:placement (:estrategia Replicated
6492 // :shard-key "tenantId")` (an off-by-one strategy typo, a
6493 // copy-paste from a Sharded sibling caixa, the "I think I
6494 // configured sharding" footgun) silently passed validate and
6495 // the typed slot's value vanished at the renderer layer with
6496 // no diagnostic — the canonical "declared-but-inert" footgun
6497 // the empty-:affinity / empty-shard-key / zero-:politicas /
6498 // empty-:contratos-target gates already close on every other
6499 // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
6500 // Lifting the rejection to a build-time gate closes the
6501 // Sharded ↔ non-Sharded partition over the typed
6502 // `:placement` slot: every validated `Placement` past this
6503 // call has `shard_key.is_some()` iff `estrategia ==
6504 // Sharded`, structurally — the future Akka reconciler can
6505 // reach for `placement.shard_key` knowing it's `Some` exactly
6506 // when the strategy consumes it, without re-deriving the
6507 // partition from inline strategy probes.
6508 PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
6509 // Route the non-`Sharded`-arm declared-but-inert refusal
6510 // through the typed [`Placement::shard_key`] accessor —
6511 // the second of the two open-coded field-access sites the
6512 // accessor lift now owns. The `Some(k)`-bound `k` narrows
6513 // from `&String` to `&str`; the `AplicacaoError::
6514 // ShardKeyOnNonSharded { shard_key: String }` diagnostic
6515 // materializes the owned `String` via `k.to_string()`
6516 // (peer to the sibling per-Membro `String`-carry sites
6517 // 4127bb6 routed through `m.nome().to_string()` /
6518 // `m.versao_requirement().to_string()`), so the whole
6519 // `Sharded` ↔ non-`Sharded` partition on the
6520 // `:shard-key` axis now flows through the same typed
6521 // dispatch as the sibling `Sharded`-arm shape gate.
6522 if let Some(k) = p.shard_key() {
6523 return Err(AplicacaoError::ShardKeyOnNonSharded {
6524 estrategia: p.estrategia(),
6525 shard_key: k.to_string(),
6526 });
6527 }
6528 }
6529 }
6530 Ok(())
6531 }
6532
6533 /// Reject `:politicas` values that are operationally meaningless.
6534 /// Each axis is optional — omitting it expresses "no policy on this
6535 /// axis". Carrying a *zero* value for a declared axis is the bug
6536 /// this function rejects: zero is either
6537 ///
6538 /// - re-interpreted as "infinite" by downstream proxies (Envoy's
6539 /// `RouteAction.timeout = 0s` disables the timeout entirely),
6540 /// directly contradicting MESH-COMPOSITION §V CSE invariant
6541 /// "every Aplicacao declares :politicas :timeout (no infinite
6542 /// blocking)", or
6543 /// - a renderer footgun (a 0-failure circuit breaker trips on the
6544 /// first call; a 0-rate rate-limit denies every request).
6545 ///
6546 /// Lifting these "0 means the opposite of what you think" idioms to
6547 /// the typed Aplicacao surface as build errors mirrors the §III.3
6548 /// promise that contract drift, capability leaks, and cycles are all
6549 /// build errors — not runtime surprises.
6550 fn validate_politicas(&self) -> Result<(), AplicacaoError> {
6551 // Route the per-`:politicas` composite-reference read through
6552 // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
6553 // than the raw `&self.politicas` field access — the per-axis
6554 // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
6555 // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
6556 // the substrate-primitive typed dispatch at the outer
6557 // composition altitude AND at every per-axis altitude, matching
6558 // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
6559 // timeout/retry-overlay emitters that already key off the same
6560 // per-axis accessor family. The four-axis fan-out is now
6561 // uniformly `p.<axis>()` — the last two raw `p.timeout` /
6562 // `p.retries` field-access sites (co-resident with the peer
6563 // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
6564 // b0e741a / 21a6c3b already lifted) now route through
6565 // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
6566 // the per-`:politicas` bracket-dispatch fan-out's raw-field-
6567 // access axis on the M3 mesh-slot family.
6568 let p = self.politicas();
6569 if let Some(t) = p.timeout() {
6570 // Zero-floor + integer-millisecond canonical-form +
6571 // upper-cap bracket on the typed `:timeout` axis. See
6572 // [`crate::render::require_positive_canonical_bounded_duration`]
6573 // for the full three-arm ordering discipline (zero-floor
6574 // strictly precedes the canonical-form arm so
6575 // `Duration::ZERO` surfaces the self-locating
6576 // `PolicyTimeoutZero` diagnostic naming the omit-axis
6577 // remediation; canonical-form strictly precedes the cap
6578 // arm so a sub-millisecond above-cap `Duration` surfaces
6579 // the more fundamental round-trip-shape diagnostic first)
6580 // and the four peer typed-`Duration` sites that now share
6581 // this canonical bracket. Every validated value lies in
6582 // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
6583 // granularity — the same top-and-bottom-edge discipline
6584 // [`POLICY_RETRIES_MAX`] and
6585 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
6586 // capped-`u32` `:politicas` axes.
6587 crate::render::require_positive_canonical_bounded_duration(
6588 t,
6589 POLICY_TIMEOUT_MAX,
6590 || AplicacaoError::PolicyTimeoutZero,
6591 |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
6592 |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
6593 )?;
6594 }
6595 if let Some(r) = p.retries() {
6596 // Zero-floor + upper-cap bracket on the typed `:retries`
6597 // axis. See [`crate::render::require_positive_bounded_u32`]
6598 // for the ordering discipline (zero-floor arm strictly
6599 // precedes cap arm so `Some(0)` surfaces the self-locating
6600 // `PolicyRetriesZero` diagnostic with its omit-axis
6601 // remediation directly named, not the misleading
6602 // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
6603 // this bracket landed the top edge ran all the way to
6604 // `u32::MAX` and a struct-literal `MeshPolicy { retries:
6605 // Some(100_000), .. }` (or the equivalent author-surface
6606 // `(:retries 100000)` / `(:retries 4294967295)` typo
6607 // landing in the slot) silently passed validate. The
6608 // runtime substrate consuming the value (Envoy's
6609 // `retry_policy.num_retries`, the future
6610 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6611 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6612 // policy into a thundering-herd amplification vector —
6613 // the caller's one request fans out to `retries`
6614 // server-side calls per edge per traversal, multiplying
6615 // load by `(retries+1)^depth` across the
6616 // synchronous-`:contratos` subgraph at the precise moment
6617 // the substrate is already failing (transient failure is
6618 // the trigger), exactly the failure mode AWS App Mesh's
6619 // explicit `maxRetries ≤ 10` schema cap exists to prevent.
6620 // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
6621 // the sibling capped-`u32` `:politicas` axes
6622 // (`max_failures`, `rate_limit.rate`) and the peer capped-
6623 // `u32` axes in `:supervisor :max-restarts` +
6624 // `:limits :cpu`; all five now route through the same
6625 // canonical bracket helper.
6626 crate::render::require_positive_bounded_u32(
6627 r,
6628 POLICY_RETRIES_MAX,
6629 || AplicacaoError::PolicyRetriesZero,
6630 |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
6631 )?;
6632 }
6633 if let Some(cb) = p.circuit_breaker() {
6634 // Zero-floor + upper-cap bracket on the typed
6635 // `:max-failures` axis. See
6636 // [`crate::render::require_positive_bounded_u32`] for the
6637 // ordering discipline (zero-floor arm strictly precedes
6638 // cap arm so `max_failures == 0` surfaces the
6639 // self-locating `PolicyBreakerZeroFailures` diagnostic
6640 // with its omit-axis remediation directly named, not the
6641 // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
6642 // false` cap-arm miss). Until this bracket landed the top
6643 // edge ran all the way to `u32::MAX` and a struct-literal
6644 // `CircuitBreaker { max_failures: 100_000, .. }` (or the
6645 // equivalent author-surface `(:max-failures 100000)` /
6646 // `(:max-failures 4294967295)` typo landing in the slot)
6647 // silently passed validate. The runtime substrate
6648 // consuming the value (Envoy's
6649 // `outlier_detection.consecutive_5xx`, the future
6650 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6651 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6652 // breaker policy into a no-op — the trip threshold is
6653 // structurally so high that no realistic
6654 // failures-per-`:window` traffic shape can reach it, the
6655 // breaker never trips, and every typed-slot consumer
6656 // emits an Envoy / Cilium L7 overlay carrying a
6657 // protection that is structurally never enforced. The
6658 // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
6659 // peer with `retries` and `rate_limit.rate` on the same
6660 // helper.
6661 crate::render::require_positive_bounded_u32(
6662 cb.max_failures(),
6663 POLICY_BREAKER_MAX_FAILURES_MAX,
6664 || AplicacaoError::PolicyBreakerZeroFailures,
6665 |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
6666 )?;
6667 // Zero-floor + integer-millisecond canonical-form +
6668 // upper-cap bracket on the typed `:window` axis. See
6669 // [`crate::render::require_positive_canonical_bounded_duration`]
6670 // for the full three-arm ordering discipline (peer to the
6671 // `:timeout` site immediately above); every validated
6672 // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
6673 // (1ms..=1h), integer-millisecond granularity — the same
6674 // top-and-bottom-edge discipline
6675 // [`POLICY_TIMEOUT_MAX`] applies on the sibling
6676 // duration-typed `:politicas :timeout` axis.
6677 crate::render::require_positive_canonical_bounded_duration(
6678 cb.window(),
6679 POLICY_BREAKER_WINDOW_MAX,
6680 || AplicacaoError::PolicyBreakerZeroWindow,
6681 |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
6682 |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
6683 )?;
6684 }
6685 if let Some(rl) = p.rate_limit() {
6686 // Zero-floor + upper-cap bracket on the typed
6687 // `:rate-limit` rate axis. See
6688 // [`crate::render::require_positive_bounded_u32`] for the
6689 // ordering discipline (zero-floor arm strictly precedes
6690 // cap arm so `rl.rate == 0` surfaces the self-locating
6691 // `PolicyRateLimitZero` diagnostic with its omit-axis
6692 // remediation directly named, not the misleading
6693 // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
6694 // Until this bracket landed the top edge ran all the way
6695 // to `u32::MAX` and a struct-literal
6696 // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
6697 // author-surface `(:rate-limit "4294967295/s")` /
6698 // `(:rate-limit "100000000/m")` typo landing in the slot)
6699 // silently passed validate. The runtime substrate
6700 // consuming the value (Envoy's
6701 // `local_rate_limit.token_bucket.max_tokens`, the future
6702 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6703 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6704 // rate-limit policy into a no-op limiter: the bucket
6705 // capacity is structurally so high that no realistic
6706 // per-edge traffic shape can drain it, the limiter never
6707 // trips, and every typed-slot consumer emits a "rate
6708 // declared" L7 overlay carrying enforcement that is
6709 // structurally never reached — the canonical
6710 // declared-but-inert footgun the sibling
6711 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
6712 // the peer no-op-breaker shape. The bracket set is
6713 // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
6714 // `max_failures` on the same helper. The rate bracket
6715 // strictly precedes the window-canonical gate so a
6716 // structurally absurd rate magnitude surfaces the more
6717 // fundamental amplification-shape diagnostic before the
6718 // narrower codec-round-trip-shape diagnostic on `:window`.
6719 crate::render::require_positive_bounded_u32(
6720 rl.rate(),
6721 POLICY_RATE_LIMIT_MAX,
6722 || AplicacaoError::PolicyRateLimitZero,
6723 |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
6724 )?;
6725 // The `:rate-limit` author surface is the canonical
6726 // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
6727 // accepts exactly the three-unit set (1s/60s/3600s) the
6728 // [`rate_limit_codec::render`] formatter emits the canonical
6729 // unit suffix for. A `RateLimit` whose `:window` is anything
6730 // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
6731 // programmatically (struct literals in Rust + the typed
6732 // `Duration` field) but renders to a `<n>/<k>s` fragment
6733 // (the codec's fall-through) the parser then rejects on
6734 // round-trip — silently breaking the THEORY.md §V.2.7
6735 // render-determinism contract for any consumer that
6736 // serializes-then-deserializes the typed slot. Lifting the
6737 // canonical-window invariant to a build-time gate at
6738 // `validate_politicas` makes the codec's round-trip property
6739 // a structural property of the validated typed value:
6740 // every `RateLimit` past `AplicacaoSpec::validate` has a
6741 // window the codec round-trips losslessly, so the next
6742 // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
6743 // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
6744 // §III.2 #3) reaches for `rate_limit.window` knowing the
6745 // value is in the codec's accepted set without re-validating
6746 // at the renderer layer. Same trajectory as c4213a4 (typed
6747 // WitContract endpoint/subject/slot value-shape gates) and
6748 // the b0c8389 :behavior + :upgrade-from script-path lifts:
6749 // the typed slot's valid set matches its codec's accepted
6750 // set, structurally.
6751 // Route the canonical-window shape-gate through the substrate
6752 // primitive [`RateLimit::canonical_unit`] rather than the free
6753 // module-private [`is_canonical_rate_limit_window`] predicate:
6754 // both projections resolve `Duration → Option<RateLimitUnit>`
6755 // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
6756 // arm on the closed-set typed enum), but the accessor is the
6757 // typed method every downstream consumer of the validated slot
6758 // ([`rate_limit_codec::render`]'s canonical arm above, the
6759 // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6760 // per-`:politicas :rate-limit` admission webhook, the future
6761 // per-`:contratos`-edge rate-limit-override overlay
6762 // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
6763 // production consumers of the canonical-unit axis (the codec
6764 // render and this validate gate) now key off exactly one typed
6765 // dispatch on the substrate primitive, so any future extension
6766 // to `canonical_unit` (a per-cluster canonical-window overlay
6767 // the operator pins through a future `:contratos :rate-limit
6768 // -unit-overrides` slot, a per-tenant unit-alias table the M4
6769 // CR materializer resolves per-CR) reaches both consumers by
6770 // construction rather than a coordinated rewrite of every
6771 // free-helper call site.
6772 if rl.canonical_unit().is_none() {
6773 return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
6774 window: rl.window(),
6775 });
6776 }
6777 }
6778 Ok(())
6779 }
6780
6781 /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
6782 /// A synchronous edge is any contract whose typed [`WitTarget`] is
6783 /// `Http`, `Store`, or `Capability` — the caller blocks on the
6784 /// callee, so a cycle would deadlock at runtime. Pub-sub edges
6785 /// (`WitTarget::PubSub`) are skipped: an event publisher does not
6786 /// block on its subscribers, so they can never close a sync loop.
6787 ///
6788 /// Iterative DFS with three-coloring; the reported cycle is the
6789 /// path of caixa names traversed from the back-edge target around
6790 /// to itself, in declaration order. Adjacency lists and DFS roots
6791 /// are visited in `BTreeMap` key order so the diagnostic is
6792 /// deterministic across runs.
6793 fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
6794 use std::collections::{BTreeMap, BTreeSet};
6795
6796 #[derive(Clone, Copy, PartialEq, Eq)]
6797 enum Mark {
6798 White,
6799 Gray,
6800 Black,
6801 }
6802
6803 let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
6804 for m in self.membros() {
6805 adj.entry(m.nome()).or_default();
6806 }
6807 for c in self.contratos() {
6808 // target() was already called by validate(); re-running here
6809 // keeps detect_sync_cycles self-contained for callers that
6810 // reuse it (M4 per-edge policy resolver) without revalidating.
6811 //
6812 // The pub-sub-arm check routes through the lifted
6813 // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
6814 // arm-discriminator predicate rather than a raw `matches!(…,
6815 // WitTarget::PubSub { .. })` on the variant so a future
6816 // rebrand on the axis (an M4 per-edge WIT registry split of
6817 // [`WitTarget::PubSub`] into shape-specific peers, a
6818 // per-consumer rename that the accept-set already carries)
6819 // reaches this call site through the derive rather than a
6820 // scattered per-arm `matches!` rewrite — same
6821 // `IsVariant`-derived-arm-discriminator discipline the
6822 // peer closed-set typed enums ([`crate::CaixaKind`] via
6823 // f5bba80, [`PlacementStrategy`] via 766ec63,
6824 // [`crate::supervisor::RestartStrategy`] +
6825 // [`crate::supervisor::RestartPolicy`],
6826 // [`crate::upgrade::UpgradeInstruction`] via 915a934)
6827 // already route through on the substrate's other typed-enum
6828 // arm-discriminator axes.
6829 if c.target()?.is_pubsub() {
6830 continue;
6831 }
6832 adj.entry(c.source()).or_default().insert(c.destination());
6833 }
6834
6835 let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
6836 let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
6837
6838 // Stable DFS root order — BTreeMap iteration is sorted by key.
6839 let roots: Vec<&str> = adj.keys().copied().collect();
6840
6841 // Frame: (node, sorted-neighbours snapshot, next-edge index).
6842 for root in roots {
6843 if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
6844 continue;
6845 }
6846 let root_neighbors: Vec<&str> = adj
6847 .get(root)
6848 .map(|s| s.iter().copied().collect())
6849 .unwrap_or_default();
6850 let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
6851 color.insert(root, Mark::Gray);
6852
6853 loop {
6854 // Read+advance the top frame in one borrow scope so we
6855 // can later mutate the stack (push/pop) without holding
6856 // a borrow across.
6857 let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
6858 let node = top.0;
6859 if top.2 >= top.1.len() {
6860 (node, None)
6861 } else {
6862 let nxt = top.1[top.2];
6863 top.2 += 1;
6864 (node, Some(nxt))
6865 }
6866 });
6867 let Some((node, nxt_opt)) = step else { break };
6868 let Some(nxt) = nxt_opt else {
6869 color.insert(node, Mark::Black);
6870 stack.pop();
6871 continue;
6872 };
6873 let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
6874 match nxt_color {
6875 Mark::Gray => {
6876 // Reconstruct the cycle from `node` back through
6877 // the parent chain to `nxt`, then close.
6878 let mut cycle = Vec::new();
6879 let mut cur = node;
6880 cycle.push(cur.to_string());
6881 while cur != nxt {
6882 match parent.get(cur).copied() {
6883 Some(p) => {
6884 cur = p;
6885 cycle.push(cur.to_string());
6886 }
6887 None => break,
6888 }
6889 }
6890 cycle.reverse();
6891 cycle.push(nxt.to_string());
6892 return Err(AplicacaoError::ContratoCycle { cycle });
6893 }
6894 Mark::White => {
6895 parent.insert(nxt, node);
6896 color.insert(nxt, Mark::Gray);
6897 let nxt_neighbors: Vec<&str> = adj
6898 .get(nxt)
6899 .map(|s| s.iter().copied().collect())
6900 .unwrap_or_default();
6901 stack.push((nxt, nxt_neighbors, 0));
6902 }
6903 Mark::Black => {}
6904 }
6905 }
6906 }
6907 Ok(())
6908 }
6909
6910 /// Substrate-canonical destination-facing TCP port every emitted
6911 /// per-Aplicacao artifact must key `destination`-shaped port axes
6912 /// off. Returns the typed `:entrada :port` scalar when this
6913 /// Aplicacao's `:entrada` block names `destination` under its
6914 /// `:para` axis (the destination Servico *is* the ingress apex, so
6915 /// the substrate honors the author-declared listener port
6916 /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
6917 /// fallback otherwise (every non-apex destination — the internal
6918 /// mesh Servicos `:contratos` reach across, the future per-edge
6919 /// policy resolver's per-destination probe targets, the
6920 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
6921 /// L4 port resolver — reads the same substrate-canonical port floor
6922 /// by construction).
6923 ///
6924 /// Prior to this lift the "if :entrada matches this destination use
6925 /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
6926 /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
6927 /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
6928 /// prior to this lift), with no typed method on the substrate primitive
6929 /// that named the rule. A future per-destination port axis addition
6930 /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
6931 /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
6932 /// per-Servico listener ports land, a per-cluster override the operator
6933 /// pins through a future `:placement :default-port` slot — would have
6934 /// to be threaded through every renderer's inline cascade in lockstep
6935 /// or one consumer would silently disagree on which port a given
6936 /// destination Servico's ingress lands at. Lifting the rule to a
6937 /// typed method on the substrate primitive means the M4 CR
6938 /// materializer, the future per-edge policy resolver, and every
6939 /// downstream test-fixture navigator reach for exactly one typed
6940 /// dispatch — the resolver's accept-set moves as a unit on any
6941 /// future axis addition.
6942 ///
6943 /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
6944 /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
6945 /// the typed primitive, thin projections at each consumer"
6946 /// discipline lifts on the sibling `:contratos` payload / `:politicas
6947 /// :rate-limit` unit-suffix axes; extends the discipline onto the
6948 /// destination-facing port-resolution axis every per-Aplicacao
6949 /// L4-fallback renderer consumes.
6950 #[must_use]
6951 pub fn port_for_destination(&self, destination: &str) -> u16 {
6952 // Route the per-`:entrada` composite-reference read through
6953 // the lifted [`AplicacaoSpec::entrada`] accessor rather than
6954 // the raw `self.entrada.as_ref()` field access — the
6955 // per-destination L4-port fallback resolver's composite-
6956 // projection seed is now the canonical read-side surface
6957 // every per-Aplicacao entrada consumer routes through, peer
6958 // of the sibling `validate` per-`:entrada` shape-and-
6959 // membership gate migration on the same outer-composite
6960 // axis.
6961 // Route the per-`:entrada` apex-destination membership probe
6962 // through the lifted [`Entrada::destination`] accessor rather
6963 // than the raw `e.para == destination` field access — the last
6964 // un-lifted `.para` production-code read site on the per-
6965 // `:entrada` `:para` axis, sibling to the four caixa-core
6966 // consumer sites the peer 15ddd8c converge already routed
6967 // through the accessor (the three
6968 // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
6969 // membership gate sites: the `validate_entrada_para` DNS-1123
6970 // shape gate, the per-`:membros` membership lookup, and the
6971 // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
6972 // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
6973 // `entrada.para`-projection converge at
6974 // caixa-core/src/render.rs (the `gateway_api_http_route_name`
6975 // route-name projection site). Prior to this converge the
6976 // `port_for_destination` resolver was the solitary consumer
6977 // bypassing the typed dispatch on the `.para` axis — the two
6978 // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
6979 // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
6980 // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
6981 // reach through the same accessor family compose with this
6982 // resolver at the emit boundary via the apex-identity
6983 // invariant `spec.port_for_destination(entrada.destination())
6984 // == entrada.port` the sibling
6985 // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
6986 // pin pins across four permutations. A future extension of the
6987 // `:entrada :para` axis to a richer author surface (a per-
6988 // cluster alias overlay the operator pins through a future
6989 // `:placement`-scoped slot, a namespace-qualified rewrite the
6990 // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
6991 // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
6992 // §III.2 acknowledges) that lands on the accessor would silently
6993 // disagree between this resolver and the two `caixa-mesh` emit
6994 // sites — an author-declared `:para "cart"` value the accessor
6995 // rewrote to `"cart-v2"` under a future canary arm would leave
6996 // the resolver's membership arm falling through to
6997 // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
6998 // `.para`) while the peer emit-site consumers landed on the
6999 // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
7000 // silently disagreed on which destination port a given typed
7001 // `:entrada` resolves to at cluster-apply time. Pinned by the
7002 // drift-detection test
7003 // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
7004 // below.
7005 self.entrada()
7006 .filter(|e| e.destination() == destination)
7007 .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
7008 }
7009}
7010
7011/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
7012/// entry may name the Aplicacao's own `:nome`.
7013///
7014/// An Aplicacao that lists itself as a member is a degenerate self-edge in
7015/// the typed graph — the application graph is a DAG rooted at the Aplicacao
7016/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
7017/// Servicos that compose the app; an Aplicacao is never its own constituent),
7018/// and the lacre pipeline's closure-resolution would otherwise be handed a
7019/// node that is its own parent: a one-node cycle it either rejects far from
7020/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
7021/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
7022/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
7023/// label + lacre closure root), a member whose `:caixa` equals the
7024/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
7025/// peer.
7026///
7027/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
7028/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
7029/// gate `validate_upgrade_from_against_versao` and the supervision-tree
7030/// self-parent gate `crate::supervisor::validate_no_self_supervision`
7031/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
7032/// not a tree/mesh edge" discipline, here on the second typed-graph axis
7033/// (the Aplicacao :membros set; the supervision-tree :children list was the
7034/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
7035/// every validated Supervisor's children are distinct from its `:nome`,
7036/// every validated Aplicacao's membros are distinct from its `:nome`. The
7037/// transitive consequence is that `:entrada :para` and `:contratos`
7038/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
7039/// name the Aplicacao itself, without re-deriving the partition.
7040pub fn validate_no_self_membership(
7041 membros: &[Membro],
7042 parent_nome: &str,
7043) -> Result<(), AplicacaoError> {
7044 for m in membros {
7045 if m.nome() == parent_nome {
7046 return Err(AplicacaoError::MembroIsSelfAplicacao {
7047 caixa: parent_nome.to_string(),
7048 });
7049 }
7050 }
7051 Ok(())
7052}
7053
7054#[derive(Debug, Error, PartialEq, Eq)]
7055pub enum AplicacaoError {
7056 #[error("Aplicacao must declare at least one :membros entry")]
7057 NoMembros,
7058 #[error(
7059 ":membros entry has empty :caixa (every member must name a Servico; \
7060 omit the entry instead of carrying an empty name)"
7061 )]
7062 MembroCaixaEmpty,
7063 #[error(
7064 ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
7065 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
7066 name / label value the member name lands in; use a lowercase \
7067 alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
7068 )]
7069 MembroCaixaInvalid { caixa: String, reason: String },
7070 #[error(
7071 ":membros entry {caixa:?} has empty :versao (every member must pin a \
7072 semver constraint that resolves through the lacre pipeline)"
7073 )]
7074 MembroVersaoEmpty { caixa: String },
7075 #[error(
7076 ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
7077 requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
7078 `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
7079 carries; the lacre pipeline resolves both through the same parser)"
7080 )]
7081 MembroVersaoInvalid {
7082 caixa: String,
7083 versao: String,
7084 reason: String,
7085 },
7086 #[error(
7087 ":membros entry {caixa:?} appears more than once (the graph node set \
7088 is a set, not a multiset; duplicate members produce duplicate \
7089 programs.yaml entries and ambiguous :contratos membership lookups)"
7090 )]
7091 MembroDuplicate { caixa: String },
7092 #[error(
7093 "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
7094 never its own constituent Servico (the application graph is a DAG rooted \
7095 at the Aplicacao; :membros names the *other* caixas that compose the \
7096 app, not the app itself). Since every :nome is a globally-unique \
7097 substrate identity, a member naming the Aplicacao's own :nome is a \
7098 one-node lacre-closure recursion, not a coincidentally-named peer; \
7099 drop the self-referential :membros entry or rename it to the actual \
7100 constituent caixa."
7101 )]
7102 MembroIsSelfAplicacao { caixa: String },
7103 #[error(
7104 "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
7105 caixa declared in :membros; omit the contract or fill the {slot} field with a \
7106 member name)"
7107 )]
7108 ContratoCaixaEmpty { slot: &'static str },
7109 #[error(
7110 "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
7111 :contratos {slot} value names a member of :membros, which is itself a \
7112 DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
7113 object the member name lands in — Service, Pod, identity-based Cilium \
7114 selector; use a lowercase alphanumeric + hyphen identifier like \
7115 `\"checkout\"` or `\"cart-v2\"`)"
7116 )]
7117 ContratoCaixaInvalid {
7118 slot: &'static str,
7119 caixa: String,
7120 reason: String,
7121 },
7122 #[error("contrato references caixa {caixa:?} not declared in :membros")]
7123 ContratoMemberMissing { caixa: String },
7124 #[error(
7125 "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
7126 entry is an inter-Servico contract whose :de and :para must name distinct \
7127 :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
7128 the contract, or point :para at the member it actually calls)"
7129 )]
7130 ContratoSelfLoop { caixa: String, wit: String },
7131 #[error("contrato {de:?} → {para:?} has empty :wit")]
7132 EmptyWit { de: String, para: String },
7133 #[error(
7134 "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
7135 {reason} (the substrate dispatches `:wit` values on the canonical \
7136 lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
7137 `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
7138 demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
7139 kebab-case identifier per segment)"
7140 )]
7141 ContratoWitInvalid {
7142 de: String,
7143 para: String,
7144 wit: String,
7145 reason: String,
7146 },
7147 #[error(
7148 ":entrada :para is empty (every :entrada must route to a caixa declared in \
7149 :membros; fill the :para field with a member name)"
7150 )]
7151 EntradaParaEmpty,
7152 #[error(
7153 ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
7154 :entrada :para value names a member of :membros, which is itself a DNS-1123 \
7155 label per the K8s apiserver's `metadata.name` rule on every object the \
7156 member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
7157 Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
7158 `\"checkout\"` or `\"cart-v2\"`)"
7159 )]
7160 EntradaParaInvalid { para: String, reason: String },
7161 #[error(":entrada routes to caixa {para:?} not declared in :membros")]
7162 EntradaMemberMissing { para: String },
7163 #[error(":entrada must declare a non-empty :host")]
7164 EmptyEntradaHost,
7165 #[error(
7166 ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
7167 (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
7168 `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
7169 like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
7170 )]
7171 EntradaHostInvalid { host: String, reason: String },
7172 #[error(":entrada :port must be in 1..=65535, got 0")]
7173 EntradaPortZero,
7174 #[error(":entrada :paths entry is empty (use the empty list to match all)")]
7175 EntradaPathEmpty,
7176 #[error(
7177 ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
7178 )]
7179 EntradaPathNotAbsolute { path: String },
7180 #[error(
7181 ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
7182 value: {reason} (the K8s apiserver enforces the same shape on \
7183 `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
7184 single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
7185 requires percent-encoding `%XX` for non-ASCII and whitespace)"
7186 )]
7187 EntradaPathInvalid { path: String, reason: String },
7188 #[error(":entrada :paths entry {path:?} appears more than once")]
7189 EntradaPathDuplicate { path: String },
7190 #[error(
7191 ":placement {estrategia} requires at least one :clusters entry \
7192 (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
7193 )]
7194 PlacementWithoutClusters { estrategia: PlacementStrategy },
7195 #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
7196 PlacementClusterEmpty,
7197 #[error(
7198 ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
7199 (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
7200 in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
7201 future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
7202 — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
7203 identifier like `\"rio\"` or `\"mar-east\"`)"
7204 )]
7205 PlacementClusterInvalid { cluster: String, reason: String },
7206 #[error(":placement :clusters entry {cluster:?} appears more than once")]
7207 PlacementClusterDuplicate { cluster: String },
7208 #[error(
7209 ":placement :affinity must be non-empty when set (omit :affinity to express \
7210 `no placement hint`)"
7211 )]
7212 PlacementAffinityEmpty,
7213 #[error(
7214 ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
7215 (placement hints land verbatim in the M3 Adaptive compression overlay's \
7216 `placement.affinity` field and in every future M4 placement-engine routing \
7217 axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
7218 selector — both enforce the DNS-1123 label rule on admission; use a \
7219 lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
7220 `\"low-latency\"`, or `\"anti-affinity\"`)"
7221 )]
7222 PlacementAffinityInvalid { affinity: String, reason: String },
7223 #[error(":placement Sharded requires :shard-key")]
7224 ShardedWithoutKey,
7225 #[error(
7226 ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
7227 hashes every entity onto the same shard, defeating sharding entirely)"
7228 )]
7229 ShardedKeyEmpty,
7230 #[error(
7231 ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
7232 entity-id extractor expression: {reason} (the future M4 Akka-style \
7233 cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
7234 as a single-token property reference and hashes the extracted entity ID \
7235 to compute shard placement; use a printable-ASCII extractor expression \
7236 like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
7237 `\"${{tenant}}\"`)"
7238 )]
7239 ShardKeyInvalid { shard_key: String, reason: String },
7240 #[error(
7241 ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
7242 Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
7243 convention); :estrategia Replicated runs every cluster active-active and \
7244 :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
7245 distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
7246 to :estrategia Sharded if hash-keyed routing is the intent"
7247 )]
7248 ShardKeyOnNonSharded {
7249 estrategia: PlacementStrategy,
7250 shard_key: String,
7251 },
7252 #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
7253 ContratoMissingTarget {
7254 de: String,
7255 para: String,
7256 wit: String,
7257 expected: &'static str,
7258 },
7259 #[error(
7260 "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
7261 expected `:{expected}` only"
7262 )]
7263 ContratoWrongTarget {
7264 de: String,
7265 para: String,
7266 wit: String,
7267 expected: &'static str,
7268 },
7269 #[error(
7270 "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
7271 like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
7272 that matches no traffic and silently drops every request)"
7273 )]
7274 ContratoEndpointEmpty { de: String, para: String },
7275 #[error(
7276 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
7277 (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
7278 :entrada :paths)"
7279 )]
7280 ContratoEndpointNotAbsolute {
7281 de: String,
7282 para: String,
7283 endpoint: String,
7284 },
7285 #[error(
7286 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
7287 Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
7288 emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
7289 caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
7290 shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
7291 like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
7292 and whitespace)"
7293 )]
7294 ContratoEndpointInvalid {
7295 de: String,
7296 para: String,
7297 endpoint: String,
7298 reason: String,
7299 },
7300 #[error(
7301 "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
7302 subject is a no-op subscribe; omit :subject only if the WIT world is not \
7303 pub-sub-shaped)"
7304 )]
7305 ContratoSubjectEmpty { de: String, para: String },
7306 #[error(
7307 "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
7308 NATS subject: {reason} (the NATS server's subject parser enforces the \
7309 same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
7310 single-token and `>` multi-token wildcards — at publish/subscribe time; \
7311 use a token-by-token form like `\"checkout.events.charge.failed\"` or \
7312 `\"orders.*.completed\"` — a malformed subject silently drops every \
7313 message at runtime far from the source caixa.lisp)"
7314 )]
7315 ContratoSubjectInvalid {
7316 de: String,
7317 para: String,
7318 subject: String,
7319 reason: String,
7320 },
7321 #[error(
7322 "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
7323 addresses the bucket root, defeating the per-key isolation the slot exists \
7324 for; omit :slot only if the WIT world is not store-shaped)"
7325 )]
7326 ContratoSlotEmpty { de: String, para: String },
7327 #[error(
7328 "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
7329 WASI keyvalue store slot template: {reason} (the substrate enforces \
7330 the printable-ASCII intersection-floor every kv backend admits — \
7331 use a single-token path / template expression like `\"checkout/$orderId\"`, \
7332 `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
7333 percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
7334 slot either gets rejected on write by strict backends or silently \
7335 corrupts the next read on permissive ones, far from the source caixa.lisp)"
7336 )]
7337 ContratoSlotInvalid {
7338 de: String,
7339 para: String,
7340 slot: String,
7341 reason: String,
7342 },
7343 #[error(
7344 "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
7345 or an event-sourced indirection (MESH-COMPOSITION §III.3)",
7346 cycle.join(" → ")
7347 )]
7348 ContratoCycle { cycle: Vec<String> },
7349 #[error(
7350 ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
7351 than once (the typed graph edges are a set, not a multiset; duplicate \
7352 contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
7353 values that K8s admission rejects far from the source caixa.lisp)"
7354 )]
7355 ContratoDuplicate {
7356 de: String,
7357 para: String,
7358 wit: String,
7359 target: String,
7360 },
7361 #[error(
7362 ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
7363 contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
7364 express `no per-call deadline on this axis`"
7365 )]
7366 PolicyTimeoutZero,
7367 #[error(
7368 ":politicas :retries must be > 0 when set; omit :retries to express \
7369 `no retries on transient failure`"
7370 )]
7371 PolicyRetriesZero,
7372 #[error(
7373 ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
7374 (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
7375 retry policy into a thundering-herd amplification vector on transient \
7376 failure (one caller request fans out to `(retries+1)^depth` server-side \
7377 calls across the synchronous-:contratos subgraph), exactly the failure \
7378 mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
7379 Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
7380 or omit :retries to disable retries entirely"
7381 )]
7382 PolicyRetriesExceedsCap { retries: u32 },
7383 #[error(
7384 ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
7385 breaker trips on the first call); omit :circuit-breaker to disable it"
7386 )]
7387 PolicyBreakerZeroFailures,
7388 #[error(
7389 ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
7390 mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
7391 above this cap turns the typed breaker policy into a no-op: the trip \
7392 threshold is structurally so high that no realistic failures-per-:window \
7393 traffic shape can reach it, so the breaker never trips and every typed-slot \
7394 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
7395 Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
7396 structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
7397 Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
7398 omit :circuit-breaker to disable the breaker entirely"
7399 )]
7400 PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
7401 #[error(
7402 ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
7403 tracks no failures); omit :circuit-breaker to disable it"
7404 )]
7405 PolicyBreakerZeroWindow,
7406 #[error(
7407 ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
7408 request); omit :rate-limit to disable rate limiting"
7409 )]
7410 PolicyRateLimitZero,
7411 #[error(
7412 ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
7413 (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
7414 rate-limit policy into a no-op limiter: the token-bucket capacity is \
7415 structurally so high that no realistic per-edge traffic shape can drain it, \
7416 so the limiter never trips and every typed-slot consumer (the future \
7417 CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7418 local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
7419 that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
7420 Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
7421 Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
7422 Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
7423 to disable rate limiting entirely"
7424 )]
7425 PolicyRateLimitExceedsCap { rate: u32 },
7426 #[error(
7427 ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
7428 the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
7429 rate-limit codec round-trips losslessly; got {window:?} which renders to a \
7430 non-round-trippable form (omit :rate-limit to disable, or pick one of the \
7431 three canonical windows)"
7432 )]
7433 PolicyRateLimitWindowNotCanonical { window: Duration },
7434 #[error(
7435 ":politicas :timeout must be an integer number of milliseconds — the canonical \
7436 authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
7437 duration codec round-trips losslessly; got {timeout:?} which carries a \
7438 sub-millisecond residue that either truncates to a different `Duration` on \
7439 re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
7440 to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
7441 zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
7442 (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
7443 )]
7444 PolicyTimeoutNotCanonical { timeout: Duration },
7445 #[error(
7446 ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
7447 (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
7448 per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
7449 overlays carry a deadline so long no realistic synchronous-:contratos \
7450 traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
7451 CSE invariant degenerates to enforcement only at the per-Servico \
7452 `:limits :wall-clock` layer — far above the per-edge granularity the typed \
7453 `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
7454 (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
7455 ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
7456 maxes out at the same `3600s` ceiling) or omit :timeout to express \
7457 `no per-call deadline on this axis` (the synchronous-call deadline then \
7458 relies entirely on the per-Servico `:limits :wall-clock` axis)"
7459 )]
7460 PolicyTimeoutExceedsCap { timeout: Duration },
7461 #[error(
7462 ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
7463 the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
7464 the shared duration codec round-trips losslessly; got {window:?} which carries a \
7465 sub-millisecond residue that either truncates to a different `Duration` on \
7466 re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
7467 Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
7468 )]
7469 PolicyBreakerWindowNotCanonical { window: Duration },
7470 #[error(
7471 ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
7472 (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
7473 rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
7474 is structurally so long that transient failures are never forgotten, the breaker \
7475 trips once and stays tripped for the lifetime of the component, and every typed-slot \
7476 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7477 outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
7478 Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
7479 default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
7480 the breaker entirely"
7481 )]
7482 PolicyBreakerWindowExceedsCap { window: Duration },
7483}
7484
7485#[cfg(test)]
7486mod tests {
7487 use super::*;
7488
7489 fn membro(name: &str, ver: &str) -> Membro {
7490 Membro {
7491 caixa: name.into(),
7492 versao: ver.into(),
7493 }
7494 }
7495
7496 fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
7497 WitContract {
7498 de: de.into(),
7499 para: para.into(),
7500 wit: "wasi:http/proxy".into(),
7501 endpoint: Some(ep.into()),
7502 subject: None,
7503 slot: None,
7504 }
7505 }
7506
7507 fn three_member_spec() -> AplicacaoSpec {
7508 AplicacaoSpec {
7509 membros: vec![
7510 membro("catalog", "^0.1"),
7511 membro("cart", "^0.1"),
7512 membro("payment", "^0.2"),
7513 ],
7514 contratos: vec![
7515 contract_http("cart", "catalog", "/products/:id"),
7516 contract_http("cart", "payment", "/charge"),
7517 ],
7518 politicas: MeshPolicy {
7519 timeout: Some(Duration::from_secs(30)),
7520 retries: Some(3),
7521 mtls_required: Some(true),
7522 ..Default::default()
7523 },
7524 placement: Placement {
7525 estrategia: PlacementStrategy::Replicated,
7526 clusters: vec!["rio".into(), "mar".into()],
7527 affinity: Some("data-locality".into()),
7528 shard_key: None,
7529 },
7530 entrada: Some(Entrada {
7531 host: "checkout.quero.cloud".into(),
7532 para: "cart".into(),
7533 paths: vec!["/api/cart".into(), "/api/products".into()],
7534 port: 8080,
7535 }),
7536 }
7537 }
7538
7539 #[test]
7540 fn happy_path_validates() {
7541 three_member_spec().validate().unwrap();
7542 }
7543
7544 #[test]
7545 fn rejects_empty_membros() {
7546 let mut s = three_member_spec();
7547 s.membros = vec![];
7548 assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
7549 }
7550
7551 #[test]
7552 fn rejects_empty_membro_caixa() {
7553 // A `:caixa ""` entry has no name to render into programs.yaml
7554 // and no caixa.lisp to resolve at lacre time.
7555 let mut s = three_member_spec();
7556 s.membros[1].caixa = String::new();
7557 assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
7558 }
7559
7560 #[test]
7561 fn rejects_empty_membro_versao() {
7562 // A `:versao ""` entry can't pin a semver constraint, so the
7563 // lacre pipeline fails far from the source.
7564 let mut s = three_member_spec();
7565 s.membros[2].versao = String::new();
7566 let err = s.validate().unwrap_err();
7567 assert!(
7568 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
7569 "got {err:?}"
7570 );
7571 }
7572
7573 #[test]
7574 fn rejects_duplicate_membro_caixa() {
7575 // Two `:membros` entries with the same `:caixa` collapse to one
7576 // node in the membership HashSet, which masks `:contratos`
7577 // membership errors and produces duplicate programs.yaml entries.
7578 let mut s = three_member_spec();
7579 s.membros.push(membro("cart", "^0.2"));
7580 let err = s.validate().unwrap_err();
7581 assert!(
7582 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7583 "got {err:?}"
7584 );
7585 }
7586
7587 #[test]
7588 fn rejects_invalid_membro_versao_requirement() {
7589 // The fail-before-pass-after pin: a non-empty but malformed
7590 // semver requirement (`"^bad-version"`) silently passed
7591 // `validate()` on every pre-gate codebase because the prior
7592 // shape only refused the empty string. The parse failure
7593 // surfaced far downstream at lacre-resolve time with a
7594 // `semver::Error` that didn't name which `:membros` entry
7595 // carried the typo. The new gate moves the check to caixa-build
7596 // time at the source caixa.lisp.
7597 let mut s = three_member_spec();
7598 s.membros[2].versao = "^bad-version".into();
7599 let err = s.validate().unwrap_err();
7600 assert!(
7601 matches!(
7602 err,
7603 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7604 if caixa == "payment" && versao == "^bad-version"
7605 ),
7606 "got {err:?}"
7607 );
7608 }
7609
7610 #[test]
7611 fn rejects_membro_versao_with_double_caret_typo() {
7612 // `"^^0.1"` is the canonical doubled-caret typo — looks like a
7613 // Cargo-shaped requirement on first glance but fails the parser
7614 // because semver doesn't accept stacked operators. Pin this
7615 // adjacent-shape footgun explicitly so a future relaxation that
7616 // accepts "looks-canonical-but-isn't" forms surfaces here.
7617 let mut s = three_member_spec();
7618 s.membros[0].versao = "^^0.1".into();
7619 let err = s.validate().unwrap_err();
7620 assert!(
7621 matches!(
7622 err,
7623 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7624 if caixa == "catalog" && versao == "^^0.1"
7625 ),
7626 "got {err:?}"
7627 );
7628 }
7629
7630 #[test]
7631 fn rejects_membro_versao_with_v_prefixed_tag() {
7632 // `"v0.1"` is the canonical "git-tag-shape leaking into the
7633 // semver requirement slot" typo — an author copies the
7634 // publish-side git-tag string verbatim into `:versao`, but
7635 // Cargo's semver parser rejects the leading `v` (only digits +
7636 // canonical operators are valid in the major-version
7637 // position). The gate's diagnostic names which member entry
7638 // carried the v-prefix so the fix is one edit, not a grep
7639 // through every member's `:versao`. (Note: bare `x`-glob
7640 // shorthands like `^0.1.x` are *accepted* by the semver crate
7641 // as an `*` wildcard on the patch axis — they're a Cargo-side
7642 // valid shape, not a typo, so the gate intentionally lets them
7643 // through.)
7644 let mut s = three_member_spec();
7645 s.membros[1].versao = "v0.1".into();
7646 let err = s.validate().unwrap_err();
7647 assert!(
7648 matches!(
7649 err,
7650 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7651 if caixa == "cart" && versao == "v0.1"
7652 ),
7653 "got {err:?}"
7654 );
7655 }
7656
7657 #[test]
7658 fn accepts_canonical_membro_versao_forms() {
7659 // The four Cargo-shaped requirement forms `:deps :versao`
7660 // already accepts via `crate::parse_requirement` must pass the
7661 // membros gate without re-validating at the resolver layer.
7662 // Pin every leg so a future tightening of the canonical set
7663 // surfaces here as a test failure.
7664 for form in [
7665 "^0.1", // caret — minor-range pin (the most common shape)
7666 "~0.1.2", // tilde — patch-range pin
7667 "0.1.0", // exact — single-version pin
7668 "*", // wildcard — explicitly any-version (semver::VersionReq::STAR)
7669 ">=0.1, <2", // multi-range — comma-separated comparators
7670 ] {
7671 let mut s = three_member_spec();
7672 for m in &mut s.membros {
7673 m.versao = form.into();
7674 }
7675 s.validate()
7676 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7677 }
7678 }
7679
7680 #[test]
7681 fn membro_versao_empty_takes_precedence_over_invalid() {
7682 // Order pin: the existing `MembroVersaoEmpty` diagnostic
7683 // (which doesn't try to parse) fires before the new
7684 // `MembroVersaoInvalid` parse-side diagnostic, so an empty
7685 // `:versao` keeps its narrower error message — `parse_requirement`
7686 // would also reject `""`, but the empty-string arm is the more
7687 // self-locating diagnostic for the author.
7688 let mut s = three_member_spec();
7689 s.membros[1].versao = String::new();
7690 let err = s.validate().unwrap_err();
7691 assert!(
7692 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
7693 "got {err:?}"
7694 );
7695 }
7696
7697 #[test]
7698 fn membro_versao_invalid_fires_before_duplicate_check() {
7699 // Order pin: a malformed requirement on a non-duplicate entry
7700 // surfaces *its own* diagnostic (which names the offending
7701 // `:versao` string), even when a later entry would otherwise
7702 // collapse onto an earlier name. The per-entry shape gate runs
7703 // inline before the duplicate-key insert, parallel to
7704 // `membros_validation_runs_before_contratos_membership_check`
7705 // and `duplicate_contrato_gate_runs_after_target_shape_check`.
7706 let mut s = three_member_spec();
7707 s.membros[0].versao = "^bad".into();
7708 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
7709 let err = s.validate().unwrap_err();
7710 assert!(
7711 matches!(
7712 err,
7713 AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
7714 ),
7715 "got {err:?}"
7716 );
7717 }
7718
7719 #[test]
7720 fn membro_versao_invalid_diagnostic_carries_offending_versao() {
7721 // The diagnostic-shape pin: the error names the offending
7722 // `:versao` value verbatim so the author can grep their
7723 // caixa.lisp without re-running the build, and carries a
7724 // non-empty `reason` from `semver::VersionReq::parse` so the
7725 // parser's own wording flows through to the diagnostic.
7726 let mut s = three_member_spec();
7727 s.membros[2].versao = "not-a-req".into();
7728 let err = s.validate().unwrap_err();
7729 let AplicacaoError::MembroVersaoInvalid {
7730 caixa,
7731 versao,
7732 reason,
7733 } = err
7734 else {
7735 panic!("expected MembroVersaoInvalid, got other variant");
7736 };
7737 assert_eq!(caixa, "payment");
7738 assert_eq!(versao, "not-a-req");
7739 assert!(
7740 !reason.is_empty(),
7741 "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
7742 );
7743 }
7744
7745 #[test]
7746 fn membro_versao_invalid_runs_before_contratos_check() {
7747 // A malformed `:versao` on any member must surface its own
7748 // diagnostic (which names *which* member to fix) before any
7749 // `:contratos` membership lookup raises `ContratoMemberMissing`.
7750 // The `:contratos` gate runs after `validate_membros`, so this
7751 // is structurally guaranteed — pin it explicitly so a future
7752 // refactor that reorders the gates surfaces here.
7753 let mut s = three_member_spec();
7754 s.membros[1].versao = "^^0.1".into();
7755 // Add a contrato whose `:para` doesn't exist — would normally
7756 // raise ContratoMemberMissing at the membership lookup, but
7757 // the membros gate must fire first.
7758 s.contratos
7759 .push(contract_http("cart", "phantom", "/never-reached"));
7760 let err = s.validate().unwrap_err();
7761 assert!(
7762 matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
7763 "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
7764 );
7765 }
7766
7767 #[test]
7768 fn membros_validation_runs_before_contratos_membership_check() {
7769 // If `:membros` carries a duplicate, the membership-collapse
7770 // would silently accept a `:contratos :para "phantom"` so long
7771 // as some entry hashes to "phantom". Pinning order: the
7772 // duplicate-membros error fires first, regardless of whether
7773 // contratos reference real members.
7774 let mut s = three_member_spec();
7775 s.membros = vec![
7776 membro("cart", "^0.1"),
7777 membro("cart", "^0.2"),
7778 membro("catalog", "^0.1"),
7779 membro("payment", "^0.1"),
7780 ];
7781 let err = s.validate().unwrap_err();
7782 assert!(
7783 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7784 "got {err:?}"
7785 );
7786 }
7787
7788 #[test]
7789 fn distinct_membros_validate() {
7790 // Pin the happy-path: every `:membros` entry has a non-empty
7791 // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
7792 // The fixture already satisfies this; this test makes the
7793 // invariant explicit so a future refactor of the fixture can't
7794 // silently break the guarantee.
7795 three_member_spec().validate().unwrap();
7796 }
7797
7798 // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
7799
7800 #[test]
7801 fn rejects_membro_caixa_with_uppercase() {
7802 // The canonical "I copied the Servico's display name verbatim"
7803 // typo — caixa names are lowercase per K8s DNS-1123 label rule,
7804 // but author tools often round-trip a TitleCase or CamelCase
7805 // identifier from an ADR or a sketch. Pin the diagnostic names
7806 // the offending name and suggests the lower-cased fix in one
7807 // edit, mirroring the `rejects_entrada_host_with_uppercase`
7808 // gate's shape (c7d05ec).
7809 let mut s = three_member_spec();
7810 s.membros[1].caixa = "Cart".into();
7811 let err = s.validate().unwrap_err();
7812 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7813 panic!("expected MembroCaixaInvalid, got other variant");
7814 };
7815 assert_eq!(caixa, "Cart");
7816 assert!(
7817 reason.contains("uppercase"),
7818 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
7819 );
7820 assert!(
7821 reason.contains("\"cart\""),
7822 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
7823 );
7824 }
7825
7826 #[test]
7827 fn rejects_membro_caixa_with_underscore() {
7828 // The canonical "I'm thinking of a Python module / Postgres
7829 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
7830 // label schema. K8s rejects `metadata.name: my_cart` at admission
7831 // time with an opaque `field is invalid` (no source-citing
7832 // diagnostic). The gate moves it to caixa-build time.
7833 let mut s = three_member_spec();
7834 s.membros[0].caixa = "my_cart".into();
7835 let err = s.validate().unwrap_err();
7836 assert!(
7837 matches!(
7838 err,
7839 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7840 if caixa == "my_cart" && reason.contains('_')
7841 ),
7842 "got {err:?}"
7843 );
7844 }
7845
7846 #[test]
7847 fn rejects_membro_caixa_with_dot() {
7848 // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
7849 // subdomain — even though K8s `metadata.name` itself accepts
7850 // dots (DNS-1123 subdomain rule), this string also lands as a
7851 // K8s Service name (DNS-1035 label — no dots) and as a label
7852 // value on identity-based Cilium selectors. The strictest floor
7853 // among the use sites wins. The "I want to namespace my member
7854 // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
7855 let mut s = three_member_spec();
7856 s.membros[2].caixa = "team.cart".into();
7857 let err = s.validate().unwrap_err();
7858 assert!(
7859 matches!(
7860 err,
7861 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7862 if caixa == "team.cart" && reason.contains('.')
7863 ),
7864 "got {err:?}"
7865 );
7866 }
7867
7868 #[test]
7869 fn rejects_membro_caixa_with_leading_hyphen() {
7870 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
7871 // with an alphanumeric. The K8s apiserver rejects `-cart`
7872 // outright; the renderer would emit a `metadata.name: "-cart"`
7873 // that fails admission far from the source caixa.lisp.
7874 let mut s = three_member_spec();
7875 s.membros[0].caixa = "-cart".into();
7876 let err = s.validate().unwrap_err();
7877 assert!(
7878 matches!(
7879 err,
7880 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7881 if caixa == "-cart" && reason.contains("start and end")
7882 ),
7883 "got {err:?}"
7884 );
7885 }
7886
7887 #[test]
7888 fn rejects_membro_caixa_with_trailing_hyphen() {
7889 // The symmetric arm of the boundary rule. Pin separately so
7890 // both ends of the label are covered against a future relaxation
7891 // that only checks one boundary.
7892 let mut s = three_member_spec();
7893 s.membros[1].caixa = "cart-".into();
7894 let err = s.validate().unwrap_err();
7895 assert!(
7896 matches!(
7897 err,
7898 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7899 if caixa == "cart-"
7900 ),
7901 "got {err:?}"
7902 );
7903 }
7904
7905 #[test]
7906 fn rejects_membro_caixa_with_unicode() {
7907 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
7908 // (`xn--…`) by the author before it reaches K8s. The byte-by-
7909 // byte ASCII validity check rejects multi-byte UTF-8 sequences
7910 // by the first byte that fails the `[a-z0-9-]` predicate.
7911 let mut s = three_member_spec();
7912 s.membros[2].caixa = "café".into();
7913 let err = s.validate().unwrap_err();
7914 assert!(
7915 matches!(
7916 err,
7917 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7918 if caixa == "café"
7919 ),
7920 "got {err:?}"
7921 );
7922 }
7923
7924 #[test]
7925 fn rejects_membro_caixa_with_whitespace() {
7926 // Whitespace is the canonical "I pasted from a sketch / doc"
7927 // footgun. The apiserver rejects every `metadata.name` value
7928 // carrying whitespace; pin the gate fires at the right boundary.
7929 let mut s = three_member_spec();
7930 s.membros[0].caixa = "my cart".into();
7931 let err = s.validate().unwrap_err();
7932 assert!(
7933 matches!(
7934 err,
7935 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7936 if caixa == "my cart"
7937 ),
7938 "got {err:?}"
7939 );
7940 }
7941
7942 #[test]
7943 fn rejects_membro_caixa_too_long() {
7944 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
7945 // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
7946 // exactly. The gate's reason names both the cap and the actual
7947 // length so the author can shorten in one edit.
7948 let mut s = three_member_spec();
7949 let too_long = "a".repeat(64);
7950 s.membros[1].caixa = too_long.clone();
7951 let err = s.validate().unwrap_err();
7952 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7953 panic!("expected MembroCaixaInvalid");
7954 };
7955 assert_eq!(caixa, too_long);
7956 assert!(
7957 reason.contains("63") && reason.contains("64"),
7958 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
7959 );
7960 }
7961
7962 #[test]
7963 fn membro_caixa_max_length_validates() {
7964 // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
7965 // so a future tightening (e.g. dropping to 62) surfaces here as
7966 // a regression, mirroring `entrada_host_max_length_validates`
7967 // (c7d05ec).
7968 let mut s = three_member_spec();
7969 s.membros[2].caixa = "a".repeat(63);
7970 s.entrada.as_mut().unwrap().para = "a".repeat(63);
7971 // remove contratos referencing the renamed member; they'd
7972 // raise ContratoMemberMissing otherwise
7973 s.contratos
7974 .retain(|c| c.de != "payment" && c.para != "payment");
7975 s.validate().unwrap();
7976 }
7977
7978 #[test]
7979 fn accepts_canonical_membro_caixa_forms() {
7980 // The DNS-1123 label shapes a caixa author is realistically
7981 // going to write: single-word lowercase, hyphen-joined, ending
7982 // in a digit-suffixed version (`cart-v2`), starting with a
7983 // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
7984 // DNS-1035 which requires a letter at position 0), single-
7985 // character (`a` — boundary). Pin every leg so a future
7986 // tightening that bans (e.g.) digit-start identifiers surfaces
7987 // here.
7988 for form in [
7989 "checkout",
7990 "cart",
7991 "cart-v2",
7992 "a",
7993 "c0",
7994 "3rd-party-shim",
7995 "x-1-2-3-4",
7996 ] {
7997 let mut s = three_member_spec();
7998 // Renaming a member also requires updating downstream refs;
7999 // drop everything else and rebuild a minimal spec around
8000 // just the one renamed member.
8001 s.membros = vec![membro(form, "^0.1")];
8002 s.contratos = vec![];
8003 s.entrada = None;
8004 s.validate()
8005 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8006 }
8007 }
8008
8009 #[test]
8010 fn membro_caixa_empty_takes_precedence_over_invalid() {
8011 // Order pin: the existing `MembroCaixaEmpty` diagnostic
8012 // (which doesn't try to parse) fires before the new
8013 // `MembroCaixaInvalid` parse-side diagnostic, so an empty
8014 // `:caixa` keeps its narrower error message — the new gate
8015 // would also reject `""`, but the empty-string arm is the more
8016 // self-locating diagnostic for the author. Mirrors the
8017 // `entrada_host_empty_takes_precedence_over_invalid` pin
8018 // (c7d05ec).
8019 let mut s = three_member_spec();
8020 s.membros[1].caixa = String::new();
8021 let err = s.validate().unwrap_err();
8022 assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
8023 }
8024
8025 #[test]
8026 fn membro_caixa_invalid_fires_before_versao_check() {
8027 // Order pin: an invalid-shape `:caixa` surfaces *its own*
8028 // diagnostic (which names the offending caixa name), even when
8029 // the same entry's `:versao` is also empty/invalid. The shape
8030 // gate runs first because the diagnostic is more self-locating —
8031 // an empty/invalid `:versao` on an invalid-shape caixa name is
8032 // a downstream-fix-after-the-caixa-rename concern.
8033 let mut s = three_member_spec();
8034 s.membros[1].caixa = "Cart".into();
8035 s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
8036 let err = s.validate().unwrap_err();
8037 assert!(
8038 matches!(
8039 err,
8040 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
8041 ),
8042 "got {err:?}"
8043 );
8044 }
8045
8046 #[test]
8047 fn membro_caixa_invalid_fires_before_duplicate_check() {
8048 // Order pin: a malformed-shape `:caixa` on an earlier entry
8049 // surfaces *its own* diagnostic, even when a later entry would
8050 // otherwise collapse onto a duplicate name. The per-entry shape
8051 // gate runs inline before the duplicate-key insert, parallel
8052 // to `membro_versao_invalid_fires_before_duplicate_check`.
8053 let mut s = three_member_spec();
8054 s.membros[0].caixa = "Catalog".into();
8055 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8056 let err = s.validate().unwrap_err();
8057 assert!(
8058 matches!(
8059 err,
8060 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
8061 ),
8062 "got {err:?}"
8063 );
8064 }
8065
8066 #[test]
8067 fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
8068 // The diagnostic-shape pin: the error names the offending
8069 // `:caixa` value verbatim so the author can grep their
8070 // caixa.lisp without re-running the build, and carries a
8071 // non-empty `reason` naming the specific violation. Same
8072 // shape every typed-shape gate enshrines (c7d05ec's
8073 // `entrada_host_diagnostic_carries_offending_host`,
8074 // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
8075 let mut s = three_member_spec();
8076 s.membros[2].caixa = "BAD_NAME".into();
8077 let err = s.validate().unwrap_err();
8078 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8079 panic!("expected MembroCaixaInvalid");
8080 };
8081 assert_eq!(caixa, "BAD_NAME");
8082 assert!(
8083 !reason.is_empty(),
8084 "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
8085 );
8086 }
8087
8088 #[test]
8089 fn rejects_contrato_with_unknown_de() {
8090 let mut s = three_member_spec();
8091 s.contratos.push(contract_http("phantom", "catalog", "/x"));
8092 let err = s.validate().unwrap_err();
8093 assert!(
8094 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8095 );
8096 }
8097
8098 #[test]
8099 fn rejects_contrato_with_unknown_para() {
8100 let mut s = three_member_spec();
8101 s.contratos.push(contract_http("cart", "phantom", "/x"));
8102 let err = s.validate().unwrap_err();
8103 assert!(
8104 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8105 );
8106 }
8107
8108 #[test]
8109 fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
8110 // The read-path pin: the phantom-`:de` refusal arm's
8111 // `ContratoMemberMissing.caixa` carrier must be observed through
8112 // the lifted [`WitContract::source`] accessor, not the raw
8113 // `.de.clone()` field-access `String`-carry. Peer of the sibling
8114 // per-`:contratos` self-loop arm's `.source().to_string()` /
8115 // `.world_ref().to_string()` `String`-carry sites the earlier
8116 // convergence lifted onto the same accessor pair. A future
8117 // silent detour that reintroduced the raw `.de.clone()` at the
8118 // wrap envelope while the shape-gate and membership lookup
8119 // routed through the accessor would surface here as a byte-equal
8120 // miss between the fired diagnostic's `caixa:` field and the
8121 // offending edge's `.source()` — pinning the accessor as the
8122 // sole read path across the phantom-name refusal arm's arg +
8123 // wrap-envelope emit surface.
8124 let mut s = three_member_spec();
8125 let phantom = contract_http("phantom", "catalog", "/x");
8126 s.contratos.push(phantom.clone());
8127 let err = s.validate().unwrap_err();
8128 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8129 panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
8130 };
8131 assert_eq!(
8132 caixa,
8133 phantom.source(),
8134 "ContratoMemberMissing.caixa on the phantom-:de arm must \
8135 byte-equal WitContract::source — the wrap envelope must \
8136 route through the lifted accessor rather than the raw \
8137 .de.clone() field-access String-carry"
8138 );
8139 }
8140
8141 #[test]
8142 fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8143 // The symmetric read-path pin on the `:para` phantom-name
8144 // refusal arm — same shape as the sibling `:de` pin above but
8145 // on the callee-Servico axis. Pins the wrap envelope's
8146 // `caixa:` field is observed through the lifted
8147 // [`WitContract::destination`] accessor, not the raw
8148 // `.para.clone()` field-access `String`-carry.
8149 let mut s = three_member_spec();
8150 let phantom = contract_http("cart", "phantom", "/x");
8151 s.contratos.push(phantom.clone());
8152 let err = s.validate().unwrap_err();
8153 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8154 panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
8155 };
8156 assert_eq!(
8157 caixa,
8158 phantom.destination(),
8159 "ContratoMemberMissing.caixa on the phantom-:para arm must \
8160 byte-equal WitContract::destination — the wrap envelope \
8161 must route through the lifted accessor rather than the raw \
8162 .para.clone() field-access String-carry"
8163 );
8164 }
8165
8166 #[test]
8167 fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
8168 // The read-path pin on the `:de` DNS-1123-malformed shape-gate
8169 // refusal arm — the `validate_contrato_caixa` arg must be
8170 // observed through the lifted [`WitContract::source`] accessor,
8171 // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
8172 // value routes through the shared
8173 // [`crate::render::require_valid_dns_1123_label`] floor with the
8174 // accessor-projected value; the fired
8175 // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
8176 // the offending edge's `.source()`, pinning that the arg + the
8177 // downstream `caixa: caixa.to_string()` wrap route through the
8178 // same accessor's read path.
8179 let mut s = three_member_spec();
8180 let malformed = contract_http("BAD_NAME", "catalog", "/x");
8181 s.contratos.push(malformed.clone());
8182 let err = s.validate().unwrap_err();
8183 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8184 panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
8185 };
8186 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8187 assert_eq!(
8188 caixa,
8189 malformed.source(),
8190 "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
8191 byte-equal WitContract::source — the shape-gate arg + wrap \
8192 envelope must route through the lifted accessor rather \
8193 than the raw &c.de &String-borrow"
8194 );
8195 }
8196
8197 #[test]
8198 fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8199 // Symmetric arm to the sibling `:de` malformed-shape pin above,
8200 // on the `:para` axis. Pins the shape-gate arg + wrap envelope
8201 // route through the lifted [`WitContract::destination`]
8202 // accessor. `:para` runs after the `:de` shape gate in the
8203 // canonical edge-direction order, so the `:de` value must be
8204 // well-shaped for the `:para` gate to fire — the `cart` :de is
8205 // canonical.
8206 let mut s = three_member_spec();
8207 let malformed = contract_http("cart", "BAD_NAME", "/x");
8208 s.contratos.push(malformed.clone());
8209 let err = s.validate().unwrap_err();
8210 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8211 panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
8212 };
8213 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8214 assert_eq!(
8215 caixa,
8216 malformed.destination(),
8217 "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
8218 byte-equal WitContract::destination — the shape-gate arg + \
8219 wrap envelope must route through the lifted accessor \
8220 rather than the raw &c.para &String-borrow"
8221 );
8222 }
8223
8224 // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
8225
8226 #[test]
8227 fn rejects_contrato_de_empty() {
8228 // `:de ""` previously fell through to `ContratoMemberMissing`
8229 // (with `caixa: ""`) because the validated `:membros :caixa`
8230 // set never contains the empty string. The narrower
8231 // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
8232 // the offending slot.
8233 let mut s = three_member_spec();
8234 s.contratos.push(contract_http("", "catalog", "/x"));
8235 let err = s.validate().unwrap_err();
8236 assert_eq!(
8237 err,
8238 AplicacaoError::ContratoCaixaEmpty {
8239 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8240 },
8241 "got {err:?}"
8242 );
8243 }
8244
8245 #[test]
8246 fn rejects_contrato_para_empty() {
8247 // Symmetric arm to `:de ""` — `:para ""` previously fell
8248 // through to `ContratoMemberMissing { caixa: "" }`.
8249 let mut s = three_member_spec();
8250 s.contratos.push(contract_http("cart", "", "/x"));
8251 let err = s.validate().unwrap_err();
8252 assert_eq!(
8253 err,
8254 AplicacaoError::ContratoCaixaEmpty {
8255 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8256 },
8257 "got {err:?}"
8258 );
8259 }
8260
8261 #[test]
8262 fn rejects_contrato_de_with_uppercase() {
8263 // The canonical "I copied the Servico's TitleCase display
8264 // name from an ADR" typo. Until this gate landed `:de "Cart"`
8265 // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
8266 // as "this caixa isn't in `:membros`" when the root cause is
8267 // "this `:de` value's shape can never legitimately match a
8268 // validated member (DNS-1123 labels are lowercase)". The
8269 // narrower diagnostic names the offending slot, the value
8270 // verbatim, and the parser-shaped reason.
8271 let mut s = three_member_spec();
8272 s.contratos.push(contract_http("Cart", "catalog", "/x"));
8273 let err = s.validate().unwrap_err();
8274 let AplicacaoError::ContratoCaixaInvalid {
8275 slot,
8276 caixa,
8277 reason,
8278 } = err
8279 else {
8280 panic!("expected ContratoCaixaInvalid, got other variant");
8281 };
8282 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8283 assert_eq!(caixa, "Cart");
8284 assert!(
8285 reason.contains("uppercase"),
8286 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8287 );
8288 }
8289
8290 #[test]
8291 fn rejects_contrato_para_with_underscore() {
8292 // The canonical "I'm thinking of a Python module" leak —
8293 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8294 // Pin the `:para` axis surfaces the same diagnostic shape as
8295 // the `:de` axis on the underscore violation.
8296 let mut s = three_member_spec();
8297 s.contratos.push(contract_http("cart", "my_catalog", "/x"));
8298 let err = s.validate().unwrap_err();
8299 assert!(
8300 matches!(
8301 err,
8302 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8303 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
8304 ),
8305 "got {err:?}"
8306 );
8307 }
8308
8309 #[test]
8310 fn rejects_contrato_de_with_dot() {
8311 // A `:contratos :de` value is a single DNS-1123 *label*, not
8312 // a subdomain — mirroring the `:membros :caixa` floor. The
8313 // strictest floor among the use sites wins.
8314 let mut s = three_member_spec();
8315 s.contratos
8316 .push(contract_http("team.cart", "catalog", "/x"));
8317 let err = s.validate().unwrap_err();
8318 assert!(
8319 matches!(
8320 err,
8321 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8322 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
8323 ),
8324 "got {err:?}"
8325 );
8326 }
8327
8328 #[test]
8329 fn rejects_contrato_para_with_unicode() {
8330 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8331 // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
8332 // validity check rejects multi-byte UTF-8 by the first
8333 // non-`[a-z0-9-]` byte.
8334 let mut s = three_member_spec();
8335 s.contratos.push(contract_http("cart", "café", "/x"));
8336 let err = s.validate().unwrap_err();
8337 assert!(
8338 matches!(
8339 err,
8340 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8341 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
8342 ),
8343 "got {err:?}"
8344 );
8345 }
8346
8347 #[test]
8348 fn rejects_contrato_de_with_leading_hyphen() {
8349 // DNS-1123 boundary rule: labels must start and end with an
8350 // alphanumeric. K8s rejects `-cart` outright; the narrower
8351 // shape diagnostic now names the violation at caixa-build
8352 // time rather than the misframed membership-lookup arm.
8353 let mut s = three_member_spec();
8354 s.contratos.push(contract_http("-cart", "catalog", "/x"));
8355 let err = s.validate().unwrap_err();
8356 assert!(
8357 matches!(
8358 err,
8359 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8360 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
8361 ),
8362 "got {err:?}"
8363 );
8364 }
8365
8366 #[test]
8367 fn contrato_de_empty_takes_precedence_over_invalid() {
8368 // Order pin: the `ContratoCaixaEmpty` arm fires before the
8369 // `ContratoCaixaInvalid` parse-side arm — same empty-first
8370 // cascade `validate_membro_caixa` / `validate_placement_cluster`
8371 // / `validate_entrada_host` already establish on their peer
8372 // name axes. The empty string is a structurally distinct
8373 // authoring footgun (the author left the field blank, vs.
8374 // typed a malformed value), so it gets its own diagnostic.
8375 let mut s = three_member_spec();
8376 s.contratos.push(contract_http("", "catalog", "/x"));
8377 let err = s.validate().unwrap_err();
8378 assert_eq!(
8379 err,
8380 AplicacaoError::ContratoCaixaEmpty {
8381 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8382 }
8383 );
8384 }
8385
8386 #[test]
8387 fn contrato_de_shape_fires_before_para_shape() {
8388 // Per-axis order pin: within one `:contratos` entry, the `:de`
8389 // shape gate fires before the `:para` shape gate — same
8390 // edge-direction order the existing `ContratoMemberMissing` /
8391 // `ContratoSelfLoop` / target-dispatch checks use, so the
8392 // diagnostic for a contract with both `:de` and `:para`
8393 // malformed is stable. Authors fixing the surfaced `:de`
8394 // first will see `:para`'s diagnostic on re-run.
8395 let mut s = three_member_spec();
8396 s.contratos.push(contract_http("Cart", "Catalog", "/x"));
8397 let err = s.validate().unwrap_err();
8398 assert!(
8399 matches!(
8400 err,
8401 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8402 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8403 ),
8404 "got {err:?}"
8405 );
8406 }
8407
8408 #[test]
8409 fn contrato_shape_fires_before_membership_lookup() {
8410 // The load-bearing pin: an invalid-shape `:de` surfaces its
8411 // *own* diagnostic, not the misframed `ContratoMemberMissing`.
8412 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8413 // an invalid-shape `:de` could never legitimately match any
8414 // member — the prior `ContratoMemberMissing` diagnostic was
8415 // a structural impossibility framed as a graph-membership
8416 // failure. The shape gate now routes every such input through
8417 // the narrower self-locating diagnostic.
8418 let mut s = three_member_spec();
8419 s.contratos.push(contract_http("Cart", "catalog", "/x"));
8420 let err = s.validate().unwrap_err();
8421 assert!(
8422 matches!(
8423 err,
8424 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
8425 ),
8426 "got {err:?}"
8427 );
8428 // And the symmetric case: an invalid-shape `:para` surfaces
8429 // its own diagnostic too, even when `:de` is well-shaped.
8430 let mut s = three_member_spec();
8431 s.contratos.push(contract_http("cart", "Catalog", "/x"));
8432 let err = s.validate().unwrap_err();
8433 assert!(
8434 matches!(
8435 err,
8436 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
8437 ),
8438 "got {err:?}"
8439 );
8440 }
8441
8442 #[test]
8443 fn contrato_shape_fires_before_self_edge_check() {
8444 // A `:de "Cart" :para "Cart"` entry is two distinct authoring
8445 // bugs: the shape violation (uppercase) and the self-edge
8446 // violation. The narrower per-axis shape diagnostic surfaces
8447 // first because fixing the shape may reveal that the author
8448 // also meant to point `:para` at a different member — the
8449 // self-edge framing is only useful once both endpoints have
8450 // valid shape.
8451 let mut s = three_member_spec();
8452 s.contratos.push(contract_http("Cart", "Cart", "/x"));
8453 let err = s.validate().unwrap_err();
8454 assert!(
8455 matches!(
8456 err,
8457 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8458 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8459 ),
8460 "got {err:?}"
8461 );
8462 }
8463
8464 #[test]
8465 fn contrato_well_shaped_phantom_still_raises_member_missing() {
8466 // Strict-improvement pin: a well-shaped `:de` that simply
8467 // isn't in `:membros` (a phantom reference — author meant
8468 // to add the member but didn't, or renamed and missed an
8469 // update) still surfaces `ContratoMemberMissing`, unchanged.
8470 // The shape gate only intercepts inputs that could never
8471 // legitimately match a validated member; legitimately-shaped
8472 // phantom references remain on the graph-membership axis.
8473 let mut s = three_member_spec();
8474 s.contratos
8475 .push(contract_http("phantom-shim", "catalog", "/x"));
8476 let err = s.validate().unwrap_err();
8477 assert!(
8478 matches!(
8479 err,
8480 AplicacaoError::ContratoMemberMissing { ref caixa }
8481 if caixa == "phantom-shim"
8482 ),
8483 "got {err:?}"
8484 );
8485 }
8486
8487 #[test]
8488 fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
8489 // The diagnostic-shape pin: the error names the offending
8490 // slot (`:de` or `:para`) verbatim and the offending value
8491 // verbatim plus a non-empty parser-shaped reason, so the
8492 // author can grep their caixa.lisp for `:de "<name>"` /
8493 // `:para "<name>"` and fix it in one edit. Same diagnostic
8494 // shape as `MembroCaixaInvalid` (3f9d7a0) and
8495 // `PlacementClusterInvalid` (6c8c00b).
8496 let mut s = three_member_spec();
8497 s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
8498 let err = s.validate().unwrap_err();
8499 let AplicacaoError::ContratoCaixaInvalid {
8500 slot,
8501 caixa,
8502 reason,
8503 } = err
8504 else {
8505 panic!("expected ContratoCaixaInvalid, got {err:?}");
8506 };
8507 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8508 assert_eq!(caixa, "BAD_NAME");
8509 assert!(
8510 !reason.is_empty(),
8511 "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
8512 );
8513 }
8514
8515 #[test]
8516 fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
8517 // Scalar-value pin: the two author-facing kebab-case labels the
8518 // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
8519 // admits on the `:contratos` per-entry endpoint-shape axis,
8520 // one arm per typed sub-slot. Mirrors the peer scalar-value
8521 // pin the sibling top-level M2 / M3 / Supervisor
8522 // author-facing-label consts carry
8523 // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
8524 // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
8525 // slot itself), so every altitude of the typed-slot algebra
8526 // shares the same "one canonical byte-string per arm"
8527 // discipline. A future rebrand (`:de` → `:from` matching the
8528 // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
8529 // sibling, `:para` → `:to` matching the same, or
8530 // `:de`/`:para` → `:source`/`:target` matching the WIT
8531 // world's `import`/`export` half-vocabulary) lands as an
8532 // edit to exactly one const, and every consumer that reaches
8533 // for the label picks it up at build time rather than at
8534 // runtime as a downstream `ContratoCaixaEmpty` /
8535 // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
8536 // diagnostic mismatch far from the rename's commit.
8537 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
8538 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
8539 }
8540
8541 #[test]
8542 fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
8543 // Production-through-const pin: the two per-axis labels the
8544 // per-`:contratos` entry endpoint-shape gate at
8545 // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
8546 // argument to [`validate_contrato_caixa`] route through the
8547 // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
8548 // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
8549 // future rebrand that reaches the const but not the gate (or
8550 // vice versa) surfaces here at build time rather than at
8551 // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
8552 // `slot: <stale-kebab-case>` diagnostic far from the rename's
8553 // commit. Mirror of the peer
8554 // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
8555 // pin (882f498) on the sibling M3 top-level slot axis.
8556 let mut s = three_member_spec();
8557 s.contratos.push(contract_http("", "catalog", "/x"));
8558 assert_eq!(
8559 s.validate().unwrap_err(),
8560 AplicacaoError::ContratoCaixaEmpty {
8561 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8562 }
8563 );
8564 let mut s = three_member_spec();
8565 s.contratos.push(contract_http("cart", "", "/x"));
8566 assert_eq!(
8567 s.validate().unwrap_err(),
8568 AplicacaoError::ContratoCaixaEmpty {
8569 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8570 }
8571 );
8572 }
8573
8574 #[test]
8575 fn accepts_canonical_contrato_caixa_forms() {
8576 // The DNS-1123 label shapes a caixa author is realistically
8577 // going to write on a `:contratos :de` / `:para`. Pin every
8578 // leg so a future tightening that bans (e.g.) digit-start
8579 // identifiers surfaces here, mirroring
8580 // `accepts_canonical_membro_caixa_forms` on the peer name
8581 // axis.
8582 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8583 let mut s = three_member_spec();
8584 s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
8585 s.contratos = vec![contract_http("checkout", form, "/x")];
8586 s.entrada = None;
8587 s.validate().unwrap_or_else(|e| {
8588 panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
8589 });
8590
8591 let mut s = three_member_spec();
8592 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8593 s.contratos = vec![contract_http(form, "catalog", "/x")];
8594 s.entrada = None;
8595 s.validate().unwrap_or_else(|e| {
8596 panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
8597 });
8598 }
8599 }
8600
8601 #[test]
8602 fn rejects_empty_wit() {
8603 let mut s = three_member_spec();
8604 s.contratos.push(WitContract {
8605 de: "cart".into(),
8606 para: "catalog".into(),
8607 wit: "".into(),
8608 endpoint: None,
8609 subject: None,
8610 slot: None,
8611 });
8612 let err = s.validate().unwrap_err();
8613 assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
8614 }
8615
8616 #[test]
8617 fn rejects_entrada_to_unknown_member() {
8618 let mut s = three_member_spec();
8619 s.entrada.as_mut().unwrap().para = "phantom".into();
8620 assert!(matches!(
8621 s.validate().unwrap_err(),
8622 AplicacaoError::EntradaMemberMissing { .. }
8623 ));
8624 }
8625
8626 // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
8627
8628 #[test]
8629 fn rejects_entrada_para_empty() {
8630 // `:para ""` previously fell through to
8631 // `EntradaMemberMissing { para: "" }` because the validated
8632 // `:membros :caixa` set never contains the empty string. The
8633 // narrower `EntradaParaEmpty` diagnostic now names the
8634 // offending slot directly — same empty-first cascade
8635 // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
8636 // `ContratoCaixaEmpty` establish on the peer name axes.
8637 let mut s = three_member_spec();
8638 s.entrada.as_mut().unwrap().para = String::new();
8639 let err = s.validate().unwrap_err();
8640 assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
8641 }
8642
8643 #[test]
8644 fn rejects_entrada_para_with_uppercase() {
8645 // The canonical "I copied the Servico's TitleCase display
8646 // name from an ADR" typo. Until this gate landed `:para "Cart"`
8647 // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
8648 // as "this caixa isn't in `:membros`" when the root cause is
8649 // "this `:para` value's shape can never legitimately match a
8650 // validated member (DNS-1123 labels are lowercase)". The
8651 // narrower diagnostic names the value verbatim plus the
8652 // parser-shaped reason.
8653 let mut s = three_member_spec();
8654 s.entrada.as_mut().unwrap().para = "Cart".into();
8655 let err = s.validate().unwrap_err();
8656 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8657 panic!("expected EntradaParaInvalid, got other variant");
8658 };
8659 assert_eq!(para, "Cart");
8660 assert!(
8661 reason.contains("uppercase"),
8662 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8663 );
8664 }
8665
8666 #[test]
8667 fn rejects_entrada_para_with_underscore() {
8668 // The canonical "I'm thinking of a Python module" leak —
8669 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8670 let mut s = three_member_spec();
8671 s.entrada.as_mut().unwrap().para = "my_cart".into();
8672 let err = s.validate().unwrap_err();
8673 assert!(
8674 matches!(
8675 err,
8676 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8677 if para == "my_cart" && reason.contains('_')
8678 ),
8679 "got {err:?}"
8680 );
8681 }
8682
8683 #[test]
8684 fn rejects_entrada_para_with_dot() {
8685 // An `:entrada :para` value is a single DNS-1123 *label*, not
8686 // a subdomain — mirroring the `:membros :caixa` floor. The
8687 // strictest floor among the use sites wins.
8688 let mut s = three_member_spec();
8689 s.entrada.as_mut().unwrap().para = "team.cart".into();
8690 let err = s.validate().unwrap_err();
8691 assert!(
8692 matches!(
8693 err,
8694 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8695 if para == "team.cart" && reason.contains('.')
8696 ),
8697 "got {err:?}"
8698 );
8699 }
8700
8701 #[test]
8702 fn rejects_entrada_para_with_unicode() {
8703 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8704 // (`xn--…`) before it reaches K8s.
8705 let mut s = three_member_spec();
8706 s.entrada.as_mut().unwrap().para = "café".into();
8707 let err = s.validate().unwrap_err();
8708 assert!(
8709 matches!(
8710 err,
8711 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
8712 ),
8713 "got {err:?}"
8714 );
8715 }
8716
8717 #[test]
8718 fn rejects_entrada_para_with_leading_hyphen() {
8719 // DNS-1123 boundary rule: labels must start and end with an
8720 // alphanumeric. K8s rejects `-cart` outright.
8721 let mut s = three_member_spec();
8722 s.entrada.as_mut().unwrap().para = "-cart".into();
8723 let err = s.validate().unwrap_err();
8724 assert!(
8725 matches!(
8726 err,
8727 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8728 if para == "-cart" && reason.contains("start and end")
8729 ),
8730 "got {err:?}"
8731 );
8732 }
8733
8734 #[test]
8735 fn rejects_entrada_para_with_trailing_hyphen() {
8736 // Symmetric boundary arm.
8737 let mut s = three_member_spec();
8738 s.entrada.as_mut().unwrap().para = "cart-".into();
8739 let err = s.validate().unwrap_err();
8740 assert!(
8741 matches!(
8742 err,
8743 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8744 if para == "cart-" && reason.contains("start and end")
8745 ),
8746 "got {err:?}"
8747 );
8748 }
8749
8750 #[test]
8751 fn rejects_entrada_para_too_long() {
8752 // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
8753 // bytes per label. K8s rejects longer names at admission on
8754 // every `metadata.name` axis.
8755 let mut s = three_member_spec();
8756 s.entrada.as_mut().unwrap().para = "a".repeat(64);
8757 let err = s.validate().unwrap_err();
8758 assert!(
8759 matches!(
8760 err,
8761 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8762 if para.len() == 64 && reason.contains("max length")
8763 ),
8764 "got {err:?}"
8765 );
8766 }
8767
8768 #[test]
8769 fn entrada_para_empty_takes_precedence_over_invalid() {
8770 // Order pin: the `EntradaParaEmpty` arm fires before the
8771 // `EntradaParaInvalid` parse-side arm — same empty-first
8772 // cascade `validate_membro_caixa` / `validate_placement_cluster`
8773 // / `validate_contrato_caixa` already establish.
8774 let mut s = three_member_spec();
8775 s.entrada.as_mut().unwrap().para = String::new();
8776 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
8777 }
8778
8779 #[test]
8780 fn entrada_para_shape_fires_before_membership_lookup() {
8781 // The load-bearing pin: an invalid-shape `:para` surfaces its
8782 // *own* diagnostic, not the misframed `EntradaMemberMissing`.
8783 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8784 // an invalid-shape `:para` could never legitimately match any
8785 // member — the prior `EntradaMemberMissing` diagnostic framed
8786 // a structural impossibility as a graph-membership failure.
8787 let mut s = three_member_spec();
8788 s.entrada.as_mut().unwrap().para = "Cart".into();
8789 let err = s.validate().unwrap_err();
8790 assert!(
8791 matches!(
8792 err,
8793 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
8794 ),
8795 "got {err:?}"
8796 );
8797 }
8798
8799 #[test]
8800 fn entrada_para_shape_fires_before_host_gate() {
8801 // Per-`:entrada` order pin: the `:para` shape gate fires
8802 // before the `:host` gate, mirroring the existing
8803 // `entrada_host_member_missing_takes_precedence_over_host_invalid`
8804 // ordering where the member-lookup arm preceded the host gate.
8805 // The shape gate slots ahead of that, so a malformed `:para`
8806 // surfaces its own diagnostic even when `:host` is also wrong.
8807 let mut s = three_member_spec();
8808 let e = s.entrada.as_mut().unwrap();
8809 e.para = "Cart".into();
8810 e.host = "BAD HOST".into();
8811 let err = s.validate().unwrap_err();
8812 assert!(
8813 matches!(
8814 err,
8815 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
8816 ),
8817 "got {err:?}"
8818 );
8819 }
8820
8821 #[test]
8822 fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
8823 // Strict-improvement pin: a well-shaped `:para` that simply
8824 // isn't in `:membros` (a phantom reference — author meant to
8825 // add the member but didn't, or renamed and missed an
8826 // update) still surfaces `EntradaMemberMissing`, unchanged.
8827 // The shape gate only intercepts inputs that could never
8828 // legitimately match a validated member.
8829 let mut s = three_member_spec();
8830 s.entrada.as_mut().unwrap().para = "phantom-shim".into();
8831 let err = s.validate().unwrap_err();
8832 assert!(
8833 matches!(
8834 err,
8835 AplicacaoError::EntradaMemberMissing { ref para }
8836 if para == "phantom-shim"
8837 ),
8838 "got {err:?}"
8839 );
8840 }
8841
8842 #[test]
8843 fn entrada_para_invalid_diagnostic_carries_offending_para() {
8844 // The diagnostic-shape pin: the error names the offending
8845 // `:para` value verbatim plus a non-empty parser-shaped
8846 // reason, so the author can grep their caixa.lisp for
8847 // `:para "<name>"` and fix it in one edit. Same diagnostic
8848 // shape as `MembroCaixaInvalid` (3f9d7a0),
8849 // `PlacementClusterInvalid` (6c8c00b), and
8850 // `ContratoCaixaInvalid` (8d5af6b).
8851 let mut s = three_member_spec();
8852 s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
8853 let err = s.validate().unwrap_err();
8854 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8855 panic!("expected EntradaParaInvalid, got {err:?}");
8856 };
8857 assert_eq!(para, "BAD_NAME");
8858 assert!(
8859 !reason.is_empty(),
8860 "EntradaParaInvalid `reason` must carry a parser-shaped wording"
8861 );
8862 }
8863
8864 #[test]
8865 fn accepts_canonical_entrada_para_forms() {
8866 // Positive-control sweep covering the DNS-1123 label shapes a
8867 // caixa author is realistically going to write on `:entrada
8868 // :para`. Pin every leg so a future tightening that bans
8869 // (e.g.) digit-start identifiers surfaces here, mirroring
8870 // `accepts_canonical_membro_caixa_forms` and
8871 // `accepts_canonical_contrato_caixa_forms` on the peer name
8872 // axes.
8873 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8874 let mut s = three_member_spec();
8875 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8876 s.contratos = vec![contract_http(form, "catalog", "/x")];
8877 s.entrada = Some(Entrada {
8878 host: "checkout.quero.cloud".into(),
8879 para: form.into(),
8880 paths: vec!["/api".into()],
8881 port: 8080,
8882 });
8883 s.validate().unwrap_or_else(|e| {
8884 panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
8885 });
8886 }
8887 }
8888
8889 #[test]
8890 fn rejects_replicated_without_clusters() {
8891 let mut s = three_member_spec();
8892 s.placement.clusters = vec![];
8893 assert!(matches!(
8894 s.validate().unwrap_err(),
8895 AplicacaoError::PlacementWithoutClusters { .. }
8896 ));
8897 }
8898
8899 #[test]
8900 fn rejects_sharded_without_key() {
8901 let mut s = three_member_spec();
8902 s.placement.estrategia = PlacementStrategy::Sharded;
8903 s.placement.shard_key = None;
8904 s.placement.clusters = vec!["rio".into()];
8905 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
8906 }
8907
8908 #[test]
8909 fn sharded_with_key_validates() {
8910 let mut s = three_member_spec();
8911 s.placement.estrategia = PlacementStrategy::Sharded;
8912 s.placement.shard_key = Some("$tenantId".into());
8913 s.validate().unwrap();
8914 }
8915
8916 #[test]
8917 fn round_trip_via_json_preserves_shape() {
8918 let s = three_member_spec();
8919 let json = serde_json::to_string(&s.membros).unwrap();
8920 let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
8921 assert_eq!(back, s.membros);
8922
8923 let json = serde_json::to_string(&s.contratos).unwrap();
8924 let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
8925 assert_eq!(back, s.contratos);
8926
8927 let json = serde_json::to_string(&s.placement).unwrap();
8928 let back: Placement = serde_json::from_str(&json).unwrap();
8929 assert_eq!(back, s.placement);
8930
8931 let json = serde_json::to_string(&s.entrada).unwrap();
8932 let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
8933 assert_eq!(back, s.entrada);
8934 }
8935
8936 #[test]
8937 fn rate_limit_round_trip_seconds() {
8938 let policy = MeshPolicy {
8939 rate_limit: Some(RateLimit {
8940 rate: 100,
8941 window: Duration::from_secs(1),
8942 }),
8943 ..Default::default()
8944 };
8945 let json = serde_json::to_string(&policy).unwrap();
8946 assert!(json.contains("\"100/s\""));
8947 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
8948 assert_eq!(back.rate_limit.unwrap().rate, 100);
8949 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
8950 }
8951
8952 #[test]
8953 fn rate_limit_round_trip_minutes() {
8954 let policy = MeshPolicy {
8955 rate_limit: Some(RateLimit {
8956 rate: 5000,
8957 window: Duration::from_secs(60),
8958 }),
8959 ..Default::default()
8960 };
8961 let json = serde_json::to_string(&policy).unwrap();
8962 assert!(json.contains("\"5000/m\""));
8963 }
8964
8965 #[test]
8966 fn circuit_breaker_round_trip() {
8967 let policy = MeshPolicy {
8968 circuit_breaker: Some(CircuitBreaker {
8969 max_failures: 5,
8970 window: Duration::from_secs(60),
8971 }),
8972 ..Default::default()
8973 };
8974 let json = serde_json::to_string(&policy).unwrap();
8975 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
8976 assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
8977 assert_eq!(
8978 back.circuit_breaker.unwrap().window,
8979 Duration::from_secs(60)
8980 );
8981 }
8982
8983 #[test]
8984 fn rejects_http_contrato_without_endpoint() {
8985 let mut s = three_member_spec();
8986 s.contratos.push(WitContract {
8987 de: "cart".into(),
8988 para: "catalog".into(),
8989 wit: "wasi:http/proxy".into(),
8990 endpoint: None,
8991 subject: None,
8992 slot: None,
8993 });
8994 let err = s.validate().unwrap_err();
8995 assert!(matches!(
8996 err,
8997 AplicacaoError::ContratoMissingTarget {
8998 expected: WitTarget::HTTP_FIELD_NAME,
8999 ..
9000 }
9001 ));
9002 }
9003
9004 #[test]
9005 fn rejects_http_contrato_with_subject() {
9006 let mut s = three_member_spec();
9007 s.contratos.push(WitContract {
9008 de: "cart".into(),
9009 para: "catalog".into(),
9010 wit: "wasi:http/proxy".into(),
9011 endpoint: Some("/x".into()),
9012 subject: Some("not.allowed.here".into()),
9013 slot: None,
9014 });
9015 let err = s.validate().unwrap_err();
9016 assert!(matches!(
9017 err,
9018 AplicacaoError::ContratoWrongTarget {
9019 expected: WitTarget::HTTP_FIELD_NAME,
9020 ..
9021 }
9022 ));
9023 }
9024
9025 #[test]
9026 fn rejects_pubsub_contrato_without_subject() {
9027 let mut s = three_member_spec();
9028 s.contratos.push(WitContract {
9029 de: "cart".into(),
9030 para: "catalog".into(),
9031 wit: "nats:pub-sub".into(),
9032 endpoint: None,
9033 subject: None,
9034 slot: None,
9035 });
9036 let err = s.validate().unwrap_err();
9037 assert!(matches!(
9038 err,
9039 AplicacaoError::ContratoMissingTarget {
9040 expected: WitTarget::PUBSUB_FIELD_NAME,
9041 ..
9042 }
9043 ));
9044 }
9045
9046 #[test]
9047 fn rejects_pubsub_contrato_with_endpoint() {
9048 let mut s = three_member_spec();
9049 s.contratos.push(WitContract {
9050 de: "cart".into(),
9051 para: "catalog".into(),
9052 wit: "kafka:topic".into(),
9053 endpoint: Some("/wrong".into()),
9054 subject: Some("topic.x".into()),
9055 slot: None,
9056 });
9057 let err = s.validate().unwrap_err();
9058 assert!(matches!(
9059 err,
9060 AplicacaoError::ContratoWrongTarget {
9061 expected: WitTarget::PUBSUB_FIELD_NAME,
9062 ..
9063 }
9064 ));
9065 }
9066
9067 #[test]
9068 fn rejects_store_contrato_without_slot() {
9069 let mut s = three_member_spec();
9070 s.contratos.push(WitContract {
9071 de: "cart".into(),
9072 para: "catalog".into(),
9073 wit: "wasi:keyvalue/store".into(),
9074 endpoint: None,
9075 subject: None,
9076 slot: None,
9077 });
9078 let err = s.validate().unwrap_err();
9079 assert!(matches!(
9080 err,
9081 AplicacaoError::ContratoMissingTarget {
9082 expected: WitTarget::STORE_FIELD_NAME,
9083 ..
9084 }
9085 ));
9086 }
9087
9088 // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
9089
9090 #[test]
9091 fn rejects_http_contrato_with_empty_endpoint() {
9092 // `Some("")` for an HTTP endpoint passes the presence check
9093 // (target() previously returned WitTarget::Http { endpoint: "" })
9094 // but renders as a `path: ""` Cilium L7 rule that matches no
9095 // traffic. Same value-shape footgun closed for :entrada :paths
9096 // entries (eb3456d).
9097 let mut s = three_member_spec();
9098 s.contratos.push(WitContract {
9099 de: "cart".into(),
9100 para: "catalog".into(),
9101 wit: "wasi:http/proxy".into(),
9102 endpoint: Some(String::new()),
9103 subject: None,
9104 slot: None,
9105 });
9106 let err = s.validate().unwrap_err();
9107 assert!(
9108 matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
9109 if de == "cart" && para == "catalog"),
9110 "got {err:?}"
9111 );
9112 }
9113
9114 #[test]
9115 fn rejects_http_contrato_with_relative_endpoint() {
9116 // Cilium L7 :path + Gateway API PathPrefix both require a
9117 // leading `/`. Same shape required of :entrada :paths
9118 // (eb3456d). Lifted into target() so every consumer of the
9119 // typed WitTarget view inherits the guarantee.
9120 let mut s = three_member_spec();
9121 s.contratos.push(WitContract {
9122 de: "cart".into(),
9123 para: "catalog".into(),
9124 wit: "wasi:http/proxy".into(),
9125 endpoint: Some("products/:id".into()),
9126 subject: None,
9127 slot: None,
9128 });
9129 let err = s.validate().unwrap_err();
9130 assert!(
9131 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9132 if endpoint == "products/:id"),
9133 "got {err:?}"
9134 );
9135 }
9136
9137 #[test]
9138 fn rejects_pubsub_contrato_with_empty_subject() {
9139 // NATS / Kafka publish without a subject is a no-op subscribe;
9140 // never the author's intent. Same empty-string rejection as
9141 // :membros :caixa, :placement :clusters entries, :entrada
9142 // :paths entries — every value carried by every typed slot is
9143 // value-shape-checked at validate().
9144 let mut s = three_member_spec();
9145 s.contratos.push(WitContract {
9146 de: "cart".into(),
9147 para: "catalog".into(),
9148 wit: "nats:pub-sub".into(),
9149 endpoint: None,
9150 subject: Some(String::new()),
9151 slot: None,
9152 });
9153 let err = s.validate().unwrap_err();
9154 assert!(
9155 matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
9156 if de == "cart" && para == "catalog"),
9157 "got {err:?}"
9158 );
9159 }
9160
9161 #[test]
9162 fn rejects_store_contrato_with_empty_slot() {
9163 // An empty slot template addresses the bucket root, defeating
9164 // the per-key isolation the slot exists for — a footgun on
9165 // `wasi:keyvalue/store` whose closest analog is the empty
9166 // shard-key rejected on :placement Sharded (c7c7799).
9167 let mut s = three_member_spec();
9168 s.contratos.push(WitContract {
9169 de: "cart".into(),
9170 para: "catalog".into(),
9171 wit: "wasi:keyvalue/store".into(),
9172 endpoint: None,
9173 subject: None,
9174 slot: Some(String::new()),
9175 });
9176 let err = s.validate().unwrap_err();
9177 assert!(
9178 matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
9179 if de == "cart" && para == "catalog"),
9180 "got {err:?}"
9181 );
9182 }
9183
9184 #[test]
9185 fn http_contrato_root_endpoint_validates() {
9186 // Pin the boundary case: a single-`/` endpoint is the catch-all
9187 // form the Gateway HTTPRoute renderer falls back to when
9188 // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
9189 // must remain a valid contrato endpoint too.
9190 let mut s = three_member_spec();
9191 s.contratos.push(contract_http("cart", "catalog", "/"));
9192 s.validate().unwrap();
9193 }
9194
9195 // ── :contratos :endpoint value-shape gate ────────────────────────────
9196 //
9197 // Mirrors the `:entrada :paths` value-shape suite on the peer
9198 // HTTP-path axis. Until this gate landed `WitContract::target()`
9199 // only refused the empty string + the missing-leading-`/` form
9200 // (c4213a4); a structurally invalid endpoint passed validate and
9201 // landed verbatim as a Cilium L7 `path:` rule
9202 // (caixa-mesh/src/lib.rs:311) that either silently dropped all
9203 // traffic or was rejected at apply time by Cilium policy admission.
9204 // Every authoring footgun the K8s Gateway API webhook / Cilium
9205 // policy validator would catch on admission now becomes a caixa-
9206 // build-time `ContratoEndpointInvalid` with the offending
9207 // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
9208 // shape as `EntradaPathInvalid` on the sibling axis; same shared
9209 // predicate (`crate::render::is_gateway_api_http_path`) ensures
9210 // drift between the two axes' rule enforcement is a build error
9211 // at the predicate.
9212
9213 fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
9214 // Fresh spec per call so the would-be-duplicate edge
9215 // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
9216 // `three_member_spec`'s pre-existing
9217 // `(cart, catalog, …, /products/:id)` entry — only the
9218 // endpoint payload differs.
9219 let mut s = three_member_spec();
9220 s.contratos.push(contract_http("cart", "catalog", ep));
9221 s.validate().unwrap_err()
9222 }
9223
9224 #[test]
9225 fn rejects_http_contrato_endpoint_with_query() {
9226 // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
9227 // silently rendered as a Cilium L7 `path: "/charge?token=X"`
9228 // rule the L7 matcher would never satisfy.
9229 let err = contrato_endpoint_err("/charge?token=X");
9230 assert!(
9231 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9232 if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
9233 "got {err:?}"
9234 );
9235 }
9236
9237 #[test]
9238 fn rejects_http_contrato_endpoint_with_fragment() {
9239 let err = contrato_endpoint_err("/charge#frag");
9240 assert!(
9241 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9242 if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
9243 "got {err:?}"
9244 );
9245 }
9246
9247 #[test]
9248 fn rejects_http_contrato_endpoint_with_whitespace() {
9249 let err = contrato_endpoint_err("/foo bar");
9250 assert!(
9251 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9252 if endpoint == "/foo bar" && reason.contains("whitespace")),
9253 "got {err:?}"
9254 );
9255 }
9256
9257 #[test]
9258 fn rejects_http_contrato_endpoint_with_control_char() {
9259 let err = contrato_endpoint_err("/api/\x01bar");
9260 assert!(
9261 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9262 if endpoint == "/api/\x01bar" && reason.contains("control character")),
9263 "got {err:?}"
9264 );
9265 }
9266
9267 #[test]
9268 fn rejects_http_contrato_endpoint_with_non_ascii() {
9269 let err = contrato_endpoint_err("/api/café");
9270 assert!(
9271 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9272 if endpoint == "/api/café" && reason.contains("non-ASCII")),
9273 "got {err:?}"
9274 );
9275 }
9276
9277 #[test]
9278 fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
9279 let err = contrato_endpoint_err("/api//cart");
9280 assert!(
9281 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9282 if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
9283 "got {err:?}"
9284 );
9285 }
9286
9287 #[test]
9288 fn rejects_http_contrato_endpoint_with_dot_segment() {
9289 let err = contrato_endpoint_err("/api/./cart");
9290 assert!(
9291 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9292 if endpoint == "/api/./cart" && reason.contains("`.` segment")),
9293 "got {err:?}"
9294 );
9295 }
9296
9297 #[test]
9298 fn rejects_http_contrato_endpoint_with_parent_segment() {
9299 // Path-traversal in a contrato endpoint is the canonical
9300 // "L7 rule that the workload's HTTP server's path-resolution
9301 // logic interprets differently than the policy enforcer"
9302 // footgun. Rejected outright at validate time.
9303 let err = contrato_endpoint_err("/api/../etc");
9304 assert!(
9305 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9306 if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
9307 "got {err:?}"
9308 );
9309 }
9310
9311 #[test]
9312 fn rejects_http_contrato_endpoint_too_long() {
9313 // 1025-byte endpoint — one over the Gateway API
9314 // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
9315 // path matcher has no inherent length limit but the policy
9316 // CR itself rides through the K8s apiserver, which enforces
9317 // ConfigMap-shaped limits; sharing the Gateway API cap is the
9318 // conservative floor.
9319 let big = format!("/api/{}", "a".repeat(1020));
9320 assert_eq!(big.len(), 1025);
9321 let err = contrato_endpoint_err(&big);
9322 assert!(
9323 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9324 if endpoint == &big && reason.contains("max length of 1024")),
9325 "got {err:?}"
9326 );
9327 }
9328
9329 #[test]
9330 fn http_contrato_endpoint_max_length_validates() {
9331 // 1024-byte endpoint — exactly the cap. Boundary pin: drift
9332 // in the cap surfaces here and at
9333 // `rejects_http_contrato_endpoint_too_long` simultaneously,
9334 // mirroring `entrada_path_max_length_validates` on the peer
9335 // axis.
9336 let big = format!("/api/{}", "a".repeat(1019));
9337 assert_eq!(big.len(), 1024);
9338 let mut s = three_member_spec();
9339 s.contratos.push(contract_http("cart", "catalog", &big));
9340 s.validate().unwrap();
9341 }
9342
9343 #[test]
9344 fn http_contrato_endpoint_accepts_canonical_forms() {
9345 // Positive-set sweep: every canonical HTTP-path shape the
9346 // sibling `:entrada :paths` axis accepts (the bare-root `/`,
9347 // plain paths, hidden-file-style `.config` segments distinct
9348 // from the `.` segment, digit-bearing segments, the canonical
9349 // route-template `:param` form, trailing-slash form,
9350 // percent-encoded segments, the `/foo..bar` interior-`..`-
9351 // substring forms that are NOT `..` segments) must remain a
9352 // valid contrato endpoint too. Drift between this list and
9353 // the entrada path positive sweep surfaces at the shared
9354 // `is_gateway_api_http_path` substrate-side suite — one
9355 // source of truth. Uses a fresh `(payment, catalog)` edge so
9356 // none of the swept endpoints collide with the pre-existing
9357 // `(cart, catalog, /products/:id)` / `(cart, payment,
9358 // /charge)` entries in `three_member_spec`.
9359 for ep in [
9360 "/",
9361 "/charge",
9362 "/v1/charge",
9363 "/api/.config",
9364 "/products/:id",
9365 "/api/cart/",
9366 "/api/caf%C3%A9",
9367 "/foo..bar",
9368 "/...",
9369 ] {
9370 let mut s = three_member_spec();
9371 s.contratos.push(contract_http("payment", "catalog", ep));
9372 s.validate()
9373 .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
9374 }
9375 }
9376
9377 #[test]
9378 fn contrato_endpoint_empty_takes_precedence_over_invalid() {
9379 // Ordering pin: `ContratoEndpointEmpty` is the more self-
9380 // locating diagnostic on `""` and must lead — the value-
9381 // shape gate is only reached after the empty-check fires.
9382 // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
9383 // on the peer axis.
9384 let mut s = three_member_spec();
9385 s.contratos.push(WitContract {
9386 de: "cart".into(),
9387 para: "catalog".into(),
9388 wit: "wasi:http/proxy".into(),
9389 endpoint: Some(String::new()),
9390 subject: None,
9391 slot: None,
9392 });
9393 let err = s.validate().unwrap_err();
9394 assert!(
9395 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
9396 "got {err:?}"
9397 );
9398 }
9399
9400 #[test]
9401 fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
9402 // Ordering pin: an endpoint without a leading `/` surfaces the
9403 // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
9404 // value-shape gate is only consulted on endpoints that already
9405 // satisfy the absolute-prefix invariant. Mirrors
9406 // `entrada_path_not_absolute_takes_precedence_over_invalid`.
9407 let err = contrato_endpoint_err("bad path");
9408 assert!(
9409 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9410 if endpoint == "bad path"),
9411 "got {err:?}"
9412 );
9413 }
9414
9415 #[test]
9416 fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
9417 // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
9418 // `:para` + a non-empty reason flow through verbatim so the
9419 // author can grep their caixa.lisp for the offending contrato
9420 // block and fix it in one edit. Same shape as
9421 // `entrada_path_diagnostic_carries_offending_path`.
9422 let err = contrato_endpoint_err("/api?q=1");
9423 match err {
9424 AplicacaoError::ContratoEndpointInvalid {
9425 de,
9426 para,
9427 endpoint,
9428 reason,
9429 } => {
9430 assert_eq!(de, "cart");
9431 assert_eq!(para, "catalog");
9432 assert_eq!(endpoint, "/api?q=1");
9433 assert!(!reason.is_empty(), "reason field must be non-empty");
9434 }
9435 other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
9436 }
9437 }
9438
9439 #[test]
9440 fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
9441 // The compounding theorem: every &str inside a WitTarget
9442 // returned by target() is non-empty (and absolute, for Http).
9443 // Renderers downstream of typed_view() can rely on this
9444 // without re-checking — the type system carries the proof.
9445 let http = contract_http("cart", "catalog", "/x");
9446 match http.target().unwrap() {
9447 WitTarget::Http { endpoint } => {
9448 assert!(!endpoint.is_empty());
9449 assert!(endpoint.starts_with('/'));
9450 }
9451 other => panic!("expected Http, got {other:?}"),
9452 }
9453 let nats = WitContract {
9454 de: "a".into(),
9455 para: "b".into(),
9456 wit: "nats:pub-sub".into(),
9457 endpoint: None,
9458 subject: Some("topic.x".into()),
9459 slot: None,
9460 };
9461 match nats.target().unwrap() {
9462 WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
9463 other => panic!("expected PubSub, got {other:?}"),
9464 }
9465 let kv = WitContract {
9466 de: "a".into(),
9467 para: "b".into(),
9468 wit: "wasi:keyvalue/store".into(),
9469 endpoint: None,
9470 subject: None,
9471 slot: Some("checkout/$orderId".into()),
9472 };
9473 match kv.target().unwrap() {
9474 WitTarget::Store { slot } => assert!(!slot.is_empty()),
9475 other => panic!("expected Store, got {other:?}"),
9476 }
9477 }
9478
9479 #[test]
9480 fn target_diagnostic_names_offending_endpoint_value() {
9481 // When the malformed endpoint string is non-trivial, the
9482 // diagnostic carries the actual value back to the author —
9483 // not a generic "endpoint malformed" error.
9484 let bad = WitContract {
9485 de: "src".into(),
9486 para: "dst".into(),
9487 wit: "wasi:http/proxy".into(),
9488 endpoint: Some("api/v1/charge".into()),
9489 subject: None,
9490 slot: None,
9491 };
9492 match bad.target().unwrap_err() {
9493 AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
9494 assert_eq!(de, "src");
9495 assert_eq!(para, "dst");
9496 assert_eq!(endpoint, "api/v1/charge");
9497 }
9498 other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
9499 }
9500 }
9501
9502 #[test]
9503 fn rejects_unknown_wit_with_target_set() {
9504 let mut s = three_member_spec();
9505 s.contratos.push(WitContract {
9506 de: "cart".into(),
9507 para: "catalog".into(),
9508 wit: "custom:exchange".into(),
9509 endpoint: Some("/leaked".into()),
9510 subject: None,
9511 slot: None,
9512 });
9513 let err = s.validate().unwrap_err();
9514 assert!(matches!(
9515 err,
9516 AplicacaoError::ContratoWrongTarget {
9517 expected: WitTarget::CAPABILITY_EXPECTED,
9518 ..
9519 }
9520 ));
9521 }
9522
9523 #[test]
9524 fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
9525 // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
9526 // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
9527 // fourth arm of the same "which payload field name goes in the
9528 // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
9529 // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
9530 // consts cover on the peer HTTP / PubSub / Store arms
9531 // (`wit_target_field_name_pins_per_variant`). Until this lift
9532 // landed the byte-string sat twice — once inline in the
9533 // [`WitContract::target`] Capability-arm rejection at the
9534 // production dispatch, once in `rejects_unknown_wit_with_target_set`
9535 // pinning against the same literal — with no compile-time link
9536 // between them. Same "one canonical declaration, next to the
9537 // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
9538 // lift established for the payload-less arm's human-readable
9539 // label axis; this test is the shape peer of
9540 // `wit_target_label_pins_per_variant`'s Capability-arm assertion
9541 // pair (routes-through-const + scalar-value pin) on the
9542 // wrong-target diagnostic-scalar axis.
9543 //
9544 // Fail-before-pass-after was verified locally by mutating the
9545 // const declaration to `"capability"` — the scalar-value pin
9546 // below fires (`"capability" != "none"`) and the routes-through
9547 // assertion below still holds (production and const walk in
9548 // lockstep), which is the correct behavior: a rename on the
9549 // const drifts here first, not at a downstream consumer.
9550 assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
9551
9552 let mut s = three_member_spec();
9553 s.contratos.push(WitContract {
9554 de: "cart".into(),
9555 para: "catalog".into(),
9556 wit: "custom:exchange".into(),
9557 endpoint: Some("/leaked".into()),
9558 subject: None,
9559 slot: None,
9560 });
9561 match s.validate().unwrap_err() {
9562 AplicacaoError::ContratoWrongTarget { expected, .. } => {
9563 assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
9564 }
9565 other => panic!("expected ContratoWrongTarget, got {other:?}"),
9566 }
9567 }
9568
9569 #[test]
9570 fn unknown_wit_capability_only_validates() {
9571 let mut s = three_member_spec();
9572 s.contratos.push(WitContract {
9573 de: "cart".into(),
9574 para: "catalog".into(),
9575 // A WIT world we haven't yet shaped — accept it as a typed
9576 // capability edge so authors aren't blocked while the WIT
9577 // registry catches up. No payload field may be carried.
9578 wit: "custom:exchange".into(),
9579 endpoint: None,
9580 subject: None,
9581 slot: None,
9582 });
9583 s.validate().unwrap();
9584 let added = s.contratos.last().unwrap();
9585 assert_eq!(added.target().unwrap(), WitTarget::Capability);
9586 }
9587
9588 #[test]
9589 fn target_typed_view_round_trips_each_shape() {
9590 let http = contract_http("cart", "catalog", "/products/:id");
9591 assert_eq!(
9592 http.target().unwrap(),
9593 WitTarget::Http {
9594 endpoint: "/products/:id"
9595 }
9596 );
9597 let nats = WitContract {
9598 de: "a".into(),
9599 para: "b".into(),
9600 wit: "nats:pub-sub".into(),
9601 endpoint: None,
9602 subject: Some("topic.x".into()),
9603 slot: None,
9604 };
9605 assert_eq!(
9606 nats.target().unwrap(),
9607 WitTarget::PubSub { subject: "topic.x" }
9608 );
9609 let kv = WitContract {
9610 de: "a".into(),
9611 para: "b".into(),
9612 wit: "wasi:keyvalue/store".into(),
9613 endpoint: None,
9614 subject: None,
9615 slot: Some("checkout/$orderId".into()),
9616 };
9617 assert_eq!(
9618 kv.target().unwrap(),
9619 WitTarget::Store {
9620 slot: "checkout/$orderId"
9621 }
9622 );
9623 }
9624
9625 #[test]
9626 fn wit_contract_kind_predicates() {
9627 let http = contract_http("a", "b", "/x");
9628 assert!(http.is_http());
9629 assert!(!http.is_pubsub());
9630 assert!(!http.is_store());
9631
9632 let nats = WitContract {
9633 de: "a".into(),
9634 para: "b".into(),
9635 wit: "nats:pub-sub".into(),
9636 endpoint: None,
9637 subject: Some("topic.x".into()),
9638 slot: None,
9639 };
9640 assert!(nats.is_pubsub());
9641 assert!(!nats.is_http());
9642
9643 let kv = WitContract {
9644 de: "a".into(),
9645 para: "b".into(),
9646 wit: "wasi:keyvalue/store".into(),
9647 endpoint: None,
9648 subject: None,
9649 slot: Some("checkout/$orderId".into()),
9650 };
9651 assert!(kv.is_store());
9652 assert!(!kv.is_http());
9653 }
9654
9655 // ── :contratos :wit value-shape gate ─────────────────────────────────
9656 //
9657 // Mirrors the `:contratos :endpoint` value-shape suite on the peer
9658 // dispatch-discriminator axis. Until this gate landed
9659 // `WitContract::target()` accepted any non-empty string and
9660 // silently demoted unrecognized shapes to a capability-only L4
9661 // edge — the canonical "I thought I had L7 HTTP routing, got
9662 // L4-only" footgun. Every authoring footgun the WIT registry's
9663 // own grammar rejects (uppercase, hyphen-for-colon typo,
9664 // whitespace, empty package, doubled `@`, …) now becomes a
9665 // caixa-build-time `ContratoWitInvalid` with the offending
9666 // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
9667 // as `ContratoEndpointInvalid` on the sibling axis; same shared
9668 // predicate (`crate::render::is_wit_world_ref`) ensures drift
9669 // between any two axes' rule enforcement is a build error at the
9670 // predicate, not piecemeal across renderers.
9671
9672 fn contrato_wit_err(wit: &str) -> AplicacaoError {
9673 // Fresh spec per call so the new contract doesn't collide on
9674 // identity with `three_member_spec`'s pre-existing entries.
9675 // The new edge uses `(payment, catalog)` — a pair the fixture
9676 // doesn't already declare — with no payload field set, so the
9677 // wit-shape gate fires before any payload-shape arm.
9678 let mut s = three_member_spec();
9679 s.contratos.push(WitContract {
9680 de: "payment".into(),
9681 para: "catalog".into(),
9682 wit: wit.into(),
9683 endpoint: None,
9684 subject: None,
9685 slot: None,
9686 });
9687 s.validate().unwrap_err()
9688 }
9689
9690 #[test]
9691 fn rejects_wit_with_uppercase_namespace() {
9692 // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
9693 // didn't match the lowercase `wasi:http/` prefix is_http() keys
9694 // off, so the dispatch fell through to the capability arm and
9695 // the contract silently rendered as an L4-only Cilium edge.
9696 // The new gate surfaces the uppercase typo at validate time
9697 // with the offending `:wit` named.
9698 let err = contrato_wit_err("WASI:http/proxy");
9699 assert!(
9700 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9701 if wit == "WASI:http/proxy" && reason.contains("lowercase")),
9702 "got {err:?}"
9703 );
9704 }
9705
9706 #[test]
9707 fn rejects_wit_with_hyphen_for_colon_typo() {
9708 // The canonical "I forgot the `:` separator" typo — pre-gate
9709 // this passed as Capability silently, so the renderer emitted
9710 // an L4-only policy where the author expected L7 HTTP rules.
9711 let err = contrato_wit_err("wasi-http/proxy");
9712 assert!(
9713 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9714 if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
9715 "got {err:?}"
9716 );
9717 }
9718
9719 #[test]
9720 fn rejects_wit_with_multiple_colons() {
9721 // Doubled `:` — the namespace/package split has nowhere to
9722 // anchor, so the dispatch silently demotes to Capability.
9723 let err = contrato_wit_err("wasi:http:proxy");
9724 assert!(
9725 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9726 if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
9727 "got {err:?}"
9728 );
9729 }
9730
9731 #[test]
9732 fn rejects_wit_with_empty_package() {
9733 // `wasi:` — namespace alone with no package. Pre-gate this
9734 // failed neither the is_http nor is_pubsub nor is_store
9735 // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
9736 // a bare `wasi:`), so it silently demoted to Capability.
9737 let err = contrato_wit_err("wasi:");
9738 assert!(
9739 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9740 if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
9741 "got {err:?}"
9742 );
9743 }
9744
9745 #[test]
9746 fn rejects_wit_with_underscore() {
9747 // Underscore — WIT identifiers are kebab-case, same rule
9748 // DNS-1123 enforces on its peer axes. The diagnostic carries
9749 // the explicit "use `-` instead" remediation.
9750 let err = contrato_wit_err("wasi:http_proxy");
9751 assert!(
9752 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9753 if wit == "wasi:http_proxy" && reason.contains('_')),
9754 "got {err:?}"
9755 );
9756 }
9757
9758 #[test]
9759 fn rejects_wit_with_whitespace() {
9760 // Whitespace mid-token — the prefix check matches but the
9761 // package-and-onward parse silently demoted to Capability.
9762 let err = contrato_wit_err("wasi:http proxy");
9763 assert!(
9764 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9765 if wit == "wasi:http proxy" && reason.contains("whitespace")),
9766 "got {err:?}"
9767 );
9768 }
9769
9770 #[test]
9771 fn rejects_wit_with_non_ascii() {
9772 // Un-percent-encoded non-ASCII byte — the canonical "I copied
9773 // the package name from a doc with smart quotes / accented
9774 // characters" footgun.
9775 let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
9776 assert!(
9777 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9778 if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
9779 "got {err:?}"
9780 );
9781 }
9782
9783 #[test]
9784 fn rejects_wit_with_consecutive_hyphens() {
9785 // `pub--sub` — WIT identifiers join words with single hyphens.
9786 let err = contrato_wit_err("nats:pub--sub");
9787 assert!(
9788 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9789 if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
9790 "got {err:?}"
9791 );
9792 }
9793
9794 #[test]
9795 fn rejects_wit_with_trailing_at_no_version() {
9796 // `wasi:http/proxy@` — the version-suffix author started to
9797 // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
9798 // parser would reject this; surface it at validate time.
9799 let err = contrato_wit_err("wasi:http/proxy@");
9800 assert!(
9801 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9802 if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
9803 "got {err:?}"
9804 );
9805 }
9806
9807 #[test]
9808 fn rejects_wit_too_long() {
9809 // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
9810 // The legitimate-shape arms all pass (lowercase, single `:`,
9811 // kebab-case identifiers); only the cap arm fires. Surfaces
9812 // the paste-from-binary / accidental-multi-line-blob landing
9813 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
9814 // on the peer axis.
9815 let big = format!("wasi:{}", "a".repeat(124));
9816 assert_eq!(big.len(), 129);
9817 let err = contrato_wit_err(&big);
9818 assert!(
9819 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9820 if wit == &big && reason.contains("max length of 128")),
9821 "got {err:?}"
9822 );
9823 }
9824
9825 #[test]
9826 fn wit_max_length_validates() {
9827 // 128-byte WIT reference — exactly the cap. Boundary pin:
9828 // drift in the cap surfaces here and at `rejects_wit_too_long`
9829 // simultaneously, mirroring
9830 // `http_contrato_endpoint_max_length_validates` on the peer
9831 // axis.
9832 let big = format!("wasi:{}", "a".repeat(123));
9833 assert_eq!(big.len(), 128);
9834 let mut s = three_member_spec();
9835 s.contratos.push(WitContract {
9836 de: "payment".into(),
9837 para: "catalog".into(),
9838 wit: big,
9839 endpoint: None,
9840 subject: None,
9841 slot: None,
9842 });
9843 s.validate().unwrap();
9844 }
9845
9846 #[test]
9847 fn wit_accepts_canonical_forms_at_aplicacao_layer() {
9848 // Positive-set sweep through the AplicacaoSpec::validate
9849 // surface (rather than the substrate-side predicate directly)
9850 // — pins every shape the existing test fixtures + the
9851 // checkout-aplicacao example carry, so the gate's accept-set
9852 // matches the substrate's emit-set. Drift between this list
9853 // and `render::tests::wit_world_ref_accepts_canonical_forms`
9854 // surfaces at the substrate layer's positive sweep — one
9855 // source of truth for the rule.
9856 for wit in [
9857 "wasi:http/proxy",
9858 "wasi:keyvalue/store",
9859 "nats:pub-sub",
9860 "kafka:topic",
9861 "custom:exchange",
9862 "pleme:cap/audit",
9863 "wasi:http/proxy@0.2.0",
9864 ] {
9865 // Payload field paired to the dispatched WIT shape so the
9866 // shape-↔-target arm doesn't fire instead of the wit-shape
9867 // arm we're exercising. Routes off the same
9868 // `wit_shape_is_http` / `wit_shape_is_pubsub` /
9869 // `wit_shape_is_store` free functions the production
9870 // `WitContract::is_http` / `is_pubsub` / `is_store`
9871 // methods delegate to (both consult the lifted
9872 // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
9873 // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
9874 // future prefix addition to the routing accept-set
9875 // reaches this test's payload-dispatch arm by
9876 // construction — no per-test-site drift can hide a
9877 // shape-→-target-slot mismatch that would silently
9878 // demote a canonical `:wit` value to the
9879 // `(None, None, None)` capability-only arm and let the
9880 // `AplicacaoSpec::validate` positive sweep pass on a
9881 // shape it should exercise as HTTP / pub-sub / store.
9882 let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
9883 (Some("/x".into()), None, None)
9884 } else if wit_shape_is_pubsub(wit) {
9885 (None, Some("topic.x".into()), None)
9886 } else if wit_shape_is_store(wit) {
9887 (None, None, Some("bucket/$key".into()))
9888 } else {
9889 (None, None, None)
9890 };
9891 let mut s = three_member_spec();
9892 s.contratos.push(WitContract {
9893 de: "payment".into(),
9894 para: "catalog".into(),
9895 wit: wit.into(),
9896 endpoint,
9897 subject,
9898 slot,
9899 });
9900 s.validate()
9901 .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
9902 }
9903 }
9904
9905 #[test]
9906 fn wit_shape_predicates_accept_canonical_prefix_set() {
9907 // Positive-set sweep pinning every prefix in
9908 // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
9909 // WIT_STORE_SHAPE_PREFIXES against the three free-function
9910 // dispatch predicates. The six prefixes are the load-bearing
9911 // routing keys the substrate's WIT-shape dispatch consults
9912 // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
9913 // key/value-store-slot admission); any drift between the
9914 // free-function accept-set and this list surfaces here
9915 // rather than at apply time as a silent
9916 // shape-→-capability-only demotion.
9917 assert!(wit_shape_is_http("wasi:http/proxy"));
9918 assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
9919 assert!(wit_shape_is_http("http:incoming"));
9920
9921 assert!(wit_shape_is_pubsub("nats:pub-sub"));
9922 assert!(wit_shape_is_pubsub("kafka:topic"));
9923
9924 assert!(wit_shape_is_store("wasi:keyvalue/store"));
9925 assert!(wit_shape_is_store("kv:cache/session"));
9926 }
9927
9928 #[test]
9929 fn wit_shape_predicates_reject_uncanonical_forms() {
9930 // Negative-set pin: the six canonical prefixes are
9931 // lowercase-only (mirrors the `is_wit_world_ref` substrate
9932 // predicate's lowercase invariant — see its docstring on the
9933 // "I thought I had L7 HTTP routing, got L4-only" footgun).
9934 // The empty string, an uppercase-prefixed form, a hyphen-
9935 // instead-of-colon typo, and a bare kebab identifier all miss
9936 // every shape arm — reachable-by-construction only via the
9937 // `is_wit_world_ref` gate that admission-checks the `:wit`
9938 // value first, but pinned here so any future
9939 // free-function change (e.g. a case-insensitive
9940 // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
9941 // this unit level.
9942 for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
9943 assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
9944 assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
9945 assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
9946 }
9947 }
9948
9949 #[test]
9950 fn wit_shape_predicates_partition_canonical_set() {
9951 // Every canonical prefix routes to exactly one shape arm —
9952 // the three prefix sets are pairwise disjoint. Pins the
9953 // routing property [`WitContract::target`] relies on: an
9954 // `is_http()` return of `true` guarantees `is_pubsub()` and
9955 // `is_store()` return `false`, so the shape-→-target-slot
9956 // dispatch (endpoint vs subject vs slot) is unambiguous.
9957 // Drift (e.g. a future `"kv:"` moved into the HTTP set
9958 // without removal from the store set) would silently route
9959 // one prefix to two arms and the first-matching-arm order
9960 // becomes load-bearing — this pin surfaces it as a build
9961 // error instead.
9962 for prefix in WIT_HTTP_SHAPE_PREFIXES {
9963 let sample = format!("{prefix}x");
9964 assert!(wit_shape_is_http(&sample));
9965 assert!(!wit_shape_is_pubsub(&sample));
9966 assert!(!wit_shape_is_store(&sample));
9967 }
9968 for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
9969 let sample = format!("{prefix}x");
9970 assert!(!wit_shape_is_http(&sample));
9971 assert!(wit_shape_is_pubsub(&sample));
9972 assert!(!wit_shape_is_store(&sample));
9973 }
9974 for prefix in WIT_STORE_SHAPE_PREFIXES {
9975 let sample = format!("{prefix}x");
9976 assert!(!wit_shape_is_http(&sample));
9977 assert!(!wit_shape_is_pubsub(&sample));
9978 assert!(wit_shape_is_store(&sample));
9979 }
9980 }
9981
9982 #[test]
9983 fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
9984 // Positive pin: [`wit_shape_matches`] is exactly the
9985 // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
9986 // parameterized on the accept-set. Two-prefix accept-set,
9987 // one-prefix accept-set, and empty accept-set (which must
9988 // reject everything, including the empty string — an empty
9989 // `any()` fold returns `false`) all pinned so a future
9990 // reimplementation that swaps `starts_with` for `contains`,
9991 // `==`, or a case-folded comparator surfaces at unit-test
9992 // time.
9993 let two = &["wasi:http/", "http:"];
9994 assert!(wit_shape_matches("wasi:http/proxy", two));
9995 assert!(wit_shape_matches("http:incoming", two));
9996 assert!(!wit_shape_matches("wasi:keyvalue/store", two));
9997
9998 let one = &["nats:"];
9999 assert!(wit_shape_matches("nats:pub-sub", one));
10000 assert!(!wit_shape_matches("kafka:topic", one));
10001
10002 // Empty accept-set matches nothing — the identity element
10003 // for the disjunctive `any()` fold across the prefix set.
10004 // Reachable via a future `wit_shape_is_<name>` const paired
10005 // to a still-empty prefix table on a nascent shape-arm draft.
10006 let empty: &[&str] = &[];
10007 assert!(!wit_shape_matches("wasi:http/proxy", empty));
10008 assert!(!wit_shape_matches("", empty));
10009
10010 // starts_with, not contains: a prefix embedded mid-string
10011 // never matches. Pins the routing invariant [`WitContract::target`]
10012 // relies on (an authored `:wit "custom:wasi:http/"` string
10013 // does not silently route through the HTTP arm just because
10014 // it happens to contain the canonical HTTP prefix).
10015 assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
10016 }
10017
10018 #[test]
10019 fn wit_shape_predicates_delegate_to_wit_shape_matches() {
10020 // Equivalence pin: each per-shape predicate is exactly
10021 // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
10022 // every canonical prefix + the empty string + one negative
10023 // sample against every peer so a future predicate that grew
10024 // its own inline `iter().any(starts_with)` (rather than
10025 // delegating through the lifted combinator) drifts loudly here
10026 // — the peer-const table's contents must agree with the
10027 // predicate's accept-set by construction.
10028 let samples = [
10029 String::new(),
10030 "wasi:http/proxy".to_string(),
10031 "http:incoming".to_string(),
10032 "nats:pub-sub".to_string(),
10033 "kafka:topic".to_string(),
10034 "wasi:keyvalue/store".to_string(),
10035 "kv:cache/session".to_string(),
10036 "custom-shape".to_string(),
10037 "WASI:HTTP/proxy".to_string(),
10038 ];
10039 for wit in &samples {
10040 assert_eq!(
10041 wit_shape_is_http(wit),
10042 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
10043 "wit_shape_is_http drifted from combinator on {wit:?}",
10044 );
10045 assert_eq!(
10046 wit_shape_is_pubsub(wit),
10047 wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
10048 "wit_shape_is_pubsub drifted from combinator on {wit:?}",
10049 );
10050 assert_eq!(
10051 wit_shape_is_store(wit),
10052 wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
10053 "wit_shape_is_store drifted from combinator on {wit:?}",
10054 );
10055 }
10056 }
10057
10058 #[test]
10059 fn wit_contract_shape_methods_delegate_to_free_functions() {
10060 // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
10061 // `is_store` are `&self` conveniences on top of the free
10062 // functions — for every canonical prefix the method's return
10063 // matches its free-function peer. Sweeps the union of the
10064 // three prefix sets so a future method that grew its own
10065 // inline prefix logic (rather than delegating) drifts loudly
10066 // here on the first prefix the free function accepts and the
10067 // method doesn't.
10068 for shape_set in [
10069 WIT_HTTP_SHAPE_PREFIXES,
10070 WIT_PUBSUB_SHAPE_PREFIXES,
10071 WIT_STORE_SHAPE_PREFIXES,
10072 ] {
10073 for prefix in shape_set {
10074 let c = WitContract {
10075 de: "cart".into(),
10076 para: "catalog".into(),
10077 wit: format!("{prefix}x"),
10078 endpoint: None,
10079 subject: None,
10080 slot: None,
10081 };
10082 assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
10083 assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
10084 assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
10085 }
10086 }
10087 }
10088
10089 #[test]
10090 fn empty_wit_takes_precedence_over_invalid() {
10091 // Ordering pin: `EmptyWit` is the more self-locating
10092 // diagnostic on `""` and must lead — the value-shape gate is
10093 // only reached after the empty-check fires. Mirrors
10094 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10095 // the peer payload axis.
10096 let mut s = three_member_spec();
10097 s.contratos.push(WitContract {
10098 de: "payment".into(),
10099 para: "catalog".into(),
10100 wit: String::new(),
10101 endpoint: None,
10102 subject: None,
10103 slot: None,
10104 });
10105 let err = s.validate().unwrap_err();
10106 assert!(
10107 matches!(err, AplicacaoError::EmptyWit { .. }),
10108 "got {err:?}"
10109 );
10110 }
10111
10112 #[test]
10113 fn wit_invalid_fires_before_payload_shape_arm() {
10114 // Ordering pin: a malformed `:wit` surfaces *its own*
10115 // diagnostic (which names the offending wit verbatim) before
10116 // any payload-field check — a contrato whose wit is
10117 // structurally invalid AND carries a wrong target field
10118 // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
10119 // because the dispatch on the wit is what decides which
10120 // payload field is "right" in the first place. Without this
10121 // ordering, the author would see "wrong target field" for a
10122 // wit that hasn't even been parsed, which doesn't name the
10123 // root cause.
10124 let mut s = three_member_spec();
10125 s.contratos.push(WitContract {
10126 de: "payment".into(),
10127 para: "catalog".into(),
10128 // Hyphen-for-colon typo + endpoint set: pre-gate this
10129 // raised `ContratoWrongTarget { expected: "none" }` (the
10130 // Capability arm rejecting the endpoint), masking the
10131 // real authoring mistake (the wit isn't `wasi:http/proxy`).
10132 wit: "wasi-http/proxy".into(),
10133 endpoint: Some("/x".into()),
10134 subject: None,
10135 slot: None,
10136 });
10137 let err = s.validate().unwrap_err();
10138 assert!(
10139 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
10140 if wit == "wasi-http/proxy"),
10141 "got {err:?}"
10142 );
10143 }
10144
10145 #[test]
10146 fn wit_invalid_diagnostic_carries_offending_wit() {
10147 // Diagnostic-shape pin — the offending `:wit` + `:de` +
10148 // `:para` + a non-empty reason flow through verbatim so the
10149 // author can grep their caixa.lisp for the offending contrato
10150 // block and fix it in one edit. Same shape as
10151 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
10152 let err = contrato_wit_err("WASI:HTTP/proxy");
10153 match err {
10154 AplicacaoError::ContratoWitInvalid {
10155 de,
10156 para,
10157 wit,
10158 reason,
10159 } => {
10160 assert_eq!(de, "payment");
10161 assert_eq!(para, "catalog");
10162 assert_eq!(wit, "WASI:HTTP/proxy");
10163 assert!(!reason.is_empty(), "reason field must be non-empty");
10164 }
10165 other => panic!("expected ContratoWitInvalid, got {other:?}"),
10166 }
10167 }
10168
10169 // ── :contratos :subject value-shape gate ─────────────────────────────
10170 //
10171 // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
10172 // suites on the peer payload axes. Until this gate landed
10173 // `WitContract::target()` only refused the empty string; a
10174 // structurally invalid subject silently passed validate and the
10175 // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
10176 // Subject'` on publish / subscribe, or as a silent message drop,
10177 // far from the source caixa.lisp. Every authoring footgun the
10178 // NATS server's subject parser would catch on admission now
10179 // becomes a caixa-build-time `ContratoSubjectInvalid` with the
10180 // offending `:subject` + `:de` + `:para` named verbatim. Same
10181 // diagnostic shape as `ContratoEndpointInvalid` /
10182 // `ContratoWitInvalid` on the peer payload axes; same shared
10183 // predicate (`crate::render::is_nats_subject`) ensures drift
10184 // between any two axes' rule enforcement is a build error at the
10185 // predicate, not piecemeal across renderers.
10186
10187 fn contrato_subject_err(subject: &str) -> AplicacaoError {
10188 // Fresh spec per call so the new contract doesn't collide on
10189 // identity with `three_member_spec`'s pre-existing entries.
10190 // The new edge uses `(payment, catalog)` — a pair the fixture
10191 // doesn't already declare — with `:wit "nats:pub-sub"` and the
10192 // varying `:subject`, so the subject-shape gate fires cleanly
10193 // after the wit-shape gate (which `"nats:pub-sub"` passes).
10194 let mut s = three_member_spec();
10195 s.contratos.push(WitContract {
10196 de: "payment".into(),
10197 para: "catalog".into(),
10198 wit: "nats:pub-sub".into(),
10199 endpoint: None,
10200 subject: Some(subject.into()),
10201 slot: None,
10202 });
10203 s.validate().unwrap_err()
10204 }
10205
10206 #[test]
10207 fn rejects_pubsub_contrato_subject_with_whitespace() {
10208 // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
10209 // landed at the NATS server as a malformed subject the parser
10210 // rejects with `-ERR 'Invalid Subject'`. Now caught at the
10211 // source caixa.lisp.
10212 let err = contrato_subject_err("foo bar");
10213 assert!(
10214 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10215 if subject == "foo bar" && reason.contains("whitespace")),
10216 "got {err:?}"
10217 );
10218 }
10219
10220 #[test]
10221 fn rejects_pubsub_contrato_subject_with_control_char() {
10222 let err = contrato_subject_err("foo\x01bar");
10223 assert!(
10224 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10225 if subject == "foo\x01bar" && reason.contains("control character")),
10226 "got {err:?}"
10227 );
10228 }
10229
10230 #[test]
10231 fn rejects_pubsub_contrato_subject_with_non_ascii() {
10232 // Un-percent-encoded non-ASCII byte — the canonical "I copied
10233 // the subject from a doc with smart quotes / accented
10234 // characters" footgun.
10235 let err = contrato_subject_err("foo.caf\u{e9}");
10236 assert!(
10237 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10238 if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
10239 "got {err:?}"
10240 );
10241 }
10242
10243 #[test]
10244 fn rejects_pubsub_contrato_subject_with_leading_dot() {
10245 // Empty leading token — NATS rejects.
10246 let err = contrato_subject_err(".foo");
10247 assert!(
10248 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10249 if subject == ".foo" && reason.contains("must not start with `.`")),
10250 "got {err:?}"
10251 );
10252 }
10253
10254 #[test]
10255 fn rejects_pubsub_contrato_subject_with_trailing_dot() {
10256 // Empty trailing token — NATS rejects. The remediation
10257 // (use `>` instead) is in the reason string.
10258 let err = contrato_subject_err("foo.");
10259 assert!(
10260 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10261 if subject == "foo." && reason.contains("must not end with `.`")),
10262 "got {err:?}"
10263 );
10264 }
10265
10266 #[test]
10267 fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
10268 // The canonical "I forgot to fill in the middle segment"
10269 // typo — `"foo..bar"`. NATS rejects empty tokens.
10270 let err = contrato_subject_err("foo..bar");
10271 assert!(
10272 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10273 if subject == "foo..bar" && reason.contains("consecutive `.`")),
10274 "got {err:?}"
10275 );
10276 }
10277
10278 #[test]
10279 fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
10280 // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
10281 // as the final segment. Pre-gate this passed as a typed edge
10282 // and surfaced at runtime as a NATS subscribe rejection.
10283 let err = contrato_subject_err("foo.>.bar");
10284 assert!(
10285 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10286 if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
10287 "got {err:?}"
10288 );
10289 }
10290
10291 #[test]
10292 fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
10293 // `foo*.bar` — NATS wildcards are standalone tokens. The
10294 // remediation is in the reason string.
10295 let err = contrato_subject_err("foo*.bar");
10296 assert!(
10297 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10298 if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
10299 "got {err:?}"
10300 );
10301 }
10302
10303 #[test]
10304 fn rejects_pubsub_contrato_subject_with_invalid_char() {
10305 // `foo,bar` — comma is not a valid NATS subject character.
10306 // Pinned separately from the wildcard arms so the invalid-
10307 // character diagnostic is in force.
10308 let err = contrato_subject_err("foo,bar");
10309 assert!(
10310 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10311 if subject == "foo,bar" && reason.contains("invalid character")),
10312 "got {err:?}"
10313 );
10314 }
10315
10316 #[test]
10317 fn rejects_pubsub_contrato_subject_too_long() {
10318 // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
10319 // The legitimate-shape arms all pass (one all-`a` token, no
10320 // `.`, no wildcards); only the cap arm fires. Surfaces the
10321 // paste-from-binary / accidental-multi-line-blob landing
10322 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10323 // on the peer axis.
10324 let big = "a".repeat(257);
10325 assert_eq!(big.len(), 257);
10326 let err = contrato_subject_err(&big);
10327 assert!(
10328 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10329 if subject == &big && reason.contains("max length of 256")),
10330 "got {err:?}"
10331 );
10332 }
10333
10334 #[test]
10335 fn pubsub_contrato_subject_max_length_validates() {
10336 // 256-byte subject — exactly the cap. Boundary pin: drift in
10337 // the cap surfaces here and at
10338 // `rejects_pubsub_contrato_subject_too_long` simultaneously,
10339 // mirroring `http_contrato_endpoint_max_length_validates` and
10340 // `wit_max_length_validates` on the peer axes.
10341 let big = "a".repeat(256);
10342 assert_eq!(big.len(), 256);
10343 let mut s = three_member_spec();
10344 s.contratos.push(WitContract {
10345 de: "payment".into(),
10346 para: "catalog".into(),
10347 wit: "nats:pub-sub".into(),
10348 endpoint: None,
10349 subject: Some(big),
10350 slot: None,
10351 });
10352 s.validate().unwrap();
10353 }
10354
10355 #[test]
10356 fn pubsub_contrato_subject_accepts_canonical_forms() {
10357 // Positive-set sweep: every canonical NATS subject shape the
10358 // substrate-side `is_nats_subject` predicate accepts (the
10359 // multi-dot `events.order.charged`, the snake_case / kebab-
10360 // case / mixed-case tokens, the digit-bearing tokens, the
10361 // single-token wildcard `*` at every segment position, and
10362 // the trailing `>` multi-token wildcard) must remain a valid
10363 // contrato subject too. Drift between this list and the
10364 // substrate-side `nats_subject_accepts_canonical_forms` sweep
10365 // surfaces at the shared predicate — one source of truth.
10366 // Uses a fresh `(payment, catalog)` edge so none of the swept
10367 // subjects collide with the pre-existing entries in
10368 // `three_member_spec`.
10369 for subject in [
10370 "checkout.events.charge.failed",
10371 "rio.events.order.charged",
10372 "orders",
10373 "orders.123",
10374 "snake_case.token",
10375 "kebab-case.token",
10376 "MixedCase.Token",
10377 "orders.*.charged",
10378 "*.events.*",
10379 "orders.>",
10380 ] {
10381 let mut s = three_member_spec();
10382 s.contratos.push(WitContract {
10383 de: "payment".into(),
10384 para: "catalog".into(),
10385 wit: "nats:pub-sub".into(),
10386 endpoint: None,
10387 subject: Some(subject.into()),
10388 slot: None,
10389 });
10390 s.validate()
10391 .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
10392 }
10393 }
10394
10395 #[test]
10396 fn contrato_subject_empty_takes_precedence_over_invalid() {
10397 // Ordering pin: `ContratoSubjectEmpty` is the more self-
10398 // locating diagnostic on `""` and must lead — the value-shape
10399 // gate is only reached after the empty-check fires. Mirrors
10400 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10401 // the peer payload axis.
10402 let mut s = three_member_spec();
10403 s.contratos.push(WitContract {
10404 de: "payment".into(),
10405 para: "catalog".into(),
10406 wit: "nats:pub-sub".into(),
10407 endpoint: None,
10408 subject: Some(String::new()),
10409 slot: None,
10410 });
10411 let err = s.validate().unwrap_err();
10412 assert!(
10413 matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
10414 "got {err:?}"
10415 );
10416 }
10417
10418 #[test]
10419 fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
10420 // Diagnostic-shape pin — the offending `:subject` + `:de` +
10421 // `:para` + a non-empty reason flow through verbatim so the
10422 // author can grep their caixa.lisp for the offending contrato
10423 // block and fix it in one edit. Same shape as
10424 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10425 // and `wit_invalid_diagnostic_carries_offending_wit`.
10426 let err = contrato_subject_err("foo..bar");
10427 match err {
10428 AplicacaoError::ContratoSubjectInvalid {
10429 de,
10430 para,
10431 subject,
10432 reason,
10433 } => {
10434 assert_eq!(de, "payment");
10435 assert_eq!(para, "catalog");
10436 assert_eq!(subject, "foo..bar");
10437 assert!(!reason.is_empty(), "reason field must be non-empty");
10438 }
10439 other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
10440 }
10441 }
10442
10443 #[test]
10444 fn target_view_pubsub_subject_passes_through_to_typed_view() {
10445 // The compounding theorem on the pub-sub axis: every
10446 // `WitTarget::PubSub { subject }` returned by `target()` carries
10447 // a NATS-server-accepted subject. Renderers downstream of
10448 // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
10449 // NATS Stream/Consumer CR emitter, the future `feira app graph`
10450 // view's subject labeller) can rely on this without re-checking
10451 // — the type system carries the proof. Mirrors
10452 // `target_view_payload_is_guaranteed_nonempty_after_target_call`
10453 // on the peer axes.
10454 let nats = WitContract {
10455 de: "a".into(),
10456 para: "b".into(),
10457 wit: "nats:pub-sub".into(),
10458 endpoint: None,
10459 subject: Some("orders.events.*.charged".into()),
10460 slot: None,
10461 };
10462 match nats.target().unwrap() {
10463 WitTarget::PubSub { subject } => {
10464 assert_eq!(subject, "orders.events.*.charged");
10465 }
10466 other => panic!("expected PubSub, got {other:?}"),
10467 }
10468 }
10469
10470 // ── :contratos :slot value-shape gate ────────────────────────────────
10471 //
10472 // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
10473 // (63e18a0) value-shape suites on the peer payload axes. Until this
10474 // gate landed `WitContract::target()` only refused the empty string
10475 // for the Store arm; a structurally invalid slot (raw whitespace,
10476 // control character, non-ASCII byte, paste-from-binary multi-line
10477 // blob) silently passed validate and surfaced at runtime as a
10478 // per-backend kv write rejection or a silent next-read corruption,
10479 // far from the source caixa.lisp with no field naming which
10480 // `:contratos` edge carried the typo. Every authoring footgun the
10481 // kv backend intersection-floor would catch on write now becomes a
10482 // caixa-build-time `ContratoSlotInvalid` with the offending
10483 // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
10484 // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
10485 // peer payload axes; same shared predicate
10486 // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
10487 // any two axes' rule enforcement is a build error at the
10488 // predicate, not piecemeal across renderers. Closes the typed
10489 // payload-axis value-shape trajectory across all three legs of the
10490 // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
10491
10492 fn contrato_slot_err(slot: &str) -> AplicacaoError {
10493 // Fresh spec per call so the new contract doesn't collide on
10494 // identity with `three_member_spec`'s pre-existing entries
10495 // and doesn't close a synchronous cycle the cycle detector
10496 // would reject before the slot-shape gate fires. The new edge
10497 // uses `(payment, catalog)` — a pair the fixture doesn't
10498 // already declare in either direction (the fixture carries
10499 // `cart -> catalog` and `cart -> payment`, so `payment ->
10500 // catalog` doesn't form a cycle on the sync subgraph) — with
10501 // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
10502 // slot-shape gate fires cleanly after the wit-shape gate
10503 // (which `"wasi:keyvalue/store"` passes). Same edge pair the
10504 // peer `contrato_subject_err` helper uses (63e18a0).
10505 let mut s = three_member_spec();
10506 s.contratos.push(WitContract {
10507 de: "payment".into(),
10508 para: "catalog".into(),
10509 wit: "wasi:keyvalue/store".into(),
10510 endpoint: None,
10511 subject: None,
10512 slot: Some(slot.into()),
10513 });
10514 s.validate().unwrap_err()
10515 }
10516
10517 #[test]
10518 fn rejects_store_contrato_slot_with_whitespace() {
10519 // Fail-before-pass-after pin — pre-gate `"check out/$order"`
10520 // silently landed at the kv backend with whitespace whose
10521 // runtime behavior varies unpredictably across backends (etcd
10522 // accepts, Redis accepts then breaks on next CLI op, DynamoDB
10523 // rejects on write). Now caught at the source caixa.lisp.
10524 let err = contrato_slot_err("check out/$order");
10525 assert!(
10526 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10527 if slot == "check out/$order" && reason.contains("whitespace")),
10528 "got {err:?}"
10529 );
10530 }
10531
10532 #[test]
10533 fn rejects_store_contrato_slot_with_tab() {
10534 // Tab byte arm-pinned separately from the space arm so a
10535 // future relaxation that admits one but not the other surfaces
10536 // here.
10537 let err = contrato_slot_err("check\tout");
10538 assert!(
10539 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10540 if slot == "check\tout" && reason.contains("whitespace")),
10541 "got {err:?}"
10542 );
10543 }
10544
10545 #[test]
10546 fn rejects_store_contrato_slot_with_control_char() {
10547 // SOH (0x01) — distinct from the whitespace arm. Redis admits
10548 // and corrupts on RESP protocol framing; DynamoDB rejects on
10549 // write.
10550 let err = contrato_slot_err("checkout/\x01order");
10551 assert!(
10552 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10553 if slot == "checkout/\x01order" && reason.contains("control character")),
10554 "got {err:?}"
10555 );
10556 }
10557
10558 #[test]
10559 fn rejects_store_contrato_slot_with_newline() {
10560 // Embedded newline — the canonical "the paste-from-binary slug
10561 // spans multiple lines" footgun. Distinct from the whitespace
10562 // arm because `\n` is a control character (0x0A).
10563 let err = contrato_slot_err("checkout\norder");
10564 assert!(
10565 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10566 if slot == "checkout\norder" && reason.contains("control character")),
10567 "got {err:?}"
10568 );
10569 }
10570
10571 #[test]
10572 fn rejects_store_contrato_slot_with_non_ascii() {
10573 // Un-percent-encoded non-ASCII byte — the canonical "I copied
10574 // the slot from a doc with accented characters" footgun. Each
10575 // kv backend re-encodes non-ASCII differently (etcd preserves
10576 // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
10577 // rejects), so the typed slot's value set is the intersection-
10578 // floor every backend admits identically (printable ASCII).
10579 let err = contrato_slot_err("ch\u{e9}ckout/$order");
10580 assert!(
10581 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10582 if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
10583 "got {err:?}"
10584 );
10585 }
10586
10587 #[test]
10588 fn rejects_store_contrato_slot_too_long() {
10589 // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
10590 // legitimate-shape arms all pass (a single all-`a` token, no
10591 // separators); only the cap arm fires. Surfaces the paste-
10592 // from-binary / accidental-multi-line-blob landing footgun.
10593 // Mirrors `rejects_pubsub_contrato_subject_too_long` and
10594 // `rejects_http_contrato_endpoint_too_long` on the peer
10595 // payload axes.
10596 let big = "a".repeat(513);
10597 assert_eq!(big.len(), 513);
10598 let err = contrato_slot_err(&big);
10599 assert!(
10600 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10601 if slot == &big && reason.contains("max length of 512")),
10602 "got {err:?}"
10603 );
10604 }
10605
10606 #[test]
10607 fn store_contrato_slot_max_length_validates() {
10608 // 512-byte slot — exactly the cap. Boundary pin: drift in the
10609 // cap surfaces here and at `rejects_store_contrato_slot_too_long`
10610 // simultaneously, mirroring
10611 // `pubsub_contrato_subject_max_length_validates` and
10612 // `http_contrato_endpoint_max_length_validates` on the peer
10613 // payload axes.
10614 let big = "a".repeat(512);
10615 assert_eq!(big.len(), 512);
10616 let mut s = three_member_spec();
10617 s.contratos.push(WitContract {
10618 de: "payment".into(),
10619 para: "catalog".into(),
10620 wit: "wasi:keyvalue/store".into(),
10621 endpoint: None,
10622 subject: None,
10623 slot: Some(big),
10624 });
10625 s.validate().unwrap();
10626 }
10627
10628 #[test]
10629 fn store_contrato_slot_accepts_canonical_forms() {
10630 // Positive-set sweep: every canonical kv slot template the
10631 // substrate-side `is_wasi_keyvalue_slot` predicate accepts
10632 // (single-token identifiers, path-namespaced `$`-templates,
10633 // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
10634 // snake_case / kebab-case / MixedCase tokens, digit-bearing
10635 // tokens, percent-encoded fragments) must remain valid
10636 // contrato slots too. Drift between this list and the
10637 // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
10638 // surfaces at the shared predicate — one source of truth.
10639 // Uses a fresh `(payment, catalog)` edge so none of the swept
10640 // slots collide with the pre-existing entries in
10641 // `three_member_spec`.
10642 for slot in [
10643 "checkout",
10644 "checkout/$orderId",
10645 "users:{tenant}/{id}",
10646 "session.<sid>",
10647 "session.tokens.<sid>",
10648 "snake_case_key",
10649 "kebab-case-key",
10650 "MixedCase",
10651 "shard0",
10652 "v2/key",
10653 "users/caf%C3%A9",
10654 ] {
10655 let mut s = three_member_spec();
10656 s.contratos.push(WitContract {
10657 de: "payment".into(),
10658 para: "catalog".into(),
10659 wit: "wasi:keyvalue/store".into(),
10660 endpoint: None,
10661 subject: None,
10662 slot: Some(slot.into()),
10663 });
10664 s.validate()
10665 .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
10666 }
10667 }
10668
10669 #[test]
10670 fn contrato_slot_empty_takes_precedence_over_invalid() {
10671 // Ordering pin: `ContratoSlotEmpty` is the more self-locating
10672 // diagnostic on `""` and must lead — the value-shape gate is
10673 // only reached after the empty-check fires. Mirrors
10674 // `contrato_subject_empty_takes_precedence_over_invalid` and
10675 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10676 // the peer payload axes.
10677 let mut s = three_member_spec();
10678 s.contratos.push(WitContract {
10679 de: "payment".into(),
10680 para: "catalog".into(),
10681 wit: "wasi:keyvalue/store".into(),
10682 endpoint: None,
10683 subject: None,
10684 slot: Some(String::new()),
10685 });
10686 let err = s.validate().unwrap_err();
10687 assert!(
10688 matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
10689 "got {err:?}"
10690 );
10691 }
10692
10693 #[test]
10694 fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
10695 // Diagnostic-shape pin — the offending `:slot` + `:de` +
10696 // `:para` + a non-empty reason flow through verbatim so the
10697 // author can grep their caixa.lisp for the offending contrato
10698 // block and fix it in one edit. Same shape as
10699 // `contrato_subject_invalid_diagnostic_carries_offending_subject`
10700 // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10701 // on the peer payload axes.
10702 let err = contrato_slot_err("check out/$order");
10703 match err {
10704 AplicacaoError::ContratoSlotInvalid {
10705 de,
10706 para,
10707 slot,
10708 reason,
10709 } => {
10710 assert_eq!(de, "payment");
10711 assert_eq!(para, "catalog");
10712 assert_eq!(slot, "check out/$order");
10713 assert!(!reason.is_empty(), "reason field must be non-empty");
10714 }
10715 other => panic!("expected ContratoSlotInvalid, got {other:?}"),
10716 }
10717 }
10718
10719 #[test]
10720 fn target_view_store_slot_passes_through_to_typed_view() {
10721 // The compounding theorem on the store axis: every
10722 // `WitTarget::Store { slot }` returned by `target()` carries a
10723 // kv-backend-accepted slot template. Renderers downstream of
10724 // `typed_view()` (the future per-Servico `:capabilities
10725 // wasi:keyvalue/store` axis emitter, the future `feira app
10726 // graph` view's slot labeller, the future kv-provider CR
10727 // materializer) can rely on this without re-checking — the
10728 // type system carries the proof. Mirrors
10729 // `target_view_pubsub_subject_passes_through_to_typed_view` on
10730 // the peer payload axis.
10731 let store = WitContract {
10732 de: "a".into(),
10733 para: "b".into(),
10734 wit: "wasi:keyvalue/store".into(),
10735 endpoint: None,
10736 subject: None,
10737 slot: Some("checkout/$orderId".into()),
10738 };
10739 match store.target().unwrap() {
10740 WitTarget::Store { slot } => {
10741 assert_eq!(slot, "checkout/$orderId");
10742 }
10743 other => panic!("expected Store, got {other:?}"),
10744 }
10745 }
10746
10747 #[test]
10748 fn rejects_self_loop_in_synchronous_contratos() {
10749 // A synchronous self-edge (`cart → cart` over HTTP) is now
10750 // rejected by the dedicated `ContratoSelfLoop` gate — a precise
10751 // "this edge is degenerate" diagnostic — rather than incidentally
10752 // by the cycle detector framing it as a `["cart", "cart"]`
10753 // multi-node deadlock.
10754 let mut s = three_member_spec();
10755 s.contratos.push(contract_http("cart", "cart", "/loop"));
10756 let err = s.validate().unwrap_err();
10757 match err {
10758 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10759 assert_eq!(caixa, "cart");
10760 assert_eq!(wit, "wasi:http/proxy");
10761 }
10762 other => panic!("expected ContratoSelfLoop, got {other:?}"),
10763 }
10764 }
10765
10766 #[test]
10767 fn rejects_self_loop_in_pubsub_contratos() {
10768 // The cycle detector excludes pub-sub edges (acyclic by
10769 // construction), so before the explicit gate a `nats:pub-sub`
10770 // self-edge silently validated and rendered a self-allow CNP.
10771 // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
10772 let mut s = three_member_spec();
10773 s.contratos.push(WitContract {
10774 de: "payment".into(),
10775 para: "payment".into(),
10776 wit: "nats:pub-sub".into(),
10777 endpoint: None,
10778 subject: Some("rio.events.payment".into()),
10779 slot: None,
10780 });
10781 let err = s.validate().unwrap_err();
10782 match err {
10783 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10784 assert_eq!(caixa, "payment");
10785 assert_eq!(wit, "nats:pub-sub");
10786 }
10787 other => panic!("expected ContratoSelfLoop, got {other:?}"),
10788 }
10789 }
10790
10791 #[test]
10792 fn self_loop_fires_before_payload_shape_check() {
10793 // The structural "this edge can't exist" error precedes the
10794 // narrower payload-shape diagnostics: a self-edge carrying an
10795 // otherwise-malformed endpoint still reports ContratoSelfLoop,
10796 // not ContratoEndpointInvalid.
10797 let mut s = three_member_spec();
10798 s.contratos.push(WitContract {
10799 de: "cart".into(),
10800 para: "cart".into(),
10801 wit: "wasi:http/proxy".into(),
10802 endpoint: Some("not-absolute".into()),
10803 subject: None,
10804 slot: None,
10805 });
10806 match s.validate().unwrap_err() {
10807 AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
10808 other => panic!("expected ContratoSelfLoop, got {other:?}"),
10809 }
10810 }
10811
10812 #[test]
10813 fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
10814 // A self-edge naming a non-member reports the more fundamental
10815 // ContratoMemberMissing first (the member doesn't exist), so the
10816 // self-loop gate is reached only once both endpoints resolve.
10817 let mut s = three_member_spec();
10818 s.contratos.push(contract_http("ghost", "ghost", "/loop"));
10819 match s.validate().unwrap_err() {
10820 AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
10821 other => panic!("expected ContratoMemberMissing, got {other:?}"),
10822 }
10823 }
10824
10825 #[test]
10826 fn rejects_two_node_synchronous_cycle() {
10827 let mut s = three_member_spec();
10828 // existing edges: cart → catalog, cart → payment
10829 // adding catalog → cart closes a 2-cycle on the HTTP subgraph
10830 s.contratos
10831 .push(contract_http("catalog", "cart", "/refresh"));
10832 let err = s.validate().unwrap_err();
10833 match err {
10834 AplicacaoError::ContratoCycle { cycle } => {
10835 // Cycle traversal should mention both endpoints, with
10836 // the back-edge target appearing as both first and last
10837 // element to close the loop.
10838 assert!(cycle.len() >= 3);
10839 assert_eq!(cycle.first(), cycle.last());
10840 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
10841 assert!(body.contains("cart"));
10842 assert!(body.contains("catalog"));
10843 }
10844 other => panic!("expected ContratoCycle, got {other:?}"),
10845 }
10846 }
10847
10848 #[test]
10849 fn rejects_three_node_synchronous_cycle() {
10850 let mut s = three_member_spec();
10851 // Reset to a clean 3-cycle: catalog → cart → payment → catalog
10852 s.contratos = vec![
10853 contract_http("catalog", "cart", "/x"),
10854 contract_http("cart", "payment", "/y"),
10855 contract_http("payment", "catalog", "/z"),
10856 ];
10857 let err = s.validate().unwrap_err();
10858 match err {
10859 AplicacaoError::ContratoCycle { cycle } => {
10860 assert_eq!(cycle.first(), cycle.last());
10861 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
10862 assert_eq!(body.len(), 3);
10863 assert!(body.contains("cart"));
10864 assert!(body.contains("catalog"));
10865 assert!(body.contains("payment"));
10866 }
10867 other => panic!("expected ContratoCycle, got {other:?}"),
10868 }
10869 }
10870
10871 #[test]
10872 fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
10873 // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
10874 // "acyclic by construction" — so a cycle whose closing edge
10875 // is pub-sub should NOT raise ContratoCycle.
10876 let mut s = three_member_spec();
10877 s.contratos = vec![
10878 contract_http("catalog", "cart", "/x"),
10879 contract_http("cart", "payment", "/y"),
10880 // Closing edge is pub-sub — async; not a sync deadlock.
10881 WitContract {
10882 de: "payment".into(),
10883 para: "catalog".into(),
10884 wit: "nats:pub-sub".into(),
10885 endpoint: None,
10886 subject: Some("checkout.events.charge.completed".into()),
10887 slot: None,
10888 },
10889 ];
10890 s.validate().expect("pub-sub edge breaks the sync cycle");
10891 }
10892
10893 #[test]
10894 fn store_edge_counts_as_synchronous_for_cycle_detection() {
10895 // wasi:keyvalue/store is request/response; a cycle through one
10896 // *is* a sync deadlock, just like HTTP.
10897 let mut s = three_member_spec();
10898 s.contratos = vec![
10899 contract_http("catalog", "cart", "/x"),
10900 WitContract {
10901 de: "cart".into(),
10902 para: "catalog".into(),
10903 wit: "wasi:keyvalue/store".into(),
10904 endpoint: None,
10905 subject: None,
10906 slot: Some("session/$id".into()),
10907 },
10908 ];
10909 let err = s.validate().unwrap_err();
10910 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
10911 }
10912
10913 #[test]
10914 fn capability_edge_counts_as_synchronous_for_cycle_detection() {
10915 // Capability-only edges (unknown WIT shape, no payload) default
10916 // to synchronous — safer; authors with truly async capability
10917 // semantics can model them as pub-sub explicitly.
10918 let mut s = three_member_spec();
10919 s.contratos = vec![
10920 contract_http("catalog", "cart", "/x"),
10921 WitContract {
10922 de: "cart".into(),
10923 para: "catalog".into(),
10924 wit: "custom:exchange".into(),
10925 endpoint: None,
10926 subject: None,
10927 slot: None,
10928 },
10929 ];
10930 let err = s.validate().unwrap_err();
10931 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
10932 }
10933
10934 #[test]
10935 fn long_acyclic_chain_validates() {
10936 // A long sync chain (no back-edges) must validate even when
10937 // every node is reachable from the first.
10938 let mut s = three_member_spec();
10939 s.membros = vec![
10940 membro("a", "^0.1"),
10941 membro("b", "^0.1"),
10942 membro("c", "^0.1"),
10943 membro("d", "^0.1"),
10944 membro("e", "^0.1"),
10945 ];
10946 s.contratos = vec![
10947 contract_http("a", "b", "/1"),
10948 contract_http("b", "c", "/2"),
10949 contract_http("c", "d", "/3"),
10950 contract_http("d", "e", "/4"),
10951 ];
10952 s.entrada.as_mut().unwrap().para = "a".into();
10953 s.validate().unwrap();
10954 }
10955
10956 #[test]
10957 fn diamond_acyclic_validates() {
10958 // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
10959 let mut s = three_member_spec();
10960 s.membros = vec![
10961 membro("a", "^0.1"),
10962 membro("b", "^0.1"),
10963 membro("c", "^0.1"),
10964 membro("d", "^0.1"),
10965 ];
10966 s.contratos = vec![
10967 contract_http("a", "b", "/1"),
10968 contract_http("a", "c", "/2"),
10969 contract_http("b", "d", "/3"),
10970 contract_http("c", "d", "/4"),
10971 ];
10972 s.entrada.as_mut().unwrap().para = "a".into();
10973 s.validate().unwrap();
10974 }
10975
10976 // ── duplicate-`:contratos` build-error gate ──────────────────────────
10977
10978 #[test]
10979 fn rejects_duplicate_http_contrato() {
10980 // Fail-before-pass-after pin: the fixture's `cart → catalog`
10981 // HTTP edge appears once. Push an identical entry — same
10982 // (de, para, wit, endpoint) — and validate() must reject it.
10983 // Until this gate landed the typed surface accepted the
10984 // duplicate silently and caixa-mesh's `cilium_network_policies`
10985 // emitted two ``CiliumNetworkPolicy`` objects with identical
10986 // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
10987 // admission rejects on `kubectl apply` far from the source.
10988 let mut s = three_member_spec();
10989 s.contratos
10990 .push(contract_http("cart", "catalog", "/products/:id"));
10991 let err = s.validate().unwrap_err();
10992 assert!(
10993 matches!(
10994 err,
10995 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10996 if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
10997 ),
10998 "got {err:?}"
10999 );
11000 }
11001
11002 #[test]
11003 fn rejects_duplicate_pubsub_contrato() {
11004 // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
11005 // edges with identical (de, para, subject) are degenerate;
11006 // pin that the typed surface refuses both at validate time.
11007 let mut s = three_member_spec();
11008 let pubsub = WitContract {
11009 de: "payment".into(),
11010 para: "cart".into(),
11011 wit: "nats:pub-sub".into(),
11012 endpoint: None,
11013 subject: Some("checkout.events.charge.failed".into()),
11014 slot: None,
11015 };
11016 s.contratos.push(pubsub.clone());
11017 s.contratos.push(pubsub);
11018 let err = s.validate().unwrap_err();
11019 assert!(
11020 matches!(
11021 err,
11022 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11023 if de == "payment" && para == "cart" && wit == "nats:pub-sub"
11024 ),
11025 "got {err:?}"
11026 );
11027 }
11028
11029 #[test]
11030 fn rejects_duplicate_store_contrato() {
11031 // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
11032 // edges with identical (de, para, slot) collapse to one mesh-
11033 // policy edge; pin the build error.
11034 let mut s = three_member_spec();
11035 let store = WitContract {
11036 de: "cart".into(),
11037 para: "payment".into(),
11038 wit: "wasi:keyvalue/store".into(),
11039 endpoint: None,
11040 subject: None,
11041 slot: Some("checkout/$orderId".into()),
11042 };
11043 // Drop the conflicting HTTP `cart → payment` edge from the
11044 // fixture so the duplicate-store pair is the only one
11045 // distinguishable on this pair.
11046 s.contratos
11047 .retain(|c| !(c.de == "cart" && c.para == "payment"));
11048 s.contratos.push(store.clone());
11049 s.contratos.push(store);
11050 let err = s.validate().unwrap_err();
11051 assert!(
11052 matches!(
11053 err,
11054 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11055 if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
11056 ),
11057 "got {err:?}"
11058 );
11059 }
11060
11061 #[test]
11062 fn rejects_duplicate_capability_contrato() {
11063 // Same gate on the pure-capability axis (no payload selector).
11064 // Two contracts with identical (de, para, wit) and no
11065 // endpoint/subject/slot are duplicate edges; pin so a future
11066 // `target_label` change can't accidentally collapse the
11067 // capability arm into a None-shaped key that compares equal
11068 // to a populated one.
11069 let mut s = three_member_spec();
11070 let capability = WitContract {
11071 de: "cart".into(),
11072 para: "catalog".into(),
11073 wit: "pleme:cap/audit".into(),
11074 endpoint: None,
11075 subject: None,
11076 slot: None,
11077 };
11078 s.contratos.push(capability.clone());
11079 s.contratos.push(capability);
11080 let err = s.validate().unwrap_err();
11081 match err {
11082 AplicacaoError::ContratoDuplicate {
11083 de,
11084 para,
11085 wit,
11086 target,
11087 } => {
11088 assert_eq!(de, "cart");
11089 assert_eq!(para, "catalog");
11090 assert_eq!(wit, "pleme:cap/audit");
11091 assert!(
11092 target.contains("capability"),
11093 "capability-edge duplicate diagnostic must surface the \
11094 no-payload shape (got target = {target:?})"
11095 );
11096 }
11097 other => panic!("expected ContratoDuplicate, got {other:?}"),
11098 }
11099 }
11100
11101 #[test]
11102 fn accepts_distinct_http_paths_between_same_pair() {
11103 // Negative pin: two HTTP contracts cart → catalog at distinct
11104 // endpoints (`/products/:id` and `/search`) are *not*
11105 // duplicates — they're distinct typed edges differing on the
11106 // payload axis. The duplicate-gate must not over-match here,
11107 // since the cart-calls-catalog-on-multiple-paths shape is the
11108 // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
11109 // example: cart calls catalog at /products/:id, payment at
11110 // /charge — same shape extends to two paths on one para).
11111 let mut s = three_member_spec();
11112 s.contratos
11113 .push(contract_http("cart", "catalog", "/search"));
11114 s.validate()
11115 .expect("distinct endpoints between same (de, para) must validate");
11116 }
11117
11118 #[test]
11119 fn accepts_same_endpoint_on_different_pairs() {
11120 // Negative pin: the same `/charge` endpoint reused on two
11121 // different (de, para) pairs is two distinct edges, not a
11122 // duplicate. Pinning this shape so the gate's identity key
11123 // includes both `de` and `para` (not just `(wit, endpoint)`).
11124 let mut s = three_member_spec();
11125 s.contratos
11126 .push(contract_http("payment", "catalog", "/charge"));
11127 s.validate()
11128 .expect("same endpoint reused on distinct (de, para) must validate");
11129 }
11130
11131 #[test]
11132 fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
11133 // Pin the diagnostic shape: the duplicate-edge error names
11134 // *which* target field carried the conflict, so the author
11135 // doesn't have to re-grep the source caixa.lisp to find it.
11136 // Same self-locating diagnostic discipline as
11137 // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
11138 let mut s = three_member_spec();
11139 s.contratos
11140 .push(contract_http("cart", "catalog", "/products/:id"));
11141 let err = s.validate().unwrap_err();
11142 let msg = format!("{err}");
11143 assert!(
11144 msg.contains("\"/products/:id\""),
11145 "duplicate-contrato diagnostic must name the offending \
11146 :endpoint payload (got: {msg:?})"
11147 );
11148 assert!(
11149 msg.contains("cart") && msg.contains("catalog"),
11150 "diagnostic must name both endpoints of the duplicate edge \
11151 (got: {msg:?})"
11152 );
11153 }
11154
11155 #[test]
11156 fn duplicate_contrato_gate_runs_after_membership_check() {
11157 // Order pin: a duplicate contract whose `:de` is *also* not in
11158 // `:membros` surfaces the membership error first — the
11159 // missing-member diagnostic is more locating than the
11160 // duplicate-edge one (the author has to fix the membership
11161 // before the duplicate is meaningful). Same ordering
11162 // discipline as `membros_validation_runs_before_contratos_membership_check`.
11163 let mut s = three_member_spec();
11164 s.contratos.push(contract_http("phantom", "catalog", "/x"));
11165 s.contratos.push(contract_http("phantom", "catalog", "/x"));
11166 let err = s.validate().unwrap_err();
11167 assert!(
11168 matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
11169 "membership-missing must fire before duplicate-edge (got {err:?})"
11170 );
11171 }
11172
11173 #[test]
11174 fn duplicate_contrato_gate_runs_after_target_shape_check() {
11175 // Order pin: a contract with a malformed target (e.g. an HTTP
11176 // wit world with an empty :endpoint) surfaces the target-shape
11177 // error first, not the duplicate one. Even when two such
11178 // malformed entries are identical, the per-contract `target()`
11179 // check fires inside the loop *before* the duplicate-key
11180 // insert, so the diagnostic remains the most-locating one.
11181 let mut s = three_member_spec();
11182 let malformed = WitContract {
11183 de: "cart".into(),
11184 para: "catalog".into(),
11185 wit: "wasi:http/proxy".into(),
11186 endpoint: Some(String::new()),
11187 subject: None,
11188 slot: None,
11189 };
11190 s.contratos.push(malformed.clone());
11191 s.contratos.push(malformed);
11192 let err = s.validate().unwrap_err();
11193 assert!(
11194 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
11195 "endpoint-empty must fire before duplicate-edge (got {err:?})"
11196 );
11197 }
11198
11199 #[test]
11200 fn wit_target_label_pins_per_variant_format() {
11201 // Label format is the single source of truth every duplicate-
11202 // `:contratos` diagnostic + every future `feira app graph`
11203 // consumer routes through. Pin the shape per variant so a
11204 // future edit to `WitTarget::label` (e.g. a JSON emitter that
11205 // strips the leading `:`, or a rename from `endpoint` →
11206 // `path`) surfaces as a red-red test rather than as a silent
11207 // downstream diagnostic drift. Together with the exhaustive
11208 // `match` on `WitTarget` inside `label()`, adding a future
11209 // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
11210 // peer, per-edge WIT registry variants) is a compile error at
11211 // the label site — not a fall-through into the `Capability`
11212 // "no payload" default the prior raw-field-probe helper
11213 // silently landed on.
11214 assert_eq!(
11215 WitTarget::Http {
11216 endpoint: "/charge",
11217 }
11218 .label(),
11219 "\
11220:endpoint \"/charge\""
11221 );
11222 assert_eq!(
11223 WitTarget::PubSub {
11224 subject: "events.checkout.paid",
11225 }
11226 .label(),
11227 "\
11228:subject \"events.checkout.paid\""
11229 );
11230 assert_eq!(
11231 WitTarget::Store {
11232 slot: "checkout/$order",
11233 }
11234 .label(),
11235 "\
11236:slot \"checkout/$order\""
11237 );
11238 assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
11239 // Capability-arm label routes through the lifted
11240 // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
11241 // declaration per arm, next to the variant" discipline the
11242 // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
11243 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11244 // consts already carry extends to the payload-less arm; the
11245 // byte-string equality pin below plus this label-routes-
11246 // through-the-const pin make a future rebrand on either the
11247 // const declaration or the `label()` template a build error
11248 // here rather than a downstream consumer surprise.
11249 assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
11250 assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
11251 }
11252
11253 #[test]
11254 fn wit_target_display_routes_through_label_helper() {
11255 // Fail-before-pass-after pin on the fourth (and only remaining)
11256 // typed-shape-discriminator axis to converge onto the
11257 // three-path-convergence discipline the sibling M3
11258 // [`PlacementStrategy`] (0a2f653) and M2
11259 // [`crate::supervisor::RestartStrategy`] /
11260 // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
11261 // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
11262 // through [`WitTarget::label`], so every consumer reaching for
11263 // `format!("{v}")` on a typed payload target lands on the same
11264 // stable author-facing byte-string [`WitTarget::label`] returns
11265 // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
11266 // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
11267 // `:contratos` gate seeds via [`WitTarget::label`] at
11268 // aplicacao.rs:5491 already threads through.
11269 //
11270 // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
11271 // through to the `Debug` derive's structural output
11272 // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
11273 // rather than the [`WitTarget::label`] helper's stable byte-
11274 // string (`:endpoint "/charge"` — the author-facing `:contratos`
11275 // keyword form). Every future consumer that reaches for
11276 // `format!("{target}")` — the canonical shape every user-facing
11277 // pretty-print site on the sibling typed-enum axes
11278 // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
11279 // [`crate::supervisor::RestartPolicy`]) already uses — would
11280 // silently land under a different byte-string than the
11281 // [`WitTarget::label`] callers that the duplicate-`:contratos`
11282 // diagnostic already threads through, with the mismatch
11283 // surfacing as a downstream diagnostic / graph / audit line
11284 // reading one spelling while the substrate's own gate emitted
11285 // another.
11286 //
11287 // Pin the routing here so a future
11288 // `impl std::fmt::Display for WitTarget<'_>` reimplementation
11289 // that hand-rolls the per-arm formatting instead of delegating
11290 // to [`WitTarget::label`] fails at caixa-core build time.
11291 for variant in [
11292 WitTarget::Http {
11293 endpoint: "/charge",
11294 },
11295 WitTarget::PubSub {
11296 subject: "events.checkout.paid",
11297 },
11298 WitTarget::Store {
11299 slot: "checkout/$order",
11300 },
11301 WitTarget::Capability,
11302 ] {
11303 assert_eq!(
11304 variant.to_string(),
11305 variant.label(),
11306 "WitTarget::{variant:?} Display must route through \
11307 WitTarget::label (single source of truth: the lifted \
11308 payload_pair 4-arm dispatch the label helper already \
11309 threads through)"
11310 );
11311 }
11312 }
11313
11314 #[test]
11315 fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
11316 // Consumer-side pin on the three-path convergence:
11317 // [`std::fmt::Display`] agrees byte-for-byte with the
11318 // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
11319 // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
11320 // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
11321 // Pre-lift the two paths were structurally independent — the
11322 // substrate-side gate reached for `target_view.label()` while a
11323 // future downstream diagnostic / graph / audit line reaching
11324 // for `format!("{target}")` would silently land on the `Debug`
11325 // derive's structural output. Pin the two paths byte-for-byte
11326 // here so any future variant addition (M4 `Rest`/`Grpc` split
11327 // of [`WitTarget::Http`], `Queue`-shaped peer of
11328 // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
11329 // match error at [`WitTarget::payload_pair`] rather than a
11330 // silent per-consumer dispatch miss.
11331 for variant in [
11332 WitTarget::Http {
11333 endpoint: "/charge",
11334 },
11335 WitTarget::PubSub {
11336 subject: "events.checkout.paid",
11337 },
11338 WitTarget::Store {
11339 slot: "checkout/$order",
11340 },
11341 WitTarget::Capability,
11342 ] {
11343 assert_eq!(
11344 format!("{variant}"),
11345 variant.label(),
11346 "WitTarget::{variant:?} Display byte-string must match \
11347 the AplicacaoError::ContratoDuplicate `target:` carrier \
11348 the AplicacaoSpec::validate duplicate-`:contratos` gate \
11349 seeds via WitTarget::label — three-path convergence: \
11350 Display + label + payload_pair all resolve to the same \
11351 per-arm byte-string"
11352 );
11353 }
11354 }
11355
11356 #[test]
11357 fn wit_target_payload_pair_pins_per_variant() {
11358 // Pin the per-arm `(field-name, payload)` pair single-sourced
11359 // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
11360 // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
11361 // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
11362 // and [`WitTarget::field_name`] (returns the first component)
11363 // route through. Until this lift landed [`WitTarget::label`]
11364 // dispatched on the same three arms with a per-arm
11365 // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
11366 // paired [`WitTarget::HTTP_FIELD_NAME`] /
11367 // [`WitTarget::PUBSUB_FIELD_NAME`] /
11368 // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
11369 // canonical "same shape, written N times" duplication
11370 // THEORY.md §I.3.5 promotes to a build-time concern. A future
11371 // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
11372 // [`WitTarget::Http`], `Queue`-shaped peer of
11373 // [`WitTarget::Store`]) is one match-arm edit at
11374 // [`WitTarget::payload_pair`], visible here as a compile-time
11375 // exhaustiveness error on both this pin and the label-format
11376 // pin above.
11377 assert_eq!(
11378 WitTarget::Http {
11379 endpoint: "/charge"
11380 }
11381 .payload_pair(),
11382 Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
11383 );
11384 assert_eq!(
11385 WitTarget::PubSub {
11386 subject: "events.x",
11387 }
11388 .payload_pair(),
11389 Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
11390 );
11391 assert_eq!(
11392 WitTarget::Store {
11393 slot: "checkout/$order",
11394 }
11395 .payload_pair(),
11396 Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
11397 );
11398 assert_eq!(WitTarget::Capability.payload_pair(), None);
11399 }
11400
11401 #[test]
11402 fn wit_target_field_name_pins_per_variant() {
11403 // Pin the per-arm author-facing `:contratos` payload field
11404 // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
11405 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11406 // + returned by [`WitTarget::field_name`]. Every downstream
11407 // consumer (the [`WitContract::target`] gate's `expected:`
11408 // scalar, the [`WitTarget::label`] template's keyword prefix,
11409 // the `feira app graph` verb's `endpoint=…` prefix) routes
11410 // through the same three peer consts, so a rename on the
11411 // author-surface `(defcaixa … :contratos ((:de … :para …
11412 // :wit … :endpoint …)))` field lands in exactly one place.
11413 assert_eq!(
11414 WitTarget::Http {
11415 endpoint: "/charge"
11416 }
11417 .field_name(),
11418 Some(WitTarget::HTTP_FIELD_NAME),
11419 );
11420 assert_eq!(
11421 WitTarget::PubSub {
11422 subject: "events.x",
11423 }
11424 .field_name(),
11425 Some(WitTarget::PUBSUB_FIELD_NAME),
11426 );
11427 assert_eq!(
11428 WitTarget::Store {
11429 slot: "checkout/$order",
11430 }
11431 .field_name(),
11432 Some(WitTarget::STORE_FIELD_NAME),
11433 );
11434 // Capability arm carries no payload field — the diagnostic
11435 // never reports `expected: "capability"` because the gate's
11436 // Capability arm accepts no payload at all (it fires the
11437 // "expected: none" WrongTarget error instead), so the field-
11438 // name method returns None here rather than a placeholder.
11439 assert_eq!(WitTarget::Capability.field_name(), None);
11440
11441 // Peer const scalar values pinned so a rename on either side
11442 // (author-surface field name in the `(defcaixa …)` DSL, or
11443 // the diagnostic's `expected:` scalar) can't drift without
11444 // failing here first.
11445 assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
11446 assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
11447 assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
11448 }
11449
11450 #[test]
11451 fn wit_target_field_names_are_pairwise_distinct() {
11452 // Distinctness pin: if any two of the three payload-field-name
11453 // scalars ever collapse (e.g. an accidental `endpoint` copy-
11454 // paste over the `subject` const), the [`WitContract::target`]
11455 // gate's diagnostic would point authors at the wrong field —
11456 // an "expected `:endpoint`" error on a pub-sub edge would
11457 // silently misroute the fix. Same cross-axis-distinctness
11458 // discipline as the peer M3 `:placement :estrategia` variant-
11459 // discriminator scalar-value pins (cc8f749) applied to the
11460 // payload-field-name axis.
11461 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
11462 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11463 assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11464 }
11465
11466 #[test]
11467 fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
11468 // 4-way distinctness pin extending the sibling
11469 // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
11470 // (which covers only the HTTP / PubSub / Store payload arms)
11471 // onto the fourth scalar the shared
11472 // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
11473 // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
11474 // (`"none"`), the payload-less Capability-arm rejection scalar.
11475 //
11476 // All four [`WitTarget::HTTP_FIELD_NAME`] /
11477 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11478 // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
11479 // dispatch surface [`WitContract::target`] writes onto the
11480 // `ContratoWrongTarget::expected` field — the same `&'static
11481 // str` axis authors read as "this WIT world's shape admits
11482 // (only|not) `:<field>`". Pairwise-distinctness is the invariant
11483 // downstream consumers rely on: an `expected: "endpoint"`
11484 // diagnostic on a Capability-shaped edge tells the author to
11485 // add a `:endpoint "…"` slot to a WIT world that admits none,
11486 // silently misrouting the fix. Until this pin landed the three
11487 // payload-arm consts were distinctness-guarded by the sibling
11488 // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
11489 // scalar (d4f54f2) sat unguarded — a rebrand collision (the
11490 // author-facing vocabulary shift from `"none"` to `"endpoint"`
11491 // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
11492 // into per-shape peers) would have silently landed one
11493 // Capability-arm rejection on a payload-arm's `expected:` byte-
11494 // string and desynchronized the diagnostic from the author's
11495 // typed shape.
11496 //
11497 // Same 4-way pairwise-distinctness pin discipline as the peer
11498 // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
11499 // (cc8f749) applies on the sibling M3 closed-set typed-enum
11500 // scalar-value dispatch axis; extends the pin trajectory the
11501 // sibling `wit_target_field_names_are_pairwise_distinct`
11502 // 3-way pin opened to cover the last unguarded corner on the
11503 // `ContratoWrongTarget::expected` scalar-value axis.
11504 //
11505 // Fail-before-pass-after locally verified by mutating
11506 // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
11507 // — this pin fires as expected; restoring passes.
11508 let all = [
11509 WitTarget::HTTP_FIELD_NAME,
11510 WitTarget::PUBSUB_FIELD_NAME,
11511 WitTarget::STORE_FIELD_NAME,
11512 WitTarget::CAPABILITY_EXPECTED,
11513 ];
11514 for (i, a) in all.iter().enumerate() {
11515 for (j, b) in all.iter().enumerate() {
11516 if i != j {
11517 assert_ne!(
11518 a, b,
11519 "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
11520 STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
11521 pairwise distinct — got duplicate {a:?} at indices \
11522 {i} and {j}; all four scalars thread through the \
11523 shared `AplicacaoError::ContratoWrongTarget::expected` \
11524 &'static str axis, so a collapse silently misdirects \
11525 the diagnostic on which typed shape the WIT world admits",
11526 );
11527 }
11528 }
11529 }
11530 }
11531
11532 #[test]
11533 fn wit_target_is_variant_predicates_partition_the_arm_set() {
11534 // Fail-before-pass-after pin on the
11535 // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
11536 // each of the four variants exactly one of the generated
11537 // `is_http` / `is_pubsub` / `is_store` / `is_capability`
11538 // predicates returns `true` and the other three return
11539 // `false`. Prior to this derive the only production
11540 // arm-discriminator on [`WitTarget`] — the sync-cycle
11541 // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
11542 // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
11543 // the variant that expressed no compile-time link back to
11544 // the closed-set typed dispatch a future fifth
11545 // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
11546 // split of [`WitTarget::PubSub`] into shape-specific peers,
11547 // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
11548 // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
11549 // to thread through in lockstep or the DFS exclusion would
11550 // silently disagree with the peer diagnostic templates on
11551 // which arms carry sync-versus-async semantics. Peer of the
11552 // sibling [`crate::CaixaKind`] (f5bba80),
11553 // [`PlacementStrategy`] (766ec63),
11554 // [`crate::supervisor::RestartStrategy`],
11555 // [`crate::supervisor::RestartPolicy`], and
11556 // [`crate::upgrade::UpgradeInstruction`] (915a934)
11557 // `IsVariant` derives on the sibling closed-set typed-enum
11558 // discriminator axes — extends the same one-typed-dispatch-
11559 // per-variant discipline onto the last unlifted closed-set
11560 // typed-enum discriminator on the caixa surface (the M3
11561 // mesh-slot per-`:contratos` target-arm axis), closing the
11562 // arm-discriminator convergence trajectory across every
11563 // closed-set typed enum in caixa-core.
11564 let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
11565 (
11566 WitTarget::Http { endpoint: "/x" },
11567 [true, false, false, false],
11568 ),
11569 (
11570 WitTarget::PubSub {
11571 subject: "events.x",
11572 },
11573 [false, true, false, false],
11574 ),
11575 (
11576 WitTarget::Store { slot: "kv/x" },
11577 [false, false, true, false],
11578 ),
11579 (WitTarget::Capability, [false, false, false, true]),
11580 ];
11581 for (variant, expected) in rows {
11582 let observed = [
11583 variant.is_http(),
11584 variant.is_pubsub(),
11585 variant.is_store(),
11586 variant.is_capability(),
11587 ];
11588 assert_eq!(
11589 observed, expected,
11590 "WitTarget::{variant:?} is_* predicates must partition \
11591 the arm set (http, pubsub, store, capability); got {observed:?}"
11592 );
11593 }
11594 }
11595
11596 #[test]
11597 fn wit_target_is_variant_predicates_are_const_fn() {
11598 // The [`gen_platform::IsVariant`] derive emits `const fn`
11599 // predicates on the peer [`crate::CaixaKind`] +
11600 // [`crate::upgrade::UpgradeInstruction`] +
11601 // [`crate::supervisor::RestartStrategy`] +
11602 // [`crate::supervisor::RestartPolicy`] +
11603 // [`PlacementStrategy`] closed-set typed enums — pin the
11604 // same posture on [`WitTarget`] so a future accidental
11605 // downgrade to non-`const` (an added runtime helper reachable
11606 // only from a non-`const` context, a manual hand-rolled
11607 // `impl` that shadows the derive-generated method) trips at
11608 // caixa-core build time rather than surfacing as a downstream
11609 // `const`-context regression far from the derive declaration.
11610 //
11611 // Unlike the peer unit-variant enums (`CaixaKind` /
11612 // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
11613 // whose `const` constructors need no arguments, the three
11614 // payload-carrying [`WitTarget`] arms are const-constructed
11615 // through `&'static str` payloads — the same `'static`
11616 // lifetime the closed-set typed enum's four-arm partition
11617 // pin above already threads through.
11618 const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
11619 const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
11620 const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
11621 const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
11622 const IS_HTTP: bool = HTTP.is_http();
11623 const IS_PUBSUB: bool = PUBSUB.is_pubsub();
11624 const IS_STORE: bool = STORE.is_store();
11625 const IS_CAPABILITY: bool = CAPABILITY.is_capability();
11626 assert!(IS_HTTP);
11627 assert!(IS_PUBSUB);
11628 assert!(IS_STORE);
11629 assert!(IS_CAPABILITY);
11630 }
11631
11632 #[test]
11633 fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
11634 // Consumer-side pin on the sole production converge site:
11635 // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
11636 // edges from the synchronous-subgraph DFS via the lifted
11637 // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
11638 // predicate (rebound from the prior raw
11639 // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
11640 // variant). Byte-equivalent today (`is_pubsub` is the
11641 // derive-generated `matches!(self, Self::PubSub { .. })` by
11642 // construction, the `#[is_variant(name = "pubsub")]` override
11643 // aliasing the auto-derived `is_pub_sub` back to the sibling
11644 // [`WitContract::is_pubsub`] name); pin the behavior so a
11645 // future accidental drift (a rebind onto a peer arm
11646 // predicate, a manual hand-rolled `impl` that shadows the
11647 // derive-generated method with different semantics, a peer
11648 // arm rename that shifts which variant carries sync-versus-
11649 // async semantics) trips at caixa-core test time rather than
11650 // at some downstream operator's runtime dispatch far from the
11651 // rebind commit.
11652 //
11653 // The fixture constructs a two-Servico Aplicacao with one
11654 // pub-sub edge that would close a sync-cycle if the DFS did
11655 // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
11656 // pub-sub exclusion means the DFS sees only the `b → a` HTTP
11657 // edge, which is not a cycle. A regression in the converge
11658 // (a rebind that reads the pub-sub arm as sync) would report
11659 // `AplicacaoError::ContratoCycle`.
11660 let s = AplicacaoSpec {
11661 membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
11662 contratos: vec![
11663 // Pub-sub edge: DFS must skip via is_pubsub().
11664 WitContract {
11665 de: "a".into(),
11666 para: "b".into(),
11667 wit: "nats:pub-sub".into(),
11668 endpoint: None,
11669 subject: Some("events.x".into()),
11670 slot: None,
11671 },
11672 // HTTP edge: DFS must include.
11673 WitContract {
11674 de: "b".into(),
11675 para: "a".into(),
11676 wit: "wasi:http/proxy".into(),
11677 endpoint: Some("/x".into()),
11678 subject: None,
11679 slot: None,
11680 },
11681 ],
11682 politicas: MeshPolicy::default(),
11683 placement: Placement {
11684 estrategia: PlacementStrategy::Replicated,
11685 clusters: vec!["rio".into()],
11686 affinity: None,
11687 shard_key: None,
11688 },
11689 entrada: None,
11690 };
11691 s.validate()
11692 .expect("pub-sub edge must be excluded from sync-cycle DFS");
11693 }
11694
11695 #[test]
11696 fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
11697 // Consumer-side pin: the same three peer consts thread through
11698 // both the [`WitTarget::label`] template (leading-`:` keyword
11699 // prefix in the duplicate-`:contratos` diagnostic) and the
11700 // [`WitContract::target`] gate's [`AplicacaoError::
11701 // ContratoMissingTarget`] `expected:` scalar (the field the
11702 // author needs to add). Pin both routes at once so a future
11703 // refactor can't accidentally split them onto separate string
11704 // literals — the "one place, everywhere reaches for it"
11705 // invariant the peer const set carries.
11706 let http_label = WitTarget::Http { endpoint: "/x" }.label();
11707 assert!(
11708 http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
11709 "label must lead with :{} keyword (got {http_label:?})",
11710 WitTarget::HTTP_FIELD_NAME,
11711 );
11712
11713 let mut s = three_member_spec();
11714 s.contratos.push(WitContract {
11715 de: "cart".into(),
11716 para: "catalog".into(),
11717 wit: "kafka:topic".into(),
11718 endpoint: None,
11719 subject: None,
11720 slot: None,
11721 });
11722 match s.validate().unwrap_err() {
11723 AplicacaoError::ContratoMissingTarget { expected, .. } => {
11724 assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
11725 }
11726 other => panic!("expected ContratoMissingTarget, got {other:?}"),
11727 }
11728 }
11729
11730 #[test]
11731 fn duplicate_pubsub_diagnostic_names_offending_subject() {
11732 // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
11733 // on the pub-sub target axis: the duplicate-edge diagnostic
11734 // must name the `:subject` payload verbatim (not just the
11735 // `(de, para, wit)` triple). Prior to lifting the label onto
11736 // [`WitTarget::label`] the diagnostic derived the label from
11737 // raw [`WitContract`] `Option<String>` probes — a future
11738 // `WitTarget` variant addition (M4 per-edge WIT registry)
11739 // would silently fall through to the `Capability` "no
11740 // payload" default without a compiler warning. Pinning the
11741 // pub-sub arm's format closes the second of three
11742 // payload-carrying `WitTarget` arms this diagnostic threads
11743 // through.
11744 let mut s = three_member_spec();
11745 let pubsub = WitContract {
11746 de: "payment".into(),
11747 para: "cart".into(),
11748 wit: "nats:pub-sub".into(),
11749 endpoint: None,
11750 subject: Some("events.checkout.paid".into()),
11751 slot: None,
11752 };
11753 s.contratos.push(pubsub.clone());
11754 s.contratos.push(pubsub);
11755 let err = s.validate().unwrap_err();
11756 let msg = format!("{err}");
11757 assert!(
11758 msg.contains(":subject \"events.checkout.paid\""),
11759 "duplicate-pubsub diagnostic must name the offending \
11760 :subject payload (got: {msg:?})"
11761 );
11762 }
11763
11764 #[test]
11765 fn duplicate_store_diagnostic_names_offending_slot() {
11766 // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
11767 // key-value target axis: the diagnostic must name the `:slot`
11768 // payload verbatim. Third of three payload-carrying
11769 // `WitTarget` arms this diagnostic threads through, closing
11770 // the per-arm label pin trilogy (`Http` — 6841,
11771 // `PubSub` + `Store` — this test + peer above).
11772 let mut s = three_member_spec();
11773 let store = WitContract {
11774 de: "cart".into(),
11775 para: "payment".into(),
11776 wit: "wasi:keyvalue/store".into(),
11777 endpoint: None,
11778 subject: None,
11779 slot: Some("checkout/$orderId".into()),
11780 };
11781 s.contratos
11782 .retain(|c| !(c.de == "cart" && c.para == "payment"));
11783 s.contratos.push(store.clone());
11784 s.contratos.push(store);
11785 let err = s.validate().unwrap_err();
11786 let msg = format!("{err}");
11787 assert!(
11788 msg.contains(":slot \"checkout/$orderId\""),
11789 "duplicate-store diagnostic must name the offending :slot \
11790 payload (got: {msg:?})"
11791 );
11792 }
11793
11794 #[test]
11795 fn rejects_entrada_path_without_leading_slash() {
11796 let mut s = three_member_spec();
11797 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
11798 let err = s.validate().unwrap_err();
11799 assert!(
11800 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
11801 "got {err:?}"
11802 );
11803 }
11804
11805 #[test]
11806 fn rejects_empty_entrada_path() {
11807 let mut s = three_member_spec();
11808 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
11809 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
11810 }
11811
11812 #[test]
11813 fn rejects_duplicate_entrada_paths() {
11814 let mut s = three_member_spec();
11815 s.entrada.as_mut().unwrap().paths = vec![
11816 "/api/cart".into(),
11817 "/api/products".into(),
11818 "/api/cart".into(),
11819 ];
11820 let err = s.validate().unwrap_err();
11821 assert!(
11822 matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
11823 "got {err:?}"
11824 );
11825 }
11826
11827 #[test]
11828 fn rejects_zero_entrada_port() {
11829 let mut s = three_member_spec();
11830 s.entrada.as_mut().unwrap().port = 0;
11831 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
11832 }
11833
11834 // ── :entrada :paths value-shape gate ─────────────────────────────
11835 //
11836 // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
11837 // sibling `:paths` axis. Every authoring footgun the K8s Gateway
11838 // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
11839 // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
11840 // time now becomes a caixa-build-time `EntradaPathInvalid` with
11841 // the offending `:paths` entry named verbatim.
11842
11843 #[test]
11844 fn rejects_entrada_path_with_query() {
11845 // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
11846 // silently passed validate and the Gateway API webhook
11847 // rejected it at apply time with no source citation.
11848 let mut s = three_member_spec();
11849 s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
11850 let err = s.validate().unwrap_err();
11851 assert!(
11852 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11853 if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
11854 "got {err:?}"
11855 );
11856 }
11857
11858 #[test]
11859 fn rejects_entrada_path_with_fragment() {
11860 let mut s = three_member_spec();
11861 s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
11862 let err = s.validate().unwrap_err();
11863 assert!(
11864 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11865 if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
11866 "got {err:?}"
11867 );
11868 }
11869
11870 #[test]
11871 fn rejects_entrada_path_with_space() {
11872 let mut s = three_member_spec();
11873 s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
11874 let err = s.validate().unwrap_err();
11875 assert!(
11876 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11877 if path == "/api/my cart" && reason.contains("whitespace")),
11878 "got {err:?}"
11879 );
11880 }
11881
11882 #[test]
11883 fn rejects_entrada_path_with_tab() {
11884 let mut s = three_member_spec();
11885 s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
11886 let err = s.validate().unwrap_err();
11887 assert!(
11888 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11889 if path == "/api/\tcart" && reason.contains("whitespace")),
11890 "got {err:?}"
11891 );
11892 }
11893
11894 #[test]
11895 fn rejects_entrada_path_with_control_char() {
11896 // 0x01 (SOH) — a non-whitespace control char surfaces the
11897 // distinct "control character" reason arm, separate from
11898 // the whitespace arm. Pinned so a future refactor that
11899 // collapses the two arms can't accidentally drop the more
11900 // self-locating diagnostic.
11901 let mut s = three_member_spec();
11902 s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
11903 let err = s.validate().unwrap_err();
11904 assert!(
11905 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11906 if path == "/api/\x01cart" && reason.contains("control character")),
11907 "got {err:?}"
11908 );
11909 }
11910
11911 #[test]
11912 fn rejects_entrada_path_with_non_ascii() {
11913 // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
11914 // unreserved-set rule rejects. The Gateway API webhook
11915 // rejects literal non-ASCII bytes; percent-encoding is the
11916 // only way to author non-ASCII in a path.
11917 let mut s = three_member_spec();
11918 s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
11919 let err = s.validate().unwrap_err();
11920 assert!(
11921 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11922 if path == "/api/café" && reason.contains("non-ASCII")),
11923 "got {err:?}"
11924 );
11925 }
11926
11927 #[test]
11928 fn rejects_entrada_path_with_consecutive_slashes() {
11929 let mut s = three_member_spec();
11930 s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
11931 let err = s.validate().unwrap_err();
11932 assert!(
11933 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11934 if path == "/api//cart" && reason.contains("consecutive `/`")),
11935 "got {err:?}"
11936 );
11937 }
11938
11939 #[test]
11940 fn rejects_entrada_path_with_dot_segment() {
11941 let mut s = three_member_spec();
11942 s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
11943 let err = s.validate().unwrap_err();
11944 assert!(
11945 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11946 if path == "/api/./cart" && reason.contains("`.` segment")),
11947 "got {err:?}"
11948 );
11949 }
11950
11951 #[test]
11952 fn rejects_entrada_path_with_trailing_dot_segment() {
11953 // The bare `/.` and the trailing `/foo/.` are both rejected
11954 // by the Gateway API webhook; pinned separately so a future
11955 // narrowing that catches only the inner form surfaces here.
11956 let mut s = three_member_spec();
11957 s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
11958 let err = s.validate().unwrap_err();
11959 assert!(
11960 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11961 if path == "/api/." && reason.contains("`.` segment")),
11962 "got {err:?}"
11963 );
11964 }
11965
11966 #[test]
11967 fn rejects_entrada_path_with_parent_segment() {
11968 let mut s = three_member_spec();
11969 s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
11970 let err = s.validate().unwrap_err();
11971 assert!(
11972 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11973 if path == "/api/../etc" && reason.contains("`..` parent-segment")),
11974 "got {err:?}"
11975 );
11976 }
11977
11978 #[test]
11979 fn rejects_entrada_path_with_trailing_parent_segment() {
11980 // Trailing `/..` — symmetric arm of the parent-segment rule,
11981 // pinned separately so a future relaxation that only checks
11982 // the inner form (`/../`) surfaces here.
11983 let mut s = three_member_spec();
11984 s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
11985 let err = s.validate().unwrap_err();
11986 assert!(
11987 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11988 if path == "/api/.." && reason.contains("`..` parent-segment")),
11989 "got {err:?}"
11990 );
11991 }
11992
11993 #[test]
11994 fn rejects_entrada_path_too_long() {
11995 // 1025-byte path — one over the Gateway API HTTPPathMatch.value
11996 // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
11997 // ASCII-alphanumeric body so only the length rule fires.
11998 let mut s = three_member_spec();
11999 let big = format!("/api/{}", "a".repeat(1020));
12000 assert_eq!(big.len(), 1025);
12001 s.entrada.as_mut().unwrap().paths = vec![big.clone()];
12002 let err = s.validate().unwrap_err();
12003 assert!(
12004 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12005 if path == &big && reason.contains("max length of 1024")),
12006 "got {err:?}"
12007 );
12008 }
12009
12010 #[test]
12011 fn entrada_path_max_length_validates() {
12012 // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
12013 // maxLength cap. Boundary pin: drift in the cap surfaces here
12014 // and at `rejects_entrada_path_too_long` simultaneously.
12015 let mut s = three_member_spec();
12016 let big = format!("/api/{}", "a".repeat(1019));
12017 assert_eq!(big.len(), 1024);
12018 s.entrada.as_mut().unwrap().paths = vec![big];
12019 s.validate().unwrap();
12020 }
12021
12022 #[test]
12023 fn entrada_accepts_canonical_paths() {
12024 // Positive-control sweep — every form the Gateway API
12025 // apiserver accepts must round-trip through validate. Covers
12026 // the root catch-all, plain paths, dot-prefixed segments
12027 // (hidden-file-style, distinct from `.` and `..` segments
12028 // which are rejected), digit-bearing segments, the canonical
12029 // route-template `:param` form (`:` is RFC 3986 reserved-set
12030 // valid in paths), trailing-slash form, percent-encoded
12031 // segments, and an interior `..` *substring* (`/foo..bar` is
12032 // not the `..` segment and is allowed).
12033 for path in [
12034 "/",
12035 "/api/cart",
12036 "/healthz",
12037 "/api/.config",
12038 "/v1/products",
12039 "/products/:id",
12040 "/api/cart/",
12041 "/api/caf%C3%A9",
12042 "/foo..bar",
12043 "/...",
12044 ] {
12045 let mut s = three_member_spec();
12046 s.entrada.as_mut().unwrap().paths = vec![path.into()];
12047 s.validate()
12048 .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
12049 }
12050 }
12051
12052 #[test]
12053 fn entrada_path_empty_takes_precedence_over_invalid() {
12054 // Ordering pin: `EntradaPathEmpty` is the more self-locating
12055 // diagnostic on `""` and must lead — `validate_entrada_path`
12056 // is only reached after the empty-check fires at the call
12057 // site. (The predicate itself defends against direct
12058 // invocation by returning the same error on `""`.)
12059 let mut s = three_member_spec();
12060 s.entrada.as_mut().unwrap().paths = vec!["".into()];
12061 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
12062 }
12063
12064 #[test]
12065 fn entrada_path_not_absolute_takes_precedence_over_invalid() {
12066 // Ordering pin: a path without a leading `/` surfaces the
12067 // narrower `EntradaPathNotAbsolute` diagnostic first; the
12068 // value-shape gate is only consulted on paths that already
12069 // satisfy the absolute-prefix invariant.
12070 let mut s = three_member_spec();
12071 // `bad path` would fire the whitespace rule under the
12072 // value-shape gate, but missing-leading-`/` is the more
12073 // self-locating diagnostic.
12074 s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
12075 let err = s.validate().unwrap_err();
12076 assert!(
12077 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
12078 "got {err:?}"
12079 );
12080 }
12081
12082 #[test]
12083 fn entrada_path_invalid_fires_before_duplicate_check() {
12084 // Ordering pin: a malformed path on the *first* entry of a
12085 // would-be duplicate pair fires the value-shape gate before
12086 // the duplicate gate, mirroring the
12087 // `placement_cluster_invalid_fires_before_duplicate_check`
12088 // (6cbb900) pattern on the peer axis.
12089 let mut s = three_member_spec();
12090 s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
12091 let err = s.validate().unwrap_err();
12092 assert!(
12093 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
12094 "got {err:?}"
12095 );
12096 }
12097
12098 #[test]
12099 fn entrada_path_diagnostic_carries_offending_path() {
12100 // Diagnostic-shape pin — the offending path + a non-empty
12101 // reason flow through verbatim so the author can grep their
12102 // caixa.lisp for `:paths` and fix it in one edit. Same shape
12103 // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
12104 let mut s = three_member_spec();
12105 s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
12106 let err = s.validate().unwrap_err();
12107 match err {
12108 AplicacaoError::EntradaPathInvalid { path, reason } => {
12109 assert_eq!(path, "/api?q=1");
12110 assert!(!reason.is_empty(), "reason field must be non-empty");
12111 }
12112 other => panic!("expected EntradaPathInvalid, got {other:?}"),
12113 }
12114 }
12115
12116 #[test]
12117 fn rejects_entrada_path_with_curly_brace_template_form() {
12118 // Per-axis pin on the shared `is_gateway_api_http_path`
12119 // reserved-byte arm: the canonical "I wrote an OpenAPI
12120 // path-template `{id}` instead of the Gateway API `:id` form"
12121 // footgun the K8s apiserver would otherwise catch at admission
12122 // time on every `HTTPRoute.spec.rules[].matches[].path.value`
12123 // landing site, far from the caixa.lisp. Surfaces as
12124 // `EntradaPathInvalid` carrying the offending path verbatim
12125 // plus the canonical `%7B`/`%7D` percent-encoding remediation
12126 // — the substrate-side `gateway_api_http_path_rejects_every_
12127 // reserved_printable_ascii_byte` predicate-level sweep pins the
12128 // full eleven-byte set; this per-axis pin confirms the
12129 // diagnostic flows through to the `EntradaPathInvalid` variant.
12130 let mut s = three_member_spec();
12131 s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
12132 let err = s.validate().unwrap_err();
12133 assert!(
12134 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12135 if path == "/api/cart/{id}"
12136 && reason.contains("reserved character")
12137 && reason.contains("'{'")
12138 && reason.contains("%7B")),
12139 "got {err:?}"
12140 );
12141 }
12142
12143 #[test]
12144 fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
12145 // Per-axis peer of `rejects_entrada_path_with_curly_brace_
12146 // template_form` on the sibling `:contratos :endpoint` axis.
12147 // Same shared `is_gateway_api_http_path` reserved-byte arm
12148 // fires through `ContratoEndpointInvalid`, with the offending
12149 // endpoint + `:de` + `:para` + reason flowing through verbatim.
12150 // Pins that the lifted predicate's tightening lands on both
12151 // caller axes simultaneously — one source of truth for the
12152 // Gateway API HTTPPathMatch.value accepted set.
12153 let err = contrato_endpoint_err("/api/cart/{id}");
12154 assert!(
12155 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12156 if endpoint == "/api/cart/{id}"
12157 && reason.contains("reserved character")
12158 && reason.contains("'{'")
12159 && reason.contains("%7B")),
12160 "got {err:?}"
12161 );
12162 }
12163
12164 // ── :entrada :host value-shape gate ──────────────────────────────
12165 //
12166 // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
12167 // the sibling `:host` axis. Every authoring footgun the K8s
12168 // Gateway API v1 apiserver would catch at admission time becomes
12169 // a caixa-build-time `EntradaHostInvalid` with the offending
12170 // `:host` named verbatim. Same diagnostic shape as
12171 // `MembroVersaoInvalid` (9888b13).
12172
12173 #[test]
12174 fn rejects_entrada_host_with_scheme() {
12175 // Fail-before-pass-after pin — pre-gate codebases silently
12176 // accepted `https://…` and the apiserver rejected it at apply
12177 // time with no source citation.
12178 let mut s = three_member_spec();
12179 s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
12180 let err = s.validate().unwrap_err();
12181 assert!(
12182 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12183 if host == "https://checkout.quero.cloud"),
12184 "got {err:?}"
12185 );
12186 }
12187
12188 #[test]
12189 fn rejects_entrada_host_with_port() {
12190 // The `:8080` port suffix is the canonical "I forgot the port
12191 // belongs in `:entrada :port`" footgun. The top-level `:` arm
12192 // (introduced after the per-label loop-only impl silently
12193 // surfaced a deep "label \"cloud:8080\" contains invalid
12194 // character ':'" leak) names the canonical fix verbatim — the
12195 // `:entrada :port` slot.
12196 let mut s = three_member_spec();
12197 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
12198 let err = s.validate().unwrap_err();
12199 assert!(
12200 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12201 if host == "checkout.quero.cloud:8080"
12202 && reason.contains(":entrada :port")),
12203 "got {err:?}"
12204 );
12205 }
12206
12207 #[test]
12208 fn rejects_entrada_host_with_trailing_colon() {
12209 // Trailing `:` (e.g. an in-progress `:host "example.com:"`
12210 // edit) — the per-label loop would land it as a deep
12211 // "label \"com:\" must start and end with an alphanumeric"
12212 // / "contains invalid character ':'" leak. The top-level
12213 // `:` arm pre-empts with the canonical `:port` slot
12214 // diagnostic.
12215 let mut s = three_member_spec();
12216 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
12217 let err = s.validate().unwrap_err();
12218 assert!(
12219 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12220 if host == "checkout.quero.cloud:"
12221 && reason.contains(":entrada :port")),
12222 "got {err:?}"
12223 );
12224 }
12225
12226 #[test]
12227 fn rejects_entrada_host_unbracketed_ipv6_literal() {
12228 // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
12229 // literals across the board (peer with `rejects_entrada_host_
12230 // ipv4_literal` above for the four-label-all-digit IPv4 arm).
12231 // Before this top-level `:` arm landed the per-label loop
12232 // surfaced a single-label byte-class diagnostic that named the
12233 // `:` byte but not the IP-literal prohibition. The top-level
12234 // `:` arm names both the `:port` slot and the IP-literal
12235 // prohibition verbatim, so an author whose `:host "2001:..."`
12236 // value lands here gets a self-locating fix either way.
12237 let mut s = three_member_spec();
12238 s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
12239 let err = s.validate().unwrap_err();
12240 assert!(
12241 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12242 if host == "2001:db8::1"
12243 && reason.contains("IPv6")),
12244 "got {err:?}"
12245 );
12246 }
12247
12248 #[test]
12249 fn rejects_entrada_host_wildcard_with_port() {
12250 // Wildcard host with port suffix — the `*.` strip and the
12251 // per-label loop on `["foo", "quero", "cloud:8080"]` would
12252 // surface the deep byte-class leak. The top-level `:` arm sits
12253 // upstream of the `*.` strip, so it names the canonical `:port`
12254 // fix verbatim regardless of whether the host is wildcard-led.
12255 let mut s = three_member_spec();
12256 s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
12257 let err = s.validate().unwrap_err();
12258 assert!(
12259 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12260 if host == "*.quero.cloud:8080"
12261 && reason.contains(":entrada :port")),
12262 "got {err:?}"
12263 );
12264 }
12265
12266 #[test]
12267 fn rejects_entrada_host_with_path() {
12268 let mut s = three_member_spec();
12269 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
12270 let err = s.validate().unwrap_err();
12271 assert!(
12272 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12273 if host == "checkout.quero.cloud/api"),
12274 "got {err:?}"
12275 );
12276 }
12277
12278 #[test]
12279 fn rejects_entrada_host_with_uppercase() {
12280 // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
12281 // rejected, not silently lower-cased.
12282 let mut s = three_member_spec();
12283 s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
12284 let err = s.validate().unwrap_err();
12285 assert!(
12286 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12287 if reason.contains("uppercase")),
12288 "got {err:?}"
12289 );
12290 }
12291
12292 #[test]
12293 fn rejects_entrada_host_with_underscore() {
12294 // RFC 1123 allows `[a-z0-9-]` only; underscore is the
12295 // canonical "I'm thinking of HTTP cookies / SRV records" leak.
12296 let mut s = three_member_spec();
12297 s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
12298 let err = s.validate().unwrap_err();
12299 assert!(
12300 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12301 if reason.contains('_')),
12302 "got {err:?}"
12303 );
12304 }
12305
12306 #[test]
12307 fn rejects_entrada_host_ipv4_literal() {
12308 // Gateway API v1 explicitly forbids IP literals as Hostnames.
12309 let mut s = three_member_spec();
12310 s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
12311 let err = s.validate().unwrap_err();
12312 assert!(
12313 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12314 if reason.contains("IPv4")),
12315 "got {err:?}"
12316 );
12317 }
12318
12319 #[test]
12320 fn rejects_entrada_host_with_trailing_dot() {
12321 // The Gateway API regex anchors at end-of-string with no
12322 // trailing `.` allowance — the FQDN root-dot form is rejected.
12323 let mut s = three_member_spec();
12324 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
12325 let err = s.validate().unwrap_err();
12326 assert!(
12327 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12328 if host == "checkout.quero.cloud."),
12329 "got {err:?}"
12330 );
12331 }
12332
12333 #[test]
12334 fn rejects_entrada_host_with_leading_dot() {
12335 let mut s = three_member_spec();
12336 s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
12337 let err = s.validate().unwrap_err();
12338 assert!(
12339 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12340 if reason.contains("empty label")),
12341 "got {err:?}"
12342 );
12343 }
12344
12345 #[test]
12346 fn rejects_entrada_host_with_consecutive_dots() {
12347 let mut s = three_member_spec();
12348 s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
12349 let err = s.validate().unwrap_err();
12350 assert!(
12351 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12352 if reason.contains("empty label")),
12353 "got {err:?}"
12354 );
12355 }
12356
12357 #[test]
12358 fn rejects_entrada_host_with_leading_hyphen_label() {
12359 let mut s = three_member_spec();
12360 s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
12361 let err = s.validate().unwrap_err();
12362 assert!(
12363 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12364 if reason.contains("alphanumeric")),
12365 "got {err:?}"
12366 );
12367 }
12368
12369 #[test]
12370 fn rejects_entrada_host_with_trailing_hyphen_label() {
12371 let mut s = three_member_spec();
12372 s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
12373 let err = s.validate().unwrap_err();
12374 assert!(
12375 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12376 if reason.contains("alphanumeric")),
12377 "got {err:?}"
12378 );
12379 }
12380
12381 #[test]
12382 fn rejects_entrada_host_with_inner_wildcard() {
12383 // Gateway API allows `*` only as the first label (`*.foo`);
12384 // any inner or trailing `*` is rejected.
12385 let mut s = three_member_spec();
12386 s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
12387 let err = s.validate().unwrap_err();
12388 assert!(
12389 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12390 if reason.contains("wildcard")),
12391 "got {err:?}"
12392 );
12393 }
12394
12395 #[test]
12396 fn rejects_entrada_host_bare_wildcard() {
12397 // `*.` with no domain is meaningless; Gateway API rejects it.
12398 let mut s = three_member_spec();
12399 s.entrada.as_mut().unwrap().host = "*.".into();
12400 let err = s.validate().unwrap_err();
12401 assert!(
12402 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12403 if reason.contains("wildcard")),
12404 "got {err:?}"
12405 );
12406 }
12407
12408 #[test]
12409 fn rejects_entrada_host_with_whitespace() {
12410 let mut s = three_member_spec();
12411 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12412 let err = s.validate().unwrap_err();
12413 assert!(
12414 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12415 if reason.contains("whitespace")),
12416 "got {err:?}"
12417 );
12418 }
12419
12420 #[test]
12421 fn rejects_entrada_host_space_names_offending_byte() {
12422 // Embedded space in the `:entrada :host` axis surfaces the
12423 // byte-naming diagnostic through the lifted
12424 // `find_ascii_whitespace_byte` predicate. Peer with the
12425 // sibling `parse_rejects_leading_whitespace` pins on
12426 // `supervisor::duration_codec` (a7ae622) — same "the
12427 // diagnostic carries the offending byte's `0x{b:02x}` shape"
12428 // discipline extended from the shared duration codec to the
12429 // Gateway API v1 Hostname axis.
12430 let mut s = three_member_spec();
12431 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12432 let err = s.validate().unwrap_err();
12433 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12434 panic!("expected EntradaHostInvalid, got {err:?}");
12435 };
12436 assert!(
12437 reason.contains("ASCII whitespace byte"),
12438 "expected byte-naming diagnostic, got {reason:?}"
12439 );
12440 assert!(
12441 reason.contains("0x20"),
12442 "expected offending space byte 0x20, got {reason:?}"
12443 );
12444 }
12445
12446 #[test]
12447 fn rejects_entrada_host_tab_names_offending_byte() {
12448 // Embedded tab byte in the `:entrada :host` axis — the
12449 // canonical paste-from-YAML-block-scalar / paste-from-
12450 // indented-doc footgun. Pins that the lifted predicate covers
12451 // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
12452 // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
12453 // not just the leading-space case the pre-lift `.bytes().any`
12454 // arm's opaque "must not contain whitespace" reason already
12455 // covered. Peer with `parse_rejects_tab_byte` on
12456 // `supervisor::duration_codec` (a7ae622).
12457 let mut s = three_member_spec();
12458 s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
12459 let err = s.validate().unwrap_err();
12460 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12461 panic!("expected EntradaHostInvalid, got {err:?}");
12462 };
12463 assert!(
12464 reason.contains("ASCII whitespace byte"),
12465 "expected byte-naming diagnostic, got {reason:?}"
12466 );
12467 assert!(
12468 reason.contains("0x09"),
12469 "expected offending tab byte 0x09, got {reason:?}"
12470 );
12471 }
12472
12473 #[test]
12474 fn rejects_entrada_host_lf_names_offending_byte() {
12475 // Embedded LF byte in the `:entrada :host` axis — the
12476 // canonical paste-from-shell-heredoc / paste-from-multiline-
12477 // doc footgun the caixa-mesh YAML emitter would silently
12478 // reinterpret at the Gateway API v1 HTTPRoute admission
12479 // layer (an embedded LF byte in a YAML plain scalar either
12480 // truncates the value at the emitter or crashes the parser
12481 // on the k8s-apiserver side). Pins the third representative
12482 // of the full ASCII-whitespace set through the shared
12483 // predicate.
12484 let mut s = three_member_spec();
12485 s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
12486 let err = s.validate().unwrap_err();
12487 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12488 panic!("expected EntradaHostInvalid, got {err:?}");
12489 };
12490 assert!(
12491 reason.contains("ASCII whitespace byte"),
12492 "expected byte-naming diagnostic, got {reason:?}"
12493 );
12494 assert!(
12495 reason.contains("0x0a"),
12496 "expected offending LF byte 0x0a, got {reason:?}"
12497 );
12498 }
12499
12500 #[test]
12501 fn rejects_entrada_host_nbsp_names_offending_codepoint() {
12502 // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
12503 // axis — the canonical paste-from-typography /
12504 // paste-from-word-processor footgun. Before the non-ASCII
12505 // Unicode `White_Space` scan lifted through the shared
12506 // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
12507 // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
12508 // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
12509 // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
12510 // with the far-from-source `label "…" must start and end
12511 // with an alphanumeric` diagnostic — burying the
12512 // paste-from-typography origin under a label-shape leak.
12513 // Peer with the sibling non-ASCII-whitespace pins at
12514 // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
12515 // — 1b75b38), `limits::parse_duration`,
12516 // `limits::parse_millicores`, and the shared duration codec
12517 // — same "the diagnostic carries the offending Unicode
12518 // codepoint's `U+XXXX` shape" discipline extended from every
12519 // typed-magnitude codec to the Gateway API v1 Hostname axis.
12520 let mut s = three_member_spec();
12521 s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
12522 let err = s.validate().unwrap_err();
12523 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12524 panic!("expected EntradaHostInvalid, got {err:?}");
12525 };
12526 assert!(
12527 reason.contains("non-ASCII Unicode whitespace character"),
12528 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12529 );
12530 assert!(
12531 reason.contains("U+00A0"),
12532 "expected offending NBSP codepoint U+00A0, got {reason:?}"
12533 );
12534 }
12535
12536 #[test]
12537 fn rejects_entrada_host_line_separator_names_offending_codepoint() {
12538 // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
12539 // `:entrada :host` axis — the canonical paste-from-web-doc /
12540 // paste-from-published-HTML footgun. `char::is_whitespace`
12541 // returns true for `U+2028` per the Unicode `White_Space`
12542 // property, so `str::trim` at any downstream site would
12543 // silently strip it — same drift class as NBSP but on a
12544 // different codepoint region. Pins the second representative
12545 // (non-Latin-1 `char::is_whitespace` member) through the
12546 // shared predicate. Peer with
12547 // `parse_byte_size_rejects_internal_line_separator` on
12548 // `limits::parse_byte_size` (1b75b38).
12549 let mut s = three_member_spec();
12550 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
12551 let err = s.validate().unwrap_err();
12552 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12553 panic!("expected EntradaHostInvalid, got {err:?}");
12554 };
12555 assert!(
12556 reason.contains("non-ASCII Unicode whitespace character"),
12557 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12558 );
12559 assert!(
12560 reason.contains("U+2028"),
12561 "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
12562 );
12563 }
12564
12565 #[test]
12566 fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
12567 // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
12568 // labels in the `:entrada :host` axis — the canonical
12569 // paste-from-CJK-typography footgun (CJK IMEs default to
12570 // full-width whitespace when the space bar is pressed in
12571 // Japanese / Chinese input modes). Pins the third
12572 // representative of the non-ASCII Unicode `White_Space` set
12573 // through the shared predicate: the CJK block, distinct from
12574 // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
12575 // SEPARATOR `U+2028` — covering the same axis breadth the
12576 // sibling `parse_byte_size_rejects_trailing_ideographic_space`
12577 // (1b75b38) pins on `limits::parse_byte_size`.
12578 let mut s = three_member_spec();
12579 s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
12580 let err = s.validate().unwrap_err();
12581 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12582 panic!("expected EntradaHostInvalid, got {err:?}");
12583 };
12584 assert!(
12585 reason.contains("non-ASCII Unicode whitespace character"),
12586 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12587 );
12588 assert!(
12589 reason.contains("U+3000"),
12590 "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
12591 );
12592 }
12593
12594 #[test]
12595 fn rejects_entrada_host_too_long() {
12596 // Total length cap = 253; build a 254-byte host out of two
12597 // 63-byte labels + one 62-byte label + dots.
12598 let mut s = three_member_spec();
12599 let big = format!(
12600 "{}.{}.{}.{}",
12601 "a".repeat(63),
12602 "b".repeat(63),
12603 "c".repeat(63),
12604 "d".repeat(254 - 63 * 3 - 3)
12605 );
12606 assert_eq!(big.len(), 254);
12607 s.entrada.as_mut().unwrap().host = big;
12608 let err = s.validate().unwrap_err();
12609 assert!(
12610 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12611 if reason.contains("max length of 253")),
12612 "got {err:?}"
12613 );
12614 }
12615
12616 #[test]
12617 fn rejects_entrada_host_label_too_long() {
12618 let mut s = three_member_spec();
12619 // 64-byte label — one over the per-label cap.
12620 s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
12621 let err = s.validate().unwrap_err();
12622 assert!(
12623 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12624 if reason.contains("label max length of 63")),
12625 "got {err:?}"
12626 );
12627 }
12628
12629 #[test]
12630 fn entrada_host_diagnostic_carries_offending_host() {
12631 // Diagnostic-shape pin — the offending host + a non-empty
12632 // reason flow through verbatim so the author can grep their
12633 // caixa.lisp for `:host "<host>"` and fix it in one edit.
12634 let mut s = three_member_spec();
12635 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
12636 let err = s.validate().unwrap_err();
12637 match err {
12638 AplicacaoError::EntradaHostInvalid { host, reason } => {
12639 assert_eq!(host, "checkout.quero.cloud:8080");
12640 assert!(!reason.is_empty(), "reason field must be non-empty");
12641 }
12642 other => panic!("expected EntradaHostInvalid, got {other:?}"),
12643 }
12644 }
12645
12646 #[test]
12647 fn entrada_host_empty_takes_precedence_over_invalid() {
12648 // Ordering pin: `EmptyEntradaHost` is the more self-locating
12649 // diagnostic on `""` and must lead — `validate_entrada_host`
12650 // is only reached after the empty-check fires at the call
12651 // site. (The predicate itself defends against direct
12652 // invocation by returning the same error on `""`.)
12653 let mut s = three_member_spec();
12654 s.entrada.as_mut().unwrap().host = String::new();
12655 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
12656 }
12657
12658 #[test]
12659 fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
12660 // Ordering pin: a missing :para member is the more
12661 // self-locating diagnostic and fires before the host gate.
12662 let mut s = three_member_spec();
12663 let e = s.entrada.as_mut().unwrap();
12664 e.para = "ghost".into();
12665 e.host = "BAD HOST".into();
12666 let err = s.validate().unwrap_err();
12667 assert!(
12668 matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
12669 "got {err:?}"
12670 );
12671 }
12672
12673 #[test]
12674 fn entrada_host_invalid_fires_before_port_zero() {
12675 // Ordering pin: the host gate fires before the port gate so
12676 // a malformed host is named even when the port is also wrong.
12677 let mut s = three_member_spec();
12678 let e = s.entrada.as_mut().unwrap();
12679 e.host = "Checkout.quero.cloud".into();
12680 e.port = 0;
12681 let err = s.validate().unwrap_err();
12682 assert!(
12683 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12684 if host == "Checkout.quero.cloud"),
12685 "got {err:?}"
12686 );
12687 }
12688
12689 #[test]
12690 fn entrada_accepts_canonical_hosts() {
12691 // Positive-control sweep — every form the Gateway API
12692 // apiserver accepts must round-trip through validate. Covers
12693 // a plain DNS subdomain, a leading wildcard, a single-label
12694 // host (cluster-internal), a max-length-edge label, a
12695 // hyphen-bearing label, and a Punycode IDN label.
12696 for host in [
12697 "checkout.quero.cloud",
12698 "*.quero.cloud",
12699 "checkout",
12700 // 63-byte label — exactly the per-label cap.
12701 "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
12702 "foo-bar.quero.cloud",
12703 // Punycode IDN — valid because the author pre-encoded.
12704 "xn--bcher-kva.example.com",
12705 ] {
12706 let mut s = three_member_spec();
12707 s.entrada.as_mut().unwrap().host = host.into();
12708 s.validate()
12709 .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
12710 }
12711 }
12712
12713 #[test]
12714 fn entrada_host_max_length_validates() {
12715 // 253-byte host is the cap exactly — must validate. Build a
12716 // 253-byte host out of three 63-byte labels + one 61-byte
12717 // label + 3 dots = 252 bytes, then pad one byte to 253.
12718 let mut s = three_member_spec();
12719 let host = format!(
12720 "{}.{}.{}.{}",
12721 "a".repeat(63),
12722 "b".repeat(63),
12723 "c".repeat(63),
12724 "d".repeat(253 - 63 * 3 - 3)
12725 );
12726 assert_eq!(host.len(), 253);
12727 s.entrada.as_mut().unwrap().host = host;
12728 s.validate().unwrap();
12729 }
12730
12731 #[test]
12732 fn entrada_host_total_length_cap_threads_lifted_render_const() {
12733 // Cross-crate-side pin: the aplicacao-side `:entrada :host`
12734 // total-length gate now reads the K8s Gateway API v1 Hostname
12735 // `maxLength: 253` cap from the lifted
12736 // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
12737 // of truth — the same constant every future Gateway-API-Hostname
12738 // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
12739 // materializer's per-host validator, the future per-`Certificate`
12740 // SAN emitter for cert-manager, the multi-`:entrada`
12741 // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
12742 // from. Before the lift, the aplicacao-side reader consumed a
12743 // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
12744 // 253-byte value as the peer render-side canonical bounds
12745 // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
12746 // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
12747 // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
12748 // module boundary — a future 253-byte drift on either side would
12749 // silently split into two axes' worth of admission-schema mismatch
12750 // without a build-time signal. Pin the cap through a fresh 254-
12751 // byte host that hits the total-length arm, then read the reason
12752 // for the exact byte count the shared constant carries: any future
12753 // regression on the lift (a private alias reintroduced, a hard-
12754 // coded literal at the arm, a mismatch between the aplicacao-side
12755 // and render-side canonicals) surfaces as this pin's diagnostic
12756 // failing to match, not as a per-cluster admission rejection far
12757 // from the caixa.lisp source line.
12758 let mut s = three_member_spec();
12759 let over_cap = format!(
12760 "{}.{}.{}.{}",
12761 "a".repeat(63),
12762 "b".repeat(63),
12763 "c".repeat(63),
12764 "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
12765 );
12766 assert_eq!(
12767 over_cap.len(),
12768 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
12769 );
12770 s.entrada.as_mut().unwrap().host = over_cap;
12771 let err = s.validate().unwrap_err();
12772 match err {
12773 AplicacaoError::EntradaHostInvalid { reason, .. } => {
12774 let needle = format!(
12775 "max length of {} bytes",
12776 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
12777 );
12778 assert!(
12779 reason.contains(&needle),
12780 "diagnostic must name the lifted \
12781 GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
12782 );
12783 }
12784 other => panic!("expected EntradaHostInvalid, got {other:?}"),
12785 }
12786 }
12787
12788 #[test]
12789 fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
12790 // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
12791 // on the per-label-cap axis. Before the lift, the aplicacao-side
12792 // per-label arm consumed a private const alias
12793 // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
12794 // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
12795 // split from it at the module boundary — every `.`-separated
12796 // label in a Gateway API v1 Hostname is a DNS-1123 label under
12797 // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
12798 // so the private alias's 63 and the canonical const's 63 were
12799 // pinning the same underlying rule twice. Pin the cap through a
12800 // 64-byte label that hits the per-label arm, then read the reason
12801 // for the exact byte count the shared constant carries: any
12802 // future drift on either side (a private alias reintroduced, a
12803 // hard-coded literal at the arm, a mismatch between the two
12804 // 63-byte pins) surfaces at this pin's diagnostic rather than at
12805 // a per-cluster admission rejection whose "field is invalid"
12806 // opacity misframes the root cause.
12807 let mut s = three_member_spec();
12808 let over_cap_label = format!(
12809 "{}.quero.cloud",
12810 "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
12811 );
12812 s.entrada.as_mut().unwrap().host = over_cap_label;
12813 let err = s.validate().unwrap_err();
12814 match err {
12815 AplicacaoError::EntradaHostInvalid { reason, .. } => {
12816 let needle = format!(
12817 "label max length of {} bytes",
12818 crate::render::DNS_1123_LABEL_MAX_LEN,
12819 );
12820 assert!(
12821 reason.contains(&needle),
12822 "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
12823 cap verbatim on the per-label arm, got: {reason:?}",
12824 );
12825 }
12826 other => panic!("expected EntradaHostInvalid, got {other:?}"),
12827 }
12828 }
12829
12830 #[test]
12831 fn entrada_with_empty_paths_validates() {
12832 // Empty `:paths` is the documented "match every path" form;
12833 // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
12834 let mut s = three_member_spec();
12835 s.entrada.as_mut().unwrap().paths = vec![];
12836 s.validate().unwrap();
12837 }
12838
12839 #[test]
12840 fn entrada_root_path_validates() {
12841 // The author-supplied bare-root `:entrada :paths` entry is the
12842 // same byte-shape the peer emit-side catch-all constant
12843 // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
12844 // the author's `:paths` list is empty — sweeping the test-side
12845 // probe literal onto the lifted const closes the two-axis pin
12846 // (author-side admit + emit-side canonical fallback) around
12847 // one `&'static str`, so a future rebrand of the catch-all
12848 // reaches both consumers by construction. Peer to
12849 // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
12850 // on the canonical-literal pin surface.
12851 let mut s = three_member_spec();
12852 s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
12853 s.validate().unwrap();
12854 }
12855
12856 #[test]
12857 fn placement_strategy_variants_round_trip() {
12858 for s in [
12859 PlacementStrategy::SingleNode,
12860 PlacementStrategy::Replicated,
12861 PlacementStrategy::Sharded,
12862 ] {
12863 let p = Placement {
12864 estrategia: s,
12865 clusters: vec!["rio".into()],
12866 affinity: None,
12867 shard_key: if s.is_sharded() {
12868 Some("$key".into())
12869 } else {
12870 None
12871 },
12872 };
12873 let json = serde_json::to_string(&p).unwrap();
12874 let back: Placement = serde_json::from_str(&json).unwrap();
12875 assert_eq!(back, p);
12876 }
12877 }
12878
12879 #[test]
12880 fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
12881 // The fail-before-pass-after pin: pre-lift there was no
12882 // single-source binding between the [`PlacementStrategy`]
12883 // variant name the `Serialize` derive emits and the byte-
12884 // string every downstream cluster-side dispatcher (the
12885 // `lareira-fleet-programs` aggregator's per-entry strategy
12886 // branch, the future `app-operator` reconciler, the M3
12887 // Adaptive compression pass's per-strategy weighting) probes
12888 // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
12889 // future `#[serde(rename_all = "kebab-case")]` attribute on
12890 // the enum — or a variant rename in the source — would
12891 // silently rebrand the emitted scalar under one spelling
12892 // while every downstream dispatcher still probed the other,
12893 // with the failure surfacing at the aggregator's dispatch
12894 // step or the operator's reconcile posture (workloads coming
12895 // up under the `default()` `Replicated` arm rather than the
12896 // typed slot's declared strategy) far from the source
12897 // rebrand commit and with no field naming the drift. Pinning
12898 // the two paths (the `Serialize` derive's serialized string
12899 // AND the [`PlacementStrategy::as_str`] helper) to the same
12900 // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
12901 // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
12902 // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
12903 // makes any future drift on either endpoint fail here at
12904 // caixa-core build time.
12905 for (variant, expected) in [
12906 (
12907 PlacementStrategy::SingleNode,
12908 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
12909 ),
12910 (
12911 PlacementStrategy::Replicated,
12912 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
12913 ),
12914 (
12915 PlacementStrategy::Sharded,
12916 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
12917 ),
12918 ] {
12919 let json = serde_json::to_string(&variant).unwrap();
12920 assert_eq!(
12921 json,
12922 format!("\"{expected}\""),
12923 "PlacementStrategy::{variant:?} must serialize to {expected:?}"
12924 );
12925 assert_eq!(
12926 variant.as_str(),
12927 expected,
12928 "PlacementStrategy::{variant:?}.as_str() must return the lifted \
12929 M3_PLACEMENT_ESTRATEGIA_* constant"
12930 );
12931 }
12932 }
12933
12934 #[test]
12935 fn m3_placement_estrategia_consts_are_pairwise_distinct() {
12936 // Cross-arm drift-detection pin on the M3
12937 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
12938 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
12939 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
12940 // scalar-value pentad: a future collapse of two canonical
12941 // variant byte-strings onto the same value (an accidental
12942 // copy-paste flip of
12943 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
12944 // read `"SingleNode"`, a per-arm rebrand that lands one const
12945 // without touching its paired peer) would silently reroute
12946 // every downstream operator's per-strategy dispatch onto the
12947 // sibling arm's reconcile branch and pass every
12948 // propagation-probe test that expected only the stale arm's
12949 // value — a `Replicated`-declared Aplicacao would come up
12950 // under the `SingleNode` primary-and-standby reconcile
12951 // posture, so every-cluster active-active workload would
12952 // silently collapse onto one-cluster-runs-at-a-time takeover
12953 // semantics against its declared strategy, with no field
12954 // naming the strategy-value drift root cause. Peer of the
12955 // sibling
12956 // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
12957 // (09ffb2d) /
12958 // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
12959 // (ccdf955) /
12960 // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
12961 // (d739850) distinctness pins on the sibling OTP-shape /
12962 // caixa-kind closed-set typed-enum discriminator axes — the
12963 // fourth (and structurally the M3 mesh-primitive-defining)
12964 // closed-set typed-enum axis to converge on the same
12965 // "pairwise-distinct-by-construction" discipline.
12966 //
12967 // Fail-before-pass-after locally verified by mutating
12968 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
12969 // also read `"SingleNode"` — this pin fires as expected;
12970 // restoring passes.
12971 let all = [
12972 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
12973 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
12974 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
12975 ];
12976 for (i, a) in all.iter().enumerate() {
12977 for (j, b) in all.iter().enumerate() {
12978 if i != j {
12979 assert_ne!(
12980 a, b,
12981 "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
12982 distinct — got duplicate {a:?} at indices {i} and {j}",
12983 );
12984 }
12985 }
12986 }
12987 }
12988
12989 #[test]
12990 fn placement_strategy_display_routes_through_as_str_helper() {
12991 // The fail-before-pass-after pin: pre-lift the sibling
12992 // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
12993 // / [`crate::supervisor::RestartPolicy`] both carried a stable
12994 // [`std::fmt::Display`] surface via their
12995 // `#[discriminant(also_display)]` gen-platform derive, but
12996 // [`PlacementStrategy`] did not — every consumer reaching for
12997 // a strategy byte-string past the wire format had to pick
12998 // between three paths ([`PlacementStrategy::as_str`], the
12999 // `Serialize` derive's serialized string, or `format!("{v:?}")`
13000 // on the `Debug` derive), any two of which a future variant
13001 // rename or `#[serde(rename_all = "kebab-case")]` attribute
13002 // would silently desynchronize. Wiring [`std::fmt::Display`]
13003 // through [`PlacementStrategy::as_str`] closes the third path:
13004 // every `format!("{v}")` call reaches the same lifted
13005 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
13006 // and the [`PlacementStrategy::as_str`] helper already route
13007 // through, so a future variant rename lands at exactly one
13008 // place. Pin the routing here so a future
13009 // `impl std::fmt::Display for PlacementStrategy` reimplementation
13010 // that hand-rolls the arms instead of delegating to
13011 // [`PlacementStrategy::as_str`] fails at caixa-core build time.
13012 for variant in [
13013 PlacementStrategy::SingleNode,
13014 PlacementStrategy::Replicated,
13015 PlacementStrategy::Sharded,
13016 ] {
13017 assert_eq!(
13018 variant.to_string(),
13019 variant.as_str(),
13020 "PlacementStrategy::{variant:?} Display must route through \
13021 PlacementStrategy::as_str (single source of truth: the lifted \
13022 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
13023 );
13024 }
13025 }
13026
13027 #[test]
13028 fn placement_strategy_display_matches_serialized_wire_byte_string() {
13029 // The fail-before-pass-after pin on the second half of the
13030 // three-path convergence: `Display` (user-facing text) agrees
13031 // byte-for-byte with the `Serialize` derive's wire format
13032 // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
13033 // scalar) on every variant. Pre-lift the two paths were
13034 // structurally independent — a future
13035 // `#[serde(rename_all = "kebab-case")]` attribute on the enum
13036 // would silently rebrand the emitted wire scalar
13037 // (`single-node`, `replicated`, `sharded`) while every consumer
13038 // that pretty-prints the strategy (the M3 diagnostic templates,
13039 // the future `feira app graph` per-Aplicacao strategy line,
13040 // the future M4 CR materializer's admission-webhook rejection
13041 // body) would still emit the TitleCase form the `as_str` /
13042 // `Display` route returns, with the mismatch surfacing at
13043 // consumer parse time / operator dispatch time far from the
13044 // source rebrand commit. Pin the two paths byte-for-byte here
13045 // so any future serde-attribute or variant-rename drift is a
13046 // caixa-core-build-time test failure at this call, not a
13047 // silent per-consumer dispatch miss.
13048 for variant in [
13049 PlacementStrategy::SingleNode,
13050 PlacementStrategy::Replicated,
13051 PlacementStrategy::Sharded,
13052 ] {
13053 let wire = serde_json::to_string(&variant).unwrap();
13054 // Strip the outer `"…"` the JSON string form carries — the
13055 // wire scalar the K8s / YAML apiserver consumes is the
13056 // enclosed byte-string, not the quote wrapper.
13057 let unquoted = wire
13058 .strip_prefix('"')
13059 .and_then(|s| s.strip_suffix('"'))
13060 .expect("serialized PlacementStrategy is a JSON string");
13061 assert_eq!(
13062 variant.to_string(),
13063 unquoted,
13064 "PlacementStrategy::{variant:?} Display byte-string must match the \
13065 Serialize derive's wire byte-string (three-path convergence: \
13066 Display + as_str + Serialize all resolve to the same \
13067 M3_PLACEMENT_ESTRATEGIA_* const)"
13068 );
13069 }
13070 }
13071
13072 #[test]
13073 fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
13074 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
13075 // derive on [`PlacementStrategy`]: for each of the three variants
13076 // exactly one of the generated `is_single_node` / `is_replicated`
13077 // / `is_sharded` predicates returns `true` and the other two
13078 // return `false`. Prior to this derive the three per-arm
13079 // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
13080 // (the `placement_strategy_variants_round_trip` fixture, the
13081 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
13082 // fixture, and the
13083 // `validate_placement_reads_through_lifted_estrategia_accessor`
13084 // fixture) each open-coded a per-arm PartialEq compare against
13085 // the enum variant — three sites that expressed no compile-time
13086 // link back to the closed-set typed dispatch a future fourth
13087 // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
13088 // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
13089 // would have to thread through in lockstep or one fixture would
13090 // silently disagree with the others on which arms consume the
13091 // `:shard-key` axis. Peer of the sibling
13092 // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
13093 // / [`crate::supervisor::RestartPolicy`] /
13094 // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
13095 // the sibling closed-set typed-enum discriminator axes — extends
13096 // the same one-typed-dispatch-per-variant discipline onto the
13097 // fifth (and only remaining) closed-set typed-enum discriminator
13098 // on the caixa surface, closing the axis on the M3 mesh-slot
13099 // family.
13100 let rows: [(PlacementStrategy, [bool; 3]); 3] = [
13101 (PlacementStrategy::SingleNode, [true, false, false]),
13102 (PlacementStrategy::Replicated, [false, true, false]),
13103 (PlacementStrategy::Sharded, [false, false, true]),
13104 ];
13105 for (variant, expected) in rows {
13106 let observed = [
13107 variant.is_single_node(),
13108 variant.is_replicated(),
13109 variant.is_sharded(),
13110 ];
13111 assert_eq!(
13112 observed, expected,
13113 "PlacementStrategy::{variant:?} is_* predicates must partition \
13114 the arm set (single_node, replicated, sharded); got {observed:?}"
13115 );
13116 }
13117 }
13118
13119 #[test]
13120 fn placement_strategy_is_variant_predicates_are_const_fn() {
13121 // The [`gen_platform::IsVariant`] derive emits `const fn`
13122 // predicates on the peer [`crate::CaixaKind`] +
13123 // [`crate::upgrade::UpgradeInstruction`] +
13124 // [`crate::supervisor::RestartStrategy`] +
13125 // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
13126 // pin the same posture on [`PlacementStrategy`] so a future
13127 // accidental downgrade to non-`const` (an added runtime helper
13128 // reachable only from a non-`const` context, a manual hand-rolled
13129 // `impl` that shadows the derive-generated method) trips at
13130 // caixa-core build time rather than surfacing as a downstream
13131 // `const`-context regression far from the derive declaration.
13132 const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
13133 const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
13134 const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
13135 assert!(IS_SINGLE_NODE);
13136 assert!(IS_REPLICATED);
13137 assert!(IS_SHARDED);
13138 }
13139
13140 #[test]
13141 fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
13142 // Pin the M3 diagnostic template routes through the typed
13143 // [`PlacementStrategy`] Display byte-string (rebound from the
13144 // prior `{estrategia:?}` `Debug` route). Pre-lift the two
13145 // routes emitted identical bytes (the `Debug` derive on a
13146 // unit variant emits the variant name verbatim, exactly what
13147 // `as_str` returns), but the two paths were structurally
13148 // independent — a future `#[serde(rename_all = "…")]`
13149 // attribute or variant rename would coordinate the wire /
13150 // `Display` / `as_str` triple through the lifted const but
13151 // leave the `Debug` route on the compiler-derived variant name,
13152 // silently desynchronizing the diagnostic byte-string from the
13153 // wire byte-string. Rebinding the template onto `Display`
13154 // ties the diagnostic to the same lifted
13155 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
13156 // emits — drift becomes structurally impossible. Pin the
13157 // byte-string here so a future edit that reverts the template
13158 // to `{estrategia:?}` is caught at caixa-core test time, not
13159 // at consumer dispatch time.
13160 for (variant, expected_scalar) in [
13161 (
13162 PlacementStrategy::SingleNode,
13163 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13164 ),
13165 (
13166 PlacementStrategy::Replicated,
13167 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13168 ),
13169 (
13170 PlacementStrategy::Sharded,
13171 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13172 ),
13173 ] {
13174 let err = AplicacaoError::PlacementWithoutClusters {
13175 estrategia: variant,
13176 };
13177 let msg = err.to_string();
13178 assert!(
13179 msg.starts_with(&format!(":placement {expected_scalar} requires")),
13180 "PlacementWithoutClusters diagnostic for {variant:?} must open \
13181 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
13182 );
13183 }
13184 }
13185
13186 #[test]
13187 fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
13188 // Peer of
13189 // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
13190 // on the second M3 diagnostic that carries the typed
13191 // [`PlacementStrategy`] in its `#[error(…)]` template. Both
13192 // diagnostics now route the strategy scalar through the same
13193 // [`std::fmt::Display`] surface, tying the diagnostic
13194 // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
13195 // const set the wire format also emits. The two non-Sharded
13196 // arms are exercised here (the diagnostic exists to flag a
13197 // `:shard-key` slot the current strategy will never consume);
13198 // the peer `Sharded` arm never reaches this diagnostic (the
13199 // `Sharded` strategy consumes `:shard-key` — the
13200 // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
13201 // slot instead).
13202 for (variant, expected_scalar) in [
13203 (
13204 PlacementStrategy::SingleNode,
13205 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13206 ),
13207 (
13208 PlacementStrategy::Replicated,
13209 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13210 ),
13211 ] {
13212 let err = AplicacaoError::ShardKeyOnNonSharded {
13213 estrategia: variant,
13214 shard_key: "$tenantId".into(),
13215 };
13216 let msg = err.to_string();
13217 assert!(
13218 msg.starts_with(&format!(":placement {expected_scalar} carries")),
13219 "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
13220 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
13221 );
13222 }
13223 }
13224
13225 #[test]
13226 fn placement_strategy_all_enumerates_every_variant_once() {
13227 // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
13228 // exhaustive-iteration surface: every variant appears exactly
13229 // once, and the slice length matches the arm count of the
13230 // closed set. Every consumer that walks the accepted-strategy
13231 // set (a future `feira app placement --list` CLI-side surfacing,
13232 // a future M4 admission-webhook's rejection body naming the
13233 // accepted-strategy list, the [`PlacementStrategy::from_wire`]
13234 // reverse-projection consumers that iterate the accept-set for
13235 // a "did you mean" hint) reads through this slice, so a future
13236 // variant addition (an `Anycast` mesh-anycast arm the
13237 // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
13238 // grows the enum but forgets to grow [`Self::ALL`] silently
13239 // truncates every downstream consumer's accept-set at the same
13240 // pre-addition boundary — this pin fails at caixa-core build
13241 // time on the pairwise-distinct + arm-count invariants.
13242 //
13243 // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
13244 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
13245 // pins on the peer closed-set typed-enum axes.
13246 let all: &[PlacementStrategy] = PlacementStrategy::ALL;
13247 assert_eq!(
13248 all.len(),
13249 3,
13250 "PlacementStrategy::ALL must enumerate every variant of the \
13251 three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
13252 );
13253 for (i, a) in all.iter().enumerate() {
13254 for (j, b) in all.iter().enumerate() {
13255 if i != j {
13256 assert_ne!(
13257 a, b,
13258 "PlacementStrategy::ALL must carry every variant exactly \
13259 once — got duplicate {a:?} at indices {i} and {j}"
13260 );
13261 }
13262 }
13263 }
13264 for variant in [
13265 PlacementStrategy::SingleNode,
13266 PlacementStrategy::Replicated,
13267 PlacementStrategy::Sharded,
13268 ] {
13269 assert!(
13270 all.contains(&variant),
13271 "PlacementStrategy::ALL must contain {variant:?} — a future variant \
13272 addition that grows the enum but forgets to grow the ALL slice \
13273 silently truncates every downstream consumer's accept-set at the \
13274 pre-addition boundary"
13275 );
13276 }
13277 }
13278
13279 #[test]
13280 fn placement_strategy_from_wire_accepts_every_lifted_constant() {
13281 // Fail-before-pass-after pin on the forward accept-set of the
13282 // [`PlacementStrategy::from_wire`] reverse projection: every
13283 // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
13284 // constant the [`PlacementStrategy::as_str`] emitter walks
13285 // parses back to its paired variant. Any future arm addition
13286 // that grows the emitter's `as_str` match but forgets to grow
13287 // the parser's `from_str` match silently splits the two halves
13288 // of the round-trip — the wire byte-string one non-serde
13289 // consumer parses from the one the emitter wrote — with the
13290 // failure surfacing at parse time far from the rebrand commit.
13291 // Pinning the three-arm accept-set here catches the drift at
13292 // caixa-core build time.
13293 //
13294 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
13295 // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
13296 // closed-set typed-enum `str → Self` axes.
13297 for (wire, expected) in [
13298 (
13299 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13300 PlacementStrategy::SingleNode,
13301 ),
13302 (
13303 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13304 PlacementStrategy::Replicated,
13305 ),
13306 (
13307 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13308 PlacementStrategy::Sharded,
13309 ),
13310 ] {
13311 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
13312 panic!(
13313 "PlacementStrategy::from_wire({wire:?}) must accept every \
13314 M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
13315 lifted canonical byte-string that PlacementStrategy::{expected:?} \
13316 serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
13317 )
13318 });
13319 assert_eq!(
13320 parsed, expected,
13321 "PlacementStrategy::from_wire({wire:?}) must return \
13322 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
13323 );
13324 }
13325 }
13326
13327 #[test]
13328 fn placement_strategy_from_wire_round_trips_through_as_str() {
13329 // Fail-before-pass-after pin on the closed round-trip between
13330 // the forward [`PlacementStrategy::as_str`] emitter and the
13331 // reverse [`PlacementStrategy::from_wire`] parser: for every
13332 // variant in [`PlacementStrategy::ALL`], parsing the emitter's
13333 // output must return exactly the same variant. Any per-arm
13334 // divergence — a future arm added to `as_str` but not
13335 // `from_str`, an accidental copy-paste flip in one but not the
13336 // other — silently splits the emit and parse halves and the
13337 // failure surfaces at consumer parse time far from the drift
13338 // site. The `ALL`-iterating shape means a future variant
13339 // addition picks up the coverage by construction.
13340 //
13341 // Peer of the sibling [`crate::kind::tests`] round-trip pin on
13342 // [`crate::CaixaKind::from_wire`] and the
13343 // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
13344 // sibling round-trip pin on [`RateLimitUnit`].
13345 for &variant in PlacementStrategy::ALL {
13346 let wire = variant.as_str();
13347 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
13348 panic!(
13349 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
13350 must be Some({variant:?}) — the two halves of the round-trip \
13351 dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
13352 got None on wire byte-string {wire:?}"
13353 )
13354 });
13355 assert_eq!(
13356 parsed, variant,
13357 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
13358 must round-trip to the same variant; got {parsed:?}"
13359 );
13360 }
13361 }
13362
13363 #[test]
13364 fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
13365 // Fail-before-pass-after pin on the closed-set refusal
13366 // discipline of [`PlacementStrategy::from_wire`]: every
13367 // byte-string outside the three-arm accept-set returns `None`
13368 // rather than silently collapsing onto the [`Default`]
13369 // (`Replicated`) arm or an arbitrary neighbor. The refusal set
13370 // exercised here sweeps the load-bearing drift shapes: the
13371 // empty string (a stripped serde-attribute drift), an all-
13372 // whitespace string (the canonical text-editor accidental
13373 // padding shape), the lowercased kebab-case forms a future
13374 // `#[serde(rename_all = "kebab-case")]` attribute would emit
13375 // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
13376 // coincidentally match the accepted canonical scalars, so only
13377 // `"single-node"` fires as a refusal, but pinning the case-
13378 // sensitivity of the accepted arms via the peer [`SingleNode`]
13379 // assertion in the round-trip pin makes the discipline
13380 // structurally clear), the lowercased single-word forms
13381 // (`"singlenode"`), the padded canonical scalar
13382 // (`" Sharded "`), the trailing-comma / trailing-newline shapes
13383 // (`"Sharded\n"`), and a pointer-different `&'static str` that
13384 // happens to alias a canonical byte-string by content but not
13385 // by identity (validated implicitly by the emitter's routing
13386 // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
13387 // identity a paired [`crate::assert_str_reexport_identity`] pin
13388 // in caixa-core's per-const declaration surface would catch).
13389 //
13390 // Peer of the sibling
13391 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
13392 // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
13393 for bad in [
13394 "",
13395 " ",
13396 "\n",
13397 "\t",
13398 "single-node",
13399 "singlenode",
13400 "SingleNodes",
13401 "single_node",
13402 "single node",
13403 "SINGLENODE",
13404 "SingleNode ",
13405 " SingleNode",
13406 " Sharded ",
13407 "Sharded\n",
13408 "replicated ",
13409 "sharded",
13410 "REPLICATED",
13411 "Anycast",
13412 "Global",
13413 "?",
13414 ] {
13415 assert!(
13416 PlacementStrategy::from_wire(bad).is_none(),
13417 "PlacementStrategy::from_wire({bad:?}) must return None — the \
13418 parser's accept-set is exactly the three PlacementStrategy::as_str \
13419 outputs (SingleNode, Replicated, Sharded), and this byte-string \
13420 is outside that closed set"
13421 );
13422 }
13423 }
13424
13425 #[test]
13426 fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
13427 // Fail-before-pass-after pin on the third path of the four-path
13428 // convergence: `from_str` (the reverse projection) inverts the
13429 // `Serialize` derive's wire byte-string on every variant.
13430 // Together with the pre-existing three-path convergence
13431 // (`Display` + `as_str` + `Serialize` all resolve to the same
13432 // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
13433 // the peer
13434 // [`placement_strategy_display_matches_serialized_wire_byte_string`])
13435 // this closes the round-trip: the wire byte-string the
13436 // `Serialize` derive emits parses back to the same variant
13437 // through `from_str`, so any future serde-attribute or variant-
13438 // rename drift on the emit half now surfaces as a matched drift
13439 // on the parse half at caixa-core build time — the two halves
13440 // migrate as a unit through the lifted consts on any future
13441 // rename, and the round-trip cannot silently split.
13442 //
13443 // Peer of the sibling
13444 // [`placement_strategy_display_matches_serialized_wire_byte_string`]
13445 // wire-format pin — extends the three-path convergence
13446 // (`Display` + `as_str` + `Serialize`) onto the fourth path
13447 // (`from_str`), closing the `str ↔ Self` round-trip on the
13448 // M3 `:placement :estrategia` closed-set axis.
13449 for &variant in PlacementStrategy::ALL {
13450 let wire = serde_json::to_string(&variant).unwrap();
13451 let unquoted = wire
13452 .strip_prefix('"')
13453 .and_then(|s| s.strip_suffix('"'))
13454 .expect("serialized PlacementStrategy is a JSON string");
13455 let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
13456 panic!(
13457 "PlacementStrategy::from_wire({unquoted:?}) must accept the \
13458 Serialize derive's wire byte-string for \
13459 PlacementStrategy::{variant:?} — the four-path convergence \
13460 (Display + as_str + Serialize + from_str) resolves through \
13461 the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
13462 )
13463 });
13464 assert_eq!(
13465 parsed, variant,
13466 "PlacementStrategy::from_wire of the Serialize derive's wire \
13467 byte-string for PlacementStrategy::{variant:?} must round-trip \
13468 to the same variant; got {parsed:?}"
13469 );
13470 }
13471 }
13472
13473 #[test]
13474 fn rejects_zero_policy_timeout() {
13475 let mut s = three_member_spec();
13476 s.politicas.timeout = Some(Duration::ZERO);
13477 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
13478 }
13479
13480 #[test]
13481 fn rejects_zero_policy_retries() {
13482 let mut s = three_member_spec();
13483 s.politicas.retries = Some(0);
13484 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
13485 }
13486
13487 #[test]
13488 fn rejects_policy_retries_above_cap() {
13489 // The fail-before-pass-after pin: `Some(11)` is structurally
13490 // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
13491 // passed validate on every pre-gate codebase because the
13492 // typed slot's only check was the zero-floor arm. The
13493 // thundering-herd amplification vector only surfaced at the
13494 // runtime substrate (Envoy / Cilium L7 retry overlay)
13495 // far from the source caixa.lisp with no field naming the
13496 // offending policy.
13497 let mut s = three_member_spec();
13498 s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
13499 assert_eq!(
13500 s.validate().unwrap_err(),
13501 AplicacaoError::PolicyRetriesExceedsCap {
13502 retries: POLICY_RETRIES_MAX + 1
13503 }
13504 );
13505 }
13506
13507 #[test]
13508 fn rejects_policy_retries_far_above_cap() {
13509 // The `u32::MAX` worst case — the four-billion-retry policy
13510 // a typo (`(:retries 4294967295)`) or struct-literal
13511 // copy-paste lands in the slot. Pin the cap arm's coverage
13512 // explicitly across the full `u32` overflow so a future
13513 // relaxation that drops the upper bound surfaces here.
13514 let mut s = three_member_spec();
13515 s.politicas.retries = Some(u32::MAX);
13516 assert_eq!(
13517 s.validate().unwrap_err(),
13518 AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
13519 );
13520 }
13521
13522 #[test]
13523 fn accepts_policy_retries_at_cap() {
13524 // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
13525 // must validate. The cap is inclusive on the top edge,
13526 // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
13527 // discipline on the sibling [`crate::LimitsSpec::memory`]
13528 // axis. Pin the boundary explicitly so a future off-by-one
13529 // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
13530 // surfaces here as a test failure rather than a silent
13531 // contract narrowing.
13532 let mut s = three_member_spec();
13533 s.politicas.retries = Some(POLICY_RETRIES_MAX);
13534 s.validate()
13535 .expect("retries == POLICY_RETRIES_MAX must validate");
13536 }
13537
13538 #[test]
13539 fn accepts_policy_retries_typical_values() {
13540 // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
13541 // every value in the validated set must pass. The
13542 // Envoy / Istio production-playbook recommendation band
13543 // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
13544 // (`maxRetries ≤ 10`) both lie within this set.
13545 for r in 1..=POLICY_RETRIES_MAX {
13546 let mut s = three_member_spec();
13547 s.politicas.retries = Some(r);
13548 s.validate()
13549 .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
13550 }
13551 }
13552
13553 #[test]
13554 fn policy_retries_zero_takes_precedence_over_cap() {
13555 // The cross-arm ordering pin: `Some(0)` is structurally
13556 // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
13557 // (cap), but the zero-floor diagnostic is the more
13558 // self-locating one (it directly names the omit-axis
13559 // remediation), so the validate gate must fire on zero
13560 // first. Pin the order so a future refactor that reorders
13561 // the arms surfaces here as a test failure rather than a
13562 // silent diagnostic regression. Same shape every other
13563 // zero-then-shape ordering on this surface uses
13564 // ([`AplicacaoError::PolicyTimeoutZero`] then
13565 // [`AplicacaoError::PolicyTimeoutNotCanonical`];
13566 // [`AplicacaoError::PolicyBreakerZeroWindow`] then
13567 // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
13568 let mut s = three_member_spec();
13569 s.politicas.retries = Some(0);
13570 assert_eq!(
13571 s.validate().unwrap_err(),
13572 AplicacaoError::PolicyRetriesZero,
13573 "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
13574 );
13575 }
13576
13577 #[test]
13578 fn policy_retries_cap_diagnostic_carries_offending_value() {
13579 // The diagnostic-shape pin: the offending `u32` is carried
13580 // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
13581 // variant so the surfaced error message names the value the
13582 // author wrote (`":politicas :retries (47) exceeds the
13583 // mesh-policy ceiling …"`), not just the cap. Same
13584 // self-locating diagnostic shape every other typed-cap arm
13585 // on this surface carries
13586 // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
13587 // offending byte count verbatim).
13588 let mut s = three_member_spec();
13589 s.politicas.retries = Some(47);
13590 let err = s.validate().unwrap_err();
13591 assert!(
13592 matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
13593 "got {err:?}"
13594 );
13595 let msg = err.to_string();
13596 assert!(
13597 msg.contains("47"),
13598 ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
13599 );
13600 }
13601
13602 #[test]
13603 fn policy_retries_cap_is_aws_app_mesh_aligned() {
13604 // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
13605 // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
13606 // schema cap — the only upstream mesh-policy schema that
13607 // documents an explicit hard cap. Pinning the literal value
13608 // here surfaces a future drift (a relaxation to 20, a
13609 // tightening to 5) as a deliberate test edit, not a silent
13610 // contract narrowing.
13611 assert_eq!(POLICY_RETRIES_MAX, 10);
13612 }
13613
13614 #[test]
13615 fn rejects_circuit_breaker_zero_max_failures() {
13616 let mut s = three_member_spec();
13617 s.politicas.circuit_breaker = Some(CircuitBreaker {
13618 max_failures: 0,
13619 window: Duration::from_secs(60),
13620 });
13621 assert_eq!(
13622 s.validate().unwrap_err(),
13623 AplicacaoError::PolicyBreakerZeroFailures
13624 );
13625 }
13626
13627 #[test]
13628 fn rejects_circuit_breaker_max_failures_above_cap() {
13629 // The fail-before-pass-after pin: `1001` is structurally one
13630 // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
13631 // silently passed validate on every pre-gate codebase
13632 // because the typed slot's only check was the zero-floor
13633 // arm. The breaker-no-op vector only surfaced at the runtime
13634 // substrate (Envoy / Cilium L7 outlier-detection overlay)
13635 // far from the source caixa.lisp with no field naming the
13636 // offending policy.
13637 let mut s = three_member_spec();
13638 s.politicas.circuit_breaker = Some(CircuitBreaker {
13639 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13640 window: Duration::from_secs(60),
13641 });
13642 assert_eq!(
13643 s.validate().unwrap_err(),
13644 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13645 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13646 }
13647 );
13648 }
13649
13650 #[test]
13651 fn rejects_circuit_breaker_max_failures_far_above_cap() {
13652 // The `u32::MAX` worst case — the four-billion-failure
13653 // threshold a typo (`(:max-failures 4294967295)`) or a
13654 // struct-literal copy-paste lands in the slot. Pin the cap
13655 // arm's coverage explicitly across the full `u32` overflow
13656 // so a future relaxation that drops the upper bound surfaces
13657 // here.
13658 let mut s = three_member_spec();
13659 s.politicas.circuit_breaker = Some(CircuitBreaker {
13660 max_failures: u32::MAX,
13661 window: Duration::from_secs(60),
13662 });
13663 assert_eq!(
13664 s.validate().unwrap_err(),
13665 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13666 max_failures: u32::MAX,
13667 }
13668 );
13669 }
13670
13671 #[test]
13672 fn accepts_circuit_breaker_max_failures_at_cap() {
13673 // The boundary value — exactly
13674 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
13675 // cap is inclusive on the top edge, matching the
13676 // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
13677 // discipline on the sibling capped axes. Pin the boundary
13678 // explicitly so a future off-by-one tightening
13679 // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
13680 // surfaces here as a test failure rather than a silent
13681 // contract narrowing.
13682 let mut s = three_member_spec();
13683 s.politicas.circuit_breaker = Some(CircuitBreaker {
13684 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
13685 window: Duration::from_secs(60),
13686 });
13687 s.validate()
13688 .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
13689 }
13690
13691 #[test]
13692 fn accepts_circuit_breaker_max_failures_typical_values() {
13693 // The documented production-playbook band positive-control
13694 // sweep — every value Hystrix / Istio / Envoy / Polly /
13695 // Resilience4j recommend (5..=50) must pass, plus a sweep
13696 // through the hyperscale band (100, 500, 1000) the cap
13697 // accepts. Pin the inclusive validated set explicitly so a
13698 // future tightening of the ceiling surfaces here.
13699 for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
13700 let mut s = three_member_spec();
13701 s.politicas.circuit_breaker = Some(CircuitBreaker {
13702 max_failures: n,
13703 window: Duration::from_secs(60),
13704 });
13705 s.validate()
13706 .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
13707 }
13708 }
13709
13710 #[test]
13711 fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
13712 // The cross-arm ordering pin: `0` is structurally outside
13713 // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
13714 // (cap), but the zero-floor diagnostic is the more
13715 // self-locating one (it directly names the omit-axis
13716 // remediation), so the validate gate must fire on zero
13717 // first. Same shape every other zero-then-shape ordering on
13718 // this surface uses
13719 // ([`AplicacaoError::PolicyRetriesZero`] then
13720 // [`AplicacaoError::PolicyRetriesExceedsCap`];
13721 // [`AplicacaoError::PolicyTimeoutZero`] then
13722 // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
13723 let mut s = three_member_spec();
13724 s.politicas.circuit_breaker = Some(CircuitBreaker {
13725 max_failures: 0,
13726 window: Duration::from_secs(60),
13727 });
13728 assert_eq!(
13729 s.validate().unwrap_err(),
13730 AplicacaoError::PolicyBreakerZeroFailures,
13731 "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
13732 );
13733 }
13734
13735 #[test]
13736 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
13737 // The cross-arm ordering pin between the cap and the
13738 // sibling `:window` gates (zero-window, canonical-window).
13739 // A breaker carrying both an over-cap `max_failures` AND a
13740 // structurally invalid window (zero, sub-ms) must surface
13741 // the cap diagnostic first — the cap arm is wired
13742 // immediately after the zero-failure arm and strictly
13743 // before the window arms, so the offending value the
13744 // diagnostic names matches the order the author would
13745 // discover the gates by reading top-to-bottom through
13746 // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
13747 // future refactor that reorders the arms surfaces here as a
13748 // test failure rather than a silent diagnostic regression.
13749 let mut s = three_member_spec();
13750 s.politicas.circuit_breaker = Some(CircuitBreaker {
13751 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13752 window: Duration::ZERO,
13753 });
13754 assert_eq!(
13755 s.validate().unwrap_err(),
13756 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13757 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13758 },
13759 "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
13760 );
13761 }
13762
13763 #[test]
13764 fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
13765 // The diagnostic-shape pin: the offending `u32` is carried
13766 // verbatim into the
13767 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
13768 // variant so the surfaced error message names the value the
13769 // author wrote (`":politicas :circuit-breaker :max-failures
13770 // (50000) exceeds the mesh-policy ceiling …"`), not just
13771 // the cap. Same self-locating diagnostic shape every other
13772 // typed-cap arm on this surface carries
13773 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
13774 // offending retry count verbatim,
13775 // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
13776 // offending byte count verbatim).
13777 let mut s = three_member_spec();
13778 s.politicas.circuit_breaker = Some(CircuitBreaker {
13779 max_failures: 50_000,
13780 window: Duration::from_secs(60),
13781 });
13782 let err = s.validate().unwrap_err();
13783 assert!(
13784 matches!(
13785 err,
13786 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13787 max_failures: 50_000
13788 }
13789 ),
13790 "got {err:?}"
13791 );
13792 let msg = err.to_string();
13793 assert!(
13794 msg.contains("50000"),
13795 ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
13796 );
13797 }
13798
13799 #[test]
13800 fn policy_breaker_max_failures_cap_pins_canonical_value() {
13801 // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
13802 // value at 1000 — an order of magnitude above every
13803 // documented production-playbook recommendation band
13804 // (Hystrix `requestVolumeThreshold` default 20, Istio
13805 // `outlierDetection.consecutive5xxErrors` default 5, Envoy
13806 // `outlier_detection.consecutive_5xx` default 5, Polly /
13807 // Resilience4j typical 5..=50) and below the
13808 // clearly-pathological "effectively no protection" floor
13809 // (10_000, 100_000, u32::MAX). Pinning the literal value
13810 // here surfaces a future drift (a relaxation to 10_000, a
13811 // tightening to 100) as a deliberate test edit, not a
13812 // silent contract narrowing.
13813 assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
13814 }
13815
13816 #[test]
13817 fn rejects_circuit_breaker_zero_window() {
13818 let mut s = three_member_spec();
13819 s.politicas.circuit_breaker = Some(CircuitBreaker {
13820 max_failures: 5,
13821 window: Duration::ZERO,
13822 });
13823 assert_eq!(
13824 s.validate().unwrap_err(),
13825 AplicacaoError::PolicyBreakerZeroWindow
13826 );
13827 }
13828
13829 #[test]
13830 fn rejects_zero_rate_limit() {
13831 let mut s = three_member_spec();
13832 s.politicas.rate_limit = Some(RateLimit {
13833 rate: 0,
13834 window: Duration::from_secs(1),
13835 });
13836 assert_eq!(
13837 s.validate().unwrap_err(),
13838 AplicacaoError::PolicyRateLimitZero
13839 );
13840 }
13841
13842 #[test]
13843 fn rejects_rate_limit_zero_window() {
13844 // `RateLimit { rate: 100, window: Duration::ZERO }` is
13845 // constructible programmatically (the typed `Duration` field
13846 // imposes no nonzero invariant) but renders through
13847 // `rate_limit_codec::render` as `"100/0s"` — a fragment the
13848 // codec's `parse` rejects as `unknown rate-limit window unit
13849 // "0s"`. Until this validate-time gate landed the typed slot
13850 // accepted the value silently and the round-trip break only
13851 // surfaced at deserialize time (potentially in a downstream
13852 // consumer that never re-validates). Pin the rejection at
13853 // `AplicacaoSpec::validate` so the typed slot's valid set
13854 // matches the codec's round-trippable set structurally.
13855 let mut s = three_member_spec();
13856 s.politicas.rate_limit = Some(RateLimit {
13857 rate: 100,
13858 window: Duration::ZERO,
13859 });
13860 assert_eq!(
13861 s.validate().unwrap_err(),
13862 AplicacaoError::PolicyRateLimitWindowNotCanonical {
13863 window: Duration::ZERO
13864 }
13865 );
13866 }
13867
13868 #[test]
13869 fn rejects_rate_limit_arbitrary_seconds_window() {
13870 // 45 seconds is a valid `Duration` but not one of the three
13871 // canonical rate-limit windows the codec round-trips
13872 // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
13873 // refuses on round-trip — same round-trip-break shape the
13874 // zero-window arm above pins, with a non-zero magnitude to
13875 // guard against a future "reject only zero" half-measure.
13876 let mut s = three_member_spec();
13877 let window = Duration::from_secs(45);
13878 s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
13879 assert_eq!(
13880 s.validate().unwrap_err(),
13881 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13882 );
13883 }
13884
13885 #[test]
13886 fn rejects_rate_limit_two_minute_window() {
13887 // 120 seconds = 2 minutes is a "looks-canonical" but
13888 // not-canonical window: it's a clean integer multiple of the
13889 // minute unit, but the codec only round-trips the
13890 // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
13891 // A `Duration::from_secs(120)` window renders as `"100/120s"`
13892 // which the parser rejects. Pinning this case rules out a
13893 // future "accept any clean multiple of s/m/h" relaxation
13894 // that would silently break the codec contract.
13895 let mut s = three_member_spec();
13896 let window = Duration::from_secs(120);
13897 s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
13898 assert_eq!(
13899 s.validate().unwrap_err(),
13900 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13901 );
13902 }
13903
13904 #[test]
13905 fn rejects_rate_limit_subsecond_window() {
13906 // A sub-second window (e.g. 500ms) is a valid `Duration` but
13907 // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
13908 // Pin the rejection so a future relaxation can't silently
13909 // admit fractional-second windows that the codec can't
13910 // round-trip.
13911 let mut s = three_member_spec();
13912 let window = Duration::from_millis(500);
13913 s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
13914 assert_eq!(
13915 s.validate().unwrap_err(),
13916 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13917 );
13918 }
13919
13920 #[test]
13921 fn rejects_policy_rate_limit_above_cap() {
13922 // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
13923 // is structurally one past the cap and silently passed
13924 // validate on every pre-gate codebase because the typed slot's
13925 // only `rate` check was the zero-floor arm. The no-op-limiter
13926 // shape only surfaced at the runtime substrate (Envoy's
13927 // `local_rate_limit.token_bucket.max_tokens`, the future
13928 // Cilium L7 rate-limit overlay) far from the source caixa.lisp
13929 // with no field naming the offending policy.
13930 let mut s = three_member_spec();
13931 s.politicas.rate_limit = Some(RateLimit {
13932 rate: POLICY_RATE_LIMIT_MAX + 1,
13933 window: Duration::from_secs(1),
13934 });
13935 assert_eq!(
13936 s.validate().unwrap_err(),
13937 AplicacaoError::PolicyRateLimitExceedsCap {
13938 rate: POLICY_RATE_LIMIT_MAX + 1
13939 }
13940 );
13941 }
13942
13943 #[test]
13944 fn rejects_policy_rate_limit_far_above_cap() {
13945 // The `u32::MAX` worst case — the four-billion-token rate-limit
13946 // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
13947 // copy-paste lands in the slot. Pin the cap arm's coverage
13948 // explicitly across the full `u32` overflow so a future
13949 // relaxation that drops the upper bound surfaces here. Peer to
13950 // `rejects_policy_retries_far_above_cap` on the sibling
13951 // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
13952 // on the sibling `:max-failures` axis.
13953 let mut s = three_member_spec();
13954 s.politicas.rate_limit = Some(RateLimit {
13955 rate: u32::MAX,
13956 window: Duration::from_secs(1),
13957 });
13958 assert_eq!(
13959 s.validate().unwrap_err(),
13960 AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
13961 );
13962 }
13963
13964 #[test]
13965 fn accepts_policy_rate_limit_at_cap() {
13966 // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
13967 // must validate. The cap is inclusive on the top edge, matching
13968 // every other typed upper bound in this crate
13969 // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
13970 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
13971 // across all three canonical windows so a future off-by-one
13972 // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
13973 // window-conditional cap surfaces here as a test failure rather
13974 // than a silent contract narrowing.
13975 for secs in [1u64, 60, 3600] {
13976 let mut s = three_member_spec();
13977 s.politicas.rate_limit = Some(RateLimit {
13978 rate: POLICY_RATE_LIMIT_MAX,
13979 window: Duration::from_secs(secs),
13980 });
13981 s.validate().unwrap_or_else(|e| {
13982 panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
13983 });
13984 }
13985 }
13986
13987 #[test]
13988 fn accepts_policy_rate_limit_typical_values() {
13989 // The documented production-playbook recommendation band —
13990 // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
13991 // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
13992 // Enterprise ~1M per-hour. Every value in the validated set
13993 // must pass; pin the band explicitly so a future tightening
13994 // surfaces here.
13995 for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
13996 for secs in [1u64, 60, 3600] {
13997 let mut s = three_member_spec();
13998 s.politicas.rate_limit = Some(RateLimit {
13999 rate,
14000 window: Duration::from_secs(secs),
14001 });
14002 s.validate().unwrap_or_else(|e| {
14003 panic!("rate={rate} window={secs}s must validate; got {e:?}")
14004 });
14005 }
14006 }
14007 }
14008
14009 #[test]
14010 fn policy_rate_limit_zero_takes_precedence_over_cap() {
14011 // The cross-arm ordering pin: `rate == 0` is structurally
14012 // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
14013 // (cap), but the zero-floor diagnostic is the more
14014 // self-locating one (it directly names the omit-axis
14015 // remediation). Pin the order so a future refactor that
14016 // reorders the arms surfaces here as a test failure rather
14017 // than a silent diagnostic regression. Same shape every other
14018 // zero-then-cap ordering on this surface uses
14019 // ([`AplicacaoError::PolicyRetriesZero`] then
14020 // [`AplicacaoError::PolicyRetriesExceedsCap`];
14021 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
14022 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
14023 let mut s = three_member_spec();
14024 s.politicas.rate_limit = Some(RateLimit {
14025 rate: 0,
14026 window: Duration::from_secs(1),
14027 });
14028 assert_eq!(
14029 s.validate().unwrap_err(),
14030 AplicacaoError::PolicyRateLimitZero,
14031 "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
14032 );
14033 }
14034
14035 #[test]
14036 fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
14037 // Two-axis-bad pin: rate above cap *and* window non-canonical.
14038 // The validate gate must fire on the rate cap first — the
14039 // amplification-shape (no-op limiter) diagnostic is the more
14040 // fundamental one; the window-canonical diagnostic is the
14041 // narrower codec-round-trip shape. Pin the ordering so a future
14042 // refactor that reorders the rate-then-window check arms
14043 // surfaces here as a test failure rather than a silent
14044 // diagnostic regression.
14045 let mut s = three_member_spec();
14046 s.politicas.rate_limit = Some(RateLimit {
14047 rate: POLICY_RATE_LIMIT_MAX + 1,
14048 window: Duration::from_secs(45),
14049 });
14050 assert_eq!(
14051 s.validate().unwrap_err(),
14052 AplicacaoError::PolicyRateLimitExceedsCap {
14053 rate: POLICY_RATE_LIMIT_MAX + 1
14054 },
14055 "above-cap rate must surface the cap diagnostic, not the window diagnostic"
14056 );
14057 }
14058
14059 #[test]
14060 fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
14061 // The diagnostic-shape pin: the offending `u32` is carried
14062 // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
14063 // variant so the surfaced error message names the value the
14064 // author wrote (`":politicas :rate-limit rate (5000000) exceeds
14065 // the mesh-policy ceiling …"`), not just the cap. Same
14066 // self-locating diagnostic shape every other typed-cap arm on
14067 // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
14068 // carries the offending retries count verbatim,
14069 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
14070 // the offending failure count verbatim).
14071 let mut s = three_member_spec();
14072 s.politicas.rate_limit = Some(RateLimit {
14073 rate: 5_000_000,
14074 window: Duration::from_secs(1),
14075 });
14076 let err = s.validate().unwrap_err();
14077 assert!(
14078 matches!(
14079 err,
14080 AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
14081 ),
14082 "got {err:?}"
14083 );
14084 let msg = err.to_string();
14085 assert!(
14086 msg.contains("5000000"),
14087 ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
14088 );
14089 }
14090
14091 #[test]
14092 fn policy_rate_limit_cap_pins_canonical_value() {
14093 // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
14094 // 1_000_000 — two-to-three orders of magnitude above every
14095 // documented production-playbook recommendation band (Envoy /
14096 // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
14097 // Gateway 10_000..=100_000 per-minute) and below the
14098 // clearly-pathological "paste-from-binary blob" floor
14099 // (100_000_000, u32::MAX). Pinning the literal value here
14100 // surfaces a future drift (a relaxation to 10_000_000, a
14101 // tightening to 100_000) as a deliberate test edit, not a
14102 // silent contract narrowing.
14103 assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
14104 }
14105
14106 #[test]
14107 fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
14108 // Both axes are invalid here: rate == 0 *and* window is
14109 // non-canonical. The validate gate must fire on rate first
14110 // (matching the existing `rejects_zero_rate_limit` ordering),
14111 // so the existing diagnostic continues to lead with the
14112 // simpler "zero rate" framing. Pinning the order of checks
14113 // so a future refactor that reorders the arms surfaces here
14114 // as a test failure rather than a silent diagnostic
14115 // regression.
14116 let mut s = three_member_spec();
14117 s.politicas.rate_limit = Some(RateLimit {
14118 rate: 0,
14119 window: Duration::from_secs(45),
14120 });
14121 assert_eq!(
14122 s.validate().unwrap_err(),
14123 AplicacaoError::PolicyRateLimitZero
14124 );
14125 }
14126
14127 #[test]
14128 fn rate_limit_canonical_windows_validate() {
14129 // The three canonical windows the codec round-trips
14130 // losslessly — 1s / 60s / 3600s — must all pass `validate()`
14131 // unchanged. Pin the full canonical set as a positive case
14132 // (the existing `rate_limit_round_trip_seconds` /
14133 // `rate_limit_round_trip_minutes` tests pin the
14134 // serialize-then-deserialize property at the codec layer; this
14135 // test pins the validate-side complement so a future tightening
14136 // of the canonical set — e.g. dropping `:hour` — surfaces here
14137 // as a test failure rather than a silent contract narrowing).
14138 for secs in [1u64, 60, 3600] {
14139 let mut s = three_member_spec();
14140 s.politicas.rate_limit = Some(RateLimit {
14141 rate: 100,
14142 window: Duration::from_secs(secs),
14143 });
14144 s.validate().expect("canonical window must validate");
14145 }
14146 }
14147
14148 #[test]
14149 fn rate_limit_validated_value_round_trips_through_codec() {
14150 // The structural property the validate gate enforces:
14151 // every `RateLimit` past `AplicacaoSpec::validate` round-trips
14152 // losslessly through the `rate_limit_codec` (serialize → string
14153 // → deserialize → equal value). Pin this end-to-end so a future
14154 // change to either side (the validate gate's accepted window
14155 // set, the codec's parse/render unit set) that breaks the
14156 // alignment surfaces here. The previous-state shape (typed
14157 // slot accepts arbitrary `Duration`, codec only round-trips
14158 // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
14159 // window — the validate gate now forecloses that.
14160 for secs in [1u64, 60, 3600] {
14161 let mut s = three_member_spec();
14162 s.politicas.rate_limit = Some(RateLimit {
14163 rate: 250,
14164 window: Duration::from_secs(secs),
14165 });
14166 s.validate().unwrap();
14167 let json = serde_json::to_string(&s.politicas).unwrap();
14168 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14169 assert_eq!(
14170 back.rate_limit, s.politicas.rate_limit,
14171 "every validated :rate-limit must round-trip losslessly through the codec"
14172 );
14173 }
14174 }
14175
14176 #[test]
14177 fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
14178 // The hour-window canonical form (`"<n>/h"`) was missing from
14179 // the prior `rate_limit_round_trip_seconds` / `_minutes` test
14180 // pair. Now that the validate gate pins 3600s as part of the
14181 // canonical set, pin its serialize-side render shape too so
14182 // the third leg of the s/m/h tripod is explicitly tested.
14183 let policy = MeshPolicy {
14184 rate_limit: Some(RateLimit {
14185 rate: 10000,
14186 window: Duration::from_secs(3600),
14187 }),
14188 ..Default::default()
14189 };
14190 let json = serde_json::to_string(&policy).unwrap();
14191 assert!(
14192 json.contains("\"10000/h\""),
14193 "hour-window canonical form must render with `h` suffix (got: {json})"
14194 );
14195 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14196 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
14197 }
14198
14199 #[test]
14200 fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
14201 // Pin the substrate-primitive [`RateLimit::canonical_unit`]
14202 // typed accessor's accepted-window set against the codec's
14203 // accepted set explicitly. A future addition to the codec
14204 // (e.g. accepting `:day`/`:week` as authoring units) must be
14205 // accompanied by a parallel addition here, and a regression
14206 // that drops one of the three canonical units from either
14207 // side surfaces as a test failure. The accessor is the
14208 // single source of truth for the canonical-window set —
14209 // [`AplicacaoSpec::validate_politicas`]'s canonical-window
14210 // gate and [`rate_limit_codec::render`]'s canonical arm both
14211 // read through it — this test enshrines that its
14212 // `Duration → Option<RateLimitUnit>` projection matches the
14213 // codec's parse / render arms' accepted-window set exactly.
14214 //
14215 // Predecessor: this pin previously read the module-private
14216 // free helper `is_canonical_rate_limit_window` — a delegate
14217 // that composed [`RateLimitUnit::from_window`] with `.is_some()`
14218 // — but the helper had no production consumers left after the
14219 // validate-gate migration onto [`RateLimit::canonical_unit`]
14220 // and was deleted; the closed-set arm-window bijection now
14221 // lives on exactly one typed dispatch on the substrate
14222 // primitive.
14223 let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
14224 RateLimit { rate: 1, window }.canonical_unit()
14225 };
14226 assert!(canonical_unit(Duration::from_secs(1)).is_some());
14227 assert!(canonical_unit(Duration::from_secs(60)).is_some());
14228 assert!(canonical_unit(Duration::from_secs(3600)).is_some());
14229 // Non-canonical windows the accessor rejects.
14230 assert!(canonical_unit(Duration::ZERO).is_none());
14231 assert!(canonical_unit(Duration::from_secs(2)).is_none());
14232 assert!(canonical_unit(Duration::from_secs(30)).is_none());
14233 assert!(canonical_unit(Duration::from_secs(120)).is_none());
14234 assert!(canonical_unit(Duration::from_secs(86400)).is_none());
14235 // Sub-second windows: even `Duration::from_millis(1000)` is
14236 // exactly 1s and accepted; `Duration::from_millis(500)` is
14237 // sub-second and rejected.
14238 assert!(canonical_unit(Duration::from_millis(1000)).is_some());
14239 assert!(canonical_unit(Duration::from_millis(500)).is_none());
14240 assert!(canonical_unit(Duration::from_millis(1500)).is_none());
14241 }
14242
14243 #[test]
14244 fn rate_limit_unit_table_projections_are_mutual_inverses() {
14245 // Bidirection pin against the closed-set typed enum
14246 // [`RateLimitUnit`] arm-table (the canonical
14247 // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
14248 // of the rate-limit unit surface reads from). The two
14249 // projection directions [`RateLimitUnit::from_suffix`] /
14250 // [`RateLimitUnit::window`] (str → Duration, exposed as one
14251 // typed dispatch through [`RateLimitUnit::window_from_suffix`])
14252 // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
14253 // (Duration → str, exposed as one typed dispatch through
14254 // [`RateLimit::canonical_unit`] composed with
14255 // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
14256 // codec's parse arm ([`rate_limit_codec::parse`] via
14257 // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
14258 // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
14259 // and the validate gate ([`AplicacaoSpec::validate_politicas`]
14260 // via [`RateLimit::canonical_unit`]) all key off. A future
14261 // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
14262 // sub-second window) is one variant + one arm per method on the
14263 // closed-set enum; the compiler-enforced exhaustiveness on
14264 // every consumer's `match self` arms picks it up by
14265 // construction. This pin enshrines that both projection
14266 // directions agree on every canonical arm row and neither
14267 // leaks a spurious entry the other doesn't recognize.
14268 //
14269 // Predecessor: this test previously read the two vestigial
14270 // module-private free helpers `rate_limit_window_unit` and
14271 // `rate_limit_window_from_unit` on the `Duration → &str` and
14272 // `&str → Duration` axes; the former was deleted after its
14273 // sole production consumer ([`rate_limit_codec::render`])
14274 // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
14275 // the latter is folded here into the substrate primitive
14276 // [`RateLimitUnit::window_from_suffix`] so both projection
14277 // directions live on the closed-set enum's arm-table.
14278 for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
14279 let window = super::RateLimitUnit::window_from_suffix(unit)
14280 .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
14281 assert_eq!(
14282 window,
14283 Duration::from_secs(secs),
14284 "unit {unit:?} must resolve to {secs}s"
14285 );
14286 let projected_suffix = RateLimit { rate: 1, window }
14287 .canonical_unit()
14288 .map(super::RateLimitUnit::as_suffix);
14289 assert_eq!(
14290 projected_suffix,
14291 Some(unit),
14292 "Duration({secs}s) must render as {unit:?} \
14293 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
14294 );
14295 }
14296 // Non-table units yield None on the `unit → Duration`
14297 // projection — a future `"d"` addition to the table would
14298 // flip this arm; today it pins the current three-row table's
14299 // rejection semantics.
14300 assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
14301 assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
14302 assert!(super::RateLimitUnit::window_from_suffix("").is_none());
14303 // Non-table Durations yield None on the `Duration → unit`
14304 // projection — pins that the two projections agree on the
14305 // "not in the table" semantic too, so a drift where the
14306 // parse-side accepts a value the render-side can't emit is
14307 // a build error at the two-arm pair, not a silent codec
14308 // round-trip break.
14309 let projected_suffix = |window: Duration| -> Option<&'static str> {
14310 RateLimit { rate: 1, window }
14311 .canonical_unit()
14312 .map(super::RateLimitUnit::as_suffix)
14313 };
14314 assert!(projected_suffix(Duration::from_secs(2)).is_none());
14315 assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
14316 assert!(projected_suffix(Duration::from_millis(1500)).is_none());
14317 }
14318
14319 #[test]
14320 fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
14321 // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
14322 // substrate-primitive `&str → Duration` associated method the
14323 // codec's parse arm ([`rate_limit_codec::parse`]) now routes
14324 // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
14325 // to the same [`Duration`] the two-step composition
14326 // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
14327 // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
14328 // `"MIN"`) must project to [`None`] on both paths. A future
14329 // implementation of `window_from_suffix` that took a shortcut
14330 // through a per-suffix `match` table (bypassing the arm-table's
14331 // `Self::from_suffix` scan and the arm-table's `Self::window`
14332 // dispatch) would silently split the accept-set — the parse
14333 // arm would accept a suffix the enum's arm-table doesn't know,
14334 // or reject a suffix the enum's arm-table does; this pin
14335 // surfaces that drift at caixa-core build time rather than at a
14336 // downstream serde round-trip audit on a live `MeshPolicy`.
14337 //
14338 // Same byte-parity discipline the sibling
14339 // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
14340 // pin carries on the peer `Duration → RateLimitUnit` axis via
14341 // [`RateLimit::canonical_unit`], and the peer
14342 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
14343 // carries on the bidirectional arm-table axis — extended here
14344 // onto the fifth (and last unlifted) projection axis on the
14345 // closed-set enum's arm-table.
14346 let composition = |suffix: &str| -> Option<Duration> {
14347 super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
14348 };
14349 for suffix in ["s", "m", "h"] {
14350 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
14351 let via_composition = composition(suffix);
14352 assert_eq!(
14353 via_method, via_composition,
14354 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
14355 from_suffix({suffix:?}).map(window) — the substrate-primitive \
14356 method must delegate to the arm-table's two typed dispatches, \
14357 not shortcut through a per-suffix match table"
14358 );
14359 assert!(
14360 via_method.is_some(),
14361 "canonical suffix {suffix:?} must resolve to Some(Duration) via \
14362 RateLimitUnit::window_from_suffix"
14363 );
14364 }
14365 for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
14366 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
14367 let via_composition = composition(suffix);
14368 assert_eq!(
14369 via_method, via_composition,
14370 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
14371 from_suffix({suffix:?}).map(window) on the non-arm rejection \
14372 axis too"
14373 );
14374 assert!(
14375 via_method.is_none(),
14376 "non-arm suffix {suffix:?} must project to None via \
14377 RateLimitUnit::window_from_suffix — a future extension that \
14378 accepted this suffix without a corresponding arm on the enum \
14379 would split the codec's parse-accepted set from the enum's \
14380 arm-table"
14381 );
14382 }
14383 // And the codec's parse arm now reads through this method: a
14384 // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
14385 // the same `Duration` the method returns for its unit, closing
14386 // the two-consumer drift surface (the codec's parse arm and the
14387 // enum's arm-table) with one typed dispatch on the substrate
14388 // primitive.
14389 for suffix in ["s", "m", "h"] {
14390 let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
14391 let mp: MeshPolicy = serde_json::from_str(&wire)
14392 .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
14393 let parsed = mp.rate_limit().expect("rate_limit payload present");
14394 let via_method = super::RateLimitUnit::window_from_suffix(suffix)
14395 .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
14396 assert_eq!(
14397 parsed.window(),
14398 via_method,
14399 "codec parse arm on {wire:?} must resolve the window through \
14400 RateLimitUnit::window_from_suffix, not a divergent path"
14401 );
14402 }
14403 }
14404
14405 #[test]
14406 fn rate_limit_unit_all_enumerates_every_arm_once() {
14407 // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
14408 // enumerate every arm of the closed-set enum exactly once, in
14409 // the canonical shortest-to-longest window order (Second before
14410 // Minute before Hour) — the same order the sibling
14411 // [`crate::supervisor::RestartStrategy`] /
14412 // [`crate::supervisor::RestartPolicy`] /
14413 // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
14414 // typed enums carry (the arm declared first is the arm listed
14415 // first). A future variant addition that extends the enum
14416 // without appending to [`RateLimitUnit::ALL`] leaves the
14417 // exhaustive iteration surface silently short one arm — the
14418 // codec's parse arm would then reject the new suffix even
14419 // though the enum knows it. This pin closes the drift.
14420 assert_eq!(
14421 super::RateLimitUnit::ALL,
14422 &[
14423 super::RateLimitUnit::Second,
14424 super::RateLimitUnit::Minute,
14425 super::RateLimitUnit::Hour,
14426 ],
14427 "RateLimitUnit::ALL must enumerate every arm exactly once, \
14428 in canonical shortest-to-longest window order"
14429 );
14430 }
14431
14432 #[test]
14433 fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
14434 // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
14435 // every arm's [`RateLimitUnit::as_suffix`] output must parse
14436 // back through [`RateLimitUnit::from_suffix`] to the same
14437 // variant. A future arm addition that lands `as_suffix` but
14438 // forgets `from_suffix` (`from_suffix` iterates
14439 // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
14440 // is the load-bearing carrier of the round-trip; the sibling
14441 // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
14442 // the `ALL` half) trips here at caixa-core build time rather
14443 // than surfacing as a codec round-trip miss (a `render` emit
14444 // that lands a suffix the paired `parse` cannot decode).
14445 for unit in super::RateLimitUnit::ALL {
14446 let suffix = unit.as_suffix();
14447 let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
14448 panic!(
14449 "RateLimitUnit::from_suffix({suffix:?}) must accept every \
14450 RateLimitUnit::as_suffix output — got None for {unit:?}"
14451 )
14452 });
14453 assert_eq!(
14454 parsed, *unit,
14455 "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
14456 must return RateLimitUnit::{unit:?}"
14457 );
14458 }
14459 }
14460
14461 #[test]
14462 fn rate_limit_unit_from_window_and_window_round_trip() {
14463 // Total round-trip pin on the `(from_window, window)` pair:
14464 // every arm's [`RateLimitUnit::window`] output must parse back
14465 // through [`RateLimitUnit::from_window`] to the same variant.
14466 // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
14467 // on the peer `Duration` axis — the two round-trip pins
14468 // together enshrine that both projections of the typed
14469 // canonical-unit bijection are total on the arm-set.
14470 for unit in super::RateLimitUnit::ALL {
14471 let window = unit.window();
14472 let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
14473 panic!(
14474 "RateLimitUnit::from_window({window:?}) must accept every \
14475 RateLimitUnit::window output — got None for {unit:?}"
14476 )
14477 });
14478 assert_eq!(
14479 parsed, *unit,
14480 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
14481 must return RateLimitUnit::{unit:?}"
14482 );
14483 }
14484 }
14485
14486 #[test]
14487 fn rate_limit_unit_projections_are_pairwise_distinct() {
14488 // Distinctness pin: [`RateLimitUnit::as_suffix`] and
14489 // [`RateLimitUnit::window`] outputs must be pairwise distinct
14490 // across every arm — an accidental copy-paste flip that
14491 // reroutes one arm's suffix or window to also match another
14492 // silently collapses two arms onto one, so
14493 // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
14494 // (both using `find` on `Self::ALL`) would return whichever
14495 // arm the linear scan lands on first — a match-arm-ordering-
14496 // dependent outcome the closed-set typed-enum shape is meant
14497 // to rule out structurally. Peer of the sibling
14498 // `caixa_kind_wire_consts_are_pairwise_distinct` /
14499 // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
14500 // other closed-set typed-enum discriminator axes.
14501 let all = super::RateLimitUnit::ALL;
14502 for (i, a) in all.iter().enumerate() {
14503 for (j, b) in all.iter().enumerate() {
14504 if i != j {
14505 assert_ne!(
14506 a.as_suffix(),
14507 b.as_suffix(),
14508 "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
14509 must be distinct — a collision silently collapses two \
14510 arms onto one under from_suffix's linear scan"
14511 );
14512 assert_ne!(
14513 a.window(),
14514 b.window(),
14515 "RateLimitUnit::{a:?}.window() and {b:?}.window() \
14516 must be distinct — a collision silently collapses two \
14517 arms onto one under from_window's linear scan"
14518 );
14519 }
14520 }
14521 }
14522 }
14523
14524 #[test]
14525 fn rate_limit_unit_display_routes_through_as_suffix() {
14526 // Route pin: [`std::fmt::Display`] must byte-equal
14527 // [`RateLimitUnit::as_suffix`] on every arm — the single
14528 // source of truth for the canonical suffix. A future
14529 // reimplementation that hand-rolls the arms instead of
14530 // delegating to [`RateLimitUnit::as_suffix`] would silently
14531 // desynchronize `format!("{u}")` from the codec's parse arm
14532 // (which uses `as_suffix` to compare suffixes). Peer of the
14533 // sibling `caixa_kind_display_routes_through_as_str_helper` /
14534 // `placement_strategy_display_routes_through_as_str_helper`
14535 // pins on the peer closed-set typed-enum Display axes.
14536 for unit in super::RateLimitUnit::ALL {
14537 assert_eq!(
14538 unit.to_string(),
14539 unit.as_suffix(),
14540 "RateLimitUnit::{unit:?} Display must route through \
14541 as_suffix (single source of truth: the canonical suffix \
14542 the codec parses and renders)"
14543 );
14544 }
14545 }
14546
14547 #[test]
14548 fn rate_limit_unit_from_window_rejects_non_canonical() {
14549 // Rejection pin on the parser's accept-set: any Duration
14550 // outside the three-arm [`RateLimitUnit::window`] output set
14551 // (sub-second residue, or a second-magnitude outside `{1, 60,
14552 // 3600}`) must return `None`. A future accidental widening of
14553 // the accept-set (rounding down sub-second residue to the
14554 // nearest arm, admitting `Duration::from_secs(30)` as a
14555 // half-minute unit) would silently drift the parser's accept-
14556 // set from the emitter's — a validated slot with a
14557 // non-canonical window would then round-trip through the
14558 // codec to a canonical form the author never wrote.
14559 assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
14560 assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
14561 assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
14562 assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
14563 assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
14564 assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
14565 assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
14566 }
14567
14568 #[test]
14569 fn rate_limit_unit_from_suffix_rejects_unknown() {
14570 // Rejection pin on the suffix parser's accept-set: any string
14571 // outside the three-arm [`RateLimitUnit::as_suffix`] output
14572 // set must return `None`. Peer of the sibling
14573 // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
14574 // the [`crate::CaixaKind`] `from_wire` accept-set.
14575 for bad in [
14576 "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
14577 " s",
14578 ] {
14579 assert!(
14580 super::RateLimitUnit::from_suffix(bad).is_none(),
14581 "RateLimitUnit::from_suffix({bad:?}) must return None — the \
14582 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
14583 outputs"
14584 );
14585 }
14586 }
14587
14588 #[test]
14589 fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
14590 // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
14591 // every canonical `:window` magnitude the validate gate
14592 // accepts must map to the paired [`RateLimitUnit`] arm through
14593 // this accessor. A future validate-gate rebrand that widened
14594 // the accepted-window set without extending [`RateLimitUnit`]
14595 // would silently split the accessor's `Some`-return set from
14596 // the validate gate's accept-set — a slot that satisfies
14597 // validate would land at the accessor with `None`, so a
14598 // consumer past validate that pattern-matches on the returned
14599 // `Some` would silently miss the newly-accepted magnitude.
14600 for (window_secs, expected) in [
14601 (1u64, super::RateLimitUnit::Second),
14602 (60, super::RateLimitUnit::Minute),
14603 (3600, super::RateLimitUnit::Hour),
14604 ] {
14605 let rl = RateLimit {
14606 rate: 100,
14607 window: Duration::from_secs(window_secs),
14608 };
14609 assert_eq!(
14610 rl.canonical_unit(),
14611 Some(expected),
14612 "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
14613 must return Some({expected:?})"
14614 );
14615 }
14616 // Non-canonical windows the validate gate rejects also return
14617 // None here — the accessor is the typed-enum projection of
14618 // the sibling `is_canonical_rate_limit_window` predicate.
14619 let bad = RateLimit {
14620 rate: 100,
14621 window: Duration::from_secs(30),
14622 };
14623 assert!(
14624 bad.canonical_unit().is_none(),
14625 "RateLimit with a non-canonical window must return None from \
14626 canonical_unit — the validate gate rejects the same set"
14627 );
14628 }
14629
14630 #[test]
14631 fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
14632 // Fail-before-pass-after byte-parity pin: for every canonical
14633 // window the [`rate_limit_codec::render`] arm's emitted string
14634 // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
14635 // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
14636 // the vestigial free helper [`rate_limit_window_unit`] (a
14637 // `find_map`-walked `Duration → &'static str` delegate) onto the
14638 // substrate primitive [`RateLimit::canonical_unit`] typed method
14639 // (a closed-set `match self.window` arm on
14640 // [`RateLimitUnit::from_window`], projected through
14641 // [`RateLimitUnit::as_suffix`] via the enum's
14642 // [`std::fmt::Display`] impl). A future re-routing of the render
14643 // arm through a differently-computed unit projection would break
14644 // this pin at build time rather than as a silent per-consumer
14645 // codec round-trip drift far from the substrate primitive edit.
14646 //
14647 // Sibling to the peer
14648 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
14649 // on the free-helper axis: that pin locks the two projections
14650 // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
14651 // on the closed-set arm table; this pin locks the codec's render
14652 // arm reads through the typed accessor rather than the free
14653 // helper. Two production consumers of the canonical-unit axis
14654 // now key off one typed dispatch on the substrate primitive.
14655 for (window_secs, unit) in [
14656 (1u64, super::RateLimitUnit::Second),
14657 (60, super::RateLimitUnit::Minute),
14658 (3600, super::RateLimitUnit::Hour),
14659 ] {
14660 let rl = RateLimit {
14661 rate: 42,
14662 window: Duration::from_secs(window_secs),
14663 };
14664 let policy = MeshPolicy {
14665 rate_limit: Some(rl),
14666 ..Default::default()
14667 };
14668 let json = serde_json::to_string(&policy).unwrap();
14669 let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
14670 assert!(
14671 json.contains(&expected),
14672 "rate_limit_codec::render must emit {expected} (via \
14673 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
14674 for a {window_secs}s window; serialized MeshPolicy was: {json}"
14675 );
14676 // And the accessor route resolves to the same typed unit
14677 // the render arm's Display formatting is asked to produce —
14678 // so a future edit that split the two paths (one through
14679 // the accessor, one through a re-introduced free helper)
14680 // trips this pin.
14681 assert_eq!(
14682 rl.canonical_unit(),
14683 Some(unit),
14684 "RateLimit::canonical_unit must return Some({unit:?}) for a \
14685 {window_secs}s window; the codec render arm reads the same \
14686 typed unit through this accessor"
14687 );
14688 }
14689 }
14690
14691 #[test]
14692 fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
14693 // Fail-before-pass-after byte-parity pin on the validate gate's
14694 // canonical-window shape probe: every non-canonical `:window`
14695 // the free-helper predicate [`is_canonical_rate_limit_window`]
14696 // rejects is also rejected by the substrate primitive
14697 // [`RateLimit::canonical_unit`] `.is_none()` route the validate
14698 // gate now reads through, and vice versa on the accepted set
14699 // (the three canonical windows). Locks the migration from the
14700 // free helper onto the substrate primitive: a future re-routing
14701 // of one of the two paths through a differently-computed unit
14702 // projection would silently split the codec's accepted set from
14703 // the validate gate's accepted set — a two-consumer drift the
14704 // codec-round-trip pin
14705 // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
14706 // above closes on the render arm and this pin closes on the
14707 // validate arm.
14708 for canonical_window_secs in [1u64, 60, 3600] {
14709 let mut s = three_member_spec();
14710 let rl = RateLimit {
14711 rate: 100,
14712 window: Duration::from_secs(canonical_window_secs),
14713 };
14714 s.politicas.rate_limit = Some(rl);
14715 assert!(
14716 s.validate().is_ok(),
14717 "canonical {canonical_window_secs}s window must pass \
14718 validate_politicas — the validate gate now reads \
14719 RateLimit::canonical_unit().is_none() and the accessor \
14720 returns Some on every canonical arm"
14721 );
14722 assert!(
14723 rl.canonical_unit().is_some(),
14724 "canonical {canonical_window_secs}s window must resolve to \
14725 Some on RateLimit::canonical_unit — the validate gate reads \
14726 this accessor directly"
14727 );
14728 }
14729 for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
14730 let mut s = three_member_spec();
14731 let rl = RateLimit {
14732 rate: 100,
14733 window: Duration::from_secs(non_canonical_window_secs),
14734 };
14735 s.politicas.rate_limit = Some(rl);
14736 assert_eq!(
14737 s.validate().unwrap_err(),
14738 AplicacaoError::PolicyRateLimitWindowNotCanonical {
14739 window: rl.window(),
14740 },
14741 "non-canonical {non_canonical_window_secs}s window must be \
14742 rejected by validate_politicas — the validate gate now \
14743 keys off RateLimit::canonical_unit().is_none()"
14744 );
14745 assert!(
14746 rl.canonical_unit().is_none(),
14747 "non-canonical {non_canonical_window_secs}s window must \
14748 resolve to None on RateLimit::canonical_unit — the two \
14749 paths (the free helper the validate gate previously read \
14750 and the substrate primitive the validate gate now reads) \
14751 must agree on the same rejected set"
14752 );
14753 }
14754 // And the substrate-primitive [`RateLimit::canonical_unit`]
14755 // accessor's accepted-window set matches the codec's parse arm's
14756 // accepted-suffix set on every canonical / non-canonical shape,
14757 // so a future silent drift between the codec's accepted set and
14758 // the validate gate's accepted set is a build error at test time
14759 // (both consumers key off the same closed-set enum's `match self`
14760 // arms). The predecessor free helper `is_canonical_rate_limit_window`
14761 // — a delegate that composed [`RateLimitUnit::from_window`] with
14762 // `.is_some()` — was deleted after this migration; the
14763 // canonical-window set now lives on exactly one typed dispatch
14764 // on the substrate primitive.
14765 for (secs, expected) in [
14766 (1u64, true),
14767 (60, true),
14768 (3600, true),
14769 (2, false),
14770 (30, false),
14771 (86_400, false),
14772 ] {
14773 let window = Duration::from_secs(secs);
14774 let rl = RateLimit { rate: 1, window };
14775 assert_eq!(
14776 rl.canonical_unit().is_some(),
14777 expected,
14778 "RateLimit::canonical_unit().is_some() must agree with the \
14779 codec-accepted canonical-window set on {secs}s"
14780 );
14781 let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
14782 1 => "s",
14783 60 => "m",
14784 3600 => "h",
14785 _ => return,
14786 })
14787 .is_some_and(|d| d == window);
14788 if expected {
14789 assert!(
14790 suffix_from_axis,
14791 "the codec's `&str → Duration` axis \
14792 ({secs}s) must round-trip to the same Duration the \
14793 substrate primitive's accessor returns Some on"
14794 );
14795 }
14796 }
14797 }
14798
14799 #[test]
14800 fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
14801 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
14802 // derive: for each of the three variants, exactly one of the
14803 // generated `is_second` / `is_minute` / `is_hour` predicates
14804 // returns `true` and the other two return `false`. Peer of
14805 // the sibling
14806 // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
14807 // sibling `IsVariant`-derived closed-set typed-enum pins.
14808 let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
14809 (super::RateLimitUnit::Second, [true, false, false]),
14810 (super::RateLimitUnit::Minute, [false, true, false]),
14811 (super::RateLimitUnit::Hour, [false, false, true]),
14812 ];
14813 for (variant, expected) in rows {
14814 let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
14815 assert_eq!(
14816 observed, expected,
14817 "RateLimitUnit::{variant:?} is_* predicates must partition \
14818 the arm set (second, minute, hour); got {observed:?}"
14819 );
14820 }
14821 }
14822
14823 #[test]
14824 fn rejects_policy_timeout_sub_millisecond() {
14825 // A purely sub-millisecond `Duration` (`from_micros(500)` =
14826 // 500_000 ns) is not the zero `Duration` — the `is_zero()`
14827 // arm passes — but `as_millis() == 0`, so the shared codec's
14828 // `render` arm returns the literal `"0s"`, which the
14829 // codec's `parse` arm then deserializes as `Duration::ZERO`
14830 // and the `PolicyTimeoutZero` zero-floor gate would reject
14831 // on re-validate. Pin the rejection at the typed slot's
14832 // canonical-floor gate so the round-trip break surfaces at
14833 // validate time, naming the offending `Duration`, rather
14834 // than at the next serialize → deserialize round-trip far
14835 // from the source `caixa.lisp`.
14836 let mut s = three_member_spec();
14837 let timeout = Duration::from_micros(500);
14838 s.politicas.timeout = Some(timeout);
14839 assert_eq!(
14840 s.validate().unwrap_err(),
14841 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
14842 );
14843 }
14844
14845 #[test]
14846 fn rejects_policy_timeout_non_integer_millisecond() {
14847 // A `Duration` with non-integer-millisecond residue
14848 // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
14849 // through the shared codec's `render` arm as `"1ms"` (the
14850 // `as_millis()` floor truncates), which the codec's `parse`
14851 // arm then deserializes as `Duration::from_millis(1)` =
14852 // 1_000_000 ns — silently *different* from the original.
14853 // Pin the rejection so this round-trip break surfaces at
14854 // validate time, where the offending `Duration` is named,
14855 // rather than as a silent value-laundered round-trip on the
14856 // next codec round-trip.
14857 let mut s = three_member_spec();
14858 let timeout = Duration::from_micros(1500);
14859 s.politicas.timeout = Some(timeout);
14860 assert_eq!(
14861 s.validate().unwrap_err(),
14862 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
14863 );
14864 }
14865
14866 #[test]
14867 fn accepts_policy_timeout_integer_millisecond_forms() {
14868 // The codec's accepted set — integer multiples of 1ms — is
14869 // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
14870 // `1h` all pass the canonical gate. Pin the canonical-forms
14871 // sweep so a future tightening of the codec's grammar (e.g.
14872 // dropping `:ms`) surfaces here as a test failure rather
14873 // than a silent contract narrowing on the typed slot.
14874 for timeout in [
14875 Duration::from_millis(1),
14876 Duration::from_millis(500),
14877 Duration::from_millis(1500),
14878 Duration::from_secs(30),
14879 Duration::from_secs(120),
14880 Duration::from_secs(3600),
14881 ] {
14882 let mut s = three_member_spec();
14883 s.politicas.timeout = Some(timeout);
14884 s.validate()
14885 .expect("integer-millisecond :timeout must validate");
14886 }
14887 }
14888
14889 #[test]
14890 fn policy_timeout_zero_takes_precedence_over_canonical() {
14891 // `Duration::ZERO` carries `subsec_nanos() == 0` and would
14892 // pass the canonical-millisecond gate; the more self-locating
14893 // `PolicyTimeoutZero` arm (which names the omit-axis
14894 // remediation directly) must fire first. Pin the ordering so
14895 // a future refactor that reorders the arms surfaces here as a
14896 // test failure rather than a silent diagnostic regression.
14897 let mut s = three_member_spec();
14898 s.politicas.timeout = Some(Duration::ZERO);
14899 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
14900 }
14901
14902 #[test]
14903 fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
14904 // The diagnostic envelope carries the offending `Duration`
14905 // verbatim so the author can grep their `caixa.lisp` for
14906 // `:timeout "<value>"` and fix it in one edit. Same
14907 // diagnostic shape every other typed-slot canonical-form
14908 // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
14909 // peer `:rate-limit :window` axis.
14910 let mut s = three_member_spec();
14911 let timeout = Duration::from_nanos(1_000_001);
14912 s.politicas.timeout = Some(timeout);
14913 match s.validate().unwrap_err() {
14914 AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
14915 assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
14916 }
14917 other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
14918 }
14919 }
14920
14921 #[test]
14922 fn rejects_policy_timeout_above_cap() {
14923 // The fail-before-pass-after pin: 3601s = 1h + 1s is
14924 // structurally one canonical-tick past the
14925 // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
14926 // integer-millisecond magnitude the canonical-form arm above
14927 // accepts cleanly, that the codec round-trips losslessly as
14928 // `"3601s"`, and that silently passed validate on every
14929 // pre-gate codebase because the typed slot's only checks were
14930 // the zero-floor and canonical-form arms. The mesh-level
14931 // deadline degenerates only at the runtime substrate (Envoy
14932 // / Cilium L7 timeout overlay) far from the source
14933 // `caixa.lisp` with no field naming the offending policy.
14934 let mut s = three_member_spec();
14935 let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
14936 s.politicas.timeout = Some(timeout);
14937 assert_eq!(
14938 s.validate().unwrap_err(),
14939 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
14940 );
14941 }
14942
14943 #[test]
14944 fn rejects_policy_timeout_one_millisecond_above_cap() {
14945 // Boundary case: exactly 1ms past the cap (the granularity
14946 // the canonical-form gate enforces). Catches a future
14947 // "strictly less than" half-measure and pins the diagnostic
14948 // to name the offending `Duration` verbatim. Peer of
14949 // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
14950 // boundary pin on the sibling `:limits :memory` top edge.
14951 let mut s = three_member_spec();
14952 let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
14953 s.politicas.timeout = Some(timeout);
14954 assert_eq!(
14955 s.validate().unwrap_err(),
14956 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
14957 );
14958 }
14959
14960 #[test]
14961 fn rejects_policy_timeout_far_above_cap() {
14962 // The "obvious authoring footgun" case: a `(:timeout "24h")`
14963 // or `(:timeout "86400s")` — values the canonical-form arm
14964 // accepts as integer-millisecond magnitudes, the codec
14965 // round-trips losslessly through serde, but the mesh-level
14966 // policy cannot honor (a 24-hour synchronous-`:contratos`
14967 // deadline is operationally indistinguishable from
14968 // omit-the-axis). Until this gate landed validate accepted
14969 // it. Pin both common above-cap values (24h, 7d) so a future
14970 // relaxation that drops the upper bound surfaces here.
14971 for timeout in [
14972 Duration::from_secs(86_400), // 24h
14973 Duration::from_secs(604_800), // 7d
14974 Duration::from_secs(1_000_000), // ~11.5 days
14975 ] {
14976 let mut s = three_member_spec();
14977 s.politicas.timeout = Some(timeout);
14978 assert_eq!(
14979 s.validate().unwrap_err(),
14980 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
14981 );
14982 }
14983 }
14984
14985 #[test]
14986 fn accepts_policy_timeout_at_cap() {
14987 // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
14988 // must validate. The cap is inclusive on the top edge,
14989 // matching the [`POLICY_RETRIES_MAX`] /
14990 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
14991 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
14992 // sibling capped axes. Pin the boundary explicitly so a
14993 // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
14994 // instead of `>`) surfaces here as a test failure rather
14995 // than a silent contract narrowing.
14996 let mut s = three_member_spec();
14997 s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
14998 s.validate()
14999 .expect("timeout == POLICY_TIMEOUT_MAX must validate");
15000 }
15001
15002 #[test]
15003 fn accepts_policy_timeout_typical_values() {
15004 // The documented production-playbook band positive-control
15005 // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
15006 // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
15007 // plus a sweep through the long-running-workflow band
15008 // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
15009 // validated set explicitly so a future tightening of the
15010 // ceiling surfaces here as a deliberate test edit, not a
15011 // silent contract narrowing.
15012 for timeout in [
15013 Duration::from_millis(1),
15014 Duration::from_millis(500),
15015 Duration::from_secs(1),
15016 Duration::from_secs(10),
15017 Duration::from_secs(15), // Envoy default
15018 Duration::from_secs(30),
15019 Duration::from_secs(60), // AWS App Mesh typical
15020 Duration::from_secs(300),
15021 Duration::from_secs(900),
15022 Duration::from_secs(1800),
15023 Duration::from_secs(3600), // exactly 1h, the cap
15024 ] {
15025 let mut s = three_member_spec();
15026 s.politicas.timeout = Some(timeout);
15027 s.validate()
15028 .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
15029 }
15030 }
15031
15032 #[test]
15033 fn policy_timeout_zero_takes_precedence_over_cap() {
15034 // The cross-arm ordering pin: `Duration::ZERO` is
15035 // structurally outside both `>= 1ms` (zero-floor) and
15036 // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
15037 // diagnostic is the more self-locating one (it directly
15038 // names the omit-axis remediation), so the validate gate
15039 // must fire on zero first. Same shape every other
15040 // zero-then-shape ordering on this surface uses
15041 // ([`AplicacaoError::PolicyRetriesZero`] then
15042 // [`AplicacaoError::PolicyRetriesExceedsCap`];
15043 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
15044 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
15045 let mut s = three_member_spec();
15046 s.politicas.timeout = Some(Duration::ZERO);
15047 assert_eq!(
15048 s.validate().unwrap_err(),
15049 AplicacaoError::PolicyTimeoutZero,
15050 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
15051 );
15052 }
15053
15054 #[test]
15055 fn policy_timeout_canonical_takes_precedence_over_cap() {
15056 // The cross-arm ordering pin: a `Duration` that is *both*
15057 // sub-millisecond (non-canonical-form) and structurally
15058 // above the cap surfaces the canonical-form diagnostic
15059 // first, because the round-trip-shape break is the more
15060 // fundamental issue (the value can't even round-trip
15061 // through the codec, so the cap diagnostic naming
15062 // `1ms..=1h` would be misleading — there's no integer-ms
15063 // form of the offending value). Pin the order so a future
15064 // refactor that reorders the arms surfaces here as a test
15065 // failure rather than a silent diagnostic regression.
15066 let mut s = three_member_spec();
15067 // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
15068 // *and* total magnitude above the 1h cap.
15069 let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
15070 s.politicas.timeout = Some(timeout);
15071 assert_eq!(
15072 s.validate().unwrap_err(),
15073 AplicacaoError::PolicyTimeoutNotCanonical { timeout },
15074 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
15075 );
15076 }
15077
15078 #[test]
15079 fn policy_timeout_cap_diagnostic_carries_offending_value() {
15080 // The diagnostic-shape pin: the offending `Duration` is
15081 // carried verbatim into the
15082 // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
15083 // surfaced error message names the value the author wrote
15084 // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
15085 // exceeds the mesh-policy ceiling …"`), not just the cap.
15086 // Same self-locating diagnostic shape every other typed-cap
15087 // arm on this surface carries
15088 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
15089 // offending retry count verbatim).
15090 let mut s = three_member_spec();
15091 let timeout = Duration::from_secs(7200); // 2h
15092 s.politicas.timeout = Some(timeout);
15093 let err = s.validate().unwrap_err();
15094 assert!(
15095 matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
15096 "got {err:?}"
15097 );
15098 let msg = err.to_string();
15099 assert!(
15100 msg.contains("7200"),
15101 ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
15102 );
15103 }
15104
15105 #[test]
15106 fn policy_timeout_cap_pins_canonical_value() {
15107 // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
15108 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
15109 // the shared duration codec emits as a clean canonical
15110 // string (`"<n>h"`). Pinning the literal value here surfaces
15111 // a future drift (a relaxation to 24h, a tightening to 5m)
15112 // as a deliberate test edit, not a silent contract
15113 // narrowing. Same shape every other typed-cap value pin on
15114 // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
15115 assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
15116 assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
15117 }
15118
15119 #[test]
15120 fn policy_timeout_cap_value_round_trips_through_codec() {
15121 // The codec round-trip property the cap arm preserves: the
15122 // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
15123 // the shared duration codec — every value at the cap renders
15124 // to a clean canonical string (`"1h"`) and parses back to
15125 // the same `Duration`. Pin this so a future drift between
15126 // the cap constant and the codec's largest emitted unit
15127 // surfaces here. Same shape every other typed boundary pin
15128 // on this surface uses
15129 // (`wasm32_memory_cap_matches_parsed_4_gib`).
15130 let policy = MeshPolicy {
15131 timeout: Some(POLICY_TIMEOUT_MAX),
15132 ..Default::default()
15133 };
15134 let json = serde_json::to_string(&policy).unwrap();
15135 // The codec emits `"1h"` for the canonical 1-hour magnitude.
15136 assert!(
15137 json.contains("\"1h\""),
15138 "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
15139 );
15140 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15141 assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
15142 }
15143
15144 #[test]
15145 fn rejects_circuit_breaker_window_sub_millisecond() {
15146 // Peer of the `:timeout` sub-millisecond arm on the second
15147 // typed-`Duration` `:politicas` axis: a purely sub-ms
15148 // `Duration` (`from_micros(500)`) renders through the shared
15149 // codec as `"0s"`, which the codec parses back to
15150 // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
15151 // zero-floor gate then rejects on re-validate.
15152 let mut s = three_member_spec();
15153 let window = Duration::from_micros(500);
15154 s.politicas.circuit_breaker = Some(CircuitBreaker {
15155 max_failures: 5,
15156 window,
15157 });
15158 assert_eq!(
15159 s.validate().unwrap_err(),
15160 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
15161 );
15162 }
15163
15164 #[test]
15165 fn rejects_circuit_breaker_window_non_integer_millisecond() {
15166 // Peer of the `:timeout` non-integer-ms arm: a `Duration`
15167 // with non-integer-millisecond residue renders through the
15168 // shared codec as the truncated `"<n>ms"` form, parsing back
15169 // to a *different* `Duration` on the next round-trip.
15170 let mut s = three_member_spec();
15171 let window = Duration::from_micros(1500);
15172 s.politicas.circuit_breaker = Some(CircuitBreaker {
15173 max_failures: 5,
15174 window,
15175 });
15176 assert_eq!(
15177 s.validate().unwrap_err(),
15178 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
15179 );
15180 }
15181
15182 #[test]
15183 fn accepts_circuit_breaker_window_integer_millisecond_forms() {
15184 // The canonical-forms sweep on the breaker axis: every
15185 // integer-ms multiple the codec round-trips losslessly
15186 // passes the canonical gate.
15187 for window in [
15188 Duration::from_millis(1),
15189 Duration::from_millis(500),
15190 Duration::from_millis(1500),
15191 Duration::from_secs(30),
15192 Duration::from_secs(60),
15193 Duration::from_secs(3600),
15194 ] {
15195 let mut s = three_member_spec();
15196 s.politicas.circuit_breaker = Some(CircuitBreaker {
15197 max_failures: 5,
15198 window,
15199 });
15200 s.validate()
15201 .expect("integer-millisecond :circuit-breaker :window must validate");
15202 }
15203 }
15204
15205 #[test]
15206 fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
15207 // `Duration::ZERO` would pass the canonical-ms gate (the
15208 // sub-ns residue is zero) but must surface the narrower
15209 // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
15210 // remediation.
15211 let mut s = three_member_spec();
15212 s.politicas.circuit_breaker = Some(CircuitBreaker {
15213 max_failures: 5,
15214 window: Duration::ZERO,
15215 });
15216 assert_eq!(
15217 s.validate().unwrap_err(),
15218 AplicacaoError::PolicyBreakerZeroWindow
15219 );
15220 }
15221
15222 #[test]
15223 fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
15224 // Both axes invalid: max_failures == 0 *and* window is
15225 // sub-ms. The validate gate must fire on max_failures first
15226 // (matching the existing ordering pin
15227 // `rejects_circuit_breaker_zero_max_failures` enshrines), so
15228 // the existing diagnostic continues to lead with the simpler
15229 // "zero threshold" framing.
15230 let mut s = three_member_spec();
15231 s.politicas.circuit_breaker = Some(CircuitBreaker {
15232 max_failures: 0,
15233 window: Duration::from_micros(500),
15234 });
15235 assert_eq!(
15236 s.validate().unwrap_err(),
15237 AplicacaoError::PolicyBreakerZeroFailures
15238 );
15239 }
15240
15241 #[test]
15242 fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
15243 let mut s = three_member_spec();
15244 let window = Duration::from_nanos(60_000_000_001);
15245 s.politicas.circuit_breaker = Some(CircuitBreaker {
15246 max_failures: 5,
15247 window,
15248 });
15249 match s.validate().unwrap_err() {
15250 AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
15251 assert_eq!(w, window, "diagnostic must carry the offending Duration");
15252 }
15253 other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
15254 }
15255 }
15256
15257 #[test]
15258 fn rejects_circuit_breaker_window_above_cap() {
15259 // The fail-before-pass-after pin: 3601s = 1h + 1s is
15260 // structurally one canonical-tick past the
15261 // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
15262 // integer-millisecond magnitude the canonical-form arm above
15263 // accepts cleanly, that the codec round-trips losslessly as
15264 // `"3601s"`, and that silently passed validate on every
15265 // pre-gate codebase because the typed slot's only checks were
15266 // the zero-floor and canonical-form arms. The
15267 // rolling-window-to-lifetime-counter degeneration surfaces
15268 // only at the runtime substrate (Envoy's outlier_detection
15269 // interval, the future CiliumClusterwideEnvoyConfig overlay)
15270 // far from the source `caixa.lisp` with no field naming the
15271 // offending policy.
15272 let mut s = three_member_spec();
15273 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
15274 s.politicas.circuit_breaker = Some(CircuitBreaker {
15275 max_failures: 5,
15276 window,
15277 });
15278 assert_eq!(
15279 s.validate().unwrap_err(),
15280 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
15281 );
15282 }
15283
15284 #[test]
15285 fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
15286 // Boundary case: exactly 1ms past the cap (the granularity the
15287 // canonical-form gate enforces). Catches a future "strictly
15288 // less than" half-measure and pins the diagnostic to name the
15289 // offending `Duration` verbatim. Peer of
15290 // `rejects_policy_timeout_one_millisecond_above_cap` on the
15291 // sibling duration-typed `:politicas :timeout` top edge.
15292 let mut s = three_member_spec();
15293 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
15294 s.politicas.circuit_breaker = Some(CircuitBreaker {
15295 max_failures: 5,
15296 window,
15297 });
15298 assert_eq!(
15299 s.validate().unwrap_err(),
15300 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
15301 );
15302 }
15303
15304 #[test]
15305 fn rejects_circuit_breaker_window_far_above_cap() {
15306 // The "obvious authoring footgun" case: a `(:window "24h")` or
15307 // `(:window "86400s")` — values the canonical-form arm
15308 // accepts as integer-millisecond magnitudes, the codec
15309 // round-trips losslessly through serde, but the
15310 // rolling-window breaker contract cannot honor (a 24-hour
15311 // rolling failure window is operationally a lifetime counter).
15312 // Until this gate landed validate accepted it. Pin both common
15313 // above-cap values (24h, 7d) so a future relaxation that
15314 // drops the upper bound surfaces here.
15315 for window in [
15316 Duration::from_secs(86_400), // 24h
15317 Duration::from_secs(604_800), // 7d
15318 Duration::from_secs(1_000_000), // ~11.5 days
15319 ] {
15320 let mut s = three_member_spec();
15321 s.politicas.circuit_breaker = Some(CircuitBreaker {
15322 max_failures: 5,
15323 window,
15324 });
15325 assert_eq!(
15326 s.validate().unwrap_err(),
15327 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
15328 );
15329 }
15330 }
15331
15332 #[test]
15333 fn accepts_circuit_breaker_window_at_cap() {
15334 // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
15335 // (1h) — must validate. The cap is inclusive on the top edge,
15336 // matching the [`POLICY_TIMEOUT_MAX`] /
15337 // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
15338 // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
15339 // sibling capped axes. Pin the boundary explicitly so a
15340 // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
15341 // instead of `>`) surfaces here as a test failure rather than
15342 // a silent contract narrowing.
15343 let mut s = three_member_spec();
15344 s.politicas.circuit_breaker = Some(CircuitBreaker {
15345 max_failures: 5,
15346 window: POLICY_BREAKER_WINDOW_MAX,
15347 });
15348 s.validate()
15349 .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
15350 }
15351
15352 #[test]
15353 fn accepts_circuit_breaker_window_typical_values() {
15354 // The documented production-playbook band positive-control
15355 // sweep — every value Hystrix / resilience4j / Istio / Envoy
15356 // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
15357 // through the long-tail failure-detection band (15m, 30m, 1h)
15358 // the cap accepts. Pin the inclusive validated set explicitly
15359 // so a future tightening of the ceiling surfaces here as a
15360 // deliberate test edit, not a silent contract narrowing.
15361 for window in [
15362 Duration::from_millis(1),
15363 Duration::from_millis(500),
15364 Duration::from_secs(1),
15365 Duration::from_secs(10), // Hystrix / Istio / Envoy default
15366 Duration::from_secs(30),
15367 Duration::from_secs(60), // resilience4j typical
15368 Duration::from_secs(300), // AWS App Mesh typical
15369 Duration::from_secs(900),
15370 Duration::from_secs(1800),
15371 Duration::from_secs(3600), // exactly 1h, the cap
15372 ] {
15373 let mut s = three_member_spec();
15374 s.politicas.circuit_breaker = Some(CircuitBreaker {
15375 max_failures: 5,
15376 window,
15377 });
15378 s.validate()
15379 .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
15380 }
15381 }
15382
15383 #[test]
15384 fn circuit_breaker_zero_window_takes_precedence_over_cap() {
15385 // The cross-arm ordering pin: `Duration::ZERO` is structurally
15386 // outside both `>= 1ms` (zero-floor) and
15387 // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
15388 // diagnostic is the more self-locating one (it directly names
15389 // the omit-axis remediation), so the validate gate must fire
15390 // on zero first. Same shape every other zero-then-cap
15391 // ordering on this surface uses
15392 // ([`AplicacaoError::PolicyTimeoutZero`] then
15393 // [`AplicacaoError::PolicyTimeoutExceedsCap`];
15394 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
15395 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
15396 let mut s = three_member_spec();
15397 s.politicas.circuit_breaker = Some(CircuitBreaker {
15398 max_failures: 5,
15399 window: Duration::ZERO,
15400 });
15401 assert_eq!(
15402 s.validate().unwrap_err(),
15403 AplicacaoError::PolicyBreakerZeroWindow,
15404 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
15405 );
15406 }
15407
15408 #[test]
15409 fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
15410 // The cross-arm ordering pin: a `Duration` that is *both*
15411 // sub-millisecond (non-canonical-form) and structurally above
15412 // the cap surfaces the canonical-form diagnostic first,
15413 // because the round-trip-shape break is the more fundamental
15414 // issue (the value can't even round-trip through the codec, so
15415 // the cap diagnostic naming `1ms..=1h` would be misleading —
15416 // there's no integer-ms form of the offending value). Pin the
15417 // order so a future refactor that reorders the arms surfaces
15418 // here as a test failure rather than a silent diagnostic
15419 // regression. Peer of
15420 // `policy_timeout_canonical_takes_precedence_over_cap` on the
15421 // sibling duration-typed `:politicas :timeout` axis.
15422 let mut s = three_member_spec();
15423 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
15424 s.politicas.circuit_breaker = Some(CircuitBreaker {
15425 max_failures: 5,
15426 window,
15427 });
15428 assert_eq!(
15429 s.validate().unwrap_err(),
15430 AplicacaoError::PolicyBreakerWindowNotCanonical { window },
15431 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
15432 );
15433 }
15434
15435 #[test]
15436 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
15437 // The cross-arm ordering pin between the two breaker axes: a
15438 // `CircuitBreaker` whose *both* `max_failures` is above its
15439 // cap *and* `window` is above its cap surfaces the
15440 // max-failures cap diagnostic first, because the validate
15441 // gate visits the failures arm before the window arm. Pin the
15442 // order so a future refactor that reorders the breaker arms
15443 // surfaces here.
15444 let mut s = three_member_spec();
15445 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
15446 s.politicas.circuit_breaker = Some(CircuitBreaker {
15447 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15448 window,
15449 });
15450 assert_eq!(
15451 s.validate().unwrap_err(),
15452 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15453 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
15454 },
15455 "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
15456 );
15457 }
15458
15459 #[test]
15460 fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
15461 // The diagnostic-shape pin: the offending `Duration` is
15462 // carried verbatim into the
15463 // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
15464 // the surfaced error message names the value the author wrote
15465 // (`":politicas :circuit-breaker :window (Duration { secs:
15466 // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
15467 // just the cap. Same self-locating diagnostic shape every
15468 // other typed-cap arm on this surface carries
15469 // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
15470 // offending `Duration` verbatim).
15471 let mut s = three_member_spec();
15472 let window = Duration::from_secs(7200); // 2h
15473 s.politicas.circuit_breaker = Some(CircuitBreaker {
15474 max_failures: 5,
15475 window,
15476 });
15477 let err = s.validate().unwrap_err();
15478 assert!(
15479 matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
15480 "got {err:?}"
15481 );
15482 let msg = err.to_string();
15483 assert!(
15484 msg.contains("7200"),
15485 ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
15486 );
15487 }
15488
15489 #[test]
15490 fn circuit_breaker_window_cap_pins_canonical_value() {
15491 // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
15492 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
15493 // shared duration codec emits as a clean canonical string
15494 // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
15495 // the sibling duration-typed `:politicas :timeout` axis (the
15496 // two duration-typed `:politicas` axes share a uniform top
15497 // edge). Pinning the literal value here surfaces a future
15498 // drift (a relaxation to 24h, a tightening to 5m) as a
15499 // deliberate test edit, not a silent contract narrowing. Same
15500 // shape every other typed-cap value pin on this surface uses
15501 // (`policy_timeout_cap_pins_canonical_value`).
15502 assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
15503 assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
15504 assert_eq!(
15505 POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
15506 "the two duration-typed `:politicas` caps share the same top edge"
15507 );
15508 }
15509
15510 #[test]
15511 fn circuit_breaker_window_cap_value_round_trips_through_codec() {
15512 // The codec round-trip property the cap arm preserves: the
15513 // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
15514 // through the shared duration codec — every value at the cap
15515 // renders to a clean canonical string (`"1h"`) and parses back
15516 // to the same `Duration`. Pin this so a future drift between
15517 // the cap constant and the codec's largest emitted unit
15518 // surfaces here. Same shape every other typed boundary pin on
15519 // this surface uses
15520 // (`policy_timeout_cap_value_round_trips_through_codec`).
15521 let policy = MeshPolicy {
15522 circuit_breaker: Some(CircuitBreaker {
15523 max_failures: 5,
15524 window: POLICY_BREAKER_WINDOW_MAX,
15525 }),
15526 ..Default::default()
15527 };
15528 let json = serde_json::to_string(&policy).unwrap();
15529 // The codec emits `"1h"` for the canonical 1-hour magnitude.
15530 assert!(
15531 json.contains("\"1h\""),
15532 "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
15533 );
15534 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15535 assert_eq!(
15536 back.circuit_breaker.unwrap().window,
15537 POLICY_BREAKER_WINDOW_MAX
15538 );
15539 }
15540
15541 #[test]
15542 fn is_integer_millisecond_duration_predicate_tracks_codec() {
15543 // Pin the predicate's accepted set against the codec's
15544 // accepted set explicitly. The codec parses
15545 // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
15546 // accepted value is an integer-millisecond multiple — so the
15547 // predicate must accept exactly that set. Same shape every
15548 // other predicate-on-the-typed-slot helper carries
15549 // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
15550 // Read directly from the codec-owned predicate — the crate's
15551 // single source of truth every typed-`Duration` axis now routes
15552 // through via
15553 // [`crate::render::require_positive_canonical_bounded_duration`].
15554 use super::supervisor::duration_codec::is_integer_millisecond_duration;
15555 assert!(is_integer_millisecond_duration(Duration::ZERO));
15556 assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
15557 assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
15558 assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
15559 assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
15560 assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
15561 // Non-integer-millisecond residue: rejected.
15562 assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
15563 assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
15564 assert!(!is_integer_millisecond_duration(Duration::from_micros(
15565 1500
15566 )));
15567 assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
15568 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
15569 999_999
15570 )));
15571 // The 1-ns-past-1ms boundary: rejected (no longer a clean
15572 // integer-millisecond multiple).
15573 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
15574 1_000_001
15575 )));
15576 }
15577
15578 #[test]
15579 fn policy_timeout_validated_value_round_trips_through_codec() {
15580 // The structural property the canonical-ms gate enforces:
15581 // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
15582 // round-trips losslessly through the shared `duration_codec`
15583 // (serialize → string → deserialize → equal value). Pin this
15584 // end-to-end so a future change to either side (the validate
15585 // gate's accepted granularity, the codec's parse/render unit
15586 // set) that breaks the alignment surfaces here. The
15587 // previous-state shape (typed slot accepts arbitrary
15588 // `Duration`, codec only round-trips integer-ms) would fail
15589 // this test for any `Duration::from_micros(1500)` timeout —
15590 // the validate gate now forecloses that.
15591 for timeout in [
15592 Duration::from_millis(1),
15593 Duration::from_millis(1500),
15594 Duration::from_secs(30),
15595 Duration::from_secs(3600),
15596 ] {
15597 let mut s = three_member_spec();
15598 s.politicas.timeout = Some(timeout);
15599 s.validate().unwrap();
15600 let json = serde_json::to_string(&s.politicas).unwrap();
15601 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15602 assert_eq!(
15603 back.timeout, s.politicas.timeout,
15604 "every validated :timeout must round-trip losslessly through the codec"
15605 );
15606 }
15607 }
15608
15609 #[test]
15610 fn circuit_breaker_window_validated_value_round_trips_through_codec() {
15611 // Peer of the `:timeout` round-trip property on the breaker
15612 // axis.
15613 for window in [
15614 Duration::from_millis(1),
15615 Duration::from_millis(1500),
15616 Duration::from_secs(30),
15617 Duration::from_secs(3600),
15618 ] {
15619 let mut s = three_member_spec();
15620 s.politicas.circuit_breaker = Some(CircuitBreaker {
15621 max_failures: 5,
15622 window,
15623 });
15624 s.validate().unwrap();
15625 let json = serde_json::to_string(&s.politicas).unwrap();
15626 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15627 assert_eq!(
15628 back.circuit_breaker.unwrap().window,
15629 window,
15630 "every validated :circuit-breaker :window must round-trip losslessly"
15631 );
15632 }
15633 }
15634
15635 #[test]
15636 fn empty_politicas_validates() {
15637 // Omitting every policy axis is fine — defaults express "no
15638 // policy on this axis", not "policy = 0". The fixture's typical
15639 // values continue to validate; this test pins that
15640 // MeshPolicy::default() is a clean pass through validate().
15641 let mut s = three_member_spec();
15642 s.politicas = MeshPolicy::default();
15643 s.validate().unwrap();
15644 }
15645
15646 #[test]
15647 fn typical_politicas_validates_with_every_axis_set() {
15648 // The full §III.1 example block (timeout + retries + breaker +
15649 // mtls + rate-limit) — every axis nonzero — must remain a
15650 // clean pass.
15651 let mut s = three_member_spec();
15652 s.politicas = MeshPolicy {
15653 timeout: Some(Duration::from_secs(30)),
15654 retries: Some(3),
15655 circuit_breaker: Some(CircuitBreaker {
15656 max_failures: 5,
15657 window: Duration::from_secs(60),
15658 }),
15659 mtls_required: Some(true),
15660 rate_limit: Some(RateLimit {
15661 rate: 100,
15662 window: Duration::from_secs(1),
15663 }),
15664 };
15665 s.validate().unwrap();
15666 }
15667
15668 #[test]
15669 fn rejects_empty_cluster_name() {
15670 let mut s = three_member_spec();
15671 s.placement.clusters = vec!["rio".into(), "".into()];
15672 assert_eq!(
15673 s.validate().unwrap_err(),
15674 AplicacaoError::PlacementClusterEmpty
15675 );
15676 }
15677
15678 #[test]
15679 fn rejects_duplicate_cluster_names() {
15680 let mut s = three_member_spec();
15681 s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
15682 let err = s.validate().unwrap_err();
15683 assert!(
15684 matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
15685 "got {err:?}"
15686 );
15687 }
15688
15689 #[test]
15690 fn rejects_placement_cluster_with_uppercase() {
15691 // The canonical "I copied the cluster's display name verbatim"
15692 // typo — K8s context names are lowercase per DNS-1123 label
15693 // rule, but org docs often round-trip a TitleCase identifier
15694 // (`Rio`, `Mar-East`) from an ADR. Mirrors the
15695 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
15696 // on the peer name axis.
15697 let mut s = three_member_spec();
15698 s.placement.clusters = vec!["Rio".into(), "mar".into()];
15699 let err = s.validate().unwrap_err();
15700 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15701 panic!("expected PlacementClusterInvalid, got other variant");
15702 };
15703 assert_eq!(cluster, "Rio");
15704 assert!(
15705 reason.contains("uppercase"),
15706 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
15707 );
15708 assert!(
15709 reason.contains("\"rio\""),
15710 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
15711 );
15712 }
15713
15714 #[test]
15715 fn rejects_placement_cluster_with_underscore() {
15716 // The canonical "I'm thinking of an env var / hostname slug"
15717 // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
15718 // schema. K8s context filtering on `my_cluster` silently misses
15719 // the cluster the author intended; the gate moves it to caixa-
15720 // build time. Same shape as `rejects_membro_caixa_with_underscore`
15721 // (3f9d7a0).
15722 let mut s = three_member_spec();
15723 s.placement.clusters = vec!["my_cluster".into()];
15724 let err = s.validate().unwrap_err();
15725 assert!(
15726 matches!(
15727 err,
15728 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15729 if cluster == "my_cluster" && reason.contains('_')
15730 ),
15731 "got {err:?}"
15732 );
15733 }
15734
15735 #[test]
15736 fn rejects_placement_cluster_with_dot() {
15737 // A `:placement :clusters` entry is a single DNS-1123 *label*,
15738 // not a subdomain — even though K8s context names sometimes
15739 // carry a dotted form via kubeconfig conventions, the strictest
15740 // floor among the use sites (DNS-1035 cluster.x-k8s.io
15741 // `metadata.name`, Cilium identity label values) wins. The "I
15742 // want to namespace my cluster names with `.`" intent is
15743 // expressed via `-` (`mar-east`).
15744 let mut s = three_member_spec();
15745 s.placement.clusters = vec!["team.rio".into()];
15746 let err = s.validate().unwrap_err();
15747 assert!(
15748 matches!(
15749 err,
15750 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15751 if cluster == "team.rio" && reason.contains('.')
15752 ),
15753 "got {err:?}"
15754 );
15755 }
15756
15757 #[test]
15758 fn rejects_placement_cluster_with_leading_hyphen() {
15759 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
15760 // with an alphanumeric. The K8s apiserver rejects `-rio`
15761 // outright; the rendered fan-out would emit a `metadata.name:
15762 // "-rio"` that fails admission far from the source caixa.lisp.
15763 let mut s = three_member_spec();
15764 s.placement.clusters = vec!["-rio".into()];
15765 let err = s.validate().unwrap_err();
15766 assert!(
15767 matches!(
15768 err,
15769 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15770 if cluster == "-rio" && reason.contains("start and end")
15771 ),
15772 "got {err:?}"
15773 );
15774 }
15775
15776 #[test]
15777 fn rejects_placement_cluster_with_trailing_hyphen() {
15778 // The symmetric arm of the boundary rule. Pin separately so
15779 // both ends are covered against a future relaxation that only
15780 // checks one boundary (parallel to
15781 // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
15782 let mut s = three_member_spec();
15783 s.placement.clusters = vec!["rio-".into()];
15784 let err = s.validate().unwrap_err();
15785 assert!(
15786 matches!(
15787 err,
15788 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15789 if cluster == "rio-"
15790 ),
15791 "got {err:?}"
15792 );
15793 }
15794
15795 #[test]
15796 fn rejects_placement_cluster_with_unicode() {
15797 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
15798 // before it reaches K8s. The byte-by-byte ASCII validity check
15799 // rejects multi-byte UTF-8 sequences by the first byte that
15800 // fails `[a-z0-9-]`.
15801 let mut s = three_member_spec();
15802 s.placement.clusters = vec!["rió".into()];
15803 let err = s.validate().unwrap_err();
15804 assert!(
15805 matches!(
15806 err,
15807 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15808 if cluster == "rió"
15809 ),
15810 "got {err:?}"
15811 );
15812 }
15813
15814 #[test]
15815 fn rejects_placement_cluster_with_whitespace() {
15816 // Whitespace is the canonical "I pasted from a sketch / doc"
15817 // footgun. The apiserver rejects every cluster `metadata.name`
15818 // value carrying whitespace.
15819 let mut s = three_member_spec();
15820 s.placement.clusters = vec!["rio cluster".into()];
15821 let err = s.validate().unwrap_err();
15822 assert!(
15823 matches!(
15824 err,
15825 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15826 if cluster == "rio cluster"
15827 ),
15828 "got {err:?}"
15829 );
15830 }
15831
15832 #[test]
15833 fn rejects_placement_cluster_too_long() {
15834 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
15835 // pin. The diagnostic names both the cap (63) and the actual
15836 // length so the author can shorten in one edit. Mirrors
15837 // `rejects_membro_caixa_too_long` (3f9d7a0).
15838 let mut s = three_member_spec();
15839 let too_long = "a".repeat(64);
15840 s.placement.clusters = vec![too_long.clone()];
15841 let err = s.validate().unwrap_err();
15842 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15843 panic!("expected PlacementClusterInvalid");
15844 };
15845 assert_eq!(cluster, too_long);
15846 assert!(
15847 reason.contains("63") && reason.contains("64"),
15848 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
15849 );
15850 }
15851
15852 #[test]
15853 fn placement_cluster_max_length_validates() {
15854 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
15855 // future tightening (e.g. dropping to 62) surfaces here as a
15856 // regression, mirroring `membro_caixa_max_length_validates`
15857 // (3f9d7a0).
15858 let mut s = three_member_spec();
15859 s.placement.clusters = vec!["a".repeat(63)];
15860 s.validate().unwrap();
15861 }
15862
15863 #[test]
15864 fn accepts_canonical_placement_cluster_forms() {
15865 // The DNS-1123 label shapes a caixa author is realistically
15866 // going to write for cluster names: single-word lowercase
15867 // (`rio`), regional hyphen-joined (`mar-east`), single
15868 // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
15869 // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
15870 // Pin every leg so a future tightening that bans (e.g.) digit-
15871 // start identifiers surfaces here.
15872 for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
15873 let mut s = three_member_spec();
15874 s.placement.clusters = vec![form.into()];
15875 s.validate().unwrap_or_else(|e| {
15876 panic!("canonical cluster form {form:?} must validate, got {e:?}")
15877 });
15878 }
15879 }
15880
15881 #[test]
15882 fn placement_cluster_empty_takes_precedence_over_invalid() {
15883 // Order pin: the existing `PlacementClusterEmpty` diagnostic
15884 // (which doesn't try to parse) fires before the new
15885 // `PlacementClusterInvalid` parse-side diagnostic, so an empty
15886 // `:clusters` entry keeps its narrower error message — the new
15887 // gate would also reject `""`, but the empty-string arm is the
15888 // more self-locating diagnostic. Mirrors the
15889 // `membro_caixa_empty_takes_precedence_over_invalid` pin
15890 // (3f9d7a0).
15891 let mut s = three_member_spec();
15892 s.placement.clusters = vec!["rio".into(), "".into()];
15893 let err = s.validate().unwrap_err();
15894 assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
15895 }
15896
15897 #[test]
15898 fn placement_cluster_invalid_fires_before_duplicate_check() {
15899 // Order pin: a malformed-shape `:clusters` entry surfaces *its
15900 // own* diagnostic, even when a later entry would otherwise
15901 // collapse onto a duplicate name. The per-entry shape gate runs
15902 // inline before the duplicate-key insert, parallel to
15903 // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
15904 let mut s = three_member_spec();
15905 s.placement.clusters = vec!["Rio".into(), "rio".into()];
15906 let err = s.validate().unwrap_err();
15907 assert!(
15908 matches!(
15909 err,
15910 AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
15911 ),
15912 "got {err:?}"
15913 );
15914 }
15915
15916 #[test]
15917 fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
15918 // The diagnostic-shape pin: the error names the offending
15919 // `:clusters` value verbatim so the author can grep their
15920 // caixa.lisp without re-running the build, and carries a
15921 // non-empty `reason` naming the specific violation. Same shape
15922 // every typed-shape gate enshrines
15923 // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
15924 // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
15925 let mut s = three_member_spec();
15926 s.placement.clusters = vec!["BAD_CLUSTER".into()];
15927 let err = s.validate().unwrap_err();
15928 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15929 panic!("expected PlacementClusterInvalid");
15930 };
15931 assert_eq!(cluster, "BAD_CLUSTER");
15932 assert!(
15933 !reason.is_empty(),
15934 "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
15935 );
15936 }
15937
15938 #[test]
15939 fn rejects_sharded_with_empty_clusters() {
15940 // §III.1: Sharded uses :clusters as the shard pool. An empty
15941 // pool means "shard across no clusters" — meaningless, same as
15942 // Replicated with no hosts.
15943 let mut s = three_member_spec();
15944 s.placement.estrategia = PlacementStrategy::Sharded;
15945 s.placement.shard_key = Some("$tenantId".into());
15946 s.placement.clusters = vec![];
15947 assert!(matches!(
15948 s.validate().unwrap_err(),
15949 AplicacaoError::PlacementWithoutClusters {
15950 estrategia: PlacementStrategy::Sharded
15951 }
15952 ));
15953 }
15954
15955 #[test]
15956 fn rejects_sharded_with_empty_shard_key() {
15957 let mut s = three_member_spec();
15958 s.placement.estrategia = PlacementStrategy::Sharded;
15959 s.placement.shard_key = Some("".into());
15960 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
15961 }
15962
15963 #[test]
15964 fn rejects_shard_key_under_replicated_strategy() {
15965 // The fail-before-pass-after pin: a `:placement (:estrategia
15966 // Replicated :shard-key "tenantId")` manifest carries the
15967 // hash-keyed-distribution slot on a strategy that never consumes
15968 // it. Before the gate the typed slot's value silently vanished
15969 // at the renderer layer (caixa-mesh emits `placement.shardKey`
15970 // verbatim regardless of strategy; the Akka-style cluster-
15971 // sharding reconciler keys off `estrategia == Sharded` and
15972 // ignores the slot otherwise), with no diagnostic. Lifting the
15973 // rejection to a build-time gate makes the
15974 // `shard_key.is_some() == matches!(estrategia, Sharded)`
15975 // partition a structural property of every validated
15976 // [`Placement`].
15977 let mut s = three_member_spec();
15978 // The fixture already uses Replicated; just add a shard-key.
15979 s.placement.shard_key = Some("$tenantId".into());
15980 let err = s.validate().unwrap_err();
15981 let AplicacaoError::ShardKeyOnNonSharded {
15982 estrategia,
15983 shard_key,
15984 } = err
15985 else {
15986 panic!("expected ShardKeyOnNonSharded, got {err:?}");
15987 };
15988 assert_eq!(estrategia, PlacementStrategy::Replicated);
15989 assert_eq!(shard_key, "$tenantId");
15990 }
15991
15992 #[test]
15993 fn rejects_shard_key_under_singlenode_strategy() {
15994 // Peer of the Replicated case above on the SingleNode arm: OTP
15995 // distributed-app takeover (one cluster runs at a time) has no
15996 // hash-keyed routing axis to consume `:shard-key` either, so
15997 // the rejection fires on both non-Sharded arms uniformly.
15998 let mut s = three_member_spec();
15999 s.placement.estrategia = PlacementStrategy::SingleNode;
16000 s.placement.shard_key = Some("$tenantId".into());
16001 let err = s.validate().unwrap_err();
16002 let AplicacaoError::ShardKeyOnNonSharded {
16003 estrategia,
16004 shard_key,
16005 } = err
16006 else {
16007 panic!("expected ShardKeyOnNonSharded, got {err:?}");
16008 };
16009 assert_eq!(estrategia, PlacementStrategy::SingleNode);
16010 assert_eq!(shard_key, "$tenantId");
16011 }
16012
16013 #[test]
16014 fn rejects_empty_shard_key_under_replicated_strategy() {
16015 // The `Some("")` case under non-Sharded is rejected by
16016 // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
16017 // fires before the empty-value gate), not
16018 // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
16019 // the `Sharded` arm). Pin the partition so a future reorder of
16020 // the validate_placement match arms doesn't silently swap which
16021 // diagnostic the author sees — both are author errors, but
16022 // ShardKeyOnNonSharded names which strategy is the actual fix
16023 // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
16024 // only says "pick a non-empty key".
16025 let mut s = three_member_spec();
16026 s.placement.shard_key = Some(String::new());
16027 let err = s.validate().unwrap_err();
16028 assert!(
16029 matches!(
16030 err,
16031 AplicacaoError::ShardKeyOnNonSharded {
16032 estrategia: PlacementStrategy::Replicated,
16033 ref shard_key,
16034 } if shard_key.is_empty()
16035 ),
16036 "got {err:?}"
16037 );
16038 }
16039
16040 #[test]
16041 fn replicated_without_shard_key_validates() {
16042 // The complement of the rejection: `:placement :estrategia
16043 // Replicated` with `:shard-key None` is the canonical happy
16044 // path on every existing fixture. Pin the no-shard-key case so
16045 // the new gate doesn't accidentally fire on `None`.
16046 let mut s = three_member_spec();
16047 assert!(matches!(
16048 s.placement.estrategia,
16049 PlacementStrategy::Replicated
16050 ));
16051 s.placement.shard_key = None;
16052 s.validate().unwrap();
16053 }
16054
16055 #[test]
16056 fn singlenode_without_shard_key_validates() {
16057 // Peer of the Replicated no-shard-key case on the SingleNode
16058 // arm — both non-Sharded strategies must validate cleanly when
16059 // the slot is omitted.
16060 let mut s = three_member_spec();
16061 s.placement.estrategia = PlacementStrategy::SingleNode;
16062 s.placement.shard_key = None;
16063 s.validate().unwrap();
16064 }
16065
16066 fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
16067 // Fixture builder for the `:placement :shard-key` shape gate
16068 // tests: a three-member Aplicacao on the `Sharded` strategy
16069 // with the supplied `:shard-key` slot. Co-locates the
16070 // arm-construction so every test below carries one line of
16071 // setup (the offending `:shard-key` value) and the assertion.
16072 let mut s = three_member_spec();
16073 s.placement.estrategia = PlacementStrategy::Sharded;
16074 s.placement.shard_key = Some(key.into());
16075 s
16076 }
16077
16078 #[test]
16079 fn rejects_shard_key_with_embedded_space() {
16080 // The canonical paste-from-aligned-doc footgun:
16081 // `:shard-key "$tenant Id"` — the Akka-style entity-id
16082 // extractor reads the slot as a single-token reference, and an
16083 // embedded space breaks the token boundary at the runtime
16084 // hash-extractor pass with no diagnostic naming the offending
16085 // entry.
16086 let s = sharded_spec_with_key("$tenant Id");
16087 let err = s.validate().unwrap_err();
16088 assert!(
16089 matches!(
16090 err,
16091 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16092 if shard_key == "$tenant Id" && reason.contains("space")
16093 ),
16094 "got {err:?}"
16095 );
16096 }
16097
16098 #[test]
16099 fn rejects_shard_key_with_leading_space() {
16100 // Leading-space arm of the embedded-whitespace footgun — the
16101 // paste-from-aligned-doc / paste-from-CSV-cell variant where
16102 // the leading column-padding leaked into the slot.
16103 let s = sharded_spec_with_key(" $tenantId");
16104 let err = s.validate().unwrap_err();
16105 assert!(
16106 matches!(
16107 err,
16108 AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
16109 if shard_key == " $tenantId"
16110 ),
16111 "got {err:?}"
16112 );
16113 }
16114
16115 #[test]
16116 fn rejects_shard_key_with_trailing_newline() {
16117 // The canonical paste-from-shell-heredoc footgun — every
16118 // `<<EOF` heredoc terminator paste leaves a trailing newline
16119 // the YAML emitter then folds away inconsistently across
16120 // emitter implementations.
16121 let s = sharded_spec_with_key("$tenantId\n");
16122 let err = s.validate().unwrap_err();
16123 assert!(
16124 matches!(
16125 err,
16126 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16127 if shard_key == "$tenantId\n" && reason.contains("0x0a")
16128 ),
16129 "got {err:?}"
16130 );
16131 }
16132
16133 #[test]
16134 fn rejects_shard_key_with_embedded_tab() {
16135 // The paste-from-aligned-doc tab-stop variant — tabs land
16136 // alongside spaces in copy-paste from formatted columns.
16137 let s = sharded_spec_with_key("$tenant\tId");
16138 let err = s.validate().unwrap_err();
16139 assert!(
16140 matches!(
16141 err,
16142 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16143 if shard_key == "$tenant\tId" && reason.contains("tab")
16144 ),
16145 "got {err:?}"
16146 );
16147 }
16148
16149 #[test]
16150 fn rejects_shard_key_with_control_character() {
16151 // The paste-from-binary / paste-from-screen-cleared-terminal
16152 // footgun — an embedded `\x01` (SOH) byte that some YAML
16153 // emitters silently strip and others escape as ``,
16154 // breaking round-trip across emitter implementations.
16155 let s = sharded_spec_with_key("$tenant\u{0001}Id");
16156 let err = s.validate().unwrap_err();
16157 assert!(
16158 matches!(
16159 err,
16160 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16161 if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
16162 ),
16163 "got {err:?}"
16164 );
16165 }
16166
16167 #[test]
16168 fn rejects_shard_key_with_non_ascii() {
16169 // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
16170 // footgun — non-ASCII bytes normalize differently between the
16171 // caixa-mesh-side YAML emitter and the in-cluster reconciler's
16172 // YAML parser, the same entity ID can silently map to two
16173 // distinct shards on a re-render.
16174 let s = sharded_spec_with_key("$tenàntId");
16175 let err = s.validate().unwrap_err();
16176 assert!(
16177 matches!(
16178 err,
16179 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
16180 if shard_key == "$tenàntId" && reason.contains("non-ASCII")
16181 ),
16182 "got {err:?}"
16183 );
16184 }
16185
16186 #[test]
16187 fn rejects_shard_key_too_long() {
16188 // Length cap pin: 64 bytes — one byte over the
16189 // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
16190 // here is a paste-from-doc multi-line blob landing in
16191 // `:shard-key` instead of a single-token extractor expression.
16192 let too_long = "a".repeat(64);
16193 let s = sharded_spec_with_key(&too_long);
16194 let err = s.validate().unwrap_err();
16195 let AplicacaoError::ShardKeyInvalid {
16196 ref shard_key,
16197 ref reason,
16198 } = err
16199 else {
16200 panic!("expected ShardKeyInvalid, got {err:?}");
16201 };
16202 assert_eq!(shard_key, &too_long);
16203 assert!(
16204 reason.contains("63") && reason.contains("64"),
16205 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
16206 );
16207 }
16208
16209 #[test]
16210 fn shard_key_max_length_validates() {
16211 // Boundary pin: 63 bytes exactly — the
16212 // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
16213 // dropping to 62) surfaces here as a regression, mirroring
16214 // `placement_cluster_max_length_validates` /
16215 // `placement_affinity_max_length_validates` on the peer
16216 // identifier-shaped slots.
16217 let s = sharded_spec_with_key(&"a".repeat(63));
16218 s.validate().unwrap();
16219 }
16220
16221 #[test]
16222 fn accepts_canonical_shard_key_forms() {
16223 // The Akka-style entity-id extractor shapes a caixa author is
16224 // realistically going to write — pin every leg so a future
16225 // tightening that bans (e.g.) the `${...}` interpolation
16226 // variant or the `metadata.<field>` JSONPath form surfaces
16227 // here as a regression. The canonical forms span:
16228 //
16229 // - bare property name (`tenantId`, `customerId`)
16230 // - Akka `ExtractEntityId` placeholder (`$tenantId`)
16231 // - JSONPath-style nested reference (`metadata.tenantId`,
16232 // `$.user.id`)
16233 // - interpolation-style template (`${tenant}`)
16234 // - snake_case property name (`customer_id`)
16235 // - kebab-case property name (`customer-id` — accepted
16236 // because the slot is a printable-ASCII single-token
16237 // reference, not a DNS-1123 label like
16238 // `:placement :affinity` / `:clusters`)
16239 // - single character (`a`, `$` — boundary)
16240 for form in [
16241 "tenantId",
16242 "customerId",
16243 "$tenantId",
16244 "metadata.tenantId",
16245 "$.user.id",
16246 "${tenant}",
16247 "customer_id",
16248 "customer-id",
16249 "a",
16250 "$",
16251 ] {
16252 let s = sharded_spec_with_key(form);
16253 s.validate().unwrap_or_else(|e| {
16254 panic!("canonical shard-key form {form:?} must validate, got {e:?}")
16255 });
16256 }
16257 }
16258
16259 #[test]
16260 fn shard_key_empty_takes_precedence_over_invalid() {
16261 // Order pin: the existing `ShardedKeyEmpty` diagnostic
16262 // (reserved for the `Sharded` `Some("")` arm) fires before the
16263 // new `ShardKeyInvalid` parse-side diagnostic, so an empty
16264 // `:shard-key` keeps its narrower error message — the new gate
16265 // would also reject `""` defensively, but the empty-string arm
16266 // is the more self-locating diagnostic. Mirrors the
16267 // `placement_cluster_empty_takes_precedence_over_invalid` pin
16268 // on the peer identifier-shaped slot.
16269 let s = sharded_spec_with_key("");
16270 let err = s.validate().unwrap_err();
16271 assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
16272 }
16273
16274 #[test]
16275 fn shard_key_invalid_diagnostic_carries_offending_value() {
16276 // The diagnostic-shape pin: the error names the offending
16277 // `:shard-key` value verbatim so the author can grep their
16278 // caixa.lisp without re-running the build, and carries a
16279 // parser-shaped `reason:` naming the specific violation —
16280 // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
16281 // on the peer identifier-shaped slot.
16282 let s = sharded_spec_with_key("$tenant Id");
16283 let err = s.validate().unwrap_err();
16284 let AplicacaoError::ShardKeyInvalid {
16285 ref shard_key,
16286 ref reason,
16287 } = err
16288 else {
16289 panic!("expected ShardKeyInvalid, got {err:?}");
16290 };
16291 assert_eq!(shard_key, "$tenant Id");
16292 assert!(
16293 !reason.is_empty(),
16294 "reason must name the specific violation, got empty string"
16295 );
16296 }
16297
16298 #[test]
16299 fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
16300 // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
16301 // `:shard-key` carried on non-Sharded strategies) fires before
16302 // the shape gate, so a malformed `:shard-key` carried on (e.g.)
16303 // a `Replicated` strategy surfaces the more self-locating
16304 // strategy-mismatch diagnostic (naming the actual fix — drop
16305 // the slot, or switch to Sharded) rather than the shape
16306 // diagnostic. The strategy-mismatch arm is the more actionable
16307 // diagnostic: a malformed shard-key on Replicated is "you
16308 // shouldn't have a :shard-key here at all", not "your
16309 // :shard-key value is malformed".
16310 let mut s = three_member_spec();
16311 // Replicated is the default fixture strategy.
16312 s.placement.shard_key = Some("$tenant Id".into());
16313 let err = s.validate().unwrap_err();
16314 assert!(
16315 matches!(
16316 err,
16317 AplicacaoError::ShardKeyOnNonSharded {
16318 estrategia: PlacementStrategy::Replicated,
16319 ..
16320 }
16321 ),
16322 "got {err:?}"
16323 );
16324 }
16325
16326 #[test]
16327 fn rejects_empty_affinity_hint() {
16328 let mut s = three_member_spec();
16329 s.placement.affinity = Some("".into());
16330 assert_eq!(
16331 s.validate().unwrap_err(),
16332 AplicacaoError::PlacementAffinityEmpty
16333 );
16334 }
16335
16336 #[test]
16337 fn placement_without_affinity_validates() {
16338 // Omitting :affinity is fine — the placement engine falls back
16339 // to the default heuristic. Pin the no-hint case so the
16340 // affinity-empty rejection doesn't accidentally fire on `None`.
16341 let mut s = three_member_spec();
16342 s.placement.affinity = None;
16343 s.validate().unwrap();
16344 }
16345
16346 #[test]
16347 fn rejects_placement_affinity_with_uppercase() {
16348 // The canonical "I copied the ADR's display name verbatim" typo
16349 // — placement hints land verbatim in K8s label-selector
16350 // territory, where the apiserver enforces the DNS-1123 label
16351 // rule (lowercase-only) on every identity-keyed admission axis.
16352 // Mirrors `rejects_placement_cluster_with_uppercase` on the
16353 // sibling slot.
16354 let mut s = three_member_spec();
16355 s.placement.affinity = Some("DataLocality".into());
16356 let err = s.validate().unwrap_err();
16357 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
16358 panic!("expected PlacementAffinityInvalid, got other variant");
16359 };
16360 assert_eq!(affinity, "DataLocality");
16361 assert!(
16362 reason.contains("uppercase"),
16363 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
16364 );
16365 assert!(
16366 reason.contains("\"datalocality\""),
16367 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
16368 );
16369 }
16370
16371 #[test]
16372 fn rejects_placement_affinity_with_underscore() {
16373 // The canonical "I'm thinking of an env var / Python identifier"
16374 // leak — `_` is forbidden by every DNS-1123 label schema. Same
16375 // shape as `rejects_placement_cluster_with_underscore` on the
16376 // sibling slot.
16377 let mut s = three_member_spec();
16378 s.placement.affinity = Some("data_locality".into());
16379 let err = s.validate().unwrap_err();
16380 assert!(
16381 matches!(
16382 err,
16383 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
16384 if affinity == "data_locality" && reason.contains('_')
16385 ),
16386 "got {err:?}"
16387 );
16388 }
16389
16390 #[test]
16391 fn rejects_placement_affinity_with_dot() {
16392 // A `:placement :affinity` value is a single DNS-1123 *label*
16393 // (it lands as a K8s label value selector key), not a subdomain.
16394 // The "I want to namespace my hint with `.`" intent is expressed
16395 // via `-` (`data-locality-east`).
16396 let mut s = three_member_spec();
16397 s.placement.affinity = Some("data.locality".into());
16398 let err = s.validate().unwrap_err();
16399 assert!(
16400 matches!(
16401 err,
16402 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
16403 if affinity == "data.locality" && reason.contains('.')
16404 ),
16405 "got {err:?}"
16406 );
16407 }
16408
16409 #[test]
16410 fn rejects_placement_affinity_with_unicode() {
16411 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
16412 // before it reaches K8s. The byte-by-byte ASCII validity check
16413 // rejects multi-byte UTF-8 sequences by the first byte that
16414 // fails `[a-z0-9-]`.
16415 let mut s = three_member_spec();
16416 s.placement.affinity = Some("data-localité".into());
16417 let err = s.validate().unwrap_err();
16418 assert!(
16419 matches!(
16420 err,
16421 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
16422 if affinity == "data-localité"
16423 ),
16424 "got {err:?}"
16425 );
16426 }
16427
16428 #[test]
16429 fn rejects_placement_affinity_with_leading_hyphen() {
16430 // DNS-1123 boundary rule: labels must start with an
16431 // alphanumeric. Pin separately from the trailing-hyphen arm so
16432 // a future relaxation that only checks one boundary surfaces
16433 // here as a regression (parallel to
16434 // `rejects_placement_cluster_with_leading_hyphen`).
16435 let mut s = three_member_spec();
16436 s.placement.affinity = Some("-data-locality".into());
16437 let err = s.validate().unwrap_err();
16438 assert!(
16439 matches!(
16440 err,
16441 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
16442 if affinity == "-data-locality" && reason.contains("start and end")
16443 ),
16444 "got {err:?}"
16445 );
16446 }
16447
16448 #[test]
16449 fn rejects_placement_affinity_with_trailing_hyphen() {
16450 // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
16451 // ends are covered against a future relaxation.
16452 let mut s = three_member_spec();
16453 s.placement.affinity = Some("data-locality-".into());
16454 let err = s.validate().unwrap_err();
16455 assert!(
16456 matches!(
16457 err,
16458 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
16459 if affinity == "data-locality-"
16460 ),
16461 "got {err:?}"
16462 );
16463 }
16464
16465 #[test]
16466 fn rejects_placement_affinity_with_whitespace() {
16467 // Whitespace is the canonical "I pasted from a sketch / doc"
16468 // footgun. The apiserver rejects every label-selector value
16469 // carrying whitespace.
16470 let mut s = three_member_spec();
16471 s.placement.affinity = Some("data locality".into());
16472 let err = s.validate().unwrap_err();
16473 assert!(
16474 matches!(
16475 err,
16476 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
16477 if affinity == "data locality"
16478 ),
16479 "got {err:?}"
16480 );
16481 }
16482
16483 #[test]
16484 fn rejects_placement_affinity_too_long() {
16485 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
16486 // pin. The diagnostic names both the cap (63) and the actual
16487 // length so the author can shorten in one edit. Mirrors
16488 // `rejects_placement_cluster_too_long`.
16489 let mut s = three_member_spec();
16490 let too_long = "a".repeat(64);
16491 s.placement.affinity = Some(too_long.clone());
16492 let err = s.validate().unwrap_err();
16493 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
16494 panic!("expected PlacementAffinityInvalid");
16495 };
16496 assert_eq!(affinity, too_long);
16497 assert!(
16498 reason.contains("63") && reason.contains("64"),
16499 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
16500 );
16501 }
16502
16503 #[test]
16504 fn placement_affinity_max_length_validates() {
16505 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
16506 // future tightening (e.g. dropping to 62) surfaces here as a
16507 // regression, mirroring `placement_cluster_max_length_validates`.
16508 let mut s = three_member_spec();
16509 s.placement.affinity = Some("a".repeat(63));
16510 s.validate().unwrap();
16511 }
16512
16513 #[test]
16514 fn accepts_canonical_placement_affinity_forms() {
16515 // The DNS-1123 label shapes a caixa author is realistically
16516 // going to write for placement hints: the M3 canonical examples
16517 // (`data-locality`, `low-latency`, `anti-affinity`), the
16518 // single-token form (`affinity`), the single-character boundary
16519 // (`a`), the digit-start (DNS-1123 allows this, unlike
16520 // DNS-1035), and a regional-suffixed form. Pin every leg so a
16521 // future tightening that bans (e.g.) digit-start identifiers
16522 // surfaces here.
16523 for form in [
16524 "data-locality",
16525 "low-latency",
16526 "anti-affinity",
16527 "affinity",
16528 "a",
16529 "3-tier",
16530 "locality-east",
16531 ] {
16532 let mut s = three_member_spec();
16533 s.placement.affinity = Some(form.into());
16534 s.validate().unwrap_or_else(|e| {
16535 panic!("canonical affinity form {form:?} must validate, got {e:?}")
16536 });
16537 }
16538 }
16539
16540 #[test]
16541 fn placement_affinity_empty_takes_precedence_over_invalid() {
16542 // Order pin: the existing `PlacementAffinityEmpty` diagnostic
16543 // (which doesn't try to parse) fires before the new
16544 // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
16545 // `:affinity` keeps its narrower error message — the new gate
16546 // would also reject `""`, but the empty-string arm is the more
16547 // self-locating diagnostic. Mirrors the
16548 // `placement_cluster_empty_takes_precedence_over_invalid` pin.
16549 let mut s = three_member_spec();
16550 s.placement.affinity = Some(String::new());
16551 let err = s.validate().unwrap_err();
16552 assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
16553 }
16554
16555 #[test]
16556 fn placement_affinity_invalid_diagnostic_carries_offending_value() {
16557 // The diagnostic shape pin: every rejection carries the offending
16558 // `affinity:` verbatim plus a parser-shaped `reason:` so the
16559 // author can grep their caixa.lisp for `:affinity "<hint>"` and
16560 // fix it in one edit. Mirrors the
16561 // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
16562 // pin on the sibling slot.
16563 let mut s = three_member_spec();
16564 s.placement.affinity = Some("Data_Locality".into());
16565 let err = s.validate().unwrap_err();
16566 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
16567 panic!("expected PlacementAffinityInvalid");
16568 };
16569 assert_eq!(affinity, "Data_Locality");
16570 assert!(
16571 !reason.is_empty(),
16572 "diagnostic reason must not be empty (got: {reason:?})"
16573 );
16574 }
16575
16576 #[test]
16577 fn singlenode_with_takeover_candidates_validates() {
16578 // OTP distributed-application convention (MESH-COMPOSITION
16579 // §II.1): SingleNode runs on one cluster at a time but the
16580 // :clusters list enumerates the takeover candidates. Multiple
16581 // entries are not a contradiction — they are the failover pool.
16582 let mut s = three_member_spec();
16583 s.placement.estrategia = PlacementStrategy::SingleNode;
16584 s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
16585 s.validate().unwrap();
16586 }
16587
16588 // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
16589
16590 #[test]
16591 fn mesh_policy_default_is_empty() {
16592 // The Default impl carries None on every axis — the typed
16593 // analog of an unset `:politicas (())` slot. Renderers that
16594 // overlay the policy onto a cluster artifact key off this
16595 // predicate to skip the slot entirely; pinning so a future
16596 // axis added to MeshPolicy can't silently break the contract
16597 // (a new field whose Default is non-None would flip is_empty
16598 // to false on every existing caixa, surfacing here).
16599 assert!(MeshPolicy::default().is_empty());
16600 }
16601
16602 #[test]
16603 fn mesh_policy_with_only_timeout_is_not_empty() {
16604 let p = MeshPolicy {
16605 timeout: Some(Duration::from_secs(30)),
16606 ..Default::default()
16607 };
16608 assert!(!p.is_empty());
16609 }
16610
16611 #[test]
16612 fn mesh_policy_with_only_retries_is_not_empty() {
16613 let p = MeshPolicy {
16614 retries: Some(3),
16615 ..Default::default()
16616 };
16617 assert!(!p.is_empty());
16618 }
16619
16620 #[test]
16621 fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
16622 let p = MeshPolicy {
16623 circuit_breaker: Some(CircuitBreaker {
16624 max_failures: 5,
16625 window: Duration::from_secs(60),
16626 }),
16627 ..Default::default()
16628 };
16629 assert!(!p.is_empty());
16630 }
16631
16632 #[test]
16633 fn mesh_policy_with_only_mtls_required_is_not_empty() {
16634 // Even `mtls_required: Some(false)` (an explicit opt-out) is
16635 // not empty — the author *named* the axis, the renderer needs
16636 // to honor that vs. fall back to the cluster default.
16637 let p = MeshPolicy {
16638 mtls_required: Some(false),
16639 ..Default::default()
16640 };
16641 assert!(!p.is_empty());
16642 }
16643
16644 #[test]
16645 fn mesh_policy_with_only_rate_limit_is_not_empty() {
16646 let p = MeshPolicy {
16647 rate_limit: Some(RateLimit {
16648 rate: 100,
16649 window: Duration::from_secs(1),
16650 }),
16651 ..Default::default()
16652 };
16653 assert!(!p.is_empty());
16654 }
16655
16656 #[test]
16657 fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
16658 // The three-member happy-path fixture sets timeout + retries +
16659 // mtls_required — every populated axis must read non-empty.
16660 // Pin the round-trip so the M3.x per-:politicas emitter (the
16661 // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
16662 // on is_empty() to decide whether to emit at all without
16663 // re-deriving the contract from inline field probes.
16664 assert!(!three_member_spec().politicas.is_empty());
16665 }
16666
16667 // ── shared duration codec: cross-slot integer-magnitude gate ──
16668 //
16669 // The integer-magnitude discipline applied to
16670 // `supervisor::duration_codec::parse` lifts onto every typed slot
16671 // that routes through the shared codec — `MeshPolicy::timeout`
16672 // (`:politicas :timeout`) and `CircuitBreaker::window`
16673 // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
16674 // These cross-slot tests pin that the gate fires at the serde
16675 // layer for both typed slots, not just for the supervisor side.
16676
16677 #[test]
16678 fn policy_timeout_serde_rejects_fractional_seconds() {
16679 // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
16680 // so the shared codec's integer-magnitude gate applies on
16681 // deserialize. `"1.5s"` previously parsed to 1500ms and round-
16682 // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
16683 // deserialize with the canonical-form diagnostic naming the
16684 // offending `"1.5"` and the remediation `"1500ms"`.
16685 let payload = r#"{"timeout":"1.5s"}"#;
16686 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16687 let msg = err.to_string();
16688 assert!(
16689 msg.contains("not a non-negative integer"),
16690 "expected integer-magnitude diagnostic in {msg:?}"
16691 );
16692 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
16693 assert!(
16694 msg.contains("\"1500ms\""),
16695 "missing canonical-form remediation in {msg:?}"
16696 );
16697 }
16698
16699 #[test]
16700 fn policy_timeout_serde_rejects_leading_plus_sign() {
16701 // Pin the leading-`+` arm cross-slot — the prior f64 parser
16702 // accepted `"+30s"` silently and round-tripped to `"30s"`.
16703 let payload = r#"{"timeout":"+30s"}"#;
16704 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16705 let msg = err.to_string();
16706 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
16707 }
16708
16709 #[test]
16710 fn circuit_breaker_window_serde_rejects_fractional_minutes() {
16711 // `CircuitBreaker::window` uses `with =
16712 // "supervisor::duration_codec_required"` (the required-Duration
16713 // variant that delegates to the same shared parser). `"0.5m"`
16714 // parsed to 30s and round-tripped to `"30s"` on next emit —
16715 // DRIFT closed.
16716 let payload = format!(
16717 r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
16718 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
16719 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
16720 );
16721 let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
16722 let msg = err.to_string();
16723 assert!(
16724 msg.contains("not a non-negative integer"),
16725 "expected integer-magnitude diagnostic in {msg:?}"
16726 );
16727 assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
16728 assert!(
16729 msg.contains("\"30s\""),
16730 "missing canonical-form remediation in {msg:?}"
16731 );
16732 }
16733
16734 #[test]
16735 fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
16736 // Pin the happy-path on the cross-slot side: every canonical
16737 // author shape `render` ever emits parses cleanly through the
16738 // shared codec on the `CircuitBreaker` slot. The
16739 // codec's accepted set (post-gate) is exactly its emitted set
16740 // for the integer-magnitude class.
16741 for window_lit in ["30s", "500ms", "2m", "1h"] {
16742 let payload = format!(
16743 r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
16744 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
16745 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
16746 );
16747 let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
16748 panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
16749 });
16750 assert_eq!(cb.max_failures, 5);
16751 }
16752 }
16753
16754 // ── rate_limit_codec: integer-magnitude gate ──
16755 //
16756 // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
16757 // / 737a676 / d53c922 trajectory landed on every typed-duration /
16758 // typed-byte-size codec in caixa-core lifts onto the fifth typed
16759 // codec — `rate_limit_codec` — through the digit-only magnitude
16760 // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
16761 // These tests pin the gate at the serde layer for `:politicas
16762 // :rate-limit` (the only typed slot the codec backs), and at the
16763 // codec-internal `parse` layer for the canonical positive cases.
16764
16765 #[test]
16766 fn rate_limit_serde_rejects_fractional_rate() {
16767 // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
16768 // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
16769 // wording, which didn't name the canonical-form remediation or
16770 // the round-trip drift the next emit would produce. Now refused
16771 // at deserialize with the canonical-form diagnostic naming the
16772 // offending `"1.5"` magnitude and the round-trip drift wording.
16773 let payload = r#"{"rateLimit":"1.5/s"}"#;
16774 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16775 let msg = err.to_string();
16776 assert!(
16777 msg.contains("not a non-negative integer"),
16778 "expected integer-magnitude diagnostic in {msg:?}"
16779 );
16780 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
16781 assert!(
16782 msg.contains("THEORY.md"),
16783 "missing render-determinism contract citation in {msg:?}"
16784 );
16785 }
16786
16787 #[test]
16788 fn rate_limit_serde_rejects_leading_plus_sign() {
16789 // `u32::from_str("+100")` returns `Ok(100)` (Rust's
16790 // permissive-`+` parse), so `"+100/s"` silently parsed to
16791 // `RateLimit { 100, 1s }` and round-tripped through `render` to
16792 // `"100/s"` — a *different* canonical string on the next emit,
16793 // breaking the THEORY.md Part V render-determinism contract
16794 // exactly the way the peer duration codecs' `"+30s"` case did.
16795 // This is the load-bearing class the digit-only gate closes
16796 // beyond what `u32::from_str`'s strictness covers on its own.
16797 let payload = r#"{"rateLimit":"+100/s"}"#;
16798 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16799 let msg = err.to_string();
16800 assert!(
16801 msg.contains("not a non-negative integer"),
16802 "expected integer-magnitude diagnostic in {msg:?}"
16803 );
16804 assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
16805 }
16806
16807 #[test]
16808 fn rate_limit_serde_rejects_leading_minus_sign() {
16809 // The signed-negative arm: `"-1/s"` lands on the
16810 // non-canonical-but-numeric branch via the `i64` fallback (the
16811 // `f64` parse also succeeds), surfacing the canonical-form
16812 // diagnostic. Replaces the prior value-laundered "not a u32"
16813 // wording with the unified diagnostic across signs.
16814 let payload = r#"{"rateLimit":"-1/s"}"#;
16815 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16816 let msg = err.to_string();
16817 assert!(
16818 msg.contains("not a non-negative integer"),
16819 "expected integer-magnitude diagnostic in {msg:?}"
16820 );
16821 assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
16822 }
16823
16824 #[test]
16825 fn rate_limit_serde_rejects_decimal_shaped_integer() {
16826 // `"100.0/s"` is integer-valued numerically but not in the
16827 // codec's accepted set — `render` emits `"100/s"`, so the
16828 // round-trip would drift. Lifted to the canonical-form
16829 // diagnostic peer with the duration codec's `"1.0s"` case
16830 // (1c55a2a).
16831 let payload = r#"{"rateLimit":"100.0/s"}"#;
16832 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16833 let msg = err.to_string();
16834 assert!(
16835 msg.contains("not a non-negative integer"),
16836 "expected integer-magnitude diagnostic in {msg:?}"
16837 );
16838 assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
16839 }
16840
16841 #[test]
16842 fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
16843 // Non-numeric, non-digit-only input lands on the existing
16844 // narrower `"not a u32"` arm (preserved for diagnostic-shape
16845 // stability on the parser-shape footgun case). Pin this so a
16846 // future relaxation of the numeric-fallback predicate doesn't
16847 // silently collapse garbage onto the canonical-form arm — same
16848 // partition the peer duration codecs draw between
16849 // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
16850 let payload = r#"{"rateLimit":"abc/s"}"#;
16851 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16852 let msg = err.to_string();
16853 assert!(
16854 msg.contains("not a u32"),
16855 "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
16856 );
16857 assert!(
16858 !msg.contains("not a non-negative integer"),
16859 "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
16860 );
16861 }
16862
16863 #[test]
16864 fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
16865 // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
16866 // u32's range. The digit-only gate passes; `u32::from_str`
16867 // fails on overflow. Surface that with the overflow-shaped
16868 // diagnostic naming the offending magnitude verbatim, peer
16869 // with `supervisor::duration_codec`'s overflow arm. Pinning
16870 // the wording so a future refactor doesn't silently collapse
16871 // overflow onto the canonical-form arm.
16872 let payload = r#"{"rateLimit":"4294967296/s"}"#;
16873 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16874 let msg = err.to_string();
16875 assert!(
16876 msg.contains("overflows u32"),
16877 "expected overflow diagnostic in {msg:?}"
16878 );
16879 assert!(
16880 msg.contains("\"4294967296\""),
16881 "missing offending magnitude in {msg:?}"
16882 );
16883 }
16884
16885 #[test]
16886 fn rate_limit_serde_rejects_leading_zero_magnitude() {
16887 // `"0100/s"` is digit-only, so the existing
16888 // non-digit-only / sign / fractional arm doesn't catch it —
16889 // `u32::from_str("0100")` returns `Ok(100)`, so before this
16890 // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
16891 // round-tripped through `render` to `"100/s"` — a *different*
16892 // canonical string on the next emit, breaking the THEORY.md
16893 // Part V render-determinism contract exactly the way the
16894 // peer `"+100/s"` case did before the leading-`+` arm landed.
16895 // This is the load-bearing class the leading-zero gate closes
16896 // beyond what the existing digit-only / sign / fractional
16897 // gates cover, and the peer arm to the leading-`+` test
16898 // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
16899 // canonical-form-drift axis.
16900 let payload = r#"{"rateLimit":"0100/s"}"#;
16901 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16902 let msg = err.to_string();
16903 assert!(
16904 msg.contains("non-canonical leading zero"),
16905 "expected leading-zero diagnostic in {msg:?}"
16906 );
16907 assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
16908 assert!(
16909 msg.contains("THEORY.md"),
16910 "missing render-determinism contract citation in {msg:?}"
16911 );
16912 }
16913
16914 #[test]
16915 fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
16916 // `"00/s"` is the degenerate leading-zero case — every byte
16917 // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
16918 // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
16919 // a *different* canonical string, same render-determinism
16920 // violation. The single-byte `"0/s"` itself is in the
16921 // accepted set (round-trips losslessly through `render`,
16922 // refused downstream by `PolicyRateLimitZero`); the
16923 // multi-byte `"00/s"` is not. Pins the boundary between the
16924 // accepted single-`0` and the rejected leading-zero class.
16925 let payload = r#"{"rateLimit":"00/s"}"#;
16926 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16927 let msg = err.to_string();
16928 assert!(
16929 msg.contains("non-canonical leading zero"),
16930 "expected leading-zero diagnostic in {msg:?}"
16931 );
16932 assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
16933 }
16934
16935 #[test]
16936 fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
16937 // Cross-window pin — the gate is window-agnostic; the
16938 // leading-zero class is a property of the magnitude, not the
16939 // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
16940 // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
16941 // single-window coverage extended across the three canonical
16942 // windows the codec accepts.
16943 let payload = r#"{"rateLimit":"007/h"}"#;
16944 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16945 let msg = err.to_string();
16946 assert!(
16947 msg.contains("non-canonical leading zero"),
16948 "expected leading-zero diagnostic in {msg:?}"
16949 );
16950 assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
16951 }
16952
16953 #[test]
16954 fn rate_limit_serde_rejects_leading_whitespace() {
16955 // `" 100/s"` — the canonical paste-from-aligned-doc /
16956 // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
16957 // the top-level `s.trim()` silently ate the leading space and
16958 // parsed the value to `RateLimit { 100, 1s }`, which then
16959 // round-tripped through `render` to `"100/s"` (a *different*
16960 // canonical string on the next emit) — the exact
16961 // canonical-form-drift class the leading-`+` / leading-zero
16962 // arms already close, extended to the whitespace byte class.
16963 let payload = r#"{"rateLimit":" 100/s"}"#;
16964 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16965 let msg = err.to_string();
16966 assert!(
16967 msg.contains("contains whitespace byte"),
16968 "expected whitespace diagnostic in {msg:?}"
16969 );
16970 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
16971 assert!(
16972 msg.contains("THEORY.md"),
16973 "missing render-determinism contract citation in {msg:?}"
16974 );
16975 }
16976
16977 #[test]
16978 fn rate_limit_serde_rejects_trailing_whitespace() {
16979 // `"100/s "` — the canonical shell-history / trailing-space
16980 // paste footgun. Before this gate the top-level `s.trim()`
16981 // silently ate the trailing space and parsed to
16982 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
16983 // next emit — same canonical-form drift as the leading-space
16984 // sibling, closed on the same whitespace-byte arm.
16985 let payload = r#"{"rateLimit":"100/s "}"#;
16986 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16987 let msg = err.to_string();
16988 assert!(
16989 msg.contains("contains whitespace byte"),
16990 "expected whitespace diagnostic in {msg:?}"
16991 );
16992 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
16993 }
16994
16995 #[test]
16996 fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
16997 // `"100 / s"` — the canonical typographically-spaced author
16998 // shape (the same idiom every prose reference to a rate limit
16999 // renders as, mistakenly retained when the value is pasted
17000 // into a codec-shaped slot). Before this gate the per-part
17001 // `rate_str.trim()` / `unit.trim()` calls silently ate both
17002 // spaces on either side of `/` and parsed to
17003 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
17004 // codec's *internal* whitespace-tolerance vector, orthogonal
17005 // to the leading / trailing surface but the same canonical-
17006 // form-drift class. Pins the arm as strictly stronger than the
17007 // pre-existing top-level `s.trim()` behavior: it fires on
17008 // whitespace anywhere in the value, not just at the string
17009 // boundary.
17010 let payload = r#"{"rateLimit":"100 / s"}"#;
17011 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17012 let msg = err.to_string();
17013 assert!(
17014 msg.contains("contains whitespace byte"),
17015 "expected whitespace diagnostic in {msg:?}"
17016 );
17017 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
17018 }
17019
17020 #[test]
17021 fn rate_limit_serde_rejects_tab_byte() {
17022 // `"\t100/s"` — the canonical paste-from-indented-doc /
17023 // paste-from-YAML-block-scalar footgun where a tab byte leads
17024 // the magnitude. Pins that the gate covers tab (`0x09`) as
17025 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
17026 // members and both would be silently swallowed by `s.trim()`
17027 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
17028 // space alone to the full ASCII-whitespace set (space `0x20`,
17029 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
17030 // the tab arm as a representative of the non-space members.
17031 let payload = r#"{"rateLimit":"\t100/s"}"#;
17032 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17033 let msg = err.to_string();
17034 assert!(
17035 msg.contains("contains whitespace byte"),
17036 "expected whitespace diagnostic in {msg:?}"
17037 );
17038 assert!(
17039 msg.contains("0x09"),
17040 "missing offending tab byte in {msg:?}"
17041 );
17042 }
17043
17044 // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
17045 //
17046 // Successor to the ASCII-whitespace arm (1ad7755) on
17047 // `rate_limit_codec` — closes the strictly-complementary class the
17048 // byte-scan cannot see, through the lifted
17049 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
17050
17051 #[test]
17052 fn rate_limit_serde_rejects_leading_nbsp() {
17053 // NBSP prefix — paste-from-typography footgun. Byte-scan
17054 // misses, `str::trim` silently strips it, value drifts to
17055 // `"100/s"` on next serialize.
17056 let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
17057 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17058 let msg = err.to_string();
17059 assert!(
17060 msg.contains("non-ASCII Unicode whitespace character"),
17061 "expected non-ASCII whitespace diagnostic in {msg:?}"
17062 );
17063 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
17064 }
17065
17066 #[test]
17067 fn rate_limit_serde_rejects_internal_em_space() {
17068 // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
17069 // paste-from-typography footgun on the `<integer>/<unit>`
17070 // shape.
17071 let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
17072 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
17073 let msg = err.to_string();
17074 assert!(
17075 msg.contains("non-ASCII Unicode whitespace character"),
17076 "expected non-ASCII whitespace diagnostic in {msg:?}"
17077 );
17078 assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
17079 }
17080
17081 #[test]
17082 fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
17083 // Positive-control pin: every ASCII-only canonical form the
17084 // renderer emits stays accepted through the new arm.
17085 for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
17086 let payload = format!(r#"{{"rateLimit":{lit}}}"#);
17087 let p: MeshPolicy = serde_json::from_str(&payload)
17088 .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
17089 assert!(p.rate_limit.is_some());
17090 }
17091 }
17092
17093 #[test]
17094 fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
17095 // The boundary case — `"0/s"` is the canonical form
17096 // `render(RateLimit { 0, 1s })` emits, so the codec accepts
17097 // it at the parse layer; the downstream
17098 // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
17099 // `rate == 0` at the typed-validate layer above. Pins the
17100 // partition: the leading-zero gate at the codec layer does
17101 // not poach the rate-zero semantic-validation arm at the
17102 // typed-validate layer above (a future stricter codec must
17103 // not reject `"0/s"` here, or it'd collapse the diagnostic
17104 // partitioning that lets `PolicyRateLimitZero` name the
17105 // offending typed slot).
17106 let payload = r#"{"rateLimit":"0/s"}"#;
17107 let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
17108 panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
17109 });
17110 let rl = policy.rate_limit.expect("rate_limit must be Some");
17111 assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
17112 assert_eq!(
17113 rl.window,
17114 Duration::from_secs(1),
17115 "single-`0` magnitude with `s` unit must parse to window=1s"
17116 );
17117 }
17118
17119 #[test]
17120 fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
17121 // The complementary boundary pin — every magnitude
17122 // `render` emits starts with `[1-9]` (or is the single byte
17123 // `"0"`), so the canonical-form predicate is `(len == 1) ||
17124 // (first byte != '0')`. Pinning the `len > 1 && first byte ==
17125 // '1'` case explicitly so a future tightening of the gate
17126 // (e.g. an over-eager "no leading digit < 5" rule, or a
17127 // mistakenly anchored start-of-magnitude byte check) lands
17128 // here before the canonical-forms-iterating test would catch
17129 // it.
17130 let payload = r#"{"rateLimit":"100/s"}"#;
17131 let policy: MeshPolicy = serde_json::from_str(payload)
17132 .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
17133 let rl = policy.rate_limit.expect("rate_limit must be Some");
17134 assert_eq!(
17135 rl.rate, 100,
17136 "canonical-100 magnitude must parse to rate=100"
17137 );
17138 }
17139
17140 #[test]
17141 fn rate_limit_serde_accepts_integer_canonical_forms() {
17142 // Pin the happy-path: every canonical author shape `render`
17143 // ever emits parses cleanly through the codec post-gate. The
17144 // codec's accepted set (post-gate) is exactly its emitted set
17145 // for the integer-magnitude class — same property
17146 // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
17147 // gates guarantee on the peer codecs. Iterating across rate
17148 // magnitudes (including `"0"`, which the codec accepts even
17149 // though `validate_politicas` rejects `rate == 0` at the typed
17150 // layer above) closes the codec contract at the parse layer
17151 // independently of the validate layer.
17152 for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
17153 for unit_lit in ["s", "m", "h"] {
17154 let lit = format!("{rate_lit}/{unit_lit}");
17155 let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
17156 let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
17157 panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
17158 });
17159 let rl = policy.rate_limit.expect("rate_limit must be Some");
17160 assert_eq!(
17161 rl.rate,
17162 rate_lit.parse::<u32>().unwrap(),
17163 "rate mismatch for {lit:?}"
17164 );
17165 }
17166 }
17167 }
17168
17169 #[test]
17170 fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
17171 // The structural property the gate enforces: serialize ∘
17172 // deserialize is the identity on every canonical author shape.
17173 // Peer of `parse_byte_size`'s and `parse_duration`'s
17174 // `_round_trips_through_render_for_every_canonical_form` tests
17175 // on the rate-limit axis. Before the gate, `"+100/s"` violated
17176 // this (`parse` → `RateLimit { 100, 1s }` → `render` →
17177 // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
17178 for rate in [1u32, 100, 5000, 1_000_000] {
17179 for (window, unit) in [
17180 (Duration::from_secs(1), "s"),
17181 (Duration::from_secs(60), "m"),
17182 (Duration::from_secs(3600), "h"),
17183 ] {
17184 let policy = MeshPolicy {
17185 rate_limit: Some(RateLimit { rate, window }),
17186 ..Default::default()
17187 };
17188 let json = serde_json::to_string(&policy).unwrap();
17189 let expected = format!("\"{rate}/{unit}\"");
17190 assert!(
17191 json.contains(&expected),
17192 "expected {expected:?} in {json:?}"
17193 );
17194 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17195 assert_eq!(
17196 back.rate_limit, policy.rate_limit,
17197 "round-trip for {json:?}"
17198 );
17199 }
17200 }
17201 }
17202
17203 // ── self-membership cross-slot gate ──────────────────────────────
17204
17205 #[test]
17206 fn validate_no_self_membership_rejects_self_named_membro() {
17207 // An Aplicacao whose `:membros` lists its own `:nome` is a
17208 // one-node lacre-closure recursion — rejected, naming the parent.
17209 let membros = vec![
17210 membro("catalog", "^0.1"),
17211 membro("checkout", "^0.1"),
17212 membro("cart", "^0.1"),
17213 ];
17214 let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
17215 assert!(
17216 matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
17217 "got {err:?}"
17218 );
17219 }
17220
17221 #[test]
17222 fn validate_no_self_membership_accepts_distinct_membros() {
17223 // Positive control: distinct member names (including a member
17224 // that is itself an Aplicacao — recursive composition is valid,
17225 // MESH-COMPOSITION §V) pass the gate.
17226 let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
17227 validate_no_self_membership(&membros, "checkout").unwrap();
17228 }
17229
17230 #[test]
17231 fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
17232 // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
17233 // `NoMembros` arm (the more-fundamental "graph must have nodes"
17234 // gate), not by this cross-slot self-edge gate. Keeping the
17235 // self-membership predicate vacuously-ok on the empty input
17236 // matches its supervisor-axis peer
17237 // (`validate_no_self_supervision_empty_children_is_ok`) and
17238 // makes the gate composable from any future call site (an M4
17239 // CR materializer's per-membros validator) without re-checking
17240 // emptiness.
17241 validate_no_self_membership(&[], "checkout").unwrap();
17242 }
17243
17244 #[test]
17245 fn validate_no_self_membership_diagnostic_names_offending_caixa() {
17246 // Pinning the Display: the self-membership diagnostic must name
17247 // the offending caixa verbatim + the "lists itself" framing the
17248 // author can grep for, so the cluster-far failure surfaces at
17249 // build time with one-line remediation. Same diagnostic shape
17250 // as the supervisor-axis `ChildSupervisesSelf` peer.
17251 let membros = vec![membro("orquestra", "^0.1")];
17252 let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
17253 let msg = err.to_string();
17254 assert!(
17255 msg.contains("orquestra"),
17256 "diagnostic must name the offending caixa nome (got: {msg:?})"
17257 );
17258 assert!(
17259 msg.contains("lists itself"),
17260 "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
17261 );
17262 }
17263
17264 #[test]
17265 fn default_servico_port_constant_pins_canonical_8080_literal() {
17266 // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
17267 // at the verbatim `8080` literal both consumers (the
17268 // `Entrada::port` serde default via [`default_port`] and the
17269 // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
17270 // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
17271 // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
17272 // discipline (a085b26) on the per-renderer canonical-K8s-axis
17273 // string-constant axis: a future refactor that drifts the
17274 // constant out from under either consumer surfaces here ahead
17275 // of every per-renderer's first emission. The literal value
17276 // matches the well-known HTTP-alt port the `pleme-computeunit`
17277 // library chart already emits as its `trigger.service.port`
17278 // default — by construction the same value the substrate
17279 // assumes about every Servico's in-cluster L4 listener.
17280 assert_eq!(
17281 DEFAULT_SERVICO_PORT, 8080,
17282 "canonical Servico port literal must remain `8080` verbatim — \
17283 this is the value both the `Entrada::port` serde default and the \
17284 caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
17285 );
17286 }
17287
17288 #[test]
17289 fn default_port_helper_returns_canonical_servico_port_constant() {
17290 // The bridge-arm — pins that the [`default_port`] helper
17291 // [`Entrada::port`]'s `#[serde(default = "default_port")]`
17292 // attribute hooks routes through the lifted
17293 // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
17294 // literal. A future refactor that re-introduces the `8080`
17295 // literal at the helper's return site (silently re-opening
17296 // the drift footgun this lift closed) surfaces here ahead of
17297 // every author-side `(:entrada (:host … :para …))` slot
17298 // without an explicit `:port`. Peer with the
17299 // `default_namespace_re_export_points_at_caixa_core_canonical`
17300 // pin on the caixa-mesh-side re-export axis.
17301 assert_eq!(
17302 default_port(),
17303 DEFAULT_SERVICO_PORT,
17304 "the serde-default helper must route through the lifted constant"
17305 );
17306 }
17307
17308 #[test]
17309 fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
17310 // The end-to-end pin — an author-surface `(:entrada (:host …
17311 // :para …))` without an explicit `:port` slot deserializes to
17312 // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
17313 // verbatim. Routes the canonical lifted constant through both
17314 // the serde-default machinery (the `#[serde(default =
17315 // "default_port")]` attribute) and the typed-value-shape
17316 // contract (the resulting [`Entrada::port`] value). A future
17317 // refactor that drifts either axis — replacing the serde
17318 // hook's helper, changing the typed slot's wire shape — would
17319 // surface here before any per-renderer's CNP / Gateway /
17320 // HTTPRoute emission consumed the drifted default.
17321 let entrada: Entrada =
17322 serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
17323 assert_eq!(
17324 entrada.port, DEFAULT_SERVICO_PORT,
17325 "the serde default must materialize as the lifted canonical Servico port"
17326 );
17327 }
17328
17329 #[test]
17330 fn servico_port_min_pins_canonical_accept_set_floor() {
17331 // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
17332 // verbatim `1` literal every typed `:entrada :port` acceptance
17333 // gate keys off. Peer with the
17334 // [`default_servico_port_constant_pins_canonical_8080_literal`]
17335 // discipline on the canonical-Servico-port-constant axis: a
17336 // future refactor that drifts the accept-set floor out from
17337 // under the sole consumer at [`AplicacaoSpec::validate`]'s
17338 // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
17339 // every per-`:entrada` `EntradaPortZero` diagnostic. The
17340 // literal value matches the IANA-registered TCP/UDP port
17341 // space floor (`1..=65535` — port `0` is the "any ephemeral"
17342 // sentinel, not a well-defined destination the substrate's
17343 // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
17344 // axis can honor).
17345 assert_eq!(
17346 SERVICO_PORT_MIN, 1,
17347 "canonical Servico port accept-set floor must remain `1` verbatim — \
17348 this is the value the `AplicacaoSpec::validate` gate at \
17349 `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
17350 );
17351 }
17352
17353 #[test]
17354 fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
17355 // The cross-const invariant pin — the substrate's canonical
17356 // default port must satisfy its own accept-set floor by
17357 // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
17358 // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
17359 // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
17360 // override the operator pins through a future
17361 // `:placement :default-port` slot that lands out-of-range, a
17362 // per-edition Servico-port migration that lifted the floor
17363 // above the previous default without coordinating the pair —
17364 // would silently invalidate the serde-default emission at
17365 // every author-side `(:entrada (:host … :para …))` slot
17366 // without an explicit `:port`: the default port would fall
17367 // below the accept-set floor, the `AplicacaoSpec::validate`
17368 // gate would reject every default-carrying Aplicacao as
17369 // `EntradaPortZero`, and the substrate's typed
17370 // `(defcaixa … :kind Aplicacao)` surface would fail validate
17371 // on every Aplicacao whose author omitted `:entrada :port`
17372 // for the substrate's chosen default — a class of authoring-
17373 // surface footguns the compile-time pin structurally closes.
17374 // Peer with the
17375 // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
17376 // (27f9b34) cross-const invariant pin discipline on the peer
17377 // canonical-Helm-per-values-block child-chart-enablement-toggle
17378 // axis pair.
17379 assert!(
17380 SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
17381 "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
17382 satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
17383 every default-carrying `(:entrada (:host … :para …))` slot without an \
17384 explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
17385 hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
17386 );
17387 }
17388
17389 #[test]
17390 fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
17391 // The gate-site pin — asserts the `AplicacaoSpec::validate`
17392 // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
17393 // `EntradaPortZero` diagnostic on the below-floor input
17394 // `port: 0` (the only below-floor value the `u16` field can
17395 // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
17396 // is the singleton `{0}`). A future refactor that drifts the
17397 // gate off the lifted const (silently re-introducing an
17398 // inline `if e.port == 0` byte-check) surfaces here — the
17399 // pin cannot distinguish `< 1` from `== 0` on the current
17400 // floor, but it *does* pin that the diagnostic fires on `0`
17401 // through whichever gate is wired, so any future accept-set
17402 // floor migration (a hypothetical unprivileged-only
17403 // migration lifting `SERVICO_PORT_MIN` to `1024`) must
17404 // update this test alongside the const declaration —
17405 // structurally guaranteeing the gate + accept-set + pin
17406 // trio move together. Peer with the
17407 // [`rejects_zero_entrada_port`] behavioral pin on the same
17408 // per-`:entrada :port` axis — that pin asserts the pre-lift
17409 // behavioral contract (`port: 0` → `EntradaPortZero`); this
17410 // pin adds the structural link to the lifted floor const.
17411 assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
17412 let mut s = three_member_spec();
17413 s.entrada.as_mut().unwrap().port = 0;
17414 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
17415 }
17416
17417 // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
17418
17419 #[test]
17420 fn membro_serde_keys_match_lifted_membro_key_consts() {
17421 // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
17422 // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
17423 // name the exact camelCase JSON keys the
17424 // `#[serde(rename_all = "camelCase")]` attribute on
17425 // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
17426 // that each canonical byte-sequence appears verbatim in the
17427 // JSON — a future accidental `rename_all = "snake_case"` /
17428 // `"kebab-case"` / verbatim-field-name flip at the derive
17429 // attribute (any of which would silently break every downstream
17430 // JSON consumer that reaches for one of the two consts via
17431 // `Value::get(...)`) surfaces here as a build-time test failure
17432 // at `aplicacao.rs`, not as an apply-time
17433 // `.get(<stale-canonical-const>)` returning `None` far from the
17434 // derive-attr drift's commit. Peer with the sibling
17435 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
17436 // (40cc4e5) pin on the M2 supervision-tree top-level axis —
17437 // same discipline the SupervisorSpec top-level lift established,
17438 // extended here to the M3 [`Membro`] per-`:membros` axis.
17439 let m = Membro {
17440 caixa: "catalog".into(),
17441 versao: "^0.1".into(),
17442 };
17443 let json = serde_json::to_string(&m).unwrap();
17444 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
17445 let quoted = format!("\"{key}\"");
17446 assert!(
17447 json.contains("ed),
17448 "serialized Membro must carry the lifted MEMBRO_KEY_* \
17449 byte-sequence {quoted} verbatim in the JSON emission \
17450 (got: {json})",
17451 );
17452 }
17453 }
17454
17455 #[test]
17456 fn membro_key_consts_are_pairwise_distinct() {
17457 // Cross-axis drift-detection pin: a future collapse of the two
17458 // canonical [`Membro`] per-entry byte-strings onto the same
17459 // value (e.g. an accidental copy-paste flip of
17460 // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
17461 // silently reroute every downstream probe on one axis onto the
17462 // sibling axis's overlay entry and pass every propagation-probe
17463 // test that expected only the stale axis's value. Peer of the
17464 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
17465 // (40cc4e5).
17466 let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
17467 for (i, a) in all.iter().enumerate() {
17468 for b in all.iter().skip(i + 1) {
17469 assert_ne!(
17470 a, b,
17471 "MEMBRO_KEY_* consts must be pairwise-distinct \
17472 canonical byte-sequences — got `{a}` == `{b}`",
17473 );
17474 }
17475 }
17476 }
17477
17478 // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
17479 // URL-path fallback resolver every HTTPRoute-aware renderer
17480 // reaching for a per-rule path-list resolution routes through.
17481 // The four pin tests below fix the four-way accept-set the
17482 // resolver must always honor: (:paths-non-empty-verbatim,
17483 // :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
17484 // :paths-preserves-order-across-multiple-entries) — drift on any
17485 // arm surfaces at caixa-core build time rather than at cluster-
17486 // apply time. Peer discipline with `MeshPolicy::is_empty` on the
17487 // sibling `:politicas` typed-primitive dispatch axis.
17488
17489 fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
17490 Entrada {
17491 host: "example.com".into(),
17492 para: "cart".into(),
17493 paths: paths.into_iter().map(String::from).collect(),
17494 port: DEFAULT_SERVICO_PORT,
17495 }
17496 }
17497
17498 #[test]
17499 fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
17500 // The typed `:entrada :paths` slot carries an author-declared
17501 // list — the resolver returns each entry verbatim, no
17502 // catch-all substitution. The canonical "author declared
17503 // paths, honor them verbatim" arm of the path-list dispatch.
17504 let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
17505 assert_eq!(
17506 e.resolved_paths(),
17507 vec!["/api/cart", "/api/products"],
17508 "resolved_paths must return each `:entrada :paths` entry \
17509 verbatim when the typed slot is non-empty (got {:?})",
17510 e.resolved_paths(),
17511 );
17512 }
17513
17514 #[test]
17515 fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
17516 // Empty `:entrada :paths` slot — the resolver substitutes the
17517 // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
17518 // catch-all fallback verbatim. Pins the empty-arm of the
17519 // resolver's four-way accept-set against a future silent
17520 // detour that returned an empty Vec (which would emit an
17521 // HTTPRoute with zero rules — silently dropping every
17522 // external `:entrada` flow at admission time), routed to a
17523 // different fallback shape, or dropped the catch-all
17524 // altogether.
17525 let e = entrada_with_paths(vec![]);
17526 assert_eq!(
17527 e.resolved_paths(),
17528 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
17529 "resolved_paths on empty `:entrada :paths` must fall back \
17530 to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
17531 all — got {:?}",
17532 e.resolved_paths(),
17533 );
17534 }
17535
17536 #[test]
17537 fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
17538 // Single-entry `:entrada :paths` — the resolver returns the
17539 // single declared path verbatim, NOT the catch-all fallback
17540 // (author declared a path, honor it — the empty-arm and the
17541 // len-1 arm are semantically distinct axes of the resolver's
17542 // accept-set). Pins that the resolver treats "author declared
17543 // one path" as authored input, not as the empty case.
17544 let e = entrada_with_paths(vec!["/api/only"]);
17545 assert_eq!(
17546 e.resolved_paths(),
17547 vec!["/api/only"],
17548 "resolved_paths on single-entry `:entrada :paths` must \
17549 return the declared path verbatim, NOT the catch-all \
17550 fallback (got {:?})",
17551 e.resolved_paths(),
17552 );
17553 }
17554
17555 #[test]
17556 fn resolved_paths_preserves_author_declared_order() {
17557 // The `:entrada :paths` list is author-ordered — the resolver
17558 // preserves the author's declaration order verbatim, since
17559 // per-rule dispatch order at the K8s Gateway API HTTPRoute
17560 // consumer is significant (first-match-wins under the
17561 // path-prefix matcher). Pins against a future silent
17562 // re-sort / dedup / normalize detour that reordered author
17563 // input.
17564 let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
17565 assert_eq!(
17566 e.resolved_paths(),
17567 vec!["/z/last", "/a/first", "/m/mid"],
17568 "resolved_paths must preserve author-declared `:entrada \
17569 :paths` order verbatim — got {:?}",
17570 e.resolved_paths(),
17571 );
17572 }
17573
17574 // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
17575 // slot `&[String]` slice accessor every per-`:entrada` consumer
17576 // that must see the author's declaration verbatim (not the
17577 // fallback-applied projection the sibling `resolved_paths`
17578 // returns) routes through. The three pin tests below fix the
17579 // accept-set the accessor must honor: (:non-empty-byte-equal,
17580 // :empty-projects-empty-slice, :preserves-author-declared-order)
17581 // — drift on any arm surfaces at caixa-core build time rather
17582 // than at cluster-apply time. Peer discipline with the sibling
17583 // [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
17584 // peer M3 mesh-slot `Vec<String>`-carry axis.
17585
17586 #[test]
17587 fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
17588 // Byte-equal pin: [`Entrada::paths`] must project the raw
17589 // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
17590 // slice borrowed from the typed slot's own [`Vec<String>`]
17591 // storage — no re-ordering, no dedup, no per-entry normalization,
17592 // no fallback substitution (the fallback-applying projection is
17593 // the sibling [`Entrada::resolved_paths`] resolver). Pins against
17594 // a future silent detour that re-normalized the list, dropped
17595 // duplicates the [`AplicacaoSpec::validate`]
17596 // `EntradaPathDuplicate` refusal already rejects at build time,
17597 // or (most severe) accidentally routed through the fallback-
17598 // applying sibling and returned the substrate catch-all when
17599 // the author declared an empty list — collapsing the raw-slot
17600 // and fallback-applied axes into one and breaking the
17601 // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
17602 //
17603 // Peer of the sibling
17604 // [`Placement::clusters`]-shape byte-equal pin
17605 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
17606 // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
17607 let fixtures: Vec<Vec<String>> = vec![
17608 Vec::new(),
17609 vec!["/api/cart".into()],
17610 vec!["/api/cart".into(), "/api/products".into()],
17611 vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
17612 ];
17613 for paths in fixtures {
17614 let e = Entrada {
17615 host: "example.com".into(),
17616 para: "cart".into(),
17617 paths: paths.clone(),
17618 port: DEFAULT_SERVICO_PORT,
17619 };
17620 assert_eq!(
17621 e.paths(),
17622 paths.as_slice(),
17623 "Entrada::paths must return :entrada :paths verbatim \
17624 (got {:?}, expected {:?})",
17625 e.paths(),
17626 paths.as_slice(),
17627 );
17628 assert_eq!(
17629 e.paths(),
17630 e.paths.as_slice(),
17631 "Entrada::paths accessor and .paths.as_slice() field \
17632 access must byte-equal — the accessor is the substrate-\
17633 primitive typed dispatch every downstream per-`:entrada` \
17634 raw-slot path-list consumer must route through",
17635 );
17636 assert_eq!(
17637 e.paths().len(),
17638 e.paths.len(),
17639 "Entrada::paths().len() must byte-equal self.paths.len() \
17640 — a length drift would silently split the paired \
17641 pre-flight cascade-head `.is_empty()` probe input in \
17642 the sibling [`Entrada::resolved_paths`] resolver from \
17643 the per-entry validate loop's traversal input in \
17644 [`AplicacaoSpec::validate`]",
17645 );
17646 }
17647 }
17648
17649 #[test]
17650 fn resolved_paths_reads_through_lifted_paths_accessor() {
17651 // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
17652 // pre-flight `.paths().is_empty()` cascade-head probe (which
17653 // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
17654 // catch-all fallback arm when the accessor projects the empty
17655 // slice) and the per-entry `.paths().iter().map(String::as_str)`
17656 // projection (which must reach every entry in the same order
17657 // the accessor projects, so the sibling
17658 // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
17659 // per-entry projection stay in lockstep by construction) must
17660 // both key off the lifted accessor. Pins the two-site coherence
17661 // by exercising each production consumer end-to-end: (1) the
17662 // catch-all-fallback arm under the empty slice, (2) the
17663 // author-declared-verbatim arm under a two-entry cohort whose
17664 // per-entry projection must byte-equal the input's per-entry
17665 // author-declared paths in the author's declared order.
17666 //
17667 // Peer of the sibling M3
17668 // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
17669 // `validate_placement_reads_through_lifted_clusters_accessor`
17670 // on the sibling `Placement::clusters` reader-site convergence.
17671 let empty = entrada_with_paths(vec![]);
17672 assert_eq!(
17673 empty.resolved_paths(),
17674 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
17675 "resolved_paths on empty :entrada :paths must trip the \
17676 lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
17677 catch-all fallback — routing through the lifted paths() \
17678 accessor must not silently drop the fallback arm",
17679 );
17680
17681 let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
17682 assert_eq!(
17683 declared.resolved_paths(),
17684 vec!["/api/cart", "/api/products"],
17685 "resolved_paths on non-empty :entrada :paths must return each \
17686 entry verbatim in the author's declared order — routing \
17687 through the lifted paths() accessor must not silently \
17688 reorder or drop entries",
17689 );
17690 // Byte-equal pin against the raw-slot accessor to keep the
17691 // fallback-applying resolver's per-entry projection input in
17692 // lockstep with the raw-slot accessor's projection.
17693 let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
17694 assert_eq!(
17695 declared.resolved_paths(),
17696 raw_projected,
17697 "resolved_paths non-empty projection must byte-equal the \
17698 lifted paths() accessor's per-entry String::as_str projection \
17699 — the two projections share the same input slice by \
17700 construction, so any drift here would surface a silent \
17701 re-ordering / dedup / normalization detour in the resolver",
17702 );
17703 }
17704
17705 #[test]
17706 fn validate_reads_through_lifted_entrada_paths_accessor() {
17707 // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
17708 // per-entry value-shape gate's `for p in e.paths()` traversal
17709 // (which must reach every entry in the same order the accessor
17710 // projects, so both the per-entry `EntradaPathEmpty` /
17711 // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
17712 // the duplicate-detection HashSet insert that trips
17713 // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
17714 // projection) must route through the lifted accessor. Pins the
17715 // coherence by exercising each production consumer end-to-end:
17716 // (1) the `EntradaPathEmpty` refusal fires on the second entry
17717 // of a two-entry cohort whose head is valid but tail is empty
17718 // (which requires the loop to reach the second entry through
17719 // the accessor), and (2) the `EntradaPathDuplicate` refusal
17720 // fires on the second entry of a two-entry cohort that shares
17721 // a path (which requires the loop to reach both entries — a
17722 // first-entry-only projection would silently pass since the
17723 // dedup HashSet has room for the first insert).
17724 //
17725 // Peer of the sibling
17726 // `validate_placement_reads_through_lifted_clusters_accessor`
17727 // on the sibling `Placement::clusters` reader-site convergence.
17728 let base = crate::AplicacaoSpec {
17729 membros: vec![crate::Membro {
17730 caixa: "cart".into(),
17731 versao: "^0.1".into(),
17732 }],
17733 contratos: Vec::new(),
17734 politicas: crate::MeshPolicy::default(),
17735 placement: crate::Placement {
17736 estrategia: crate::PlacementStrategy::SingleNode,
17737 clusters: vec!["rio".into()],
17738 shard_key: None,
17739 affinity: None,
17740 },
17741 entrada: Some(Entrada {
17742 host: "example.com".into(),
17743 para: "cart".into(),
17744 paths: vec!["/api/cart".into(), String::new()],
17745 port: DEFAULT_SERVICO_PORT,
17746 }),
17747 };
17748 assert_eq!(
17749 base.validate(),
17750 Err(crate::AplicacaoError::EntradaPathEmpty),
17751 "validate must trip EntradaPathEmpty on the second entry of \
17752 a two-entry cohort — routing through the lifted paths() \
17753 accessor must not silently short-circuit the loop at the \
17754 valid head entry",
17755 );
17756
17757 let mut dup = base;
17758 dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
17759 assert_eq!(
17760 dup.validate(),
17761 Err(crate::AplicacaoError::EntradaPathDuplicate {
17762 path: "/api/cart".into(),
17763 }),
17764 "validate must trip EntradaPathDuplicate on the second entry \
17765 of a two-entry cohort that shares a path — routing through \
17766 the lifted paths() accessor must not silently short-circuit \
17767 the dedup HashSet insert at the first entry",
17768 );
17769 }
17770
17771 // ── Entrada::hostname / Entrada::hostnames — the substrate-
17772 // canonical per-`:entrada` DNS-hostname resolver pair every
17773 // Gateway-API-aware renderer reaching for a per-listener
17774 // singular `hostname:` filter (Gateway) or a per-route plural
17775 // `spec.hostnames[]` filter list (HTTPRoute) routes through.
17776 // The three pin tests below fix the two-way accept-set the pair
17777 // must always honor: (:singular-byte-equal-to-host,
17778 // :plural-is-singleton-of-singular, :plural-len-is-one) — drift
17779 // on any arm surfaces at caixa-core build time rather than at
17780 // cluster-apply time when the API server refuses the HTTPRoute
17781 // for non-intersecting hostname filters. Peer discipline with
17782 // the sibling `resolved_paths` accept-set pin block above on the
17783 // per-`:entrada` path-list resolver axis.
17784
17785 fn entrada_with_host(host: &str) -> Entrada {
17786 Entrada {
17787 host: host.into(),
17788 para: "cart".into(),
17789 paths: Vec::new(),
17790 port: DEFAULT_SERVICO_PORT,
17791 }
17792 }
17793
17794 #[test]
17795 fn hostname_returns_entrada_host_byte_equal() {
17796 // The canonical singular-axis pin: [`Entrada::hostname`] must
17797 // return the `:entrada :host` field byte-for-byte, borrowed
17798 // from the typed slot's own [`String`] storage. Pins against a
17799 // future silent detour that re-normalized the host (an
17800 // accidental `.to_lowercase()` — validate_entrada_host already
17801 // enforces lowercase, so any re-normalization is redundant + a
17802 // drift surface between the validator and the accessor), a
17803 // trailing-`.` fully-qualified DNS shape substitution, or a
17804 // Punycode round-trip that lowered a Unicode host through IDNA.
17805 let e = entrada_with_host("checkout.quero.cloud");
17806 assert_eq!(
17807 e.hostname(),
17808 "checkout.quero.cloud",
17809 "Entrada::hostname must return :entrada :host verbatim \
17810 (got {:?})",
17811 e.hostname(),
17812 );
17813 assert_eq!(
17814 e.hostname(),
17815 e.host.as_str(),
17816 "Entrada::hostname must byte-equal the .host field access",
17817 );
17818 }
17819
17820 #[test]
17821 fn hostnames_returns_singleton_of_hostname_accessor() {
17822 // The pair-invariant pin: [`Entrada::hostnames`] must always
17823 // return exactly `vec![hostname()]` — the singleton list whose
17824 // sole entry is the substrate's canonical per-`:entrada`
17825 // singular hostname. Pins the two-consumer coherence axis: the
17826 // Gateway listener's singular `hostname:` filter and the
17827 // HTTPRoute's plural `spec.hostnames[]` filter list must
17828 // agree, else the Gateway API v1.x conformance layer rejects
17829 // the HTTPRoute at attach time with
17830 // `Accepted:False/NoMatchingParent` (the parent Gateway's
17831 // listener hostname doesn't intersect the route's hostname
17832 // filter list) — a divergence whose apply-time symptom is far
17833 // from any single-site commit and never surfaces in the
17834 // emitted YAML. Pinning the pair-invariant here makes any
17835 // future accidental split (an accidental `.to_string() + "."`
17836 // trailing-`.` on the plural side that didn't land on the
17837 // singular side, an accidental prefix stripping on one axis,
17838 // an accidental wildcard prepend the SNI fan-out overlay
17839 // authors on the plural side without a paired singular
17840 // migration) trip at caixa-core build time.
17841 let e = entrada_with_host("checkout.quero.cloud");
17842 assert_eq!(
17843 e.hostnames(),
17844 vec![e.hostname()],
17845 "Entrada::hostnames must return `vec![hostname()]` under \
17846 the pair-invariant — got {:?} vs. singleton {:?}",
17847 e.hostnames(),
17848 vec![e.hostname()],
17849 );
17850 }
17851
17852 #[test]
17853 fn hostnames_is_singleton_under_single_host_author_surface() {
17854 // The singleton-shape pin: under today's single-hostname-per-
17855 // `:entrada` author surface (the `:host` slot is a single
17856 // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
17857 // must always return a list of length exactly one. Pins
17858 // against a future silent detour that returned an empty list
17859 // (which would emit an HTTPRoute with `spec.hostnames: []` —
17860 // matching every incoming Host header regardless of the
17861 // Aplicacao's declared ingress apex, silently over-matching
17862 // every foreign VirtualHost the parent Gateway also fronts) or
17863 // a duplicated entry (which the Gateway API v1.x parser
17864 // accepts as a `[]-length-2 list of equal hostnames]` but
17865 // whose semantics differ from the intended singleton). The
17866 // author-surface extension point ("a future `:entrada
17867 // :alt-hosts` list overlay" the docstring names) is the sole
17868 // future axis that flips this pin — that migration will re-
17869 // author this test to pin the new plural cardinality.
17870 let e = entrada_with_host("checkout.quero.cloud");
17871 assert_eq!(
17872 e.hostnames().len(),
17873 1,
17874 "Entrada::hostnames must be a singleton under today's \
17875 single-hostname-per-`:entrada` author surface — got \
17876 length {}: {:?}",
17877 e.hostnames().len(),
17878 e.hostnames(),
17879 );
17880 }
17881
17882 // ── Entrada::destination — the substrate-canonical per-`:entrada`
17883 // destination-Servico scalar accessor every Gateway-API
17884 // HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
17885 // discriminator arg (HTTPRoute name composer) or a per-rule
17886 // `backendRefs[0].name` axis routes through. The two pin tests
17887 // below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
17888 // either arm surfaces at caixa-core build time rather than at
17889 // cluster-apply time when an HTTPRoute's `metadata.name` and
17890 // `backendRefs[]` silently disagree on which destination Servico
17891 // the ingress fronts. Peer discipline with the sibling
17892 // `resolved_paths` + `hostname` + `hostnames` accept-set pin
17893 // blocks above on the per-`:entrada` path-list / DNS-hostname
17894 // resolver axes.
17895
17896 #[test]
17897 fn destination_returns_entrada_para_byte_equal() {
17898 // The canonical destination-scalar pin: [`Entrada::destination`]
17899 // must return the `:entrada :para` field byte-for-byte, borrowed
17900 // from the typed slot's own [`String`] storage. Pins against a
17901 // future silent detour that re-normalized the destination (an
17902 // accidental `.to_lowercase()` — the destination Servico is
17903 // already validated as a DNS-1123 label upstream, so any
17904 // re-normalization is redundant + a drift surface between the
17905 // validator and the accessor), a namespace-prefix rewrite (an
17906 // accidental `format!("{namespace}/{para}")` per-CR fully-
17907 // qualified rewrite that didn't land on the peer axis), or a
17908 // per-cluster suffix stamp the operator authors on one
17909 // consumer without the other.
17910 for para in ["cart", "checkout", "catalog", "orders-v2"] {
17911 let e = Entrada {
17912 host: "checkout.quero.cloud".into(),
17913 para: para.into(),
17914 paths: Vec::new(),
17915 port: DEFAULT_SERVICO_PORT,
17916 };
17917 assert_eq!(
17918 e.destination(),
17919 para,
17920 "Entrada::destination must return :entrada :para verbatim \
17921 (got {:?}, expected {para:?})",
17922 e.destination(),
17923 );
17924 assert_eq!(
17925 e.destination(),
17926 e.para.as_str(),
17927 "Entrada::destination must byte-equal the .para field access",
17928 );
17929 }
17930 }
17931
17932 #[test]
17933 fn destination_borrows_from_entrada_para_storage() {
17934 // The borrow-not-copy pin: [`Entrada::destination`] must
17935 // return a `&str` slice that borrows from the typed slot's
17936 // own [`String`] storage — same-address invariant with
17937 // `entrada.para.as_str()`. Pins against a future silent detour
17938 // that allocated a fresh `String` (`self.para.clone()` in the
17939 // body would type-check but silently drop the borrow, and
17940 // every downstream consumer that assumed the returned slice
17941 // outlives `&self` would break on a stale-reference use-after-
17942 // free). Peer with the sibling `hostname_returns_entrada_
17943 // host_byte_equal` on the singular-DNS-hostname axis.
17944 let e = entrada_with_host("checkout.quero.cloud");
17945 let dest = e.destination();
17946 let para_slice = e.para.as_str();
17947 assert_eq!(
17948 dest.as_ptr(),
17949 para_slice.as_ptr(),
17950 "Entrada::destination must borrow from the .para String's \
17951 backing storage — a fresh allocation here means the \
17952 accessor no longer names the substrate-primitive typed \
17953 dispatch and every downstream consumer would silently \
17954 carry a detached copy",
17955 );
17956 assert_eq!(
17957 dest.len(),
17958 para_slice.len(),
17959 "Entrada::destination and .para.as_str() must byte-equal in \
17960 length as well as in address",
17961 );
17962 }
17963
17964 #[test]
17965 fn port_returns_entrada_port_verbatim_across_permutations() {
17966 // The canonical L4-port-scalar pin: [`Entrada::port`] must
17967 // return the `:entrada :port` field verbatim as a `u16` across
17968 // every author-declared value in the validated accept-set
17969 // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
17970 // silent detour that clamped the port (an accidental
17971 // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
17972 // land on the peer [`AplicacaoSpec::port_for_destination`]
17973 // resolver), rewrote it through a per-cluster port-remap table
17974 // the operator authors on one consumer without the other, or
17975 // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
17976 // serde-default value (which would silently collapse the
17977 // distinction between "author explicitly declared `:port 8080`"
17978 // and "author omitted the slot and inherited the default" the
17979 // future per-cluster override slot depends on). Peer with the
17980 // sibling `destination_returns_entrada_para_byte_equal` +
17981 // `hostname_returns_entrada_host_byte_equal` pins on the
17982 // per-`:entrada` `&str` scalar axes.
17983 for port in [
17984 SERVICO_PORT_MIN,
17985 DEFAULT_SERVICO_PORT,
17986 8443u16,
17987 9090u16,
17988 u16::MAX,
17989 ] {
17990 let e = Entrada {
17991 host: "checkout.quero.cloud".into(),
17992 para: "cart".into(),
17993 paths: Vec::new(),
17994 port,
17995 };
17996 assert_eq!(
17997 e.port(),
17998 port,
17999 "Entrada::port must return :entrada :port verbatim \
18000 (got {}, expected {port})",
18001 e.port(),
18002 );
18003 assert_eq!(
18004 e.port(),
18005 e.port,
18006 "Entrada::port accessor and .port field access must \
18007 byte-equal — the accessor is the substrate-primitive \
18008 typed dispatch every downstream L4-port consumer must \
18009 route through",
18010 );
18011 }
18012 }
18013
18014 #[test]
18015 fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
18016 // Two-consumer coherence pin: the
18017 // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
18018 // (which reads through [`Entrada::port`] to compare against
18019 // [`SERVICO_PORT_MIN`]) and the
18020 // [`AplicacaoSpec::port_for_destination`] resolver (which reads
18021 // through [`Entrada::port`] to emit the per-destination
18022 // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
18023 // lifted accessor, so any future rebrand on the typed slot's
18024 // reader shape lands at exactly one place. Pins the two-site
18025 // coherence by exercising a below-floor port through validate
18026 // (which must reject) and a validated in-accept-set port through
18027 // port_for_destination (which must emit the same value the
18028 // accessor returns).
18029 let mut spec = three_member_spec();
18030 if let Some(e) = spec.entrada.as_mut() {
18031 e.port = 0;
18032 }
18033 assert_eq!(
18034 spec.validate().unwrap_err(),
18035 AplicacaoError::EntradaPortZero,
18036 "validate must reject `:entrada :port 0` through the lifted \
18037 Entrada::port accessor — port zero lies below \
18038 SERVICO_PORT_MIN and the validator routes through port() \
18039 to name the floor",
18040 );
18041
18042 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
18043 let mut spec = three_member_spec();
18044 if let Some(e) = spec.entrada.as_mut() {
18045 e.port = port;
18046 }
18047 spec.validate().expect(
18048 "entrada with in-accept-set :port must validate — the \
18049 structural-floor gate reads through Entrada::port",
18050 );
18051 let entrada_ref = spec.entrada.as_ref().expect(":entrada present");
18052 assert_eq!(
18053 spec.port_for_destination(entrada_ref.destination()),
18054 entrada_ref.port(),
18055 "port_for_destination(entrada.destination()) must equal \
18056 entrada.port() — the two consumers of the per-:entrada \
18057 L4-port axis (validator, per-destination resolver) both \
18058 route through Entrada::port",
18059 );
18060 }
18061 }
18062
18063 #[test]
18064 fn wit_contract_source_returns_de_byte_equal_across_permutations() {
18065 // The canonical caller-Servico-scalar pin: [`WitContract::source`]
18066 // must return the `:contratos :de` field byte-for-byte, borrowed
18067 // from the typed slot's own [`String`] storage. Peer of the
18068 // sibling `destination_returns_entrada_para_byte_equal` pin on
18069 // the per-`:entrada` axis — same "the substrate-primitive
18070 // accessor must byte-equal the raw field access verbatim across
18071 // every author-declared value" discipline extended to the
18072 // per-`:contratos` caller arm. Pins against a future silent
18073 // detour that re-normalized the caller (an accidental
18074 // `.to_lowercase()` — every `:contratos :de` is validated as a
18075 // DNS-1123 label upstream via `validate_contrato_caixa`, so any
18076 // re-normalization is redundant + a drift surface between the
18077 // validator and the accessor), a namespace-prefix rewrite (an
18078 // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
18079 // rewrite that didn't land on the peer axis), or a per-cluster
18080 // suffix stamp the operator authors on one consumer without the
18081 // other.
18082 for de in ["cart", "checkout", "catalog", "orders-v2"] {
18083 let c = WitContract {
18084 de: de.into(),
18085 para: "downstream".into(),
18086 wit: "wasi:http/proxy".into(),
18087 endpoint: Some("/lookup".into()),
18088 subject: None,
18089 slot: None,
18090 };
18091 assert_eq!(
18092 c.source(),
18093 de,
18094 "WitContract::source must return :contratos :de verbatim \
18095 (got {:?}, expected {de:?})",
18096 c.source(),
18097 );
18098 assert_eq!(
18099 c.source(),
18100 c.de.as_str(),
18101 "WitContract::source must byte-equal the .de field access",
18102 );
18103 }
18104 }
18105
18106 #[test]
18107 fn wit_contract_source_borrows_from_de_storage() {
18108 // The borrow-not-copy pin: [`WitContract::source`] must return a
18109 // `&str` slice that borrows from the typed slot's own [`String`]
18110 // storage — same-address invariant with `c.de.as_str()`. Pins
18111 // against a future silent detour that allocated a fresh `String`
18112 // (`self.de.clone()` in the body would type-check but silently
18113 // drop the borrow, and every downstream consumer that assumed
18114 // the returned slice outlives `&self` would break on a stale-
18115 // reference use-after-free). Peer of the sibling
18116 // `destination_borrows_from_entrada_para_storage` on the
18117 // per-`:entrada` axis.
18118 let c = WitContract {
18119 de: "cart".into(),
18120 para: "catalog".into(),
18121 wit: "wasi:http/proxy".into(),
18122 endpoint: Some("/lookup".into()),
18123 subject: None,
18124 slot: None,
18125 };
18126 let src = c.source();
18127 let de_slice = c.de.as_str();
18128 assert_eq!(
18129 src.as_ptr(),
18130 de_slice.as_ptr(),
18131 "WitContract::source must borrow from the .de String's \
18132 backing storage — a fresh allocation here means the \
18133 accessor no longer names the substrate-primitive typed \
18134 dispatch and every downstream consumer would silently \
18135 carry a detached copy",
18136 );
18137 assert_eq!(
18138 src.len(),
18139 de_slice.len(),
18140 "WitContract::source and .de.as_str() must byte-equal in \
18141 length as well as in address",
18142 );
18143 }
18144
18145 #[test]
18146 fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
18147 // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
18148 // must return the `:contratos :para` field byte-for-byte,
18149 // borrowed from the typed slot's own [`String`] storage. Peer of
18150 // the sibling `destination_returns_entrada_para_byte_equal` on
18151 // the per-`:entrada` axis — both accessors name "the destination-
18152 // Servico byte-string" concept on their respective mesh-slot
18153 // atoms (per-ingress apex vs. per-typed-edge callee) and both
18154 // must project the underlying `.para` field verbatim so every
18155 // downstream renderer that composes them with peer accessors
18156 // (e.g. `spec.port_for_destination(c.destination())` at the CNP
18157 // per-edge L4 port emit site) reads the same byte-string the
18158 // author declared.
18159 for para in ["catalog", "payment", "orders", "inventory-v3"] {
18160 let c = WitContract {
18161 de: "cart".into(),
18162 para: para.into(),
18163 wit: "wasi:http/proxy".into(),
18164 endpoint: Some("/lookup".into()),
18165 subject: None,
18166 slot: None,
18167 };
18168 assert_eq!(
18169 c.destination(),
18170 para,
18171 "WitContract::destination must return :contratos :para \
18172 verbatim (got {:?}, expected {para:?})",
18173 c.destination(),
18174 );
18175 assert_eq!(
18176 c.destination(),
18177 c.para.as_str(),
18178 "WitContract::destination must byte-equal the .para \
18179 field access",
18180 );
18181 }
18182 }
18183
18184 #[test]
18185 fn wit_contract_destination_borrows_from_para_storage() {
18186 // The borrow-not-copy pin: [`WitContract::destination`] must
18187 // return a `&str` slice that borrows from the typed slot's own
18188 // [`String`] storage — same-address invariant with
18189 // `c.para.as_str()`. Peer of the sibling
18190 // `destination_borrows_from_entrada_para_storage` on the
18191 // per-`:entrada` axis.
18192 let c = WitContract {
18193 de: "cart".into(),
18194 para: "catalog".into(),
18195 wit: "wasi:http/proxy".into(),
18196 endpoint: Some("/lookup".into()),
18197 subject: None,
18198 slot: None,
18199 };
18200 let dest = c.destination();
18201 let para_slice = c.para.as_str();
18202 assert_eq!(
18203 dest.as_ptr(),
18204 para_slice.as_ptr(),
18205 "WitContract::destination must borrow from the .para \
18206 String's backing storage — a fresh allocation here means \
18207 the accessor no longer names the substrate-primitive typed \
18208 dispatch and every downstream consumer would silently \
18209 carry a detached copy",
18210 );
18211 assert_eq!(
18212 dest.len(),
18213 para_slice.len(),
18214 "WitContract::destination and .para.as_str() must byte-equal \
18215 in length as well as in address",
18216 );
18217 }
18218
18219 #[test]
18220 fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
18221 // The canonical per-`:contratos` WIT-world-reference scalar pin:
18222 // [`WitContract::world_ref`] must return the `:contratos :wit`
18223 // field byte-for-byte, borrowed from the typed slot's own
18224 // [`String`] storage. Sibling of the peer per-`:contratos`
18225 // [`WitContract::source`] / [`WitContract::destination`]
18226 // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
18227 // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
18228 // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
18229 // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
18230 // "the substrate-primitive accessor must byte-equal the raw
18231 // field access verbatim across every author-declared value"
18232 // discipline extended to the per-`:contratos` WIT-world arm.
18233 // Pins against a future silent detour that re-canonicalized the
18234 // WIT world reference (an accidental `.to_lowercase()` pass that
18235 // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
18236 // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
18237 // gate is already lowercase-prefixed so any re-normalization is
18238 // redundant + a drift surface between the validator and the
18239 // accessor), an M4-promotion-shape rewrite that formatted a
18240 // typed WIT-world enum through [`Display`] and silently drifted
18241 // the printer output from the source `caixa.lisp`, or a per-
18242 // cluster WIT-alias rewrite that didn't land on the peer field-
18243 // access sites. Five values sweep the shape-dispatch accept-set
18244 // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
18245 // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
18246 // `wasi:keyvalue/`).
18247 for (wit, endpoint, subject, slot) in [
18248 ("wasi:http/proxy", Some("/lookup"), None, None),
18249 ("http:proxy", Some("/health"), None, None),
18250 ("nats:pub-sub", None, Some("orders.paid"), None),
18251 ("kafka:events", None, Some("checkout-events"), None),
18252 ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
18253 ] {
18254 let c = WitContract {
18255 de: "cart".into(),
18256 para: "downstream".into(),
18257 wit: wit.into(),
18258 endpoint: endpoint.map(str::to_string),
18259 subject: subject.map(str::to_string),
18260 slot: slot.map(str::to_string),
18261 };
18262 assert_eq!(
18263 c.world_ref(),
18264 wit,
18265 "WitContract::world_ref must return :contratos :wit \
18266 verbatim (got {:?}, expected {wit:?})",
18267 c.world_ref(),
18268 );
18269 assert_eq!(
18270 c.world_ref(),
18271 c.wit.as_str(),
18272 "WitContract::world_ref must byte-equal the .wit field \
18273 access",
18274 );
18275 }
18276 }
18277
18278 #[test]
18279 fn wit_contract_world_ref_borrows_from_wit_storage() {
18280 // The borrow-not-copy pin: [`WitContract::world_ref`] must
18281 // return a `&str` slice that borrows from the typed slot's own
18282 // [`String`] storage — same-address invariant with
18283 // `c.wit.as_str()`. Pins against a future silent detour that
18284 // allocated a fresh `String` (`self.wit.clone()` in the body
18285 // would type-check but silently drop the borrow, and every
18286 // downstream consumer that assumed the returned slice outlives
18287 // `&self` would break on a stale-reference use-after-free — the
18288 // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
18289 // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
18290 // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
18291 // / [`is_pubsub`][WitContract::is_pubsub] /
18292 // [`is_store`][WitContract::is_store] methods route through —
18293 // each borrow from the WitContract's own storage and each would
18294 // silently misbehave if this accessor produced a detached copy).
18295 // Peer of the sibling per-`:contratos` [`WitContract::source`] /
18296 // [`WitContract::destination`] and per-`:entrada`
18297 // [`Entrada::destination`] / [`Entrada::hostname`] and
18298 // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
18299 // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
18300 let c = WitContract {
18301 de: "cart".into(),
18302 para: "catalog".into(),
18303 wit: "wasi:http/proxy".into(),
18304 endpoint: Some("/lookup".into()),
18305 subject: None,
18306 slot: None,
18307 };
18308 let world = c.world_ref();
18309 let wit_slice = c.wit.as_str();
18310 assert_eq!(
18311 world.as_ptr(),
18312 wit_slice.as_ptr(),
18313 "WitContract::world_ref must borrow from the .wit String's \
18314 backing storage — a fresh allocation here means the \
18315 accessor no longer names the substrate-primitive typed \
18316 dispatch and every downstream consumer would silently carry \
18317 a detached copy",
18318 );
18319 assert_eq!(
18320 world.len(),
18321 wit_slice.len(),
18322 "WitContract::world_ref and .wit.as_str() must byte-equal in \
18323 length as well as in address",
18324 );
18325 }
18326
18327 #[test]
18328 fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
18329 // Sibling-triple invariant pin composing all three per-`:contratos`
18330 // substrate-primitive typed dispatches — [`WitContract::source`]
18331 // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
18332 // [`WitContract::world_ref`] — at the joint
18333 // `(source(), destination(), world_ref())` call shape every
18334 // renderer that fans on per-edge caller-callee-shape identity
18335 // keys off. The invariant, evaluated per-contract:
18336 //
18337 // (c.source(), c.destination(), c.world_ref())
18338 // == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
18339 //
18340 // Closes the last unlifted per-`:contratos` scalar axis — every
18341 // downstream consumer that reads the triple now routes through
18342 // exactly three typed dispatches on the substrate primitive,
18343 // not two typed + one open-coded field access. A future refactor
18344 // that silently split any one accessor's projection (an
18345 // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
18346 // canonicalization that didn't reach the peer `source`/
18347 // `destination` arms, an accidental `source()` per-cluster
18348 // caller-alias rewrite that didn't land on the `world_ref` peer)
18349 // surfaces at caixa-core build time. Peer of the sibling per-
18350 // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
18351 // per-`:entrada` `(hostname(), destination())` (6db982c /
18352 // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
18353 // axes, extended to the per-`:contratos` triple.
18354 for (de, para, wit, endpoint, subject, slot) in [
18355 (
18356 "cart",
18357 "catalog",
18358 "wasi:http/proxy",
18359 Some("/lookup"),
18360 None,
18361 None,
18362 ),
18363 (
18364 "checkout",
18365 "orders",
18366 "nats:pub-sub",
18367 None,
18368 Some("orders.paid"),
18369 None,
18370 ),
18371 (
18372 "cart",
18373 "kv",
18374 "wasi:keyvalue/store",
18375 None,
18376 None,
18377 Some("carts/{cart_id}"),
18378 ),
18379 (
18380 "orders-v2",
18381 "inventory-v3",
18382 "http:proxy",
18383 Some("/reserve"),
18384 None,
18385 None,
18386 ),
18387 ] {
18388 let c = WitContract {
18389 de: de.into(),
18390 para: para.into(),
18391 wit: wit.into(),
18392 endpoint: endpoint.map(str::to_string),
18393 subject: subject.map(str::to_string),
18394 slot: slot.map(str::to_string),
18395 };
18396 assert_eq!(
18397 (c.source(), c.destination(), c.world_ref()),
18398 (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
18399 "(WitContract::source, ::destination, ::world_ref) must \
18400 project (.de, .para, .wit) verbatim across every author-\
18401 declared triple (got ({:?}, {:?}, {:?}), expected \
18402 ({de:?}, {para:?}, {wit:?}))",
18403 c.source(),
18404 c.destination(),
18405 c.world_ref(),
18406 );
18407 }
18408 }
18409
18410 #[test]
18411 fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
18412 // The canonical per-`:contratos` owned-form caller-callee-pair
18413 // pin: [`WitContract::edge_pair`] must return the
18414 // `(source(), destination())` tuple in owned form byte-for-byte,
18415 // projected through the lifted [`WitContract::source`] /
18416 // [`WitContract::destination`] scalar accessors. Pins the
18417 // composite-projection invariant on the per-`:contratos`
18418 // mesh-slot atom — every author-declared `(de, para)` pair must
18419 // round-trip verbatim through the substrate primitive's typed
18420 // dispatch, so the nine [`AplicacaoError`] diagnostic-
18421 // construction sites the accessor now feeds
18422 // ([`AplicacaoError::EmptyWit`],
18423 // [`AplicacaoError::ContratoEndpointEmpty`],
18424 // [`AplicacaoError::ContratoEndpointNotAbsolute`],
18425 // [`AplicacaoError::ContratoEndpointInvalid`],
18426 // [`AplicacaoError::ContratoSubjectEmpty`],
18427 // [`AplicacaoError::ContratoSubjectInvalid`],
18428 // [`AplicacaoError::ContratoSlotEmpty`],
18429 // [`AplicacaoError::ContratoSlotInvalid`],
18430 // [`AplicacaoError::ContratoDuplicate`]) all read the same
18431 // `(de, para)` label pair every author sees at the source
18432 // `caixa.lisp`. Pins against a future silent detour that swapped
18433 // the `.0` / `.1` arms (an accidental `(destination(),
18434 // source())` re-order in the body would silently invert every
18435 // downstream diagnostic's `de:` / `para:` label pair, silently
18436 // reversing the direction of every operator-facing typed error
18437 // arrow), a fresh-allocation shape drift (an accidental
18438 // `.to_string()` on one arm but not the other would leave the
18439 // owned/borrowed pair mismatched vs. the sibling `source()` /
18440 // `destination()` returns), or an M4 per-cluster caller/callee-
18441 // alias rewrite that landed on `source()` without reaching
18442 // `destination()` (or vice versa). Peer of the sibling per-
18443 // `:contratos` `(source, destination, world_ref)` triple
18444 // pin above on the mesh-slot-atom scalar-value axes, extended
18445 // to the owned-form pair-projection axis.
18446 for (de, para, wit, endpoint, subject, slot) in [
18447 (
18448 "cart",
18449 "catalog",
18450 "wasi:http/proxy",
18451 Some("/lookup"),
18452 None,
18453 None,
18454 ),
18455 (
18456 "checkout",
18457 "orders",
18458 "nats:pub-sub",
18459 None,
18460 Some("orders.paid"),
18461 None,
18462 ),
18463 (
18464 "cart",
18465 "kv",
18466 "wasi:keyvalue/store",
18467 None,
18468 None,
18469 Some("carts/{cart_id}"),
18470 ),
18471 (
18472 "orders-v2",
18473 "inventory-v3",
18474 "http:proxy",
18475 Some("/reserve"),
18476 None,
18477 None,
18478 ),
18479 ] {
18480 let c = WitContract {
18481 de: de.into(),
18482 para: para.into(),
18483 wit: wit.into(),
18484 endpoint: endpoint.map(str::to_string),
18485 subject: subject.map(str::to_string),
18486 slot: slot.map(str::to_string),
18487 };
18488 assert_eq!(
18489 c.edge_pair(),
18490 (de.to_string(), para.to_string()),
18491 "WitContract::edge_pair must return (:contratos :de, \
18492 :contratos :para) as an owned tuple verbatim (got {:?}, \
18493 expected ({de:?}, {para:?}))",
18494 c.edge_pair(),
18495 );
18496 }
18497 }
18498
18499 #[test]
18500 fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
18501 // The composition pin: [`WitContract::edge_pair`] must return
18502 // exactly `(source().to_string(), destination().to_string())` —
18503 // the owned form of the sibling accessor pair — so any future
18504 // refactor that silently re-authored the caller-arm / callee-arm
18505 // projection to bypass the lifted scalar accessors (an accidental
18506 // `(self.de.clone(), self.para.clone())` regression back to the
18507 // raw field-access shape, an M4-typed-caller-enum `Display`
18508 // re-canonicalization on `source()` that didn't reach
18509 // `edge_pair()`, a per-cluster alias rewrite the operator lands
18510 // on `destination()` without reaching this composite projection)
18511 // trips at caixa-core build time. Pins the "typed dispatch
18512 // composes with typed dispatch, not with raw field access"
18513 // discipline every downstream diagnostic-construction site now
18514 // routes through — a `de:` / `para:` label pair whose
18515 // projection silently drifted off the substrate primitive's
18516 // scalar accessors would silently split the diagnostic's self-
18517 // locating signal from the source `caixa.lisp` author's view.
18518 // Peer of the sibling per-`:politicas` `is_empty` /
18519 // `validate_politicas` accessor-routing-pin family on the M3
18520 // mesh-slot family (18575, 18739, 18918, 19140, 19371).
18521 let c = WitContract {
18522 de: "cart".into(),
18523 para: "catalog".into(),
18524 wit: "wasi:http/proxy".into(),
18525 endpoint: Some("/lookup".into()),
18526 subject: None,
18527 slot: None,
18528 };
18529 assert_eq!(
18530 c.edge_pair(),
18531 (c.source().to_string(), c.destination().to_string()),
18532 "WitContract::edge_pair must compose exactly \
18533 (source().to_string(), destination().to_string()) — a \
18534 bypass of either sibling accessor here would silently \
18535 decouple the composite-projection axis from the \
18536 substrate-primitive scalar accessors every downstream \
18537 consumer routes through",
18538 );
18539 }
18540
18541 #[test]
18542 fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
18543 {
18544 // The canonical per-`:contratos` owned-form
18545 // caller-callee-world-ref-triple pin:
18546 // [`WitContract::edge_triple`] must return the
18547 // `(source(), destination(), world_ref())` tuple in owned form
18548 // byte-for-byte, projected through the lifted
18549 // [`WitContract::source`] / [`WitContract::destination`] /
18550 // [`WitContract::world_ref`] scalar accessors. Pins the
18551 // composite-projection invariant on the per-`:contratos`
18552 // mesh-slot atom — every author-declared `(de, para, wit)`
18553 // triple must round-trip verbatim through the substrate
18554 // primitive's typed dispatch, so the nine
18555 // [`AplicacaoError`] diagnostic-construction sites the
18556 // accessor now feeds (the [`WitTarget`]-dispatch's eight
18557 // wrong-target / missing-target / invalid-wit / capability-
18558 // with-payload arms in [`WitContract::target`], plus the
18559 // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
18560 // diagnostic constructor in [`AplicacaoSpec::validate`]) all
18561 // read the same `(de, para, wit)` triple every author sees at
18562 // the source `caixa.lisp`. Pins against a future silent
18563 // detour that swapped any two arms (an accidental `(destination(),
18564 // source(), world_ref())` re-order in the body would silently
18565 // invert every downstream diagnostic's `de:` / `para:` label
18566 // pair, silently reversing the direction of every operator-
18567 // facing typed error arrow), a fresh-allocation shape drift
18568 // (an accidental `.to_string()` skipped on one arm would leave
18569 // the owned/borrowed triple mismatched vs. the sibling
18570 // `source()` / `destination()` / `world_ref()` returns), or an
18571 // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
18572 // canonicalization pass that landed on one accessor without
18573 // reaching the peers. Peer of the sibling per-`:contratos`
18574 // caller-callee-pair
18575 // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
18576 // pin on the mesh-slot-atom composite-projection axis,
18577 // extended to the triple-projection axis.
18578 for (de, para, wit, endpoint, subject, slot) in [
18579 (
18580 "cart",
18581 "catalog",
18582 "wasi:http/proxy",
18583 Some("/lookup"),
18584 None,
18585 None,
18586 ),
18587 (
18588 "checkout",
18589 "orders",
18590 "nats:pub-sub",
18591 None,
18592 Some("orders.paid"),
18593 None,
18594 ),
18595 (
18596 "cart",
18597 "kv",
18598 "wasi:keyvalue/store",
18599 None,
18600 None,
18601 Some("carts/{cart_id}"),
18602 ),
18603 (
18604 "orders-v2",
18605 "inventory-v3",
18606 "http:proxy",
18607 Some("/reserve"),
18608 None,
18609 None,
18610 ),
18611 ] {
18612 let c = WitContract {
18613 de: de.into(),
18614 para: para.into(),
18615 wit: wit.into(),
18616 endpoint: endpoint.map(str::to_string),
18617 subject: subject.map(str::to_string),
18618 slot: slot.map(str::to_string),
18619 };
18620 assert_eq!(
18621 c.edge_triple(),
18622 (de.to_string(), para.to_string(), wit.to_string()),
18623 "WitContract::edge_triple must return (:contratos :de, \
18624 :contratos :para, :contratos :wit) as an owned triple \
18625 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
18626 c.edge_triple(),
18627 );
18628 }
18629 }
18630
18631 #[test]
18632 fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
18633 // The composition pin: [`WitContract::edge_triple`] must return
18634 // exactly `(source().to_string(), destination().to_string(),
18635 // world_ref().to_string())` — the owned form of the sibling
18636 // scalar-accessor triple — so any future refactor that silently
18637 // re-authored one arm's projection to bypass the lifted scalar
18638 // accessors (an accidental `(self.de.clone(), self.para.clone(),
18639 // self.wit.clone())` regression back to the raw field-access
18640 // shape the internal `edge` closure and the ContratoDuplicate
18641 // diagnostic both carried before this lift landed, an
18642 // M4-typed-caller-enum `Display` re-canonicalization on
18643 // `source()` that didn't reach `edge_triple()`, a per-cluster
18644 // alias rewrite the operator lands on `destination()` /
18645 // `world_ref()` without reaching this composite projection)
18646 // trips at caixa-core build time. Pins the "typed dispatch
18647 // composes with typed dispatch, not with raw field access"
18648 // discipline every downstream diagnostic-construction site now
18649 // routes through — a `de:` / `para:` / `wit:` triple whose
18650 // projection silently drifted off the substrate primitive's
18651 // scalar accessors would silently split the diagnostic's self-
18652 // locating signal from the source `caixa.lisp` author's view.
18653 // Peer of the sibling per-`:contratos` edge_pair composition-
18654 // pin above on the mesh-slot-atom composite-projection axis.
18655 let c = WitContract {
18656 de: "cart".into(),
18657 para: "catalog".into(),
18658 wit: "wasi:http/proxy".into(),
18659 endpoint: Some("/lookup".into()),
18660 subject: None,
18661 slot: None,
18662 };
18663 assert_eq!(
18664 c.edge_triple(),
18665 (
18666 c.source().to_string(),
18667 c.destination().to_string(),
18668 c.world_ref().to_string(),
18669 ),
18670 "WitContract::edge_triple must compose exactly \
18671 (source().to_string(), destination().to_string(), \
18672 world_ref().to_string()) — a bypass of any sibling accessor \
18673 here would silently decouple the composite-projection axis \
18674 from the substrate-primitive scalar accessors every \
18675 downstream consumer routes through",
18676 );
18677 }
18678
18679 #[test]
18680 fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
18681 // The canonical semantics-pin: [`WitContract::edge_triple`] must
18682 // project the full `(de, para, wit)` identity of a `:contratos`
18683 // edge — the sub-triple every triple-carrying
18684 // [`AplicacaoError::Contrato*`] diagnostic weaves into its
18685 // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
18686 // missing-target, capability-with-payload, invalid-wit, and the
18687 // duplicate-gate). Rejects a drift in shape (an accidental
18688 // silent detour that returned a `(de, para)` pair or added an
18689 // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
18690 // would trip here because the return type would no longer
18691 // pattern-match the eight `let (de, para, wit) = edge();`
18692 // destructures the [`WitContract::target`] dispatch feeds off
18693 // + the paired duplicate-gate `let (de, para, wit) =
18694 // c.edge_triple();` destructure in
18695 // [`AplicacaoSpec::validate`]). Peer of the sibling per-
18696 // `:contratos` caller-callee-pair pin above extended to the
18697 // triple projection surface: closes the "one composite
18698 // accessor per typed diagnostic-construction sub-tuple"
18699 // discipline on the per-`:contratos` mesh-slot-atom axis.
18700 let c = WitContract {
18701 de: "checkout".into(),
18702 para: "orders".into(),
18703 wit: "nats:pub-sub".into(),
18704 endpoint: None,
18705 subject: Some("orders.paid".into()),
18706 slot: None,
18707 };
18708 let (de, para, wit) = c.edge_triple();
18709 assert_eq!(de, "checkout");
18710 assert_eq!(para, "orders");
18711 assert_eq!(wit, "nats:pub-sub");
18712 }
18713
18714 #[test]
18715 fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
18716 {
18717 // The composition pin: [`WitContract::identity`] must return
18718 // exactly `(source(), destination(), world_ref(), endpoint(),
18719 // subject(), slot())` — the borrowed form of the six-scalar-
18720 // accessor identity axis. Any future refactor that silently
18721 // re-authored one arm's projection to bypass a scalar accessor
18722 // (a `self.de.as_str()` regression back to raw field access on
18723 // any of the three required arms, a `self.endpoint.as_deref()`
18724 // regression on any of the three optional arms, an M4 per-
18725 // cluster caller/callee-alias rewrite the operator lands on
18726 // `source()` / `destination()` without reaching this composite
18727 // projection) trips at caixa-core build time. Sweeps four
18728 // permutations of the WIT-shape × payload lattice — HTTP with
18729 // endpoint, pub-sub with subject, store with slot, payload-less
18730 // capability — so every payload arm is exercised. Peer of the
18731 // sibling per-`:contratos`
18732 // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
18733 // composition pin on the mesh-slot-atom composite-projection
18734 // axis; extends the discipline from the (de, para, wit) prefix
18735 // onto the full-identity axis carrying the three payload arms.
18736 for (de, para, wit, endpoint, subject, slot) in [
18737 (
18738 "cart",
18739 "catalog",
18740 "wasi:http/proxy",
18741 Some("/lookup"),
18742 None,
18743 None,
18744 ),
18745 (
18746 "checkout",
18747 "orders",
18748 "nats:pub-sub",
18749 None,
18750 Some("orders.paid"),
18751 None,
18752 ),
18753 (
18754 "cart",
18755 "kv",
18756 "wasi:keyvalue/store",
18757 None,
18758 None,
18759 Some("carts/{cart_id}"),
18760 ),
18761 ("audit", "sink", "wasi:logging", None, None, None),
18762 ] {
18763 let c = WitContract {
18764 de: de.into(),
18765 para: para.into(),
18766 wit: wit.into(),
18767 endpoint: endpoint.map(str::to_owned),
18768 subject: subject.map(str::to_owned),
18769 slot: slot.map(str::to_owned),
18770 };
18771 assert_eq!(
18772 c.identity(),
18773 (
18774 c.source(),
18775 c.destination(),
18776 c.world_ref(),
18777 c.endpoint(),
18778 c.subject(),
18779 c.slot(),
18780 ),
18781 "WitContract::identity must compose exactly \
18782 (source(), destination(), world_ref(), endpoint(), \
18783 subject(), slot()) — a bypass of any sibling accessor \
18784 here would silently decouple the identity-projection \
18785 axis from the substrate-primitive scalar accessors \
18786 every dedup-key consumer routes through",
18787 );
18788 }
18789 }
18790
18791 #[test]
18792 fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
18793 // The canonical semantics-pin: [`WitContract::identity`] must
18794 // project the six-axis (de, para, wit, endpoint, subject, slot)
18795 // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
18796 // gate keys off — two `WitContract`s that agree on all six axes
18797 // are the same typed edge declared twice, the graph-edge
18798 // analogue of duplicate `:membros` / `:placement :clusters` /
18799 // `:entrada :paths` entries. Rejects a shape drift (an
18800 // accidental silent detour that returned a prefix tuple or
18801 // added an extra field) by pattern-matching the six-arm shape.
18802 // Peer of the sibling per-`:contratos`
18803 // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
18804 // pin extended from the (de, para, wit) prefix onto the full
18805 // six-axis identity that the dedup key rides.
18806 let c = WitContract {
18807 de: "cart".into(),
18808 para: "catalog".into(),
18809 wit: "wasi:http/proxy".into(),
18810 endpoint: Some("/products/:id".into()),
18811 subject: None,
18812 slot: None,
18813 };
18814 let (de, para, wit, endpoint, subject, slot) = c.identity();
18815 assert_eq!(de, "cart");
18816 assert_eq!(para, "catalog");
18817 assert_eq!(wit, "wasi:http/proxy");
18818 assert_eq!(endpoint, Some("/products/:id"));
18819 assert_eq!(subject, None);
18820 assert_eq!(slot, None);
18821
18822 // Two byte-identical contracts must produce equal identities —
18823 // the dedup key's foundational invariant.
18824 let c2 = c.clone();
18825 assert_eq!(c.identity(), c2.identity());
18826
18827 // Any change on any of the six axes must break the identity —
18828 // sweeps by mutating one axis at a time.
18829 let mut mutated = c.clone();
18830 mutated.de = "search".into();
18831 assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
18832 let mut mutated = c.clone();
18833 mutated.para = "warehouse".into();
18834 assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
18835 let mut mutated = c.clone();
18836 mutated.wit = "http:legacy".into();
18837 assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
18838 let mut mutated = c.clone();
18839 mutated.endpoint = Some("/search".into());
18840 assert_ne!(
18841 c.identity(),
18842 mutated.identity(),
18843 "endpoint axis must partition"
18844 );
18845 let mut mutated = c.clone();
18846 mutated.subject = Some("orders.paid".into());
18847 assert_ne!(
18848 c.identity(),
18849 mutated.identity(),
18850 "subject axis must partition"
18851 );
18852 let mut mutated = c;
18853 mutated.slot = Some("carts/{id}".into());
18854 assert_ne!(mutated.identity().5, None, "slot axis must partition");
18855 }
18856
18857 #[test]
18858 fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
18859 // The canonical per-`:contratos` structural-self-edge pin:
18860 // [`WitContract::is_self_loop`] must return `true` when the
18861 // `:de` and `:para` fields agree byte-for-byte, across every
18862 // WIT-shape variant the per-edge shape family carries. Pins
18863 // the shape-agnostic identity-space partition the
18864 // [`AplicacaoSpec::validate`] self-edge gate at
18865 // caixa-core/src/aplicacao.rs:5559 fires against — all four
18866 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
18867 // under the same one predicate. Four permutations sweep the
18868 // accept-set: HTTP with endpoint, pub-sub with subject, KV
18869 // store with slot, and payload-less capability.
18870 for (nome, wit, endpoint, subject, slot) in [
18871 ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
18872 ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
18873 (
18874 "kv",
18875 "wasi:keyvalue/store",
18876 None,
18877 None,
18878 Some("carts/{cart_id}"),
18879 ),
18880 ("audit", "wasi:logging", None, None, None),
18881 ] {
18882 let c = WitContract {
18883 de: nome.into(),
18884 para: nome.into(),
18885 wit: wit.into(),
18886 endpoint: endpoint.map(str::to_string),
18887 subject: subject.map(str::to_string),
18888 slot: slot.map(str::to_string),
18889 };
18890 assert!(
18891 c.is_self_loop(),
18892 "WitContract::is_self_loop must return true when \
18893 :contratos :de == :contratos :para (got false on \
18894 {nome:?} under {wit:?})",
18895 );
18896 }
18897 }
18898
18899 #[test]
18900 fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
18901 // The complement pin: [`WitContract::is_self_loop`] must return
18902 // `false` on every well-shaped inter-Servico contract (the
18903 // author-intended `:contratos` shape MESH-COMPOSITION §III.1
18904 // names — "Servico A calls Servico B" between two distinct
18905 // graph nodes). Pins against a future silent detour that
18906 // inverted the predicate (an accidental `!= ` swap for `==`
18907 // would silently reject every legitimate inter-Servico edge
18908 // and admit every self-edge — the exact inversion of the
18909 // author-intended shape). Four permutations sweep the same
18910 // WIT-shape accept-set the sibling positive-arm test carries.
18911 for (de, para, wit, endpoint, subject, slot) in [
18912 (
18913 "cart",
18914 "catalog",
18915 "wasi:http/proxy",
18916 Some("/lookup"),
18917 None,
18918 None,
18919 ),
18920 (
18921 "checkout",
18922 "orders",
18923 "nats:pub-sub",
18924 None,
18925 Some("orders.paid"),
18926 None,
18927 ),
18928 (
18929 "cart",
18930 "kv",
18931 "wasi:keyvalue/store",
18932 None,
18933 None,
18934 Some("carts/{cart_id}"),
18935 ),
18936 ("audit", "sink", "wasi:logging", None, None, None),
18937 ] {
18938 let c = WitContract {
18939 de: de.into(),
18940 para: para.into(),
18941 wit: wit.into(),
18942 endpoint: endpoint.map(str::to_string),
18943 subject: subject.map(str::to_string),
18944 slot: slot.map(str::to_string),
18945 };
18946 assert!(
18947 !c.is_self_loop(),
18948 "WitContract::is_self_loop must return false when \
18949 :contratos :de differs from :contratos :para (got true \
18950 on {de:?} → {para:?} under {wit:?})",
18951 );
18952 }
18953 }
18954
18955 #[test]
18956 fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
18957 // The composition pin: [`WitContract::is_self_loop`] must
18958 // resolve to exactly `self.source() == self.destination()` —
18959 // the equality probe of the sibling scalar-accessor pair — so
18960 // any future refactor that silently re-authored the predicate
18961 // to bypass the lifted scalar accessors (an accidental
18962 // `self.de == self.para` regression back to the raw field-
18963 // access shape, an M4-typed-caller-enum identity-comparison
18964 // rule that landed on `source()` without reaching
18965 // `destination()`, a per-cluster alias rewrite the operator
18966 // pins on `destination()` without reaching this predicate)
18967 // trips at caixa-core build time. Pins the "typed dispatch
18968 // composes with typed dispatch, not with raw field access"
18969 // discipline the sibling [`WitContract::edge_pair`] /
18970 // [`WitContract::edge_triple`] composite-projection accessors
18971 // already carry, extended onto the per-edge endpoint-equality
18972 // predicate axis. Positive and complement arms both fire.
18973 let self_edge = WitContract {
18974 de: "cart".into(),
18975 para: "cart".into(),
18976 wit: "wasi:http/proxy".into(),
18977 endpoint: Some("/lookup".into()),
18978 subject: None,
18979 slot: None,
18980 };
18981 assert_eq!(
18982 self_edge.is_self_loop(),
18983 self_edge.source() == self_edge.destination(),
18984 "WitContract::is_self_loop must compose exactly \
18985 `source() == destination()` — a bypass of either sibling \
18986 accessor here would silently decouple the endpoint-\
18987 equality predicate from the substrate-primitive scalar \
18988 accessors every downstream consumer routes through",
18989 );
18990 let inter_edge = WitContract {
18991 de: "cart".into(),
18992 para: "catalog".into(),
18993 wit: "wasi:http/proxy".into(),
18994 endpoint: Some("/lookup".into()),
18995 subject: None,
18996 slot: None,
18997 };
18998 assert_eq!(
18999 inter_edge.is_self_loop(),
19000 inter_edge.source() == inter_edge.destination(),
19001 "WitContract::is_self_loop must compose exactly \
19002 `source() == destination()` on the complement arm too",
19003 );
19004 }
19005
19006 #[test]
19007 fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
19008 // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
19009 // pin: [`WitContract::endpoint`] must return the `:contratos
19010 // :endpoint` field byte-for-byte, borrowed from the typed slot's
19011 // own `Option<String>` storage. Peer of the sibling
19012 // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
19013 // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
19014 // mesh-slot `Option<String>` optional-scalar axes — same "the
19015 // substrate-primitive accessor must byte-equal the raw field
19016 // access verbatim across every author-declared value" discipline
19017 // extended to the per-`:contratos` HTTP-payload-carrier arm.
19018 // Pins against a future silent detour that re-canonicalized the
19019 // endpoint (an accidental percent-encoding pass that didn't
19020 // reach the peer field-access site at the dedup key, a per-CR
19021 // fully-qualified prefix rewrite the operator authors on one
19022 // consumer without the other, or an M4 typed-path-template
19023 // `Display` re-canonicalization that silently drifted the
19024 // printer output from the source `caixa.lisp`). Four values
19025 // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
19026 // gate upstream admits (short root-path, dashed, param-shaped,
19027 // deep-hierarchy).
19028 for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
19029 let c = WitContract {
19030 de: "cart".into(),
19031 para: "catalog".into(),
19032 wit: "wasi:http/proxy".into(),
19033 endpoint: Some(endpoint.into()),
19034 subject: None,
19035 slot: None,
19036 };
19037 assert_eq!(
19038 c.endpoint(),
19039 Some(endpoint),
19040 "WitContract::endpoint must return :contratos :endpoint \
19041 verbatim (got {:?}, expected Some({endpoint:?}))",
19042 c.endpoint(),
19043 );
19044 assert_eq!(
19045 c.endpoint(),
19046 c.endpoint.as_deref(),
19047 "WitContract::endpoint must byte-equal the .endpoint \
19048 field's `.as_deref()` projection",
19049 );
19050 }
19051 }
19052
19053 #[test]
19054 fn wit_contract_endpoint_none_when_field_is_none() {
19055 // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
19056 // payload-carrier accessor pin: when the typed slot is absent —
19057 // the canonical shape under a non-HTTP `:wit` world per the
19058 // [`WitContract::target`]-enforced shape ↔ target partition
19059 // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
19060 // carries `:slot`, [`WitTarget::Capability`] carries none) —
19061 // [`WitContract::endpoint`] must return `None`. Pins against a
19062 // future silent detour that projected the absent slot to a
19063 // `Some("")` empty-string default (the canonical `Option<String>`
19064 // → `String` collapse footgun the sibling M2
19065 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
19066 // emptiness predicates already guard on the peer M2 typed-slot
19067 // surfaces), a `Some("None")` stringified-None round-trip, or a
19068 // `Some` arm whose contents were derived from a sibling slot (an
19069 // accidental fallback to the `:subject` / `:slot` payload that
19070 // read the pub-sub / store payload into the endpoint axis).
19071 // Three contracts sweep the accept-set every non-HTTP `:wit`
19072 // world lands on — pub-sub NATS, key/value, and payload-less
19073 // capability.
19074 for (wit, subject, slot) in [
19075 ("nats:pub-sub", Some("orders.paid"), None),
19076 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
19077 ("wasi:cli/environment", None, None),
19078 ] {
19079 let c = WitContract {
19080 de: "cart".into(),
19081 para: "downstream".into(),
19082 wit: wit.into(),
19083 endpoint: None,
19084 subject: subject.map(str::to_string),
19085 slot: slot.map(str::to_string),
19086 };
19087 assert!(
19088 c.endpoint().is_none(),
19089 "WitContract::endpoint must return None when the typed \
19090 slot is absent under :wit {wit:?} (got {:?})",
19091 c.endpoint(),
19092 );
19093 assert_eq!(
19094 c.endpoint(),
19095 c.endpoint.as_deref(),
19096 "WitContract::endpoint must byte-equal the .endpoint \
19097 field's `.as_deref()` projection in the absent arm",
19098 );
19099 }
19100 }
19101
19102 #[test]
19103 fn wit_contract_endpoint_borrows_from_endpoint_storage() {
19104 // The borrow-not-copy pin: [`WitContract::endpoint`] must return
19105 // an `Option<&str>` whose `Some` arm borrows from the typed
19106 // slot's own [`String`] storage — same-address invariant with
19107 // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
19108 // detour that allocated a fresh `String`
19109 // (`self.endpoint.clone().map(...)` in the body would type-check
19110 // but silently drop the borrow, and every downstream consumer
19111 // that assumed the returned slice outlives `&self` would break
19112 // on a stale-reference use-after-free — the [`WitContract::target`]
19113 // Http-arm payload extraction rebinds the returned `Option<&str>`
19114 // through `.ok_or_else(...)` and threads the `&str` payload into
19115 // [`WitTarget::Http { endpoint: &'a str }`], the
19116 // [`AplicacaoSpec::validate`] duplicate-`:contratos`
19117 // [`ContratoIdentity`] dedup key threads the returned
19118 // `Option<&str>` into the six-tuple's HTTP arm — each borrow
19119 // from the WitContract's own storage and each would silently
19120 // misbehave if this accessor produced a detached copy). Peer of
19121 // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
19122 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
19123 // shaped optional-scalar axes — first extension of the
19124 // `Option<&str>` borrow-not-copy discipline onto the
19125 // per-`:contratos` HTTP-shaped payload-carrier axis.
19126 let c = WitContract {
19127 de: "cart".into(),
19128 para: "catalog".into(),
19129 wit: "wasi:http/proxy".into(),
19130 endpoint: Some("/lookup".into()),
19131 subject: None,
19132 slot: None,
19133 };
19134 let ep = c.endpoint().expect("Some arm");
19135 let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
19136 assert_eq!(
19137 ep.as_ptr(),
19138 storage_slice.as_ptr(),
19139 "WitContract::endpoint must borrow from the .endpoint \
19140 String's backing storage — a fresh allocation here means \
19141 the accessor no longer names the substrate-primitive typed \
19142 dispatch and every downstream consumer would silently \
19143 carry a detached copy",
19144 );
19145 assert_eq!(
19146 ep.len(),
19147 storage_slice.len(),
19148 "WitContract::endpoint and .endpoint.as_deref() must byte-\
19149 equal in length as well as in address",
19150 );
19151 }
19152
19153 #[test]
19154 fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
19155 // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
19156 // pin: [`WitContract::subject`] must return the `:contratos
19157 // :subject` field byte-for-byte, borrowed from the typed slot's
19158 // own `Option<String>` storage. Peer of the sibling per-`:contratos`
19159 // [`WitContract::endpoint`] (7020470) accessor pin on the M3
19160 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
19161 // optional-scalar axis — same "the substrate-primitive accessor
19162 // must byte-equal the raw field access verbatim across every
19163 // author-declared value" discipline extended to the pub-sub arm.
19164 // Pins against a future silent detour that re-canonicalized the
19165 // subject (an accidental `.to_lowercase()` normalization that
19166 // didn't reach the peer field-access site at the dedup key, a
19167 // per-CR fully-qualified prefix rewrite the operator authors on
19168 // one consumer without the other, or an M4 typed-subject-template
19169 // `Display` re-canonicalization that silently drifted the printer
19170 // output from the source `caixa.lisp`). Four values sweep the
19171 // NATS accept-set every pub-sub author-declared subject lands on
19172 // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
19173 for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
19174 let c = WitContract {
19175 de: "cart".into(),
19176 para: "notifier".into(),
19177 wit: "nats:pub-sub".into(),
19178 endpoint: None,
19179 subject: Some(subject.into()),
19180 slot: None,
19181 };
19182 assert_eq!(
19183 c.subject(),
19184 Some(subject),
19185 "WitContract::subject must return :contratos :subject \
19186 verbatim (got {:?}, expected Some({subject:?}))",
19187 c.subject(),
19188 );
19189 assert_eq!(
19190 c.subject(),
19191 c.subject.as_deref(),
19192 "WitContract::subject must byte-equal the .subject \
19193 field's `.as_deref()` projection",
19194 );
19195 }
19196 }
19197
19198 #[test]
19199 fn wit_contract_subject_none_when_field_is_none() {
19200 // The absent-`:subject` arm of the per-`:contratos` pub-sub-
19201 // shaped payload-carrier accessor pin: when the typed slot is
19202 // absent — the canonical shape under a non-pub-sub `:wit` world
19203 // per the [`WitContract::target`]-enforced shape ↔ target
19204 // partition ([`WitTarget::Http`] carries `:endpoint`,
19205 // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
19206 // carries none) — [`WitContract::subject`] must return `None`.
19207 // Pins against a future silent detour that projected the absent
19208 // slot to a `Some("")` empty-string default (the canonical
19209 // `Option<String>` → `String` collapse footgun the sibling M2
19210 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
19211 // emptiness predicates already guard on the peer M2 typed-slot
19212 // surfaces), a `Some("None")` stringified-None round-trip, or a
19213 // `Some` arm whose contents were derived from a sibling slot (an
19214 // accidental fallback to the `:endpoint` / `:slot` payload that
19215 // read the HTTP / store payload into the subject axis). Three
19216 // contracts sweep the accept-set every non-pub-sub `:wit` world
19217 // lands on — HTTP proxy, key/value store, and payload-less
19218 // capability.
19219 for (wit, endpoint, slot) in [
19220 ("wasi:http/proxy", Some("/lookup"), None),
19221 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
19222 ("wasi:cli/environment", None, None),
19223 ] {
19224 let c = WitContract {
19225 de: "cart".into(),
19226 para: "downstream".into(),
19227 wit: wit.into(),
19228 endpoint: endpoint.map(str::to_string),
19229 subject: None,
19230 slot: slot.map(str::to_string),
19231 };
19232 assert!(
19233 c.subject().is_none(),
19234 "WitContract::subject must return None when the typed \
19235 slot is absent under :wit {wit:?} (got {:?})",
19236 c.subject(),
19237 );
19238 assert_eq!(
19239 c.subject(),
19240 c.subject.as_deref(),
19241 "WitContract::subject must byte-equal the .subject \
19242 field's `.as_deref()` projection in the absent arm",
19243 );
19244 }
19245 }
19246
19247 #[test]
19248 fn wit_contract_subject_borrows_from_subject_storage() {
19249 // The borrow-not-copy pin: [`WitContract::subject`] must return
19250 // an `Option<&str>` whose `Some` arm borrows from the typed
19251 // slot's own [`String`] storage — same-address invariant with
19252 // `c.subject.as_deref().unwrap()`. Pins against a future silent
19253 // detour that allocated a fresh `String`
19254 // (`self.subject.clone().map(...)` in the body would type-check
19255 // but silently drop the borrow, and every downstream consumer
19256 // that assumed the returned slice outlives `&self` would break
19257 // on a stale-reference use-after-free — the [`WitContract::target`]
19258 // PubSub-arm payload extraction rebinds the returned
19259 // `Option<&str>` through `.ok_or_else(...)` and threads the
19260 // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
19261 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
19262 // [`ContratoIdentity`] dedup key threads the returned
19263 // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
19264 // from the WitContract's own storage and each would silently
19265 // misbehave if this accessor produced a detached copy). Peer of
19266 // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
19267 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
19268 // shaped optional-scalar axis — second extension of the
19269 // `Option<&str>` borrow-not-copy discipline onto the
19270 // per-`:contratos` payload-carrier family, this time on the
19271 // pub-sub arm.
19272 let c = WitContract {
19273 de: "cart".into(),
19274 para: "notifier".into(),
19275 wit: "nats:pub-sub".into(),
19276 endpoint: None,
19277 subject: Some("orders.paid".into()),
19278 slot: None,
19279 };
19280 let sub = c.subject().expect("Some arm");
19281 let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
19282 assert_eq!(
19283 sub.as_ptr(),
19284 storage_slice.as_ptr(),
19285 "WitContract::subject must borrow from the .subject \
19286 String's backing storage — a fresh allocation here means \
19287 the accessor no longer names the substrate-primitive typed \
19288 dispatch and every downstream consumer would silently \
19289 carry a detached copy",
19290 );
19291 assert_eq!(
19292 sub.len(),
19293 storage_slice.len(),
19294 "WitContract::subject and .subject.as_deref() must byte-\
19295 equal in length as well as in address",
19296 );
19297 }
19298
19299 #[test]
19300 fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
19301 // The canonical per-`:contratos` key/value-store-shaped
19302 // `:slot`-scalar pin: [`WitContract::slot`] must return the
19303 // `:contratos :slot` field byte-for-byte, borrowed from the
19304 // typed slot's own `Option<String>` storage. Peer of the
19305 // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
19306 // [`WitContract::subject`] (90de675) accessor pins on the M3
19307 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
19308 // optional-scalar axis — same "the substrate-primitive
19309 // accessor must byte-equal the raw field access verbatim
19310 // across every author-declared value" discipline extended to
19311 // the store arm. Pins against a future silent detour that
19312 // re-canonicalized the slot template (an accidental
19313 // `.to_lowercase()` bucket-prefix normalization that didn't
19314 // reach the peer field-access site at the dedup key, a per-CR
19315 // fully-qualified prefix rewrite the operator authors on one
19316 // consumer without the other, or an M4 typed-key-template
19317 // `Display` re-canonicalization that silently drifted the
19318 // printer output from the source `caixa.lisp`). Four values
19319 // sweep the wasi:keyvalue accept-set every store-shaped
19320 // author-declared slot lands on (flat bucket, single-param
19321 // template, multi-param template, nested-hierarchy template).
19322 for slot in [
19323 "sessions",
19324 "carts/{cart_id}",
19325 "orders/{tenant}/{order_id}",
19326 "cache/tenant-a/orders/{id}",
19327 ] {
19328 let c = WitContract {
19329 de: "cart".into(),
19330 para: "kv".into(),
19331 wit: "wasi:keyvalue/store".into(),
19332 endpoint: None,
19333 subject: None,
19334 slot: Some(slot.into()),
19335 };
19336 assert_eq!(
19337 c.slot(),
19338 Some(slot),
19339 "WitContract::slot must return :contratos :slot \
19340 verbatim (got {:?}, expected Some({slot:?}))",
19341 c.slot(),
19342 );
19343 assert_eq!(
19344 c.slot(),
19345 c.slot.as_deref(),
19346 "WitContract::slot must byte-equal the .slot field's \
19347 `.as_deref()` projection",
19348 );
19349 }
19350 }
19351
19352 #[test]
19353 fn wit_contract_slot_none_when_field_is_none() {
19354 // The absent-`:slot` arm of the per-`:contratos` store-shaped
19355 // payload-carrier accessor pin: when the typed slot is absent —
19356 // the canonical shape under a non-store `:wit` world per the
19357 // [`WitContract::target`]-enforced shape ↔ target partition
19358 // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
19359 // carries `:subject`, [`WitTarget::Capability`] carries none) —
19360 // [`WitContract::slot`] must return `None`. Pins against a
19361 // future silent detour that projected the absent slot to a
19362 // `Some("")` empty-string default (the canonical
19363 // `Option<String>` → `String` collapse footgun the sibling M2
19364 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
19365 // emptiness predicates already guard on the peer M2 typed-slot
19366 // surfaces), a `Some("None")` stringified-None round-trip, or
19367 // a `Some` arm whose contents were derived from a sibling
19368 // slot (an accidental fallback to the `:endpoint` / `:subject`
19369 // payload that read the HTTP / pub-sub payload into the store
19370 // axis). Three contracts sweep the accept-set every non-store
19371 // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
19372 // payload-less capability.
19373 for (wit, endpoint, subject) in [
19374 ("wasi:http/proxy", Some("/lookup"), None),
19375 ("nats:pub-sub", None, Some("orders.paid")),
19376 ("wasi:cli/environment", None, None),
19377 ] {
19378 let c = WitContract {
19379 de: "cart".into(),
19380 para: "downstream".into(),
19381 wit: wit.into(),
19382 endpoint: endpoint.map(str::to_string),
19383 subject: subject.map(str::to_string),
19384 slot: None,
19385 };
19386 assert!(
19387 c.slot().is_none(),
19388 "WitContract::slot must return None when the typed \
19389 slot is absent under :wit {wit:?} (got {:?})",
19390 c.slot(),
19391 );
19392 assert_eq!(
19393 c.slot(),
19394 c.slot.as_deref(),
19395 "WitContract::slot must byte-equal the .slot field's \
19396 `.as_deref()` projection in the absent arm",
19397 );
19398 }
19399 }
19400
19401 #[test]
19402 fn wit_contract_slot_borrows_from_slot_storage() {
19403 // The borrow-not-copy pin: [`WitContract::slot`] must return
19404 // an `Option<&str>` whose `Some` arm borrows from the typed
19405 // slot's own [`String`] storage — same-address invariant with
19406 // `c.slot.as_deref().unwrap()`. Pins against a future silent
19407 // detour that allocated a fresh `String`
19408 // (`self.slot.clone().map(...)` in the body would type-check
19409 // but silently drop the borrow, and every downstream consumer
19410 // that assumed the returned slice outlives `&self` would
19411 // break on a stale-reference use-after-free — the
19412 // [`WitContract::target`] Store-arm payload extraction rebinds
19413 // the returned `Option<&str>` through `.ok_or_else(...)` and
19414 // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
19415 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
19416 // [`ContratoIdentity`] dedup key threads the returned
19417 // `Option<&str>` into the six-tuple's store arm — each borrow
19418 // from the WitContract's own storage and each would silently
19419 // misbehave if this accessor produced a detached copy). Peer
19420 // of the sibling per-`:contratos` [`WitContract::endpoint`]
19421 // (7020470) / [`WitContract::subject`] (90de675)
19422 // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
19423 // shaped optional-scalar axis — third and final extension of
19424 // the `Option<&str>` borrow-not-copy discipline onto the
19425 // per-`:contratos` payload-carrier family, this time on the
19426 // store arm.
19427 let c = WitContract {
19428 de: "cart".into(),
19429 para: "kv".into(),
19430 wit: "wasi:keyvalue/store".into(),
19431 endpoint: None,
19432 subject: None,
19433 slot: Some("carts/{cart_id}".into()),
19434 };
19435 let slot = c.slot().expect("Some arm");
19436 let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
19437 assert_eq!(
19438 slot.as_ptr(),
19439 storage_slice.as_ptr(),
19440 "WitContract::slot must borrow from the .slot String's \
19441 backing storage — a fresh allocation here means the \
19442 accessor no longer names the substrate-primitive typed \
19443 dispatch and every downstream consumer would silently \
19444 carry a detached copy",
19445 );
19446 assert_eq!(
19447 slot.len(),
19448 storage_slice.len(),
19449 "WitContract::slot and .slot.as_deref() must byte-equal \
19450 in length as well as in address",
19451 );
19452 }
19453
19454 #[test]
19455 fn membro_nome_returns_caixa_byte_equal_across_permutations() {
19456 // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
19457 // [`Membro::nome`] must return the `:membros :caixa` field
19458 // byte-for-byte, borrowed from the typed slot's own [`String`]
19459 // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
19460 // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19461 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
19462 // slot-atom scalar-value axes — same "the substrate-primitive
19463 // accessor must byte-equal the raw field access verbatim across
19464 // every author-declared value" discipline extended to the
19465 // per-`:membros` member-identity arm. Pins against a future
19466 // silent detour that re-normalized the member identity (an
19467 // accidental `.to_lowercase()` — every `:membros :caixa` is
19468 // validated as a DNS-1123 label upstream via
19469 // [`validate_membro_caixa`], so any re-normalization is
19470 // redundant + a drift surface between the validator and the
19471 // accessor), a namespace-prefix rewrite (an accidental
19472 // `format!("{namespace}/{caixa}")` per-CR fully-qualified
19473 // rewrite that didn't land on the peer axes), or a per-cluster
19474 // alias stamp the operator authors on one consumer without the
19475 // other. Four values sweep the accept-set the DNS-1123 gate
19476 // upstream admits (short single-word / dashed / v-suffixed
19477 // member names).
19478 for name in ["cart", "checkout", "catalog", "orders-v2"] {
19479 let m = Membro {
19480 caixa: name.into(),
19481 versao: "^0.1".into(),
19482 };
19483 assert_eq!(
19484 m.nome(),
19485 name,
19486 "Membro::nome must return :membros :caixa verbatim \
19487 (got {:?}, expected {name:?})",
19488 m.nome(),
19489 );
19490 assert_eq!(
19491 m.nome(),
19492 m.caixa.as_str(),
19493 "Membro::nome must byte-equal the .caixa field access",
19494 );
19495 }
19496 }
19497
19498 #[test]
19499 fn membro_nome_borrows_from_caixa_storage() {
19500 // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
19501 // slice that borrows from the typed slot's own [`String`]
19502 // storage — same-address invariant with `m.caixa.as_str()`. Pins
19503 // against a future silent detour that allocated a fresh `String`
19504 // (`self.caixa.clone()` in the body would type-check but
19505 // silently drop the borrow, and every downstream consumer that
19506 // assumed the returned slice outlives `&self` would break on a
19507 // stale-reference use-after-free — the `HashSet<&str>` collector
19508 // at [`AplicacaoSpec::validate`]'s `names` seed, the
19509 // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
19510 // [`AplicacaoSpec::detect_sync_cycles`], the
19511 // [`crate::render::insert_first_seen`] dedup key at
19512 // [`AplicacaoSpec::validate_membros`] — each borrow from the
19513 // Membro's own storage and each would silently misbehave if
19514 // this accessor produced a detached copy). Peer of the sibling
19515 // per-`:contratos` [`WitContract::source`] /
19516 // [`WitContract::destination`] and per-`:entrada`
19517 // [`Entrada::destination`] borrow-invariant pins on the mesh-
19518 // slot-atom scalar-value axes.
19519 let m = Membro {
19520 caixa: "checkout".into(),
19521 versao: "^0.1".into(),
19522 };
19523 let name = m.nome();
19524 let caixa_slice = m.caixa.as_str();
19525 assert_eq!(
19526 name.as_ptr(),
19527 caixa_slice.as_ptr(),
19528 "Membro::nome must borrow from the .caixa String's backing \
19529 storage — a fresh allocation here means the accessor no \
19530 longer names the substrate-primitive typed dispatch and \
19531 every downstream consumer would silently carry a detached \
19532 copy",
19533 );
19534 assert_eq!(
19535 name.len(),
19536 caixa_slice.len(),
19537 "Membro::nome and .caixa.as_str() must byte-equal in length \
19538 as well as in address",
19539 );
19540 }
19541
19542 #[test]
19543 fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
19544 // The canonical per-`:membros` member-`:versao`-scalar pin:
19545 // [`Membro::versao_requirement`] must return the
19546 // `:membros :versao` field byte-for-byte, borrowed from the typed
19547 // slot's own [`String`] storage. Sibling of the peer
19548 // `membro_nome_returns_caixa_byte_equal_across_permutations`
19549 // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
19550 // — same "the substrate-primitive accessor must byte-equal the
19551 // raw field access verbatim across every author-declared value"
19552 // discipline extended to the per-`:membros` member-`:versao`
19553 // requirement-string arm. Pins against a future silent detour
19554 // that re-canonicalized the requirement (an accidental
19555 // `.to_string()` via [`parse_requirement`] → [`Display`] round-
19556 // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
19557 // drifted the printer output away from the source `caixa.lisp`,
19558 // an accidental whitespace trim on `"^ 0.1"` that no consumer
19559 // ever produced from the field-access side, an accidental
19560 // per-cluster lacre-projected concrete-version rewrite that
19561 // didn't land on the peer field-access sites). Five values sweep
19562 // the accept-set the shared
19563 // [`crate::render::require_valid_versao_requirement`] gate
19564 // admits (caret / tilde / exact / wildcard / bare-major).
19565 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
19566 let m = Membro {
19567 caixa: "cart".into(),
19568 versao: req.into(),
19569 };
19570 assert_eq!(
19571 m.versao_requirement(),
19572 req,
19573 "Membro::versao_requirement must return :membros :versao \
19574 verbatim (got {:?}, expected {req:?})",
19575 m.versao_requirement(),
19576 );
19577 assert_eq!(
19578 m.versao_requirement(),
19579 m.versao.as_str(),
19580 "Membro::versao_requirement must byte-equal the .versao \
19581 field access",
19582 );
19583 }
19584 }
19585
19586 #[test]
19587 fn membro_versao_requirement_borrows_from_versao_storage() {
19588 // The borrow-not-copy pin: [`Membro::versao_requirement`] must
19589 // return a `&str` slice that borrows from the typed slot's own
19590 // [`String`] storage — same-address invariant with
19591 // `m.versao.as_str()`. Pins against a future silent detour that
19592 // allocated a fresh `String` (`self.versao.clone()` in the body
19593 // would type-check but silently drop the borrow, and every
19594 // downstream consumer that assumed the returned slice outlives
19595 // `&self` would break on a stale-reference use-after-free). Peer
19596 // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
19597 // per-`:contratos` [`WitContract::source`] /
19598 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19599 // [`Entrada::destination`] (6db982c) borrow-invariant pins on
19600 // the mesh-slot-atom scalar-value axes.
19601 let m = Membro {
19602 caixa: "checkout".into(),
19603 versao: "^0.1".into(),
19604 };
19605 let req = m.versao_requirement();
19606 let versao_slice = m.versao.as_str();
19607 assert_eq!(
19608 req.as_ptr(),
19609 versao_slice.as_ptr(),
19610 "Membro::versao_requirement must borrow from the .versao \
19611 String's backing storage — a fresh allocation here means \
19612 the accessor no longer names the substrate-primitive typed \
19613 dispatch and every downstream consumer would silently carry \
19614 a detached copy",
19615 );
19616 assert_eq!(
19617 req.len(),
19618 versao_slice.len(),
19619 "Membro::versao_requirement and .versao.as_str() must byte-\
19620 equal in length as well as in address",
19621 );
19622 }
19623
19624 #[test]
19625 fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
19626 // Sibling-pair invariant pin composing both per-`:membros`
19627 // substrate-primitive typed dispatches — [`Membro::nome`]
19628 // (4a32abf) and [`Membro::versao_requirement`] — at the joint
19629 // `(nome(), versao_requirement())` call shape every renderer
19630 // that fans on per-member identity + version pin keys off. The
19631 // invariant, evaluated per-member:
19632 //
19633 // (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
19634 //
19635 // Closes the last unlifted per-`:membros` scalar axis — every
19636 // downstream consumer that reads the pair now routes through
19637 // exactly two typed dispatches on the substrate primitive, not
19638 // one typed + one open-coded field access. A future refactor
19639 // that silently split either accessor's projection (an
19640 // accidental `nome()` namespace-prefix rewrite that didn't
19641 // reach the peer, an accidental `versao_requirement()` lacre-
19642 // projected concrete-version rewrite that didn't land on the
19643 // `nome()` peer) surfaces at caixa-core build time. Peer of the
19644 // sibling per-`:entrada` `(hostname(), destination())` and
19645 // per-`:contratos` `(source(), destination())` pair invariants
19646 // on the mesh-slot-atom scalar-value axes.
19647 for (caixa, versao) in [
19648 ("cart", "^0.1"),
19649 ("checkout", "~0.1.2"),
19650 ("catalog", "0.1.0"),
19651 ("orders-v2", "*"),
19652 ] {
19653 let m = Membro {
19654 caixa: caixa.into(),
19655 versao: versao.into(),
19656 };
19657 assert_eq!(
19658 (m.nome(), m.versao_requirement()),
19659 (m.caixa.as_str(), m.versao.as_str()),
19660 "(Membro::nome, Membro::versao_requirement) must project \
19661 (.caixa, .versao) verbatim across every author-declared \
19662 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
19663 m.nome(),
19664 m.versao_requirement(),
19665 );
19666 }
19667 }
19668
19669 #[test]
19670 fn validate_membros_empty_gate_routes_through_nome_accessor() {
19671 // Composition pin: [`AplicacaoSpec::validate_membros`]'s
19672 // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
19673 // not the raw `.caixa` field access. Structurally: setting
19674 // ONLY the `.caixa` field to `""` on an otherwise-well-formed
19675 // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
19676 // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
19677 // (i.e. the empty string) — so the emptiness predicate the
19678 // refusal arm reaches under is the accessor-projected value,
19679 // not a peer field that would silently drift under a future
19680 // accessor-side rewrite.
19681 //
19682 // Pins against a future silent detour that (a) re-derived the
19683 // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
19684 // instead of `self.nome().is_empty()`, silently disagreeing with
19685 // every peer consumer (the `validate_membro_caixa(m.nome())`
19686 // call one line below, the dedup-key `insert_first_seen(&mut
19687 // seen, m.nome(), …)` two lines below, the emit-side per-
19688 // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
19689 // (b) accessor-side introduced a per-tenant alias arm the
19690 // caller was unaware of, silently rewriting an author-declared
19691 // `:caixa "checkout"` to `""` — the raw-field-access gate
19692 // would fail-open while the accessor-routed peer consumers
19693 // would fail-closed, splitting the diagnostic from the actual
19694 // failure surface.
19695 //
19696 // Peer of the sibling
19697 // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
19698 // (c0110f1) composition pin — same "the shape-gate predicate
19699 // must route through the substrate-primitive typed dispatch"
19700 // discipline extended onto the per-`:membros` empty-`:caixa`
19701 // refusal-arm axis. Closes the last unlifted `.caixa` production-
19702 // code read site on `Membro` — after this converge every
19703 // caixa-core `.caixa` field access outside the accessor's own
19704 // body is either a test-side field-setter (in-module tests
19705 // constructing invalid-shape inputs) or a doc-comment reference.
19706 let mut s = three_member_spec();
19707 s.membros[1].caixa = String::new();
19708 assert!(
19709 s.membros[1].nome().is_empty(),
19710 "Membro::nome must byte-equal the .caixa field access — an \
19711 accessor-side detour that no longer projects the raw field \
19712 would silently split this drift-detection test from the \
19713 validate() refusal arm",
19714 );
19715 assert_eq!(
19716 s.membros[1].nome(),
19717 s.membros[1].caixa.as_str(),
19718 "Membro::nome and .caixa.as_str() must byte-equal on an \
19719 empty-`:caixa` entry — the emptiness gate keys off the \
19720 accessor by construction",
19721 );
19722 assert_eq!(
19723 s.validate().unwrap_err(),
19724 AplicacaoError::MembroCaixaEmpty,
19725 "validate_membros' emptiness gate must fire MembroCaixaEmpty \
19726 on an entry whose accessor-projected `nome()` is empty",
19727 );
19728 }
19729
19730 #[test]
19731 fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
19732 // The canonical per-`:placement` Akka-cluster-sharding
19733 // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
19734 // the `:placement :shard-key` field byte-for-byte, borrowed
19735 // from the typed slot's own `Option<String>` storage. Peer of
19736 // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
19737 // per-`:contratos` [`WitContract::source`] /
19738 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19739 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
19740 // slot-atom scalar-value axes — same "the substrate-primitive
19741 // accessor must byte-equal the raw field access verbatim across
19742 // every author-declared value" discipline extended to the
19743 // per-`:placement` Akka-cluster-sharding key extractor arm.
19744 // Pins against a future silent detour that re-normalized the
19745 // key (an accidental `.to_lowercase()` — every non-empty
19746 // `:shard-key` is validated as a printable-ASCII single-token
19747 // reference upstream via [`validate_placement_shard_key`], so
19748 // any re-normalization is redundant + a drift surface between
19749 // the validator and the accessor), a per-cluster alias rewrite
19750 // the operator authors on one consumer without the other, or an
19751 // accidental variable-prefix strip (`$tenantId` → `tenantId`)
19752 // that didn't land on the peer field-access sites. Four values
19753 // sweep the accept-set the shape gate admits — bare identifier,
19754 // `$`-prefixed variable, dotted path, `${}`-quoted variable —
19755 // the four canonical Akka-style entity-id extractor shapes the
19756 // future M4 cluster-sharding reconciler hashes.
19757 for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
19758 let p = Placement {
19759 estrategia: PlacementStrategy::Sharded,
19760 clusters: vec!["rio".into()],
19761 affinity: None,
19762 shard_key: Some(key.into()),
19763 };
19764 assert_eq!(
19765 p.shard_key(),
19766 Some(key),
19767 "Placement::shard_key must return :placement :shard-key \
19768 verbatim (got {:?}, expected Some({key:?}))",
19769 p.shard_key(),
19770 );
19771 assert_eq!(
19772 p.shard_key(),
19773 p.shard_key.as_deref(),
19774 "Placement::shard_key must byte-equal the .shard_key \
19775 field's `.as_deref()` projection",
19776 );
19777 }
19778 }
19779
19780 #[test]
19781 fn placement_shard_key_none_when_field_is_none() {
19782 // The absent-`:shard-key` arm of the per-`:placement`
19783 // Akka-cluster-sharding accessor pin: when the typed slot is
19784 // absent — the canonical shape under `:estrategia Replicated` /
19785 // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
19786 // enforced `shard_key.is_some() == matches!(estrategia,
19787 // Sharded)` partition — [`Placement::shard_key`] must return
19788 // `None`. Pins against a future silent detour that projected
19789 // the absent slot to a `Some("")` empty-string default (the
19790 // canonical `Option<String>` → `String` collapse footgun the
19791 // sibling M2 [`crate::LimitsSpec::is_empty`] /
19792 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
19793 // already guard on the peer M2 typed-slot surfaces), a
19794 // `Some("None")` stringified-None round-trip, or a `Some` arm
19795 // whose contents were derived from a sibling slot (an
19796 // accidental fallback to `estrategia.as_str()` that read the
19797 // strategy discriminator into the key axis). Two placements
19798 // sweep the accept-set every `validate`-passing non-`Sharded`
19799 // shape lands on — `Replicated` (Erlang/OTP distributed-app
19800 // takeover) and `SingleNode` (single-node hosting).
19801 for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
19802 let p = Placement {
19803 estrategia,
19804 clusters: vec!["rio".into()],
19805 affinity: None,
19806 shard_key: None,
19807 };
19808 assert!(
19809 p.shard_key().is_none(),
19810 "Placement::shard_key must return None when the typed \
19811 slot is absent under :estrategia {estrategia:?} (got {:?})",
19812 p.shard_key(),
19813 );
19814 assert_eq!(
19815 p.shard_key(),
19816 p.shard_key.as_deref(),
19817 "Placement::shard_key must byte-equal the .shard_key \
19818 field's `.as_deref()` projection in the absent arm",
19819 );
19820 }
19821 }
19822
19823 #[test]
19824 fn placement_shard_key_borrows_from_shard_key_storage() {
19825 // The borrow-not-copy pin: [`Placement::shard_key`] must return
19826 // an `Option<&str>` whose `Some` arm borrows from the typed
19827 // slot's own [`String`] storage — same-address invariant with
19828 // `p.shard_key.as_deref().unwrap()`. Pins against a future
19829 // silent detour that allocated a fresh `String`
19830 // (`self.shard_key.clone().map(...)` in the body would type-
19831 // check but silently drop the borrow, and every downstream
19832 // consumer that assumed the returned slice outlives `&self`
19833 // would break on a stale-reference use-after-free — the
19834 // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
19835 // gate's `Some(k)`-bound match arm reads `k: &str` under the
19836 // accessor's return type and would silently misbehave if this
19837 // accessor produced a detached copy). Peer of the sibling
19838 // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
19839 // [`WitContract::source`] / [`WitContract::destination`]
19840 // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
19841 // (6db982c) borrow-invariant pins on the mesh-slot-atom
19842 // scalar-value axes — first extension of the discipline onto
19843 // an `Option<String>`-shaped optional-scalar axis.
19844 let p = Placement {
19845 estrategia: PlacementStrategy::Sharded,
19846 clusters: vec!["rio".into()],
19847 affinity: None,
19848 shard_key: Some("tenantId".into()),
19849 };
19850 let key = p.shard_key().expect("Some arm");
19851 let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
19852 assert_eq!(
19853 key.as_ptr(),
19854 storage_slice.as_ptr(),
19855 "Placement::shard_key must borrow from the .shard_key \
19856 String's backing storage — a fresh allocation here means \
19857 the accessor no longer names the substrate-primitive typed \
19858 dispatch and every downstream consumer would silently \
19859 carry a detached copy",
19860 );
19861 assert_eq!(
19862 key.len(),
19863 storage_slice.len(),
19864 "Placement::shard_key and .shard_key.as_deref() must byte-\
19865 equal in length as well as in address",
19866 );
19867 }
19868
19869 #[test]
19870 fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
19871 // The canonical per-`:placement` M3-Adaptive-compression-hint
19872 // scalar pin: [`Placement::affinity`] must return the
19873 // `:placement :affinity` field byte-for-byte, borrowed from the
19874 // typed slot's own `Option<String>` storage. Peer of the sibling
19875 // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
19876 // pin on the sibling `Option<&str>` optional-scalar axis — same
19877 // "the substrate-primitive accessor must byte-equal the raw
19878 // field access verbatim across every author-declared value"
19879 // discipline extended to the peer per-`:placement` M3-Adaptive-
19880 // compression-hint arm. Pins against a future silent detour
19881 // that re-normalized the hint (an accidental `.to_lowercase()`
19882 // — every `:affinity` is already validated as a DNS-1123 label
19883 // upstream via [`validate_placement_affinity`], so any re-
19884 // normalization is redundant + a drift surface between the
19885 // validator and the accessor), a per-cluster alias rewrite the
19886 // operator authors on one consumer without the other, or an
19887 // accidental hint-family collapse (`low-latency` → `latency`
19888 // that dropped the qualifier prefix). Four values sweep the
19889 // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
19890 // canonical adaptive-compression-weight biases the future M4
19891 // placement engine reads.
19892 for hint in [
19893 "data-locality",
19894 "low-latency",
19895 "high-throughput",
19896 "cost-optimized",
19897 ] {
19898 let p = Placement {
19899 estrategia: PlacementStrategy::Replicated,
19900 clusters: vec!["rio".into()],
19901 affinity: Some(hint.into()),
19902 shard_key: None,
19903 };
19904 assert_eq!(
19905 p.affinity(),
19906 Some(hint),
19907 "Placement::affinity must return :placement :affinity \
19908 verbatim (got {:?}, expected Some({hint:?}))",
19909 p.affinity(),
19910 );
19911 assert_eq!(
19912 p.affinity(),
19913 p.affinity.as_deref(),
19914 "Placement::affinity must byte-equal the .affinity \
19915 field's `.as_deref()` projection",
19916 );
19917 }
19918 }
19919
19920 #[test]
19921 fn placement_affinity_none_when_field_is_none() {
19922 // The absent-`:affinity` arm of the per-`:placement`
19923 // M3-Adaptive-compression-hint accessor pin: when the typed
19924 // slot is absent — the canonical shape of an Aplicacao that
19925 // leaves the compression weighting up to the placement engine's
19926 // cluster-default arm — [`Placement::affinity`] must return
19927 // `None`. Pins against a future silent detour that projected
19928 // the absent slot to a `Some("")` empty-string default (the
19929 // canonical `Option<String>` → `String` collapse footgun the
19930 // sibling M2 [`crate::LimitsSpec::is_empty`] /
19931 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
19932 // already guard on the peer M2 typed-slot surfaces), a
19933 // `Some("None")` stringified-None round-trip, a `Some` arm
19934 // whose contents were derived from a sibling slot (an
19935 // accidental fallback to `estrategia.as_str()` that read the
19936 // strategy discriminator into the hint axis), or a
19937 // `Some("default")` implicit-default that would silently biases
19938 // the routing without the author having written one. Three
19939 // placements sweep the accept-set every `validate`-passing
19940 // `:affinity None` shape lands on — one per PlacementStrategy
19941 // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
19942 // with a shard-key), since `:affinity` is orthogonal to
19943 // `:estrategia` in the typed grammar.
19944 for (estrategia, shard_key) in [
19945 (PlacementStrategy::SingleNode, None),
19946 (PlacementStrategy::Replicated, None),
19947 (PlacementStrategy::Sharded, Some("tenantId".to_string())),
19948 ] {
19949 let p = Placement {
19950 estrategia,
19951 clusters: vec!["rio".into()],
19952 affinity: None,
19953 shard_key,
19954 };
19955 assert!(
19956 p.affinity().is_none(),
19957 "Placement::affinity must return None when the typed \
19958 slot is absent under :estrategia {estrategia:?} (got {:?})",
19959 p.affinity(),
19960 );
19961 assert_eq!(
19962 p.affinity(),
19963 p.affinity.as_deref(),
19964 "Placement::affinity must byte-equal the .affinity \
19965 field's `.as_deref()` projection in the absent arm",
19966 );
19967 }
19968 }
19969
19970 #[test]
19971 fn placement_affinity_borrows_from_affinity_storage() {
19972 // The borrow-not-copy pin: [`Placement::affinity`] must return
19973 // an `Option<&str>` whose `Some` arm borrows from the typed
19974 // slot's own [`String`] storage — same-address invariant with
19975 // `p.affinity.as_deref().unwrap()`. Pins against a future
19976 // silent detour that allocated a fresh `String`
19977 // (`self.affinity.clone().map(...)` in the body would type-
19978 // check but silently drop the borrow, and every downstream
19979 // consumer that assumed the returned slice outlives `&self`
19980 // would break on a stale-reference use-after-free — the
19981 // [`AplicacaoSpec::validate_placement`] per-hint value-shape
19982 // gate reads the accessor's `&str` return through the
19983 // [`validate_placement_affinity`] `&str` parameter and would
19984 // silently misbehave if this accessor produced a detached
19985 // copy). Peer of the sibling per-`:placement`
19986 // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
19987 // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
19988 // extends the discipline onto the sibling per-`:placement`
19989 // M3-Adaptive-compression-hint arm.
19990 let p = Placement {
19991 estrategia: PlacementStrategy::Replicated,
19992 clusters: vec!["rio".into()],
19993 affinity: Some("data-locality".into()),
19994 shard_key: None,
19995 };
19996 let hint = p.affinity().expect("Some arm");
19997 let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
19998 assert_eq!(
19999 hint.as_ptr(),
20000 storage_slice.as_ptr(),
20001 "Placement::affinity must borrow from the .affinity \
20002 String's backing storage — a fresh allocation here means \
20003 the accessor no longer names the substrate-primitive typed \
20004 dispatch and every downstream consumer would silently \
20005 carry a detached copy",
20006 );
20007 assert_eq!(
20008 hint.len(),
20009 storage_slice.len(),
20010 "Placement::affinity and .affinity.as_deref() must byte-\
20011 equal in length as well as in address",
20012 );
20013 }
20014
20015 #[test]
20016 fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
20017 // The canonical per-`:placement` distribution-strategy-scalar
20018 // pin: [`Placement::estrategia`] must return the `:placement
20019 // :estrategia` field verbatim as a [`PlacementStrategy`],
20020 // `Copy`-projected from the typed slot's own `PlacementStrategy`
20021 // storage across every variant in the closed accept-set
20022 // (`SingleNode` — Erlang/OTP distributed-app takeover;
20023 // `Replicated` — active-active across every named cluster;
20024 // `Sharded` — Akka-style hash-keyed entity distribution). Pins
20025 // against a future silent detour that re-derived the strategy
20026 // from a peer axis (an accidental fallback to
20027 // `if shard_key.is_some() { Sharded } else { Replicated }`
20028 // collapse that read the shard-key axis into the strategy
20029 // discriminator), a variant remap the operator authors on one
20030 // consumer without the other, or a stale-derive detour that
20031 // substituted [`PlacementStrategy::default`] when the field
20032 // held any explicit variant (which would silently collapse the
20033 // distinction between "author explicitly declared `:estrategia
20034 // Replicated`" and "author omitted the slot and inherited the
20035 // default" the future per-cluster override slot depends on).
20036 // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
20037 // pin on the `Copy`-return `u16` scalar axis — same "the
20038 // substrate-primitive accessor must byte-equal the raw field
20039 // access verbatim across every author-declared value" discipline
20040 // extended onto the per-`:placement` distribution-strategy
20041 // `Copy`-composite-enum scalar axis.
20042 for estrategia in [
20043 PlacementStrategy::SingleNode,
20044 PlacementStrategy::Replicated,
20045 PlacementStrategy::Sharded,
20046 ] {
20047 let shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
20048 let p = Placement {
20049 estrategia,
20050 clusters: vec!["rio".into()],
20051 affinity: None,
20052 shard_key,
20053 };
20054 assert_eq!(
20055 p.estrategia(),
20056 estrategia,
20057 "Placement::estrategia must return :placement :estrategia \
20058 verbatim (got {:?}, expected {estrategia:?})",
20059 p.estrategia(),
20060 );
20061 assert_eq!(
20062 p.estrategia(),
20063 p.estrategia,
20064 "Placement::estrategia accessor and .estrategia field \
20065 access must byte-equal — the accessor is the substrate-\
20066 primitive typed dispatch every downstream distribution-\
20067 strategy consumer must route through",
20068 );
20069 }
20070 }
20071
20072 #[test]
20073 fn validate_placement_reads_through_lifted_estrategia_accessor() {
20074 // Three-consumer coherence pin: the
20075 // [`AplicacaoSpec::validate_placement`]
20076 // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
20077 // `estrategia:` field (which reads through
20078 // [`Placement::estrategia`] to name the strategy the empty
20079 // `:clusters` list was declared against), the same method's
20080 // `Sharded ↔ non-Sharded` `match` partition dispatch (which
20081 // reads through [`Placement::estrategia`] to fan across the
20082 // shape-gate cascades), and the non-`Sharded`-arm
20083 // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
20084 // `estrategia:` field (which reads through
20085 // [`Placement::estrategia`] to name the strategy the declared-
20086 // but-inert `:shard-key` was authored under) must all key off
20087 // the lifted accessor, so any future rebrand on the typed
20088 // slot's reader shape lands at exactly one place. Pins the
20089 // three-site coherence by exercising each error surface end-
20090 // to-end and asserting the surfaced `estrategia:` field byte-
20091 // equals the accessor's return. Peer of the sibling per-
20092 // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
20093 // pin on the M3 mesh-slot `Copy`-return scalar axis.
20094
20095 // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
20096 // whose `estrategia:` field must byte-equal the accessor's return
20097 // for every variant in the closed accept-set.
20098 for estrategia in [
20099 PlacementStrategy::SingleNode,
20100 PlacementStrategy::Replicated,
20101 PlacementStrategy::Sharded,
20102 ] {
20103 let mut spec = three_member_spec();
20104 spec.placement.estrategia = estrategia;
20105 spec.placement.clusters = Vec::new();
20106 spec.placement.shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
20107 let err = spec.validate().unwrap_err();
20108 match err {
20109 AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
20110 assert_eq!(
20111 e,
20112 spec.placement.estrategia(),
20113 "PlacementWithoutClusters.estrategia must byte-equal \
20114 Placement::estrategia() — the error carrier reads \
20115 through the lifted accessor",
20116 );
20117 }
20118 other => panic!(
20119 "expected PlacementWithoutClusters, got {other:?} for \
20120 estrategia={estrategia:?}"
20121 ),
20122 }
20123 }
20124
20125 // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
20126 // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
20127 // must byte-equal the accessor's return for both non-`Sharded`
20128 // strategies.
20129 for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
20130 let mut spec = three_member_spec();
20131 spec.placement.estrategia = estrategia;
20132 spec.placement.shard_key = Some("tenantId".into());
20133 let err = spec.validate().unwrap_err();
20134 match err {
20135 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
20136 assert_eq!(
20137 e,
20138 spec.placement.estrategia(),
20139 "ShardKeyOnNonSharded.estrategia must byte-equal \
20140 Placement::estrategia() — the non-Sharded-arm \
20141 refusal reads through the lifted accessor",
20142 );
20143 }
20144 other => panic!(
20145 "expected ShardKeyOnNonSharded, got {other:?} for \
20146 estrategia={estrategia:?}"
20147 ),
20148 }
20149 }
20150 }
20151
20152 // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
20153 //
20154 // The [`Placement::clusters`] accessor lift is the second slice-return
20155 // (`&[T]`) accessor on any typed slot — sibling to the seed M2
20156 // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
20157 // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
20158 // below cover (1) the accessor's byte-equal projection against the raw
20159 // field access across the empty / singleton / cohort fixtures the
20160 // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
20161 // and the per-cluster validate loop fan between, and (2) the two-
20162 // consumer coherence of the paired pre-flight refusal probe and the
20163 // per-cluster validate loop routing through the accessor on both arms.
20164
20165 #[test]
20166 fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
20167 // The canonical per-`:placement` cluster-pool-scalar-shape pin:
20168 // [`Placement::clusters`] must return the `:placement :clusters`
20169 // typed `Vec<String>` verbatim as a `&[String]` slice-view over
20170 // the same backing buffer the raw `self.clusters.as_slice()`
20171 // field access borrows from, byte-equal across every
20172 // representative fixture in the accept-set — the empty slice
20173 // (the pre-validation sentinel every
20174 // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
20175 // the singleton slice (the minimal `SingleNode`-shape cohort),
20176 // and multi-entry cohorts (the peer `Replicated` / `Sharded`
20177 // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
20178 //
20179 // Pins against a future silent detour that returned
20180 // `&Vec<String>` (which would type-check but leak the storage-
20181 // side `Vec`'s grow/push/reserve surface no consumer of the
20182 // typed view reaches for), a fresh-allocated `Vec<String>` copy
20183 // (which would type-check via a coercion but silently break
20184 // every downstream caller that relied on the slice sharing the
20185 // backing buffer's identity), or an out-of-order or length-
20186 // drifted projection (which would silently split the paired
20187 // pre-flight `.is_empty()` refusal probe's input from the per-
20188 // cluster validate loop's traversal input).
20189 //
20190 // Peer of the sibling M2
20191 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
20192 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
20193 // `:supervisor` static-child-list axis, extended onto the M3
20194 // per-`:placement` distribution-target-list `Vec`-carry axis.
20195 let fixtures: Vec<Vec<String>> = vec![
20196 Vec::new(),
20197 vec!["rio".into()],
20198 vec!["rio".into(), "mar".into()],
20199 vec!["rio".into(), "mar".into(), "plo".into()],
20200 ];
20201 for clusters in fixtures {
20202 let p = Placement {
20203 clusters: clusters.clone(),
20204 ..Placement::default()
20205 };
20206 assert_eq!(
20207 p.clusters(),
20208 clusters.as_slice(),
20209 "Placement::clusters must return :placement :clusters \
20210 verbatim (got {:?}, expected {:?})",
20211 p.clusters(),
20212 clusters.as_slice(),
20213 );
20214 assert_eq!(
20215 p.clusters(),
20216 p.clusters.as_slice(),
20217 "Placement::clusters accessor and .clusters.as_slice() \
20218 field access must byte-equal — the accessor is the \
20219 substrate-primitive typed dispatch every downstream \
20220 cluster-pool consumer must route through",
20221 );
20222 assert_eq!(
20223 p.clusters().len(),
20224 p.clusters.len(),
20225 "Placement::clusters().len() must byte-equal \
20226 self.clusters.len() — a length-drift would silently \
20227 split the paired pre-flight `.is_empty()` refusal \
20228 probe input from the per-cluster validate loop's \
20229 traversal input",
20230 );
20231 }
20232 }
20233
20234 #[test]
20235 fn validate_placement_reads_through_lifted_clusters_accessor() {
20236 // Two-consumer coherence pin: the
20237 // [`AplicacaoSpec::validate_placement`] pre-flight
20238 // `self.placement.clusters().is_empty()` refusal probe (which
20239 // must trip [`AplicacaoError::PlacementWithoutClusters`] when
20240 // the accessor projects the empty slice) and the per-cluster
20241 // validate loop's `for c in self.placement.clusters()`
20242 // traversal (which must reach every entry in the same order
20243 // the accessor projects, so both the per-entry value-shape
20244 // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
20245 // and the duplicate-detection HashSet insert that trips
20246 // [`AplicacaoError::PlacementClusterDuplicate`] key off the
20247 // accessor's projection) must both key off the lifted
20248 // accessor, so any future rebrand on the typed slot's reader
20249 // shape lands at exactly one place. Pins the two-site
20250 // coherence by exercising each production consumer end-to-end:
20251 // (1) the `PlacementWithoutClusters` refusal under the empty
20252 // slice, (2) the `PlacementClusterInvalid` refusal fires on
20253 // the second entry of a two-cluster cohort whose head is
20254 // valid but tail is not (which requires the loop to reach the
20255 // second entry through the accessor), and (3) the
20256 // `PlacementClusterDuplicate` refusal fires on the second
20257 // entry of a two-cluster cohort that shares a name (which
20258 // requires the loop to reach both entries — a first-entry-only
20259 // projection would silently pass since the dedup HashSet has
20260 // room for the first insert).
20261 //
20262 // Peer of the sibling M2
20263 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
20264 // (bc92bce) coherence pin on the per-`:supervisor` static-
20265 // child-list axis, extended onto the M3 per-`:placement`
20266 // distribution-target-list `Vec`-carry axis.
20267
20268 // (1) Pre-flight `.is_empty()` probe: the empty slice must
20269 // trip `PlacementWithoutClusters`.
20270 let mut spec = three_member_spec();
20271 spec.placement.clusters = Vec::new();
20272 match spec.validate().unwrap_err() {
20273 AplicacaoError::PlacementWithoutClusters { .. } => {}
20274 other => panic!("expected PlacementWithoutClusters, got {other:?}"),
20275 }
20276 assert!(
20277 spec.placement.clusters().is_empty(),
20278 "the pre-flight refusal input must be the empty slice per \
20279 the accessor's projection",
20280 );
20281
20282 // (2) Per-cluster validate loop: a two-cluster cohort with an
20283 // invalid tail entry must trip `PlacementClusterInvalid` on
20284 // the tail — the loop must reach the second entry through
20285 // the accessor.
20286 let mut spec = three_member_spec();
20287 spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
20288 match spec.validate().unwrap_err() {
20289 AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
20290 assert_eq!(
20291 cluster, "BAD_CLUSTER",
20292 "PlacementClusterInvalid.cluster must carry the \
20293 tail entry the loop reached through the accessor",
20294 );
20295 }
20296 other => panic!("expected PlacementClusterInvalid, got {other:?}"),
20297 }
20298 assert_eq!(
20299 spec.placement.clusters().len(),
20300 2,
20301 "the per-cluster validate loop's traversal input must be \
20302 a two-element slice per the accessor's projection",
20303 );
20304
20305 // (3) Per-cluster validate loop: a two-cluster cohort that
20306 // shares a name must trip `PlacementClusterDuplicate` on the
20307 // second entry — the loop must reach both entries through the
20308 // accessor for the dedup HashSet's second insert to collide.
20309 let mut spec = three_member_spec();
20310 spec.placement.clusters = vec!["rio".into(), "rio".into()];
20311 match spec.validate().unwrap_err() {
20312 AplicacaoError::PlacementClusterDuplicate { cluster } => {
20313 assert_eq!(
20314 cluster, "rio",
20315 "PlacementClusterDuplicate.cluster must carry the \
20316 shared cluster name verbatim",
20317 );
20318 }
20319 other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
20320 }
20321 assert_eq!(
20322 spec.placement.clusters().len(),
20323 2,
20324 "the per-cluster validate loop's traversal input must be \
20325 a two-element slice per the accessor's projection",
20326 );
20327 }
20328
20329 #[test]
20330 fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
20331 // The canonical per-`:membros` member-list-slice-shape pin:
20332 // [`AplicacaoSpec::membros`] must return the `:membros` typed
20333 // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
20334 // same backing buffer the raw `self.membros.as_slice()` field
20335 // access borrows from, byte-equal across every representative
20336 // fixture in the accept-set — the empty slice (the pre-
20337 // validation sentinel every [`AplicacaoError::NoMembros`]
20338 // refusal keys off), the singleton slice (the minimal one-
20339 // Servico Aplicacao shape), and multi-entry cohorts (the peer
20340 // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
20341 // load-bearing identity of the application graph).
20342 //
20343 // Pins against a future silent detour that returned
20344 // `&Vec<Membro>` (which would type-check but leak the storage-
20345 // side `Vec`'s grow/push/reserve surface no consumer of the
20346 // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
20347 // (which would type-check via a coercion but silently break
20348 // every downstream caller that relied on the slice sharing the
20349 // backing buffer's identity), or an out-of-order or length-
20350 // drifted projection (which would silently split the paired
20351 // `HashSet<&str>` name-set seed's collect input from the
20352 // pre-flight `.is_empty()` refusal probe's input from the per-
20353 // member validate loop's traversal input from the
20354 // programs.yaml emitter's per-entry fan-out loop's input from
20355 // the `feira app graph` per-member print traversal's input).
20356 //
20357 // Peer of the sibling M2
20358 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
20359 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
20360 // `:supervisor` static-child-list axis and the sibling M3
20361 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20362 // (a6e18d7) `&[String]` byte-equal pin on the per-
20363 // `:placement` distribution-target-list axis — extends the
20364 // slice-return-accessor byte-equal-projection discipline onto
20365 // the outermost M3 mesh-slot type's per-Aplicacao member-list
20366 // `Vec`-carry axis.
20367 let fixtures: Vec<Vec<Membro>> = vec![
20368 Vec::new(),
20369 vec![membro("catalog", "^0.1")],
20370 vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20371 vec![
20372 membro("catalog", "^0.1"),
20373 membro("cart", "^0.1"),
20374 membro("payment", "^0.2"),
20375 ],
20376 ];
20377 for membros in fixtures {
20378 let s = AplicacaoSpec {
20379 membros: membros.clone(),
20380 contratos: Vec::new(),
20381 politicas: MeshPolicy::default(),
20382 placement: Placement::default(),
20383 entrada: None,
20384 };
20385 assert_eq!(
20386 s.membros(),
20387 membros.as_slice(),
20388 "AplicacaoSpec::membros must return :membros verbatim \
20389 (got {:?}, expected {:?})",
20390 s.membros(),
20391 membros.as_slice(),
20392 );
20393 assert_eq!(
20394 s.membros(),
20395 s.membros.as_slice(),
20396 "AplicacaoSpec::membros accessor and .membros.as_slice() \
20397 field access must byte-equal — the accessor is the \
20398 substrate-primitive typed dispatch every downstream \
20399 member-list consumer must route through",
20400 );
20401 assert_eq!(
20402 s.membros().len(),
20403 s.membros.len(),
20404 "AplicacaoSpec::membros().len() must byte-equal \
20405 self.membros.len() — a length-drift would silently \
20406 split the paired `HashSet<&str>` name-set seed's \
20407 collect input from the pre-flight `.is_empty()` \
20408 refusal probe input from the per-member validate \
20409 loop's traversal input",
20410 );
20411 }
20412 }
20413
20414 #[test]
20415 fn validate_reads_through_lifted_membros_accessor() {
20416 // Three-consumer coherence pin: the
20417 // [`AplicacaoSpec::validate_membros`] pre-flight
20418 // `self.membros().is_empty()` refusal probe (which must trip
20419 // [`AplicacaoError::NoMembros`] when the accessor projects the
20420 // empty slice), the same method's per-member validate loop's
20421 // `for m in self.membros()` traversal (which must reach every
20422 // entry in the same order the accessor projects, so both the
20423 // per-entry empty-`:caixa` gate that trips
20424 // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
20425 // detection `insert_first_seen` that trips
20426 // [`AplicacaoError::MembroDuplicate`] key off the accessor's
20427 // projection), and the peer [`AplicacaoSpec::validate`]'s
20428 // `HashSet<&str>` name-set seed's
20429 // `self.membros().iter().map(Membro::nome).collect()` collect
20430 // input (which every `:contratos` `:de` / `:para` membership
20431 // lookup rejects an unknown name against) must all three key
20432 // off the lifted accessor, so any future rebrand on the typed
20433 // slot's reader shape lands at exactly one place. Pins the
20434 // three-site coherence by exercising each production consumer
20435 // end-to-end: (1) the `NoMembros` refusal under the empty
20436 // slice, (2) the `MembroCaixaEmpty` refusal fires on the
20437 // second entry of a two-member cohort whose head is valid but
20438 // tail has an empty `:caixa` (which requires the loop to
20439 // reach the second entry through the accessor), and (3) the
20440 // `MembroDuplicate` refusal fires on the second entry of a
20441 // two-member cohort that shares a `:caixa` name (which
20442 // requires the loop to reach both entries through the
20443 // accessor for the dedup HashSet's second insert to collide).
20444 //
20445 // Peer of the sibling M2
20446 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
20447 // (bc92bce) coherence pin on the per-`:supervisor` static-
20448 // child-list axis and the sibling M3
20449 // `validate_placement_reads_through_lifted_clusters_accessor`
20450 // (a6e18d7) coherence pin on the per-`:placement` distribution-
20451 // target-list axis — extends the slice-return-accessor
20452 // multi-consumer coherence discipline onto the outermost M3
20453 // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
20454
20455 // (1) Pre-flight `.is_empty()` probe: the empty slice must
20456 // trip `NoMembros`.
20457 let mut spec = three_member_spec();
20458 spec.membros = Vec::new();
20459 assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
20460 assert!(
20461 spec.membros().is_empty(),
20462 "the pre-flight refusal input must be the empty slice per \
20463 the accessor's projection",
20464 );
20465
20466 // (2) Per-member validate loop: a two-member cohort with an
20467 // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
20468 // the tail — the loop must reach the second entry through
20469 // the accessor.
20470 let mut spec = three_member_spec();
20471 spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
20472 assert_eq!(
20473 spec.validate().unwrap_err(),
20474 AplicacaoError::MembroCaixaEmpty,
20475 );
20476 assert_eq!(
20477 spec.membros().len(),
20478 2,
20479 "the per-member validate loop's traversal input must be \
20480 a two-element slice per the accessor's projection",
20481 );
20482
20483 // (3) Per-member validate loop: a two-member cohort that
20484 // shares a `:caixa` name must trip `MembroDuplicate` on the
20485 // second entry — the loop must reach both entries through the
20486 // accessor for the dedup HashSet's second insert to collide.
20487 let mut spec = three_member_spec();
20488 spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
20489 match spec.validate().unwrap_err() {
20490 AplicacaoError::MembroDuplicate { caixa } => {
20491 assert_eq!(
20492 caixa, "catalog",
20493 "MembroDuplicate.caixa must carry the shared \
20494 member name verbatim",
20495 );
20496 }
20497 other => panic!("expected MembroDuplicate, got {other:?}"),
20498 }
20499 assert_eq!(
20500 spec.membros().len(),
20501 2,
20502 "the per-member validate loop's traversal input must be \
20503 a two-element slice per the accessor's projection",
20504 );
20505 }
20506
20507 #[test]
20508 fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
20509 // The canonical per-`:contratos` contract-list-slice-shape pin:
20510 // [`AplicacaoSpec::contratos`] must return the `:contratos`
20511 // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
20512 // slice-view over the same backing buffer the raw
20513 // `self.contratos.as_slice()` field access borrows from, byte-
20514 // equal across every representative fixture in the accept-set —
20515 // the empty slice (the pre-validation "internal-only mesh" shape
20516 // an Aplicacao whose members exchange no typed edges renders
20517 // through), the singleton slice (the minimal one-edge Aplicacao
20518 // shape), and multi-entry cohorts (the peer multi-edge shapes
20519 // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
20520 // of the application graph).
20521 //
20522 // Pins against a future silent detour that returned
20523 // `&Vec<WitContract>` (which would type-check but leak the
20524 // storage-side `Vec`'s grow/push/reserve surface no consumer of
20525 // the typed view reaches for), a fresh-allocated
20526 // `Vec<WitContract>` copy (which would type-check via a coercion
20527 // but silently break every downstream caller that relied on the
20528 // slice sharing the backing buffer's identity), or an out-of-
20529 // order or length-drifted projection (which would silently split
20530 // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
20531 // seed's traversal input from the `detect_sync_cycles` per-edge
20532 // adjacency-list seed's traversal input from the
20533 // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
20534 // BTreeMap grouping loop's traversal input from the
20535 // `feira app graph` per-contract print traversal's input).
20536 //
20537 // Peer of the immediately-adjacent sibling M3
20538 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
20539 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
20540 // node-list axis, the sibling M3
20541 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20542 // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
20543 // distribution-target-list axis, and the sibling M2
20544 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
20545 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
20546 // `:supervisor` static-child-list axis — extends the slice-
20547 // return-accessor byte-equal-projection discipline onto the
20548 // outermost M3 mesh-slot type's per-Aplicacao contract-list
20549 // `Vec`-carry axis, closing the last unlifted per-
20550 // `AplicacaoSpec` `Vec`-carry axis.
20551 let fixtures: Vec<Vec<WitContract>> = vec![
20552 Vec::new(),
20553 vec![contract_http("cart", "catalog", "/products/:id")],
20554 vec![
20555 contract_http("cart", "catalog", "/products/:id"),
20556 contract_http("cart", "payment", "/charge"),
20557 ],
20558 vec![
20559 contract_http("cart", "catalog", "/products/:id"),
20560 contract_http("cart", "payment", "/charge"),
20561 contract_http("payment", "catalog", "/audit"),
20562 ],
20563 ];
20564 for contratos in fixtures {
20565 let s = AplicacaoSpec {
20566 membros: vec![
20567 membro("catalog", "^0.1"),
20568 membro("cart", "^0.1"),
20569 membro("payment", "^0.2"),
20570 ],
20571 contratos: contratos.clone(),
20572 politicas: MeshPolicy::default(),
20573 placement: Placement::default(),
20574 entrada: None,
20575 };
20576 assert_eq!(
20577 s.contratos(),
20578 contratos.as_slice(),
20579 "AplicacaoSpec::contratos must return :contratos verbatim \
20580 (got {:?}, expected {:?})",
20581 s.contratos(),
20582 contratos.as_slice(),
20583 );
20584 assert_eq!(
20585 s.contratos(),
20586 s.contratos.as_slice(),
20587 "AplicacaoSpec::contratos accessor and \
20588 .contratos.as_slice() field access must byte-equal — \
20589 the accessor is the substrate-primitive typed dispatch \
20590 every downstream contract-list consumer must route \
20591 through",
20592 );
20593 assert_eq!(
20594 s.contratos().len(),
20595 s.contratos.len(),
20596 "AplicacaoSpec::contratos().len() must byte-equal \
20597 self.contratos.len() — a length-drift would silently \
20598 split the paired per-edge validate-loop's traversal \
20599 input from the sync-cycle adjacency-list seed's \
20600 traversal input from the cilium_network_policies \
20601 per-`(:de, :para)` BTreeMap grouping loop's traversal \
20602 input from the `feira app graph` per-contract print \
20603 traversal's input",
20604 );
20605 }
20606 }
20607
20608 #[test]
20609 fn validate_reads_through_lifted_contratos_accessor() {
20610 // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
20611 // per-`:contratos` validate-loop's `for c in self.contratos()`
20612 // traversal (which must reach every entry in the same order the
20613 // accessor projects, so both the per-entry
20614 // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
20615 // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
20616 // dedup `HashSet` insert key off the accessor's projection),
20617 // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
20618 // `for c in self.contratos()` adjacency-list seed (which drives
20619 // the sync-subgraph deadlock-detection gate via
20620 // [`AplicacaoError::SyncCycle`]), and the peer
20621 // [`caixa_mesh::cilium_network_policies`]'s
20622 // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
20623 // grouping loop (which drives the per-CNP fan-out) must all
20624 // three key off the lifted accessor, so any future rebrand on
20625 // the typed slot's reader shape lands at exactly one place. Pins
20626 // the three-site coherence by exercising the two caixa-core
20627 // production consumers end-to-end: (1) the empty-`:contratos`
20628 // slice must validate without a per-edge diagnostic (the
20629 // per-edge loop is a no-op under the empty projection), (2) the
20630 // `ContratoMemberMissing` refusal fires on the second entry of a
20631 // two-edge cohort whose head references a valid member but tail
20632 // references a phantom name (which requires the loop to reach
20633 // the second entry through the accessor), and (3) the
20634 // `SyncCycle` refusal fires on a self-referential two-edge
20635 // cohort through the sync-cycle detector's peer projection
20636 // (which requires the detector to iterate the accessor's
20637 // projection to add the back-edge to its adjacency list).
20638 //
20639 // Peer of the sibling M3
20640 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
20641 // three-consumer coherence pin on the per-`:membros` node-list
20642 // axis and the sibling M3
20643 // `validate_placement_reads_through_lifted_clusters_accessor`
20644 // (a6e18d7) coherence pin on the per-`:placement` distribution-
20645 // target-list axis — extends the slice-return-accessor multi-
20646 // consumer coherence discipline onto the outermost M3 mesh-slot
20647 // type's per-Aplicacao contract-list `Vec`-carry axis.
20648
20649 // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
20650 // and no per-edge diagnostic surfaces. Validate succeeds on
20651 // the well-formed `:membros` head.
20652 let mut spec = three_member_spec();
20653 spec.contratos = Vec::new();
20654 assert!(
20655 spec.validate().is_ok(),
20656 "empty :contratos must validate — the per-edge loop is a \
20657 no-op under the accessor's empty projection",
20658 );
20659 assert!(
20660 spec.contratos().is_empty(),
20661 "the per-edge validate loop's traversal input must be the \
20662 empty slice per the accessor's projection",
20663 );
20664
20665 // (2) Per-edge validate loop: a two-edge cohort whose tail
20666 // references a phantom `:para` member must trip
20667 // `ContratoMemberMissing` on the tail — the loop must reach
20668 // the second entry through the accessor for the membership
20669 // lookup to fail on the phantom name.
20670 let mut spec = three_member_spec();
20671 spec.contratos = vec![
20672 contract_http("cart", "catalog", "/products/:id"),
20673 contract_http("cart", "phantom", "/x"),
20674 ];
20675 let err = spec.validate().unwrap_err();
20676 assert!(
20677 matches!(
20678 err,
20679 AplicacaoError::ContratoMemberMissing { ref caixa }
20680 if caixa == "phantom"
20681 ),
20682 "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
20683 );
20684 assert_eq!(
20685 spec.contratos().len(),
20686 2,
20687 "the per-edge validate loop's traversal input must be \
20688 a two-element slice per the accessor's projection",
20689 );
20690
20691 // (3) Sync-cycle detector: a two-edge synchronous cohort
20692 // whose second edge closes the sync-subgraph back onto the
20693 // first must trip [`AplicacaoError::ContratoCycle`] — the
20694 // detector must iterate the accessor's projection to add
20695 // both edges to its adjacency list, so a length-drift on
20696 // the accessor's projection would silently disagree with
20697 // the sync-cycle detector on which edge closes the loop.
20698 // Peer projection to the `validate` per-edge loop above:
20699 // the sync-cycle detector routes through the same lifted
20700 // accessor, so a rebrand of the reader shape lands at one
20701 // place. Uses a two-edge cohort (cart → catalog → cart)
20702 // because the per-edge `ContratoSelfLoop` gate fires before
20703 // the sync-cycle detector on a single self-referential edge
20704 // (`cart → cart`) — the cycle-detector's input must be a
20705 // multi-edge cohort for its per-edge traversal input to be
20706 // observably wider than the per-edge validate loop's input.
20707 let mut spec = three_member_spec();
20708 spec.contratos = vec![
20709 contract_http("cart", "catalog", "/products/:id"),
20710 contract_http("catalog", "cart", "/callback"),
20711 ];
20712 let err = spec.validate().unwrap_err();
20713 assert!(
20714 matches!(err, AplicacaoError::ContratoCycle { .. }),
20715 "expected ContratoCycle from the sync-cycle detector on a \
20716 two-edge back-edge cohort, got {err:?}",
20717 );
20718 assert_eq!(
20719 spec.contratos().len(),
20720 2,
20721 "the sync-cycle detector's traversal input must be a \
20722 two-element slice per the accessor's projection",
20723 );
20724 }
20725
20726 #[test]
20727 fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
20728 // The canonical per-`:politicas` outer-composite-reference-shape
20729 // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
20730 // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
20731 // the same backing storage the raw `&self.politicas` field
20732 // access borrows from, byte-equal across every representative
20733 // fixture in the accept-set — the default `MeshPolicy` (the
20734 // author-empty "no policy on any axis" shape whose
20735 // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
20736 // shapes carrying one axis at a time
20737 // (`{mtls_required, timeout, retries, circuit_breaker,
20738 // rate_limit}` — the minimal five-axis fan-out over the
20739 // per-axis lifted accessor family every downstream mesh-artifact
20740 // emitter dispatches on), and the multi-axis composite (the
20741 // canonical `three_member_spec` fixture's `{timeout, retries,
20742 // mtls_required}` triple — the load-bearing shape every
20743 // Aplicacao-scoped fixture in this suite constructs).
20744 //
20745 // Pins against a future silent detour that returned a fresh-
20746 // cloned `MeshPolicy` copy (which would type-check via a `Clone`
20747 // impl but silently break every downstream caller that relied
20748 // on the reference sharing the composite's backing identity), a
20749 // reference to an operator-resolved overlay (the future
20750 // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
20751 // acknowledges — its resolution must land at exactly this
20752 // accessor body, not silently divert the raw slot away from a
20753 // second consumer), or an axis-shuffled projection (a future
20754 // detour that swapped `timeout` and `retries` through the
20755 // accessor would silently split the paired `validate_politicas`
20756 // per-axis bracket-dispatch's traversal input from the peer
20757 // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
20758 // emitter's fan-out input from the peer
20759 // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
20760 // overlay emitter's fan-out input).
20761 //
20762 // Peer of the sibling M3
20763 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
20764 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
20765 // node-list `Vec`-carry axis and the sibling M3
20766 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
20767 // (0dcc926) `&[WitContract]` byte-equal pin on the per-
20768 // `:contratos` edge-list `Vec`-carry axis — extends the outer-
20769 // accessor byte-equal-projection discipline onto the outermost
20770 // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
20771 // reference axis, the first `&Composite`-return accessor on the
20772 // outer [`AplicacaoSpec`] type.
20773 let fixtures: Vec<MeshPolicy> = vec![
20774 MeshPolicy::default(),
20775 MeshPolicy {
20776 mtls_required: Some(true),
20777 ..MeshPolicy::default()
20778 },
20779 MeshPolicy {
20780 mtls_required: Some(false),
20781 ..MeshPolicy::default()
20782 },
20783 MeshPolicy {
20784 timeout: Some(Duration::from_secs(30)),
20785 ..MeshPolicy::default()
20786 },
20787 MeshPolicy {
20788 retries: Some(3),
20789 ..MeshPolicy::default()
20790 },
20791 MeshPolicy {
20792 circuit_breaker: Some(CircuitBreaker {
20793 max_failures: 5,
20794 window: Duration::from_secs(30),
20795 }),
20796 ..MeshPolicy::default()
20797 },
20798 MeshPolicy {
20799 rate_limit: Some(RateLimit {
20800 rate: 100,
20801 window: Duration::from_secs(1),
20802 }),
20803 ..MeshPolicy::default()
20804 },
20805 MeshPolicy {
20806 timeout: Some(Duration::from_secs(30)),
20807 retries: Some(3),
20808 mtls_required: Some(true),
20809 ..MeshPolicy::default()
20810 },
20811 ];
20812 for politicas in fixtures {
20813 let s = AplicacaoSpec {
20814 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20815 contratos: Vec::new(),
20816 politicas: politicas.clone(),
20817 placement: Placement::default(),
20818 entrada: None,
20819 };
20820 assert_eq!(
20821 *s.politicas(),
20822 politicas,
20823 "AplicacaoSpec::politicas must return :politicas verbatim \
20824 (got {:?}, expected {:?})",
20825 s.politicas(),
20826 politicas,
20827 );
20828 assert!(
20829 std::ptr::eq(s.politicas(), &s.politicas),
20830 "AplicacaoSpec::politicas accessor and &self.politicas \
20831 field access must borrow the same backing storage — \
20832 the accessor is the substrate-primitive typed dispatch \
20833 every downstream mesh-policy composite consumer must \
20834 route through, and a reference-identity split would \
20835 silently break every consumer that relied on the \
20836 borrow sharing the composite's storage",
20837 );
20838 assert_eq!(
20839 s.politicas().is_empty(),
20840 s.politicas.is_empty(),
20841 "AplicacaoSpec::politicas().is_empty() must byte-equal \
20842 self.politicas.is_empty() — an emptiness-drift would \
20843 silently split the paired `validate_politicas` \
20844 per-axis bracket-dispatch's seed from the peer \
20845 caixa-mesh CNP mTLS-overlay emitter's key from the \
20846 peer caixa-mesh HTTPRoute timeout+retry overlay \
20847 emitter's key",
20848 );
20849 }
20850 }
20851
20852 #[test]
20853 fn validate_politicas_reads_through_lifted_politicas_accessor() {
20854 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
20855 // per-axis bracket-dispatch seed (`let p = self.politicas();`,
20856 // followed by the per-axis fan-out `p.timeout()` /
20857 // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
20858 // the lifted axis-level accessor family) must key off the
20859 // lifted outer accessor, so any future rebrand on the typed
20860 // slot's outer-composite reader shape lands at exactly one
20861 // place. Pins the multi-axis coherence by exercising each
20862 // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
20863 // a `Some(Duration::ZERO)` timeout under the outer accessor's
20864 // reference projection, (2) `PolicyRetriesZero` fires on a
20865 // `Some(0)` retries under the same projection, and (3) an
20866 // empty [`MeshPolicy::default`] passes `validate_politicas` —
20867 // the outer accessor's reference-projection reaches every
20868 // per-axis branch without silently short-circuiting any.
20869 //
20870 // Peer of the sibling M3
20871 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
20872 // three-consumer coherence pin on the per-`:membros` node-list
20873 // axis and the sibling M3
20874 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
20875 // three-consumer coherence pin on the per-`:contratos`
20876 // edge-list axis — extends the multi-consumer coherence
20877 // discipline onto the outermost M3 mesh-slot type's per-
20878 // Aplicacao mesh-policy composite-reference axis, the first
20879 // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
20880 // type.
20881
20882 // (1) `PolicyTimeoutZero` refusal under the outer accessor's
20883 // reference projection: a `Some(Duration::ZERO)` timeout must
20884 // trip the zero-floor gate. The bracket-dispatch's first arm
20885 // reads `p.timeout()` on the reference returned by the outer
20886 // accessor.
20887 let mut spec = three_member_spec();
20888 spec.politicas.timeout = Some(Duration::ZERO);
20889 spec.politicas.retries = None;
20890 spec.politicas.circuit_breaker = None;
20891 spec.politicas.rate_limit = None;
20892 assert_eq!(
20893 spec.validate().unwrap_err(),
20894 AplicacaoError::PolicyTimeoutZero,
20895 );
20896 assert!(
20897 std::ptr::eq(spec.politicas(), &spec.politicas),
20898 "the `validate_politicas` per-axis bracket-dispatch's \
20899 traversal input must be the same backing composite the \
20900 accessor's reference projection borrows from",
20901 );
20902
20903 // (2) `PolicyRetriesZero` refusal under the outer accessor's
20904 // reference projection: a `Some(0)` retries must trip the
20905 // zero-floor gate. The bracket-dispatch's second arm reads
20906 // `p.retries()` on the reference returned by the outer accessor.
20907 let mut spec = three_member_spec();
20908 spec.politicas.timeout = None;
20909 spec.politicas.retries = Some(0);
20910 spec.politicas.circuit_breaker = None;
20911 spec.politicas.rate_limit = None;
20912 assert_eq!(
20913 spec.validate().unwrap_err(),
20914 AplicacaoError::PolicyRetriesZero,
20915 );
20916
20917 // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
20918 // — every per-axis arm short-circuits on `None`, so the outer
20919 // accessor's reference projection reaches the fall-through
20920 // `Ok(())` without any per-axis refusal firing.
20921 let mut spec = three_member_spec();
20922 spec.politicas = MeshPolicy::default();
20923 assert!(
20924 spec.validate().is_ok(),
20925 "an empty `MeshPolicy` must pass `validate_politicas` — \
20926 every per-axis arm short-circuits on `None` under the \
20927 outer accessor's reference projection",
20928 );
20929 assert!(
20930 spec.politicas().is_empty(),
20931 "the outer accessor's reference projection must be the \
20932 empty composite per the `MeshPolicy::default()` fixture",
20933 );
20934 }
20935
20936 #[test]
20937 #[allow(clippy::too_many_lines)]
20938 fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
20939 // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
20940 // per-axis bracket-dispatch's `:timeout` and `:retries` arms
20941 // must both key off the lifted axis-level accessors
20942 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
20943 // the peer `:circuit-breaker` / `:rate-limit` arms already
20944 // routing through [`MeshPolicy::circuit_breaker`] /
20945 // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
20946 // per axis on the substrate primitive" shape at the fan-out
20947 // (four axes, four accessors, no raw-field-access site
20948 // anywhere on the bracket-dispatch). Pins the per-axis
20949 // coherence at the accept-set boundaries the bracket carves:
20950 // 1. accessor byte-equal to raw field on every representative
20951 // accept-set value (`None`, sub-cap, at-cap, past-cap
20952 // sentinel) — a future accessor drift that no longer
20953 // shipped the raw slot verbatim would surface here,
20954 // 2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
20955 // routed through the accessor's projection, proving the
20956 // first arm reads through the accessor rather than a
20957 // silent-detour peer-axis field access,
20958 // 3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
20959 // through the accessor's projection, proving the second
20960 // arm reads through the accessor,
20961 // 4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
20962 // passes validate under the accessor projection (paired
20963 // with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
20964 // sibling axis), pinning the upper-boundary accept-arm
20965 // also routes through the accessor.
20966 //
20967 // Peer of the sibling M3
20968 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
20969 // outer-composite-reference coherence pin (which asserts the
20970 // `let p = self.politicas()` seed); extends the discipline onto
20971 // the per-axis fan-out layer that consumes the seed's
20972 // reference. Same shape as
20973 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
20974 // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
20975 // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
20976 // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
20977
20978 // (1) Accessor byte-equal to raw field on the `:timeout` axis
20979 // across the accept-set boundaries the bracket dispatch's
20980 // three-arm gate carves out
20981 // ([`crate::render::require_positive_canonical_bounded_duration`]
20982 // — zero-floor + canonical-form + upper-cap).
20983 for timeout in [
20984 None,
20985 Some(Duration::ZERO),
20986 Some(Duration::from_millis(1)),
20987 Some(POLICY_TIMEOUT_MAX),
20988 ] {
20989 let p = MeshPolicy {
20990 timeout,
20991 ..MeshPolicy::default()
20992 };
20993 assert_eq!(
20994 p.timeout(),
20995 p.timeout,
20996 "MeshPolicy::timeout accessor must byte-equal the raw \
20997 .timeout field across every accept-set boundary the \
20998 validate_politicas :timeout arm carves out — a drift \
20999 here would silently split the validate bracket's arm \
21000 from the peer caixa-mesh HTTPRoute timeout-overlay \
21001 emitter's read",
21002 );
21003 }
21004
21005 // (2) Accessor byte-equal to raw field on the `:retries` axis
21006 // across the accept-set boundaries the bracket dispatch's
21007 // two-arm gate carves out
21008 // ([`crate::render::require_positive_bounded_u32`] — zero-floor
21009 // + upper-cap).
21010 for retries in [
21011 None,
21012 Some(0u32),
21013 Some(1u32),
21014 Some(POLICY_RETRIES_MAX),
21015 Some(POLICY_RETRIES_MAX + 1),
21016 Some(u32::MAX),
21017 ] {
21018 let p = MeshPolicy {
21019 retries,
21020 ..MeshPolicy::default()
21021 };
21022 assert_eq!(
21023 p.retries(),
21024 p.retries,
21025 "MeshPolicy::retries accessor must byte-equal the raw \
21026 .retries field across every accept-set boundary the \
21027 validate_politicas :retries arm carves out — a drift \
21028 here would silently split the validate bracket's arm \
21029 from the peer caixa-mesh HTTPRoute retry-overlay \
21030 emitter's read",
21031 );
21032 }
21033
21034 // (3) `PolicyTimeoutZero` fires on the accessor-projected
21035 // zero-floor boundary. A silent detour that no longer read
21036 // through `p.timeout()` (a peer-axis field read, an accidental
21037 // Option::and-then chain that collapsed the None arm to Some,
21038 // an accessor rebrand that clamped the return through the
21039 // upper cap) would fail to refuse here.
21040 let mut spec = three_member_spec();
21041 spec.politicas.timeout = Some(Duration::ZERO);
21042 spec.politicas.retries = None;
21043 spec.politicas.circuit_breaker = None;
21044 spec.politicas.rate_limit = None;
21045 assert_eq!(
21046 spec.politicas().timeout(),
21047 Some(Duration::ZERO),
21048 "the accessor projection must reflect the fixture's \
21049 `Some(Duration::ZERO)` :timeout verbatim",
21050 );
21051 assert_eq!(
21052 spec.validate().unwrap_err(),
21053 AplicacaoError::PolicyTimeoutZero,
21054 "the validate_politicas :timeout zero-floor arm must fire \
21055 through the lifted accessor's projection — a silent \
21056 detour to a peer-axis field would fail to refuse",
21057 );
21058
21059 // (4) `PolicyRetriesZero` fires on the accessor-projected
21060 // zero-floor boundary on the sibling `:retries` axis.
21061 let mut spec = three_member_spec();
21062 spec.politicas.timeout = None;
21063 spec.politicas.retries = Some(0);
21064 spec.politicas.circuit_breaker = None;
21065 spec.politicas.rate_limit = None;
21066 assert_eq!(
21067 spec.politicas().retries(),
21068 Some(0),
21069 "the accessor projection must reflect the fixture's \
21070 `Some(0)` :retries verbatim",
21071 );
21072 assert_eq!(
21073 spec.validate().unwrap_err(),
21074 AplicacaoError::PolicyRetriesZero,
21075 "the validate_politicas :retries zero-floor arm must fire \
21076 through the lifted accessor's projection — a silent \
21077 detour to a peer-axis field would fail to refuse",
21078 );
21079
21080 // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
21081 // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
21082 // must pass validate under the accessor projection — pins the
21083 // upper-boundary accept-arm also routes through the lifted
21084 // accessor (a drift that clamped or short-circuited at the
21085 // upper boundary would fail the whole-spec validate here).
21086 let mut spec = three_member_spec();
21087 spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
21088 spec.politicas.retries = Some(POLICY_RETRIES_MAX);
21089 spec.politicas.circuit_breaker = None;
21090 spec.politicas.rate_limit = None;
21091 assert_eq!(
21092 spec.politicas().timeout(),
21093 Some(POLICY_TIMEOUT_MAX),
21094 "the accessor projection must reflect the fixture's \
21095 at-cap :timeout verbatim",
21096 );
21097 assert_eq!(
21098 spec.politicas().retries(),
21099 Some(POLICY_RETRIES_MAX),
21100 "the accessor projection must reflect the fixture's \
21101 at-cap :retries verbatim",
21102 );
21103 assert!(
21104 spec.validate().is_ok(),
21105 "at-cap :timeout + :retries must pass validate under the \
21106 accessor projection — the upper-boundary accept-arm on \
21107 both axes routes through the lifted accessor",
21108 );
21109 }
21110
21111 #[test]
21112 fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
21113 // The canonical per-`:placement` outer-composite-reference-shape
21114 // pin: [`AplicacaoSpec::placement`] must return the `:placement`
21115 // typed `Placement` verbatim as a `&Placement` reference over the
21116 // same backing storage the raw `&self.placement` field access
21117 // borrows from, byte-equal across every representative fixture in
21118 // the accept-set — the default `Placement` (the substrate seed
21119 // shape whose [`PlacementStrategy::default`] evaluates to
21120 // `SingleNode` with an empty `:clusters` pool and both
21121 // optional-scalar axes `None`), and every canonical strategy /
21122 // cluster-pool / optional-scalar combination the
21123 // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
21124 // three [`PlacementStrategy`] variants — `SingleNode`,
21125 // `Replicated`, `Sharded` — cross-projected with a non-empty
21126 // `:clusters` pool and, on the `Sharded` arm, a non-empty
21127 // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
21128 // canonical `three_member_spec` `Replicated` fixture's
21129 // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
21130 //
21131 // Pins against a future silent detour that returned a fresh-
21132 // cloned `Placement` copy (which would type-check via a `Clone`
21133 // impl but silently break every downstream caller that relied on
21134 // the reference sharing the composite's backing identity), a
21135 // reference to an operator-resolved overlay (the future per-
21136 // cluster `:placement-overrides` slot MESH-COMPOSITION §V
21137 // acknowledges — its resolution must land at exactly this
21138 // accessor body, not silently divert the raw slot away from a
21139 // second consumer), or an axis-shuffled projection (a future
21140 // detour that swapped `clusters` and `affinity` through the
21141 // accessor would silently split the paired `validate_placement`
21142 // per-axis bracket-dispatch's traversal input from the peer
21143 // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
21144 // programs.yaml distribution-annotation emitter's fan-out input
21145 // from the peer `feira app graph` per-Aplicacao print line's
21146 // input).
21147 //
21148 // Peer of the sibling M3
21149 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
21150 // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
21151 // outer mesh-policy composite-reference axis, and of the sibling
21152 // slice-return `aplicacao_spec_membros_returns_membros_slice_
21153 // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
21154 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
21155 // across_permutations` (0dcc926) `&[WitContract]` pins — extends
21156 // the outer-accessor byte-equal-projection discipline onto the
21157 // outermost M3 mesh-slot type's per-Aplicacao distribution
21158 // composite-reference axis, the second `&Composite`-return
21159 // accessor on the outer [`AplicacaoSpec`] type.
21160 let fixtures: Vec<Placement> = vec![
21161 Placement::default(),
21162 Placement {
21163 estrategia: PlacementStrategy::SingleNode,
21164 clusters: vec!["rio".into()],
21165 affinity: None,
21166 shard_key: None,
21167 },
21168 Placement {
21169 estrategia: PlacementStrategy::Replicated,
21170 clusters: vec!["rio".into(), "mar".into()],
21171 affinity: None,
21172 shard_key: None,
21173 },
21174 Placement {
21175 estrategia: PlacementStrategy::Replicated,
21176 clusters: vec!["rio".into(), "mar".into()],
21177 affinity: Some("data-locality".into()),
21178 shard_key: None,
21179 },
21180 Placement {
21181 estrategia: PlacementStrategy::Sharded,
21182 clusters: vec!["rio".into(), "mar".into()],
21183 affinity: None,
21184 shard_key: Some("tenantId".into()),
21185 },
21186 Placement {
21187 estrategia: PlacementStrategy::Sharded,
21188 clusters: vec!["rio".into(), "mar".into(), "sol".into()],
21189 affinity: Some("low-latency".into()),
21190 shard_key: Some("metadata.tenantId".into()),
21191 },
21192 ];
21193 for placement in fixtures {
21194 let s = AplicacaoSpec {
21195 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
21196 contratos: Vec::new(),
21197 politicas: MeshPolicy::default(),
21198 placement: placement.clone(),
21199 entrada: None,
21200 };
21201 assert_eq!(
21202 *s.placement(),
21203 placement,
21204 "AplicacaoSpec::placement must return :placement verbatim \
21205 (got {:?}, expected {:?})",
21206 s.placement(),
21207 placement,
21208 );
21209 assert!(
21210 std::ptr::eq(s.placement(), &s.placement),
21211 "AplicacaoSpec::placement accessor and &self.placement \
21212 field access must borrow the same backing storage — the \
21213 accessor is the substrate-primitive typed dispatch every \
21214 downstream distribution-composite consumer must route \
21215 through, and a reference-identity split would silently \
21216 break every consumer that relied on the borrow sharing \
21217 the composite's storage",
21218 );
21219 assert_eq!(
21220 s.placement().estrategia(),
21221 s.placement.estrategia,
21222 "AplicacaoSpec::placement().estrategia() must byte-equal \
21223 self.placement.estrategia — a strategy-drift would \
21224 silently split the paired `validate_placement` \
21225 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
21226 peer caixa-mesh programs.yaml `placement.estrategia` \
21227 emitter's key from the peer `feira app graph` printer's \
21228 strategy label",
21229 );
21230 assert_eq!(
21231 s.placement().clusters(),
21232 s.placement.clusters.as_slice(),
21233 "AplicacaoSpec::placement().clusters() must byte-equal \
21234 self.placement.clusters — a cluster-pool drift would \
21235 silently split the paired `validate_placement` \
21236 pre-flight `.is_empty()` refusal probe's traversal from \
21237 the peer caixa-mesh programs.yaml `placement.clusters` \
21238 emitter's fan-out from the peer `feira app graph` \
21239 printer's cluster list",
21240 );
21241 }
21242 }
21243
21244 #[test]
21245 fn validate_placement_reads_through_lifted_placement_accessor() {
21246 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
21247 // per-axis bracket-dispatch seed (`let p = self.placement();`,
21248 // followed by the per-axis fan-out `p.clusters()` /
21249 // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
21250 // lifted axis-level accessor family) must key off the lifted
21251 // outer accessor, so any future rebrand on the typed slot's
21252 // outer-composite reader shape lands at exactly one place. Pins
21253 // the multi-axis coherence by exercising each per-axis refusal
21254 // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
21255 // `:clusters` pool under the outer accessor's reference
21256 // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
21257 // strategy with a `None` `:shard-key` under the same projection,
21258 // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
21259 // with a `Some` `:shard-key` under the same projection, and
21260 // (4) the canonical `three_member_spec` `Replicated` fixture
21261 // passes `validate_placement` under the outer accessor's
21262 // reference projection — the accessor's reference-projection
21263 // reaches every per-axis branch (cluster-pool refusal, `Sharded`
21264 // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
21265 // without silently short-circuiting any.
21266 //
21267 // Peer of the sibling M3
21268 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
21269 // (534dc21) multi-axis coherence pin on the per-`:politicas`
21270 // outer mesh-policy composite-reference axis — extends the
21271 // multi-consumer coherence discipline onto the outermost M3
21272 // mesh-slot type's per-Aplicacao distribution composite-
21273 // reference axis, the second `&Composite`-return accessor on
21274 // the outer [`AplicacaoSpec`] type.
21275
21276 // (1) `PlacementWithoutClusters` refusal under the outer
21277 // accessor's reference projection: an empty `:clusters` pool
21278 // must trip the pre-flight refusal probe. The bracket-dispatch's
21279 // first arm reads `p.clusters()` on the reference returned by
21280 // the outer accessor.
21281 let mut spec = three_member_spec();
21282 spec.placement.clusters = Vec::new();
21283 assert_eq!(
21284 spec.validate().unwrap_err(),
21285 AplicacaoError::PlacementWithoutClusters {
21286 estrategia: PlacementStrategy::Replicated,
21287 },
21288 );
21289 assert!(
21290 std::ptr::eq(spec.placement(), &spec.placement),
21291 "the `validate_placement` per-axis bracket-dispatch's \
21292 traversal input must be the same backing composite the \
21293 accessor's reference projection borrows from",
21294 );
21295
21296 // (2) `ShardedWithoutKey` refusal under the outer accessor's
21297 // reference projection: a `Sharded` strategy with a `None`
21298 // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
21299 // The bracket-dispatch's third arm reads `p.estrategia()` for
21300 // the match scrutinee then `p.shard_key()` for the cascade
21301 // scrutinee, both on the reference returned by the outer
21302 // accessor.
21303 let mut spec = three_member_spec();
21304 spec.placement.estrategia = PlacementStrategy::Sharded;
21305 spec.placement.shard_key = None;
21306 assert_eq!(
21307 spec.validate().unwrap_err(),
21308 AplicacaoError::ShardedWithoutKey,
21309 );
21310
21311 // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
21312 // reference projection: a non-`Sharded` strategy with a `Some`
21313 // `:shard-key` must trip the declared-but-inert refusal. The
21314 // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
21315 // + `p.estrategia()` for the diagnostic on the reference
21316 // returned by the outer accessor.
21317 let mut spec = three_member_spec();
21318 spec.placement.estrategia = PlacementStrategy::Replicated;
21319 spec.placement.shard_key = Some("tenantId".into());
21320 assert_eq!(
21321 spec.validate().unwrap_err(),
21322 AplicacaoError::ShardKeyOnNonSharded {
21323 estrategia: PlacementStrategy::Replicated,
21324 shard_key: "tenantId".into(),
21325 },
21326 );
21327
21328 // (4) Canonical `three_member_spec` `Replicated` fixture passes
21329 // `validate_placement` — every per-axis arm reaches the fall-
21330 // through `Ok(())` without any per-axis refusal firing under the
21331 // outer accessor's reference projection.
21332 let spec = three_member_spec();
21333 assert!(
21334 spec.validate().is_ok(),
21335 "the canonical Replicated placement fixture must pass \
21336 `validate_placement` — every per-axis arm short-circuits on \
21337 valid input under the outer accessor's reference projection",
21338 );
21339 assert_eq!(
21340 spec.placement().estrategia(),
21341 PlacementStrategy::Replicated,
21342 "the outer accessor's reference projection must be the \
21343 canonical Replicated fixture's strategy",
21344 );
21345 assert_eq!(
21346 spec.placement().clusters(),
21347 &["rio", "mar"],
21348 "the outer accessor's reference projection must be the \
21349 canonical Replicated fixture's cluster pool",
21350 );
21351 }
21352
21353 #[test]
21354 fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
21355 // The canonical per-`:entrada` outer-composite-optional-
21356 // reference-shape pin: [`AplicacaoSpec::entrada`] must return
21357 // the `:entrada` typed `Option<Entrada>` verbatim as an
21358 // `Option<&Entrada>` reference over the same backing storage
21359 // the raw `self.entrada.as_ref()` field access borrows from,
21360 // byte-equal across every representative fixture in the
21361 // accept-set — the author-omitted `None` shape (the
21362 // "internal-only mesh" partition every downstream external-
21363 // gateway emitter treats as "emit nothing"), the minimal
21364 // singleton `:entrada` composite (host + destination + empty
21365 // paths + default port), the paths-carrying composite (the
21366 // canonical `three_member_spec` fixture's ["/api" "/health"]
21367 // path-list shape every HTTPRoute per-rule fan-out emitter
21368 // reads), and the non-default port composite (the canonical
21369 // custom-port shape the port-fallback resolver reads).
21370 //
21371 // Pins against a future silent detour that returned a fresh-
21372 // cloned `Entrada` copy (which would type-check via a `Clone`
21373 // impl but silently break every downstream caller that
21374 // relied on the reference sharing the composite's backing
21375 // identity), a reference to an operator-resolved overlay
21376 // (the future per-cluster `:entrada-overrides` slot the
21377 // MESH-COMPOSITION §V federation roadmap acknowledges — its
21378 // resolution must land at exactly this accessor body, not
21379 // silently divert the raw slot away from a second consumer),
21380 // a `None` → `Some(Entrada::default)` cluster-default
21381 // projection (which would collapse the load-bearing
21382 // "author-omitted `:entrada` ⇒ internal-only mesh" partition
21383 // the peer `gateway_routes` early-return + `feira app graph`
21384 // internal-only-mesh partition both read), or an axis-
21385 // shuffled projection (a future detour that swapped
21386 // `host` and `para` through the accessor would silently
21387 // split the paired `validate` per-`:entrada` shape-and-
21388 // membership gate's traversal input from the peer
21389 // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
21390 // fan-out input from the peer `feira app graph` external-
21391 // gateway summary line).
21392 //
21393 // Peer of the sibling M3
21394 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
21395 // (534dc21) `&MeshPolicy` byte-equal pin on the per-
21396 // `:politicas` outer mesh-policy composite-reference axis
21397 // and of the sibling M3
21398 // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
21399 // (9abb8f0) `&Placement` byte-equal pin on the per-
21400 // `:placement` outer distribution-composite composite-
21401 // reference axis — extends the outer-accessor byte-equal-
21402 // projection discipline onto the last unlifted outermost M3
21403 // mesh-slot type's per-Aplicacao external-gateway composite-
21404 // reference axis, the third and final `&Composite`-return
21405 // accessor on the outer [`AplicacaoSpec`] type.
21406 let fixtures: Vec<Option<Entrada>> = vec![
21407 None,
21408 Some(Entrada {
21409 host: "checkout.quero.cloud".into(),
21410 para: "cart".into(),
21411 paths: Vec::new(),
21412 port: DEFAULT_SERVICO_PORT,
21413 }),
21414 Some(Entrada {
21415 host: "checkout.quero.cloud".into(),
21416 para: "cart".into(),
21417 paths: vec!["/api".into(), "/health".into()],
21418 port: DEFAULT_SERVICO_PORT,
21419 }),
21420 Some(Entrada {
21421 host: "checkout.quero.cloud".into(),
21422 para: "cart".into(),
21423 paths: vec!["/api".into()],
21424 port: 9443,
21425 }),
21426 ];
21427 for entrada in fixtures {
21428 let s = AplicacaoSpec {
21429 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
21430 contratos: Vec::new(),
21431 politicas: MeshPolicy::default(),
21432 placement: Placement::default(),
21433 entrada: entrada.clone(),
21434 };
21435 assert_eq!(
21436 s.entrada(),
21437 entrada.as_ref(),
21438 "AplicacaoSpec::entrada must return :entrada verbatim \
21439 (got {:?}, expected {:?})",
21440 s.entrada(),
21441 entrada.as_ref(),
21442 );
21443 match (s.entrada(), s.entrada.as_ref()) {
21444 (Some(a), Some(b)) => assert!(
21445 std::ptr::eq(a, b),
21446 "AplicacaoSpec::entrada accessor and \
21447 self.entrada.as_ref() field access must borrow \
21448 the same backing storage — the accessor is the \
21449 substrate-primitive typed dispatch every \
21450 downstream external-gateway composite consumer \
21451 must route through, and a reference-identity \
21452 split would silently break every consumer that \
21453 relied on the borrow sharing the composite's \
21454 storage",
21455 ),
21456 (None, None) => {}
21457 _ => panic!(
21458 "AplicacaoSpec::entrada presence bit must byte-\
21459 equal self.entrada.is_some() — a presence-bit \
21460 drift would silently split the paired `validate` \
21461 per-`:entrada` shape-and-membership gate's \
21462 traversal head from the peer \
21463 caixa-mesh gateway_routes early-return partition \
21464 from the peer `feira app graph` internal-only-\
21465 mesh partition",
21466 ),
21467 }
21468 assert_eq!(
21469 s.entrada().is_some(),
21470 s.entrada.is_some(),
21471 "AplicacaoSpec::entrada().is_some() must byte-equal \
21472 self.entrada.is_some() — a presence-bit drift would \
21473 silently split every downstream `Option<&Entrada>` \
21474 consumer's partition on the internal-only-mesh arm",
21475 );
21476 }
21477 }
21478
21479 #[test]
21480 fn validate_reads_through_lifted_entrada_accessor() {
21481 // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
21482 // per-`:entrada` shape-and-membership gate (`if let Some(e) =
21483 // self.entrada() { … }`, followed by the per-axis fan-out
21484 // `validate_entrada_para(&e.para)` /
21485 // `EntradaMemberMissing` membership lookup /
21486 // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
21487 // per-`e.paths` `validate_entrada_path` traversal) must key
21488 // off the lifted outer accessor, so any future rebrand on
21489 // the typed slot's outer-composite reader shape lands at
21490 // exactly one place. Pins the multi-axis coherence by
21491 // exercising each per-axis refusal end-to-end: (1) the
21492 // author-omitted `None` shape short-circuits past every
21493 // per-`:entrada` refusal (the internal-only mesh partition
21494 // the accessor's `None` arm names), (2) `EntradaMemberMissing`
21495 // fires on a well-shaped but phantom `:para` under the outer
21496 // accessor's reference projection, and (3) the canonical
21497 // `three_member_spec` `:entrada` fixture passes `validate`
21498 // under the outer accessor's reference projection.
21499 //
21500 // Peer of the sibling M3
21501 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
21502 // (534dc21) multi-axis coherence pin on the per-`:politicas`
21503 // outer mesh-policy composite-reference axis and the sibling
21504 // M3
21505 // [`validate_placement_reads_through_lifted_placement_accessor`]
21506 // (9abb8f0) multi-axis coherence pin on the per-`:placement`
21507 // outer distribution-composite composite-reference axis —
21508 // extends the multi-consumer coherence discipline onto the
21509 // last unlifted outermost M3 mesh-slot type's per-Aplicacao
21510 // external-gateway composite-reference axis, the third and
21511 // final `&Composite`-return accessor on the outer
21512 // [`AplicacaoSpec`] type.
21513
21514 // (1) `None` :entrada — the internal-only-mesh partition
21515 // short-circuits past every per-`:entrada` refusal. The outer
21516 // accessor's reference projection reaches the fall-through
21517 // `Ok(())` on the `None` arm without any per-axis refusal
21518 // firing.
21519 let mut spec = three_member_spec();
21520 spec.entrada = None;
21521 assert!(
21522 spec.validate().is_ok(),
21523 "an author-omitted `:entrada` must pass `validate` — the \
21524 internal-only-mesh partition short-circuits past every \
21525 per-`:entrada` refusal under the outer accessor's \
21526 reference projection",
21527 );
21528 assert!(
21529 spec.entrada().is_none(),
21530 "the outer accessor's reference projection must name the \
21531 internal-only-mesh partition per the `None` fixture",
21532 );
21533
21534 // (2) `EntradaMemberMissing` refusal under the outer accessor's
21535 // reference projection: a well-shaped but phantom `:para` must
21536 // trip the membership-lookup refusal. The gate's second arm
21537 // reads `e.para` on the reference returned by the outer
21538 // accessor.
21539 let mut spec = three_member_spec();
21540 if let Some(e) = spec.entrada.as_mut() {
21541 e.para = "phantom".into();
21542 }
21543 assert_eq!(
21544 spec.validate().unwrap_err(),
21545 AplicacaoError::EntradaMemberMissing {
21546 para: "phantom".into(),
21547 },
21548 );
21549 match (spec.entrada(), spec.entrada.as_ref()) {
21550 (Some(a), Some(b)) => assert!(
21551 std::ptr::eq(a, b),
21552 "the `validate` per-`:entrada` gate's traversal head \
21553 must be the same backing composite the accessor's \
21554 reference projection borrows from",
21555 ),
21556 _ => panic!("fixture must carry Some(:entrada)"),
21557 }
21558
21559 // (3) Canonical `three_member_spec` `:entrada` fixture passes
21560 // `validate` — every per-axis arm reaches the fall-through
21561 // `Ok(())` without any per-axis refusal firing under the
21562 // outer accessor's reference projection.
21563 let spec = three_member_spec();
21564 assert!(
21565 spec.validate().is_ok(),
21566 "the canonical `:entrada` fixture must pass `validate` — \
21567 every per-axis arm short-circuits on valid input under \
21568 the outer accessor's reference projection",
21569 );
21570 assert!(
21571 spec.entrada().is_some(),
21572 "the outer accessor's reference projection must be the \
21573 canonical `:entrada` fixture's composite",
21574 );
21575 }
21576
21577 #[test]
21578 fn port_for_destination_reads_through_lifted_entrada_accessor() {
21579 // Peer coherence pin: the
21580 // [`AplicacaoSpec::port_for_destination`] per-destination
21581 // L4-port fallback resolver's composite-projection seed
21582 // (`self.entrada().filter(…).map_or(…)`) must key off the
21583 // lifted outer accessor. Pins the coherence by exercising
21584 // the resolver end-to-end: (1) the `None` `:entrada` shape
21585 // falls through to `DEFAULT_SERVICO_PORT` under the outer
21586 // accessor's reference projection, (2) a non-matching
21587 // destination falls through to `DEFAULT_SERVICO_PORT` under
21588 // the outer accessor's reference projection, and (3) the
21589 // matching destination resolves to the `:entrada :port`
21590 // value under the outer accessor's reference projection.
21591 //
21592 // Peer of the sibling
21593 // [`validate_reads_through_lifted_entrada_accessor`] multi-
21594 // consumer coherence pin on the same per-`:entrada` outer-
21595 // composite axis — extends the multi-consumer coherence
21596 // discipline onto the second per-`:entrada` production
21597 // consumer, the L4-port fallback resolver.
21598
21599 // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
21600 // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
21601 // arm under the outer accessor's reference projection.
21602 let mut spec = three_member_spec();
21603 spec.entrada = None;
21604 assert_eq!(
21605 spec.port_for_destination("cart"),
21606 DEFAULT_SERVICO_PORT,
21607 "the port-fallback resolver must fall through to \
21608 DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
21609 under the outer accessor's reference projection",
21610 );
21611
21612 // (2) Non-matching destination — the resolver's `filter(…)`
21613 // arm rejects a mismatched destination and falls through
21614 // to `DEFAULT_SERVICO_PORT` under the outer accessor's
21615 // reference projection.
21616 let mut spec = three_member_spec();
21617 if let Some(e) = spec.entrada.as_mut() {
21618 e.para = "cart".into();
21619 e.port = 9443;
21620 }
21621 assert_eq!(
21622 spec.port_for_destination("catalog"),
21623 DEFAULT_SERVICO_PORT,
21624 "the port-fallback resolver must fall through to \
21625 DEFAULT_SERVICO_PORT on a non-matching destination \
21626 under the outer accessor's reference projection",
21627 );
21628
21629 // (3) Matching destination — the resolver's `map_or(…)` arm
21630 // returns the `:entrada :port` value under the outer
21631 // accessor's reference projection.
21632 let mut spec = three_member_spec();
21633 if let Some(e) = spec.entrada.as_mut() {
21634 e.para = "cart".into();
21635 e.port = 9443;
21636 }
21637 assert_eq!(
21638 spec.port_for_destination("cart"),
21639 9443,
21640 "the port-fallback resolver must return the \
21641 `:entrada :port` value on a matching destination \
21642 under the outer accessor's reference projection",
21643 );
21644 }
21645
21646 #[test]
21647 fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
21648 // The canonical per-`:politicas` `:mtls-required` mTLS-
21649 // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
21650 // must return the `:politicas :mtls-required` typed bool
21651 // verbatim as an `Option<bool>`, byte-equal to the raw field
21652 // access across every value in the three-way accept-set —
21653 // `None` (cluster default applies), `Some(true)` (mTLS
21654 // handshake enforced — the sandboxing-by-default arm the
21655 // MeshPolicy's docstring names), `Some(false)` (handshake
21656 // skipped — the explicit debug-edge opt-out).
21657 //
21658 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
21659 // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
21660 // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
21661 // shape — first `Option<Copy-T>`-return accessor on the M3
21662 // mesh-slot family. Pins against a future silent detour that
21663 // re-derived the toggle from a peer axis (an accidental
21664 // `.circuit_breaker.is_some()` collapse that assumed mTLS on
21665 // whenever a breaker is set), a `None` → `Some(false)` cluster-
21666 // default projection (the canonical `Option<bool>` → `bool`
21667 // collapse footgun the surrounding `is_empty()` predicate
21668 // guards on the peer emptiness axis), or a `Some(true)` /
21669 // `Some(false)` variant swap that landed on one consumer
21670 // without the other.
21671 for required in [None, Some(true), Some(false)] {
21672 let p = MeshPolicy {
21673 mtls_required: required,
21674 ..MeshPolicy::default()
21675 };
21676 assert_eq!(
21677 p.mtls_required(),
21678 required,
21679 "MeshPolicy::mtls_required must return :politicas \
21680 :mtls-required verbatim (got {:?}, expected {required:?})",
21681 p.mtls_required(),
21682 );
21683 assert_eq!(
21684 p.mtls_required(),
21685 p.mtls_required,
21686 "MeshPolicy::mtls_required must byte-equal the raw \
21687 .mtls_required field access across every value in the \
21688 three-way accept-set",
21689 );
21690 }
21691 }
21692
21693 #[test]
21694 fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
21695 // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
21696 // arm must key off [`MeshPolicy::mtls_required`], not the raw
21697 // `.mtls_required` field access. Structurally: toggling ONLY
21698 // the `mtls_required` slot on an otherwise-default MeshPolicy
21699 // must flip `is_empty()` from `true` (all-`None`) to `false`
21700 // (one axis carries a value); the flip must be observed for
21701 // both `Some(true)` and `Some(false)` since the emptiness
21702 // semantic reads "any axis carries a value" — not "any axis
21703 // carries a truthy value" — the same non-collapsing shape the
21704 // sibling M2 [`crate::LimitsSpec::is_empty`] /
21705 // [`crate::BehaviorSpec::is_empty`] predicates carry on their
21706 // peer `Option<T>`-typed slot surfaces.
21707 //
21708 // Pins against a future silent detour that re-derived the
21709 // emptiness predicate off a peer axis (an accidental
21710 // `.rate_limit.is_none()`-only chain that dropped the
21711 // `mtls_required` arm entirely), a `mtls_required == Some(_)`
21712 // collapse to a truthy-only check (which would silently
21713 // classify `Some(false)` as empty), or an accessor-side
21714 // detour that no longer names the substrate-primitive typed
21715 // dispatch (an accidental `self.mtls_required.unwrap_or(false)
21716 // == false` fallback in the accessor that would silently
21717 // classify both `None` and `Some(false)` as the same value).
21718 //
21719 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
21720 // (7cd2a28) accessor-composition pin on the sibling optional-
21721 // scalar axis — same "the emptiness / shape-gate predicate
21722 // must route through the substrate-primitive typed dispatch"
21723 // discipline extended onto the peer per-`:politicas` emptiness
21724 // predicate.
21725 let empty = MeshPolicy::default();
21726 assert!(
21727 empty.is_empty(),
21728 "MeshPolicy::default() must be is_empty() — every axis \
21729 defaults to None",
21730 );
21731 for required in [Some(true), Some(false)] {
21732 let p = MeshPolicy {
21733 mtls_required: required,
21734 ..MeshPolicy::default()
21735 };
21736 assert!(
21737 !p.is_empty(),
21738 "MeshPolicy::is_empty must return false when \
21739 :mtls-required is {required:?} — the emptiness \
21740 predicate reads \"any axis carries a value\", not \
21741 \"any axis carries a truthy value\"",
21742 );
21743 assert_eq!(
21744 p.mtls_required().is_none(),
21745 p.is_empty(),
21746 "when :mtls-required is the only set axis, \
21747 is_empty() must equal mtls_required().is_none() — \
21748 the accessor and the emptiness predicate must \
21749 route through the same substrate-primitive typed \
21750 dispatch on the :mtls-required arm",
21751 );
21752 }
21753 }
21754
21755 #[test]
21756 fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
21757 // The by-copy pin: [`MeshPolicy::mtls_required`] returns
21758 // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
21759 // accessor must return by value, not by reference. Peer of the
21760 // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
21761 // borrow-invariant pin on the sibling `Option<String>` slot,
21762 // but extended onto the peer `Option<bool>` copy-invariant
21763 // shape — the accessor's returned `Option<bool>` must outlive
21764 // `&self` (multiple calls must return equal values from a
21765 // dropped-`&self` copy, since the returned Option carries no
21766 // borrow), and calling the accessor twice on the same
21767 // MeshPolicy must yield the same `Option<bool>` verbatim
21768 // (idempotent, no side effects on `&self`).
21769 //
21770 // Pins against a future silent detour that returned
21771 // `Option<&bool>` (which would type-check but silently break
21772 // every downstream caller — [`single_field_overlay`]'s first
21773 // parameter is `Option<T: Clone>`, and `&bool` would fold to a
21774 // detached copy at the call site), an accidental
21775 // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
21776 // would also type-check but return `Option<&bool>`), or a
21777 // one-arm-only accessor that reads `Some(*b)` in the Some arm
21778 // but reads a fresh Default::default() in the None arm.
21779 for required in [None, Some(true), Some(false)] {
21780 let p = MeshPolicy {
21781 mtls_required: required,
21782 ..MeshPolicy::default()
21783 };
21784 let first = p.mtls_required();
21785 let second = p.mtls_required();
21786 assert_eq!(
21787 first, second,
21788 "MeshPolicy::mtls_required must be idempotent — two \
21789 successive calls on the same &self must return the \
21790 same Option<bool>",
21791 );
21792 assert_eq!(
21793 first, required,
21794 "MeshPolicy::mtls_required must return :politicas \
21795 :mtls-required verbatim by copy — got {first:?}, \
21796 expected {required:?}",
21797 );
21798 }
21799 }
21800
21801 #[test]
21802 fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
21803 // The canonical per-`:politicas` `:retries` transient-failure-
21804 // retry-budget scalar pin: [`MeshPolicy::retries`] must return
21805 // the `:politicas :retries` typed `u32` verbatim as an
21806 // `Option<u32>`, byte-equal to the raw field access across every
21807 // representative value in the accept-set — `None` (cluster
21808 // default applies — typically "no retries beyond a single
21809 // dispatch attempt" the caixa-mesh `retry_overlay` builder
21810 // documents), `Some(1)` (the lower boundary of the
21811 // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
21812 // `AplicacaoSpec::validate_politicas` gate carves out on the
21813 // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
21814 // (the upper boundary the same gate carves out on the sibling
21815 // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
21816 // past-the-guard sentinel that pins the accessor doesn't perform
21817 // a silent bounds-collapse at the return path).
21818 //
21819 // Sibling of the peer per-`:politicas`
21820 // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
21821 // sibling `Option<Copy-T>` optional-scalar axis, extended to the
21822 // peer per-`:politicas` `Option<u32>` shape — second
21823 // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
21824 // Pins against a future silent detour that re-derived the retry
21825 // cap from a peer axis (an accidental `.circuit_breaker
21826 // .as_ref().map(|b| b.max_failures)` collapse that read the
21827 // breaker's max-failure count as a retry budget), a
21828 // `None → Some(0)` cluster-default projection (which would
21829 // silently re-introduce the `PolicyRetriesZero` refusal case at
21830 // the emit boundary), or a bounds-collapsing accessor that
21831 // clamped the return through `POLICY_RETRIES_MAX` (the
21832 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
21833 // must ship the raw slot verbatim so a validate-time gate
21834 // regression surfaces at the emit boundary rather than being
21835 // silently absorbed).
21836 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
21837 let p = MeshPolicy {
21838 retries,
21839 ..MeshPolicy::default()
21840 };
21841 assert_eq!(
21842 p.retries(),
21843 retries,
21844 "MeshPolicy::retries must return :politicas :retries \
21845 verbatim (got {:?}, expected {retries:?})",
21846 p.retries(),
21847 );
21848 assert_eq!(
21849 p.retries(),
21850 p.retries,
21851 "MeshPolicy::retries must byte-equal the raw .retries \
21852 field access across every value in the accept-set",
21853 );
21854 }
21855 }
21856
21857 #[test]
21858 fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
21859 // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
21860 // must key off [`MeshPolicy::retries`], not the raw `.retries`
21861 // field access. Structurally: toggling ONLY the `retries` slot
21862 // on an otherwise-default MeshPolicy must flip `is_empty()`
21863 // from `true` (all-`None`) to `false` (one axis carries a
21864 // value); the flip must be observed for every value in the
21865 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
21866 // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
21867 // the emptiness semantic reads "any axis carries a value" —
21868 // not "any axis carries a value the validate gate accepts" —
21869 // the same non-collapsing shape the peer M2
21870 // [`crate::LimitsSpec::is_empty`] /
21871 // [`crate::BehaviorSpec::is_empty`] predicates carry.
21872 //
21873 // Pins against a future silent detour that re-derived the
21874 // emptiness predicate off a peer axis (an accidental
21875 // `.rate_limit.is_none()`-only chain that dropped the
21876 // `retries` arm entirely), a `retries == Some(_)` collapse
21877 // that key-off a validate-gate-clamped bounds check (which
21878 // would silently classify a past-the-guard `Some(u32::MAX)`
21879 // as empty because it fails the `1..=POLICY_RETRIES_MAX`
21880 // check), or an accessor-side detour that no longer names the
21881 // substrate-primitive typed dispatch.
21882 //
21883 // Sibling of the peer per-`:politicas`
21884 // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
21885 // pin on the sibling `Option<Copy-T>` optional-scalar axis —
21886 // same "the emptiness predicate must route through the
21887 // substrate-primitive typed dispatch" discipline extended onto
21888 // the peer per-`:politicas` `Option<u32>` axis.
21889 let empty = MeshPolicy::default();
21890 assert!(
21891 empty.is_empty(),
21892 "MeshPolicy::default() must be is_empty() — every axis \
21893 defaults to None",
21894 );
21895 for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
21896 let p = MeshPolicy {
21897 retries,
21898 ..MeshPolicy::default()
21899 };
21900 assert!(
21901 !p.is_empty(),
21902 "MeshPolicy::is_empty must return false when \
21903 :retries is {retries:?} — the emptiness \
21904 predicate reads \"any axis carries a value\", not \
21905 \"any axis carries a value the validate gate \
21906 accepts\"",
21907 );
21908 assert_eq!(
21909 p.retries().is_none(),
21910 p.is_empty(),
21911 "when :retries is the only set axis, is_empty() \
21912 must equal retries().is_none() — the accessor and \
21913 the emptiness predicate must route through the same \
21914 substrate-primitive typed dispatch on the :retries \
21915 arm",
21916 );
21917 }
21918 }
21919
21920 #[test]
21921 fn mesh_policy_retries_projects_option_u32_by_copy() {
21922 // The by-copy pin: [`MeshPolicy::retries`] returns
21923 // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
21924 // accessor must return by value, not by reference. Sibling of
21925 // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
21926 // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
21927 // extended onto the sibling `Option<u32>` copy-invariant
21928 // shape — the accessor's returned `Option<u32>` must outlive
21929 // `&self` (multiple calls must return equal values from a
21930 // dropped-`&self` copy, since the returned Option carries no
21931 // borrow), and calling the accessor twice on the same
21932 // MeshPolicy must yield the same `Option<u32>` verbatim
21933 // (idempotent, no side effects on `&self`).
21934 //
21935 // Pins against a future silent detour that returned
21936 // `Option<&u32>` (which would type-check but silently break
21937 // every downstream caller — [`crate::render::single_field_overlay`]'s
21938 // first parameter is `Option<T: Clone>`, and `&u32` would
21939 // fold to a detached copy at the call site), an accidental
21940 // `Option::as_ref()` projection (`self.retries.as_ref()` would
21941 // also type-check but return `Option<&u32>`), or a one-arm-
21942 // only accessor that reads `Some(*n)` in the Some arm but
21943 // reads a fresh `Default::default()` (`0_u32`) in the None
21944 // arm.
21945 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
21946 let p = MeshPolicy {
21947 retries,
21948 ..MeshPolicy::default()
21949 };
21950 let first = p.retries();
21951 let second = p.retries();
21952 assert_eq!(
21953 first, second,
21954 "MeshPolicy::retries must be idempotent — two \
21955 successive calls on the same &self must return the \
21956 same Option<u32>",
21957 );
21958 assert_eq!(
21959 first, retries,
21960 "MeshPolicy::retries must return :politicas :retries \
21961 verbatim by copy — got {first:?}, expected {retries:?}",
21962 );
21963 }
21964 }
21965
21966 #[test]
21967 fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
21968 // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
21969 // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
21970 // return the `:politicas :timeout` typed [`Duration`] verbatim
21971 // as an `Option<Duration>`, byte-equal to the raw field access
21972 // across every representative value in the accept-set — `None`
21973 // (cluster default applies — typically the gateway class's
21974 // implementation-side per-request wall-clock cap the caixa-mesh
21975 // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
21976 // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
21977 // set the surrounding `AplicacaoSpec::validate_politicas` gate
21978 // carves out on the sibling `PolicyTimeoutZero` /
21979 // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
21980 // (the upper boundary the same gate carves out on the sibling
21981 // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
21982 // (a past-the-guard sentinel that pins the accessor doesn't
21983 // perform a silent bounds-collapse into `None` on the zero-
21984 // Duration arm — validate rejects zero but the accessor must
21985 // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
21986 // past-the-guard sentinel that pins the accessor doesn't
21987 // perform a silent bounds-collapse at the return path).
21988 //
21989 // Sibling of the peer per-`:politicas`
21990 // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
21991 // `Option<u32>` optional-scalar axis and the peer per-
21992 // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
21993 // pin on the sibling `Option<bool>` optional-scalar axis,
21994 // extended onto the peer per-`:politicas` `Option<Duration>`
21995 // shape — third `Option<Copy-T>`-return accessor on the M3
21996 // mesh-slot family. Pins against a future silent detour that
21997 // re-derived the per-call cap from a peer axis (an accidental
21998 // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
21999 // read the breaker's rolling-window duration as a per-call
22000 // deadline), a `None → Some(Duration::MAX)` cluster-default
22001 // projection (which would silently re-introduce the
22002 // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
22003 // blocking" arm at the emit boundary), or a bounds-collapsing
22004 // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
22005 // (the `AplicacaoSpec::validate` gate owns the bounds; the
22006 // accessor must ship the raw slot verbatim so a validate-time
22007 // gate regression surfaces at the emit boundary rather than
22008 // being silently absorbed).
22009 for timeout in [
22010 None,
22011 Some(Duration::from_millis(1)),
22012 Some(POLICY_TIMEOUT_MAX),
22013 Some(Duration::ZERO),
22014 Some(Duration::MAX),
22015 ] {
22016 let p = MeshPolicy {
22017 timeout,
22018 ..MeshPolicy::default()
22019 };
22020 assert_eq!(
22021 p.timeout(),
22022 timeout,
22023 "MeshPolicy::timeout must return :politicas :timeout \
22024 verbatim (got {:?}, expected {timeout:?})",
22025 p.timeout(),
22026 );
22027 assert_eq!(
22028 p.timeout(),
22029 p.timeout,
22030 "MeshPolicy::timeout must byte-equal the raw .timeout \
22031 field access across every value in the accept-set",
22032 );
22033 }
22034 }
22035
22036 #[test]
22037 fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
22038 // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
22039 // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
22040 // field access. Structurally: toggling ONLY the `timeout` slot
22041 // on an otherwise-default MeshPolicy must flip `is_empty()`
22042 // from `true` (all-`None`) to `false` (one axis carries a
22043 // value); the flip must be observed for every value in the
22044 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
22045 // gate accepts (`Some(Duration::from_millis(1))`,
22046 // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
22047 // reads "any axis carries a value" — not "any axis carries a
22048 // value the validate gate accepts" — the same non-collapsing
22049 // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
22050 // [`crate::BehaviorSpec::is_empty`] predicates carry.
22051 //
22052 // Pins against a future silent detour that re-derived the
22053 // emptiness predicate off a peer axis (an accidental
22054 // `.rate_limit.is_none()`-only chain that dropped the
22055 // `timeout` arm entirely), a `timeout == Some(_)` collapse
22056 // that key-off a validate-gate-clamped bounds check (which
22057 // would silently classify a past-the-guard `Some(Duration::MAX)`
22058 // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
22059 // check), or an accessor-side detour that no longer names the
22060 // substrate-primitive typed dispatch.
22061 //
22062 // Sibling of the peer per-`:politicas`
22063 // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
22064 // the sibling `Option<u32>` optional-scalar axis and the peer
22065 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
22066 // accessor-composition pin on the sibling `Option<bool>`
22067 // optional-scalar axis — same "the emptiness predicate must
22068 // route through the substrate-primitive typed dispatch"
22069 // discipline extended onto the peer per-`:politicas`
22070 // `Option<Duration>` axis.
22071 let empty = MeshPolicy::default();
22072 assert!(
22073 empty.is_empty(),
22074 "MeshPolicy::default() must be is_empty() — every axis \
22075 defaults to None",
22076 );
22077 for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
22078 let p = MeshPolicy {
22079 timeout,
22080 ..MeshPolicy::default()
22081 };
22082 assert!(
22083 !p.is_empty(),
22084 "MeshPolicy::is_empty must return false when \
22085 :timeout is {timeout:?} — the emptiness \
22086 predicate reads \"any axis carries a value\", not \
22087 \"any axis carries a value the validate gate \
22088 accepts\"",
22089 );
22090 assert_eq!(
22091 p.timeout().is_none(),
22092 p.is_empty(),
22093 "when :timeout is the only set axis, is_empty() \
22094 must equal timeout().is_none() — the accessor and \
22095 the emptiness predicate must route through the same \
22096 substrate-primitive typed dispatch on the :timeout \
22097 arm",
22098 );
22099 }
22100 }
22101
22102 #[test]
22103 fn mesh_policy_timeout_projects_option_duration_by_copy() {
22104 // The by-copy pin: [`MeshPolicy::timeout`] returns
22105 // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
22106 // and the accessor must return by value, not by reference.
22107 // Sibling of the peer per-`:politicas`
22108 // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
22109 // sibling `Option<u32>` optional-scalar axis and the peer
22110 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
22111 // by-copy pin on the sibling `Option<bool>` optional-scalar
22112 // axis, extended onto the peer per-`:politicas`
22113 // `Option<Duration>` copy-invariant shape — the accessor's
22114 // returned `Option<Duration>` must outlive `&self` (multiple
22115 // calls must return equal values from a dropped-`&self`
22116 // copy, since the returned Option carries no borrow), and
22117 // calling the accessor twice on the same MeshPolicy must
22118 // yield the same `Option<Duration>` verbatim (idempotent, no
22119 // side effects on `&self`).
22120 //
22121 // Pins against a future silent detour that returned
22122 // `Option<&Duration>` (which would type-check but silently
22123 // break every downstream caller — [`crate::render::single_field_overlay`]'s
22124 // first parameter is `Option<T: Clone>`, and `&Duration`
22125 // would fold to a detached copy at the call site), an
22126 // accidental `Option::as_ref()` projection
22127 // (`self.timeout.as_ref()` would also type-check but return
22128 // `Option<&Duration>`), or a one-arm-only accessor that
22129 // reads `Some(*d)` in the Some arm but reads a fresh
22130 // `Default::default()` (`Duration::ZERO`) in the None arm
22131 // (which would silently re-classify every unset `:timeout`
22132 // as the `PolicyTimeoutZero`-refused zero-Duration value at
22133 // the accessor boundary).
22134 for timeout in [
22135 None,
22136 Some(Duration::from_millis(1)),
22137 Some(POLICY_TIMEOUT_MAX),
22138 Some(Duration::ZERO),
22139 Some(Duration::MAX),
22140 ] {
22141 let p = MeshPolicy {
22142 timeout,
22143 ..MeshPolicy::default()
22144 };
22145 let first = p.timeout();
22146 let second = p.timeout();
22147 assert_eq!(
22148 first, second,
22149 "MeshPolicy::timeout must be idempotent — two \
22150 successive calls on the same &self must return the \
22151 same Option<Duration>",
22152 );
22153 assert_eq!(
22154 first, timeout,
22155 "MeshPolicy::timeout must return :politicas :timeout \
22156 verbatim by copy — got {first:?}, expected {timeout:?}",
22157 );
22158 }
22159 }
22160
22161 #[test]
22162 fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
22163 // The canonical per-`:politicas` `:rate-limit` Envoy-
22164 // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
22165 // [`MeshPolicy::rate_limit`] must return the `:politicas
22166 // :rate-limit` typed [`RateLimit`] verbatim as an
22167 // `Option<RateLimit>`, byte-equal to the raw field access
22168 // across every representative value in the accept-set — `None`
22169 // (cluster default applies — no per-Aplicacao rate declaration,
22170 // the gateway-class per-listener default arm the future caixa-
22171 // mesh `local_rate_limit_overlay` emitter documents),
22172 // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
22173 // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
22174 // accept-set the surrounding
22175 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
22176 // sibling `PolicyRateLimitZero` refusal, paired with the
22177 // canonical-window "1 second" arm of the three-unit
22178 // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
22179 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
22180 // (the upper boundary the same gate carves out on the sibling
22181 // `PolicyRateLimitExceedsCap` refusal, paired with the
22182 // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
22183 // (a past-the-guard sentinel that pins the accessor doesn't
22184 // perform a silent bounds-collapse into `None` on the
22185 // zero-rate/zero-window arm — validate rejects zero but the
22186 // accessor must ship the raw slot verbatim so a validate-time
22187 // gate regression surfaces at the emit boundary rather than
22188 // being silently absorbed), and
22189 // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
22190 // (a past-the-guard sentinel that pins the accessor doesn't
22191 // perform a silent bounds-collapse at the return path).
22192 //
22193 // First `Option<Copy-composite-T>`-return accessor pin on the
22194 // M3 mesh-slot family (peer of the sibling per-`:politicas`
22195 // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
22196 // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
22197 // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
22198 // Copy accessor pins, extended onto the peer per-`:politicas`
22199 // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
22200 // and the accessor returns by value). Pins against a future
22201 // silent detour that re-derived the rate declaration from a
22202 // peer axis (an accidental
22203 // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
22204 // collapse that read the breaker's trip threshold + rolling
22205 // window as a rate declaration), a `None → Some(default())`
22206 // cluster-default projection (which would silently re-
22207 // introduce a "cluster default is 0/s" arm the emit boundary
22208 // would take as "declared but inert" — the canonical
22209 // declared-but-inert footgun the sibling
22210 // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
22211 // amplification-shape axis), a bounds-collapsing accessor
22212 // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
22213 // clamped `rl.window` through [`is_canonical_rate_limit_window`]
22214 // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
22215 // accessor must ship the raw slot verbatim), or a
22216 // by-reference detour (`Option<&RateLimit>`) that broke every
22217 // downstream consumer keying off `Option<RateLimit>` by-copy.
22218 for rl in [
22219 None,
22220 Some(RateLimit {
22221 rate: 1,
22222 window: Duration::from_secs(1),
22223 }),
22224 Some(RateLimit {
22225 rate: POLICY_RATE_LIMIT_MAX,
22226 window: Duration::from_secs(3600),
22227 }),
22228 Some(RateLimit {
22229 rate: 0,
22230 window: Duration::ZERO,
22231 }),
22232 Some(RateLimit {
22233 rate: u32::MAX,
22234 window: Duration::MAX,
22235 }),
22236 ] {
22237 let p = MeshPolicy {
22238 rate_limit: rl,
22239 ..MeshPolicy::default()
22240 };
22241 assert_eq!(
22242 p.rate_limit(),
22243 rl,
22244 "MeshPolicy::rate_limit must return :politicas :rate-limit \
22245 verbatim (got {:?}, expected {rl:?})",
22246 p.rate_limit(),
22247 );
22248 assert_eq!(
22249 p.rate_limit(),
22250 p.rate_limit,
22251 "MeshPolicy::rate_limit must byte-equal the raw \
22252 .rate_limit field access across every value in the \
22253 accept-set",
22254 );
22255 }
22256 }
22257
22258 #[test]
22259 fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
22260 // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
22261 // must key off [`MeshPolicy::rate_limit`], not the raw
22262 // `.rate_limit` field access. Structurally: toggling ONLY the
22263 // `rate_limit` slot on an otherwise-default MeshPolicy must
22264 // flip `is_empty()` from `true` (all-`None`) to `false` (one
22265 // axis carries a value); the flip must be observed for every
22266 // representative value in the accept-set the surrounding
22267 // [`AplicacaoSpec::validate_politicas`] gate accepts
22268 // (`Some(RateLimit { rate: 1, window: 1s })`,
22269 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
22270 // since the emptiness semantic reads "any axis carries a
22271 // value" — not "any axis carries a value the validate gate
22272 // accepts" — the same non-collapsing shape the peer M2
22273 // [`crate::LimitsSpec::is_empty`] /
22274 // [`crate::BehaviorSpec::is_empty`] predicates carry.
22275 //
22276 // Pins against a future silent detour that re-derived the
22277 // emptiness predicate off a peer axis (an accidental
22278 // `.timeout.is_none()`-only chain that dropped the
22279 // `rate_limit` arm entirely — the last unlifted inline field
22280 // access on `is_empty` before this lift), a `rate_limit ==
22281 // Some(_)` collapse that key-off a validate-gate-clamped
22282 // bounds check (which would silently classify a past-the-
22283 // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
22284 // because it fails the value-shape gate), or an accessor-
22285 // side detour that no longer names the substrate-primitive
22286 // typed dispatch.
22287 //
22288 // Fourth "the emptiness predicate must route through the
22289 // substrate-primitive typed dispatch" composition pin on the
22290 // M3 mesh-slot family — closes the last unlifted composition
22291 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
22292 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
22293 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
22294 // 7073d0f is_empty-composition pins on the sibling primitive-
22295 // Copy axes, extended onto the peer per-`:politicas`
22296 // composite-Copy `Option<RateLimit>` axis).
22297 let empty = MeshPolicy::default();
22298 assert!(
22299 empty.is_empty(),
22300 "MeshPolicy::default() must be is_empty() — every axis \
22301 defaults to None",
22302 );
22303 for rl in [
22304 RateLimit {
22305 rate: 1,
22306 window: Duration::from_secs(1),
22307 },
22308 RateLimit {
22309 rate: POLICY_RATE_LIMIT_MAX,
22310 window: Duration::from_secs(3600),
22311 },
22312 ] {
22313 let p = MeshPolicy {
22314 rate_limit: Some(rl),
22315 ..MeshPolicy::default()
22316 };
22317 assert!(
22318 !p.is_empty(),
22319 "MeshPolicy::is_empty must return false when \
22320 :rate-limit is {rl:?} — the emptiness predicate \
22321 reads \"any axis carries a value\", not \"any axis \
22322 carries a value the validate gate accepts\"",
22323 );
22324 assert_eq!(
22325 p.rate_limit().is_none(),
22326 p.is_empty(),
22327 "when :rate-limit is the only set axis, is_empty() \
22328 must equal rate_limit().is_none() — the accessor \
22329 and the emptiness predicate must route through the \
22330 same substrate-primitive typed dispatch on the \
22331 :rate-limit arm",
22332 );
22333 }
22334 }
22335
22336 #[test]
22337 fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
22338 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22339 // `:rate-limit` value-shape gate must key off
22340 // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
22341 // field bind. Structurally: a `MeshPolicy` whose only set
22342 // axis is a `Some(RateLimit { rate: 0, .. })` must surface
22343 // the `PolicyRateLimitZero` refusal exactly, and the same
22344 // MeshPolicy with the rate at the canonical lower boundary
22345 // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
22346 // The pair jointly pins the accessor + validate-gate
22347 // composition: any future silent detour that had the accessor
22348 // omit the `Some(RateLimit { rate: 0, .. })` arm (a
22349 // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
22350 // silently absorb the `PolicyRateLimitZero` refusal at the
22351 // accessor boundary — the composition pin catches that at
22352 // caixa-core build time.
22353 //
22354 // Sibling of the peer [`validate_politicas`]
22355 // `:mtls-required` / `:retries` / `:timeout` composition pins
22356 // on the sibling primitive-Copy optional-scalar axes — same
22357 // "the validate / shape-gate predicate must route through the
22358 // substrate-primitive typed dispatch" discipline extended
22359 // onto the peer per-`:politicas` composite-Copy
22360 // `Option<RateLimit>` axis. Second composition-with-accessor
22361 // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
22362 // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
22363 let mut spec = three_member_spec();
22364 spec.politicas = MeshPolicy {
22365 rate_limit: Some(RateLimit {
22366 rate: 0,
22367 window: Duration::from_secs(1),
22368 }),
22369 ..MeshPolicy::default()
22370 };
22371 assert!(
22372 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
22373 "validate_politicas must reject rate == 0 with \
22374 PolicyRateLimitZero — the accessor and the validate gate \
22375 must route through the same substrate-primitive typed \
22376 dispatch on the :rate-limit zero-floor arm",
22377 );
22378 spec.politicas = MeshPolicy {
22379 rate_limit: Some(RateLimit {
22380 rate: 1,
22381 window: Duration::from_secs(1),
22382 }),
22383 ..MeshPolicy::default()
22384 };
22385 assert!(
22386 spec.validate().is_ok(),
22387 "validate_politicas must accept rate == 1 (the canonical \
22388 lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
22389 set) with a canonical 1s window",
22390 );
22391 }
22392
22393 #[test]
22394 fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
22395 // The canonical per-`:politicas` `:circuit-breaker` Envoy-
22396 // `outlier_detection`-mesh consecutive-failure-ejection scalar
22397 // pin: [`MeshPolicy::circuit_breaker`] must return the
22398 // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
22399 // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
22400 // raw field access across every representative value in the
22401 // accept-set — `None` (cluster default applies — no
22402 // per-Aplicacao breaker declaration, the gateway-class per-
22403 // listener default arm the future caixa-mesh
22404 // `outlier_detection_overlay` emitter documents),
22405 // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
22406 // (the lower boundary of the accept-set the surrounding
22407 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
22408 // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
22409 // refusals),
22410 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
22411 // (the upper boundary the same gate carves out on the sibling
22412 // `PolicyBreakerMaxFailuresExceedsCap` /
22413 // `PolicyBreakerWindowExceedsCap` refusals),
22414 // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
22415 // (a past-the-guard sentinel that pins the accessor doesn't
22416 // perform a silent bounds-collapse into `None` on the
22417 // zero-failures/zero-window arm — validate rejects zero but
22418 // the accessor must ship the raw slot verbatim so a validate-
22419 // time gate regression surfaces at the emit boundary rather
22420 // than being silently absorbed), and
22421 // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
22422 // (a past-the-guard sentinel that pins the accessor doesn't
22423 // perform a silent bounds-collapse at the return path).
22424 //
22425 // Second `Option<Copy-composite-T>`-return accessor pin on the
22426 // M3 mesh-slot family (peer of the sibling per-`:politicas`
22427 // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
22428 // composite-Copy accessor pin, and of the sibling per-
22429 // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
22430 // [`MeshPolicy::retries`] bdfb399 /
22431 // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
22432 // accessor pins). Pins against a future silent detour that
22433 // re-derived the breaker declaration from a peer axis (an
22434 // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
22435 // collapse that read the rate-limit's bucket capacity + refill
22436 // period as a breaker declaration), a `None → Some(default())`
22437 // cluster-default projection (which would silently re-
22438 // introduce the `PolicyBreakerZeroFailures` /
22439 // `PolicyBreakerZeroWindow` refusal cases at the emit
22440 // boundary), a bounds-collapsing accessor that clamped
22441 // `cb.max_failures` through
22442 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
22443 // through [`POLICY_BREAKER_WINDOW_MAX`] (the
22444 // [`AplicacaoSpec::validate`] gate owns the bounds; the
22445 // accessor must ship the raw slot verbatim), or a
22446 // by-reference detour (`Option<&CircuitBreaker>`) that broke
22447 // every downstream consumer keying off `Option<CircuitBreaker>`
22448 // by-copy.
22449 for cb in [
22450 None,
22451 Some(CircuitBreaker {
22452 max_failures: 1,
22453 window: Duration::from_millis(1),
22454 }),
22455 Some(CircuitBreaker {
22456 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
22457 window: POLICY_BREAKER_WINDOW_MAX,
22458 }),
22459 Some(CircuitBreaker {
22460 max_failures: 0,
22461 window: Duration::ZERO,
22462 }),
22463 Some(CircuitBreaker {
22464 max_failures: u32::MAX,
22465 window: Duration::MAX,
22466 }),
22467 ] {
22468 let p = MeshPolicy {
22469 circuit_breaker: cb,
22470 ..MeshPolicy::default()
22471 };
22472 assert_eq!(
22473 p.circuit_breaker(),
22474 cb,
22475 "MeshPolicy::circuit_breaker must return :politicas \
22476 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
22477 p.circuit_breaker(),
22478 );
22479 assert_eq!(
22480 p.circuit_breaker(),
22481 p.circuit_breaker,
22482 "MeshPolicy::circuit_breaker must byte-equal the raw \
22483 .circuit_breaker field access across every value in \
22484 the accept-set",
22485 );
22486 }
22487 }
22488
22489 #[test]
22490 fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
22491 // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
22492 // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
22493 // `.circuit_breaker` field access. Structurally: toggling ONLY
22494 // the `circuit_breaker` slot on an otherwise-default MeshPolicy
22495 // must flip `is_empty()` from `true` (all-`None`) to `false`
22496 // (one axis carries a value); the flip must be observed for
22497 // every representative value in the accept-set the surrounding
22498 // [`AplicacaoSpec::validate_politicas`] gate accepts
22499 // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
22500 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
22501 // since the emptiness semantic reads "any axis carries a
22502 // value" — not "any axis carries a value the validate gate
22503 // accepts" — the same non-collapsing shape the peer M2
22504 // [`crate::LimitsSpec::is_empty`] /
22505 // [`crate::BehaviorSpec::is_empty`] predicates carry.
22506 //
22507 // Pins against a future silent detour that re-derived the
22508 // emptiness predicate off a peer axis (an accidental
22509 // `.rate_limit.is_none()`-only chain that dropped the
22510 // `circuit_breaker` arm entirely — the last unlifted inline
22511 // field access on `is_empty` before this lift), a
22512 // `circuit_breaker == Some(_)` collapse that key-off a
22513 // validate-gate-clamped bounds check (which would silently
22514 // classify a past-the-guard `Some(CircuitBreaker { max_failures:
22515 // 0, window: 0s })` as empty because it fails the value-shape
22516 // gate), or an accessor-side detour that no longer names the
22517 // substrate-primitive typed dispatch.
22518 //
22519 // Fifth "the emptiness predicate must route through the
22520 // substrate-primitive typed dispatch" composition pin on the
22521 // M3 mesh-slot family — closes the last unlifted composition
22522 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
22523 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
22524 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
22525 // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
22526 // composition pins on the sibling primitive-Copy + composite-
22527 // Copy axes, extended onto the peer per-`:politicas`
22528 // composite-Copy `Option<CircuitBreaker>` axis).
22529 let empty = MeshPolicy::default();
22530 assert!(
22531 empty.is_empty(),
22532 "MeshPolicy::default() must be is_empty() — every axis \
22533 defaults to None",
22534 );
22535 for cb in [
22536 CircuitBreaker {
22537 max_failures: 1,
22538 window: Duration::from_millis(1),
22539 },
22540 CircuitBreaker {
22541 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
22542 window: POLICY_BREAKER_WINDOW_MAX,
22543 },
22544 ] {
22545 let p = MeshPolicy {
22546 circuit_breaker: Some(cb),
22547 ..MeshPolicy::default()
22548 };
22549 assert!(
22550 !p.is_empty(),
22551 "MeshPolicy::is_empty must return false when \
22552 :circuit-breaker is {cb:?} — the emptiness predicate \
22553 reads \"any axis carries a value\", not \"any axis \
22554 carries a value the validate gate accepts\"",
22555 );
22556 assert_eq!(
22557 p.circuit_breaker().is_none(),
22558 p.is_empty(),
22559 "when :circuit-breaker is the only set axis, \
22560 is_empty() must equal circuit_breaker().is_none() — \
22561 the accessor and the emptiness predicate must route \
22562 through the same substrate-primitive typed dispatch \
22563 on the :circuit-breaker arm",
22564 );
22565 }
22566 }
22567
22568 #[test]
22569 fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
22570 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22571 // `:circuit-breaker` value-shape gate must key off
22572 // [`MeshPolicy::circuit_breaker`], not the raw
22573 // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
22574 // whose only set axis is a `Some(CircuitBreaker { max_failures:
22575 // 0, .. })` must surface the `PolicyBreakerZeroFailures`
22576 // refusal exactly, and the same MeshPolicy with the breaker at
22577 // the canonical lower boundary
22578 // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
22579 // pass validate. The pair jointly pins the accessor +
22580 // validate-gate composition: any future silent detour that had
22581 // the accessor omit the `Some(CircuitBreaker { max_failures:
22582 // 0, .. })` arm (a
22583 // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
22584 // collapse) would silently absorb the
22585 // `PolicyBreakerZeroFailures` refusal at the accessor
22586 // boundary — the composition pin catches that at caixa-core
22587 // build time.
22588 //
22589 // Sibling of the peer [`validate_politicas`]
22590 // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
22591 // composition pins on the sibling primitive-Copy + composite-
22592 // Copy optional-scalar axes — same "the validate / shape-gate
22593 // predicate must route through the substrate-primitive typed
22594 // dispatch" discipline extended onto the peer per-`:politicas`
22595 // composite-Copy `Option<CircuitBreaker>` axis. Second
22596 // composition-with-accessor pin on the M3 mesh-slot
22597 // `Option<CircuitBreaker>` arm alongside the
22598 // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
22599 let mut spec = three_member_spec();
22600 spec.politicas = MeshPolicy {
22601 circuit_breaker: Some(CircuitBreaker {
22602 max_failures: 0,
22603 window: Duration::from_millis(1),
22604 }),
22605 ..MeshPolicy::default()
22606 };
22607 assert!(
22608 matches!(
22609 spec.validate(),
22610 Err(AplicacaoError::PolicyBreakerZeroFailures)
22611 ),
22612 "validate_politicas must reject max_failures == 0 with \
22613 PolicyBreakerZeroFailures — the accessor and the validate \
22614 gate must route through the same substrate-primitive \
22615 typed dispatch on the :circuit-breaker zero-floor arm",
22616 );
22617 spec.politicas = MeshPolicy {
22618 circuit_breaker: Some(CircuitBreaker {
22619 max_failures: 1,
22620 window: Duration::from_millis(1),
22621 }),
22622 ..MeshPolicy::default()
22623 };
22624 assert!(
22625 spec.validate().is_ok(),
22626 "validate_politicas must accept a CircuitBreaker at the \
22627 canonical lower boundary (max_failures = 1, window = \
22628 1ms) — the accessor and the validate gate must route \
22629 through the same substrate-primitive typed dispatch on \
22630 the :circuit-breaker arm",
22631 );
22632 }
22633
22634 #[test]
22635 fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
22636 // The canonical per-`:politicas :circuit-breaker` `:max-failures`
22637 // Envoy-outlier-detection trip-threshold scalar pin:
22638 // [`CircuitBreaker::max_failures`] must return the
22639 // `:politicas :circuit-breaker :max-failures` typed `u32`
22640 // verbatim, byte-equal to the raw field access across every
22641 // representative value in the accept-set — `1` (the lower
22642 // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
22643 // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
22644 // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
22645 // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
22646 // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
22647 // refusal), `0` (a past-the-guard sentinel that pins the accessor
22648 // doesn't perform a silent bounds-collapse into `1` on the zero
22649 // arm — validate rejects zero but the accessor must ship the
22650 // raw slot verbatim so a validate-time gate regression surfaces
22651 // at the emit boundary rather than being silently absorbed),
22652 // `u32::MAX` (a past-the-guard sentinel that pins the accessor
22653 // doesn't perform a silent bounds-collapse through
22654 // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
22655 //
22656 // First sub-struct required-scalar accessor pin on the M3
22657 // mesh-slot family — sibling in shape to the peer per-`:membros`
22658 // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
22659 // (a40b0e3) required-`String`-carry accessor pins and the peer
22660 // per-`:contratos` [`WitContract::source`] /
22661 // [`WitContract::destination`] (7f0fd43) required-`String`-carry
22662 // accessor pins, extended onto the peer per-`CircuitBreaker`
22663 // required-`u32` scalar-value axis. Pins against a future silent
22664 // detour that re-derived the trip threshold from a peer axis (an
22665 // accidental `self.window.as_secs() as u32` collapse that read
22666 // the breaker's rolling-window duration as a failure count), a
22667 // `0 → 1` cluster-default projection (which would silently absorb
22668 // the `PolicyBreakerZeroFailures` refusal case at the accessor
22669 // boundary), or a bounds-collapsing accessor that clamped the
22670 // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
22671 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
22672 // must ship the raw slot verbatim).
22673 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
22674 let cb = CircuitBreaker {
22675 max_failures,
22676 window: Duration::from_secs(60),
22677 };
22678 assert_eq!(
22679 cb.max_failures(),
22680 max_failures,
22681 "CircuitBreaker::max_failures must return :politicas \
22682 :circuit-breaker :max-failures verbatim (got {}, \
22683 expected {max_failures})",
22684 cb.max_failures(),
22685 );
22686 assert_eq!(
22687 cb.max_failures(),
22688 cb.max_failures,
22689 "CircuitBreaker::max_failures must byte-equal the raw \
22690 .max_failures field access across every value in the \
22691 u32 accept-set",
22692 );
22693 }
22694 }
22695
22696 #[test]
22697 fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
22698 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22699 // `:circuit-breaker :max-failures` zero-floor arm must key off
22700 // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
22701 // field access. Structurally: a `CircuitBreaker { max_failures:
22702 // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
22703 // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
22704 // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
22705 // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
22706 // pass validate. The pair jointly pins the accessor +
22707 // validate-gate composition: any future silent detour that had
22708 // the accessor return a fresh `1` on the zero arm (a
22709 // `.max_failures().max(1)` collapse) would silently absorb the
22710 // `PolicyBreakerZeroFailures` refusal at the accessor boundary
22711 // and the validate gate would accept a struct-literal
22712 // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
22713 // catches that at caixa-core build time.
22714 //
22715 // Peer of the sibling per-`:politicas`
22716 // [`MeshPolicy::mtls_required`] (c0110f1) /
22717 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
22718 // (7073d0f) accessor-composition pins on the sibling optional-
22719 // scalar axes — same "the validate / shape-gate predicate must
22720 // route through the substrate-primitive typed dispatch"
22721 // discipline extended onto the peer per-`CircuitBreaker`
22722 // required-scalar composition axis.
22723 let mut spec = three_member_spec();
22724 spec.politicas = MeshPolicy {
22725 circuit_breaker: Some(CircuitBreaker {
22726 max_failures: 0,
22727 window: Duration::from_secs(60),
22728 }),
22729 ..MeshPolicy::default()
22730 };
22731 assert!(
22732 matches!(
22733 spec.validate(),
22734 Err(AplicacaoError::PolicyBreakerZeroFailures)
22735 ),
22736 "validate_politicas must reject max_failures == 0 with \
22737 PolicyBreakerZeroFailures — the accessor and the validate \
22738 gate must route through the same substrate-primitive typed \
22739 dispatch on the :max-failures zero-floor arm",
22740 );
22741 spec.politicas = MeshPolicy {
22742 circuit_breaker: Some(CircuitBreaker {
22743 max_failures: 1,
22744 window: Duration::from_secs(60),
22745 }),
22746 ..MeshPolicy::default()
22747 };
22748 assert!(
22749 spec.validate().is_ok(),
22750 "validate_politicas must accept max_failures == 1 (the \
22751 lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
22752 accept-set)",
22753 );
22754 }
22755
22756 #[test]
22757 fn circuit_breaker_max_failures_projects_u32_by_copy() {
22758 // The by-copy pin: [`CircuitBreaker::max_failures`] returns
22759 // `u32` by copy — `u32` is `Copy` and the accessor must return
22760 // by value, not by reference. Peer of the sibling
22761 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
22762 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
22763 // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
22764 // optional-scalar axes, extended onto the peer
22765 // per-`CircuitBreaker` required-`u32` copy-invariant shape —
22766 // the accessor's returned `u32` must outlive `&self` (multiple
22767 // calls must return equal values from a dropped-`&self` copy,
22768 // since the returned scalar carries no borrow), and calling
22769 // the accessor twice on the same CircuitBreaker must yield the
22770 // same `u32` verbatim (idempotent, no side effects on `&self`).
22771 //
22772 // Pins against a future silent detour that returned `&u32`
22773 // (which would type-check but silently break every downstream
22774 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
22775 // first parameter is `u32`, and `&u32` would fold to a detached
22776 // copy at the call site with a `*` deref the sibling accessors
22777 // don't need), an accidental `.max_failures.wrapping_add(0)`
22778 // detour that returned a fresh copy through an arithmetic
22779 // no-op (breaking a future `const fn` regression), or a
22780 // one-arm-only accessor that returned a saturating value on
22781 // some sentinel input (breaking the pass-through invariant the
22782 // sibling required-scalar accessors carry).
22783 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
22784 let cb = CircuitBreaker {
22785 max_failures,
22786 window: Duration::from_secs(60),
22787 };
22788 let first = cb.max_failures();
22789 let second = cb.max_failures();
22790 assert_eq!(
22791 first, second,
22792 "CircuitBreaker::max_failures must be idempotent — two \
22793 successive calls on the same &self must return the \
22794 same u32",
22795 );
22796 assert_eq!(
22797 first, max_failures,
22798 "CircuitBreaker::max_failures must return :politicas \
22799 :circuit-breaker :max-failures verbatim by copy — \
22800 got {first}, expected {max_failures}",
22801 );
22802 }
22803 }
22804
22805 #[test]
22806 fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
22807 // The canonical per-`:politicas :circuit-breaker` `:window`
22808 // Envoy-outlier-detection rolling-observation-interval scalar
22809 // pin: [`CircuitBreaker::window`] must return the
22810 // `:politicas :circuit-breaker :window` typed `Duration`
22811 // verbatim, byte-equal to the raw field access across every
22812 // representative value in the accept-set — `Duration::from_millis(1)`
22813 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
22814 // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
22815 // gate carves out on the sibling `PolicyBreakerZeroWindow`
22816 // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
22817 // same gate carves out on the sibling
22818 // `PolicyBreakerWindowExceedsCap` refusal),
22819 // `Duration::ZERO` (a past-the-guard sentinel that pins the
22820 // accessor doesn't perform a silent bounds-collapse into
22821 // `Duration::from_millis(1)` on the zero arm — validate rejects
22822 // zero but the accessor must ship the raw slot verbatim so a
22823 // validate-time gate regression surfaces at the emit boundary
22824 // rather than being silently absorbed),
22825 // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
22826 // far above the 1h cap — that pins the accessor doesn't perform
22827 // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
22828 // at the return path).
22829 //
22830 // Second sub-struct required-scalar accessor pin on the M3
22831 // mesh-slot family — sibling in shape to the just-landed
22832 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
22833 // (3a74062) required-`u32` accessor pin on the peer
22834 // per-`CircuitBreaker` required-axis, extended onto the
22835 // per-sub-struct required-`Duration` axis. Pins against a
22836 // future silent detour that re-derived the observation window
22837 // from a peer axis (an accidental
22838 // `Duration::from_secs(self.max_failures as u64)` collapse that
22839 // read the breaker's trip count as an observation-interval
22840 // duration), a `Duration::ZERO → Duration::from_millis(1)`
22841 // cluster-default projection (which would silently absorb the
22842 // `PolicyBreakerZeroWindow` refusal case at the accessor
22843 // boundary), or a bounds-collapsing accessor that clamped the
22844 // return through `POLICY_BREAKER_WINDOW_MAX` (the
22845 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
22846 // must ship the raw slot verbatim).
22847 for window in [
22848 Duration::from_millis(1),
22849 POLICY_BREAKER_WINDOW_MAX,
22850 Duration::ZERO,
22851 Duration::from_secs(86_400),
22852 ] {
22853 let cb = CircuitBreaker {
22854 max_failures: 5,
22855 window,
22856 };
22857 assert_eq!(
22858 cb.window(),
22859 window,
22860 "CircuitBreaker::window must return :politicas \
22861 :circuit-breaker :window verbatim (got {:?}, \
22862 expected {window:?})",
22863 cb.window(),
22864 );
22865 assert_eq!(
22866 cb.window(),
22867 cb.window,
22868 "CircuitBreaker::window must byte-equal the raw \
22869 .window field access across every value in the \
22870 Duration accept-set",
22871 );
22872 }
22873 }
22874
22875 #[test]
22876 fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
22877 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22878 // `:circuit-breaker :window` zero-floor arm must key off
22879 // [`CircuitBreaker::window`], not the raw `.window` field
22880 // access. Structurally: a `CircuitBreaker { window:
22881 // Duration::ZERO, .. }` embedded in a
22882 // `:politicas :circuit-breaker` slot must surface the
22883 // `PolicyBreakerZeroWindow` refusal exactly, and a
22884 // `CircuitBreaker { window: Duration::from_millis(1), .. }`
22885 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
22886 // accept-set) must pass validate. The pair jointly pins the
22887 // accessor + validate-gate composition: any future silent
22888 // detour that had the accessor return a fresh
22889 // `Duration::from_millis(1)` on the zero arm (a
22890 // `.window().max(Duration::from_millis(1))` collapse) would
22891 // silently absorb the `PolicyBreakerZeroWindow` refusal at the
22892 // accessor boundary and the validate gate would accept a
22893 // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
22894 // — the composition pin catches that at caixa-core build time.
22895 //
22896 // Peer of the sibling per-`CircuitBreaker`
22897 // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
22898 // pin on the peer required-scalar `:max-failures` axis — same
22899 // "the validate / shape-gate predicate must route through the
22900 // substrate-primitive typed dispatch" discipline extended onto
22901 // the peer per-`CircuitBreaker` required-`Duration` composition
22902 // axis.
22903 let mut spec = three_member_spec();
22904 spec.politicas = MeshPolicy {
22905 circuit_breaker: Some(CircuitBreaker {
22906 max_failures: 5,
22907 window: Duration::ZERO,
22908 }),
22909 ..MeshPolicy::default()
22910 };
22911 assert!(
22912 matches!(
22913 spec.validate(),
22914 Err(AplicacaoError::PolicyBreakerZeroWindow)
22915 ),
22916 "validate_politicas must reject window == Duration::ZERO \
22917 with PolicyBreakerZeroWindow — the accessor and the \
22918 validate gate must route through the same substrate-\
22919 primitive typed dispatch on the :window zero-floor arm",
22920 );
22921 spec.politicas = MeshPolicy {
22922 circuit_breaker: Some(CircuitBreaker {
22923 max_failures: 5,
22924 window: Duration::from_millis(1),
22925 }),
22926 ..MeshPolicy::default()
22927 };
22928 assert!(
22929 spec.validate().is_ok(),
22930 "validate_politicas must accept window == \
22931 Duration::from_millis(1) (the lower boundary of the \
22932 1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
22933 );
22934 }
22935
22936 #[test]
22937 fn circuit_breaker_window_projects_duration_by_copy() {
22938 // The by-copy pin: [`CircuitBreaker::window`] returns
22939 // `Duration` by copy — `Duration` is `Copy` and the accessor
22940 // must return by value, not by reference. Peer of the sibling
22941 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
22942 // (3a74062) by-copy pin on the peer required-scalar
22943 // `:max-failures` axis, extended onto the peer
22944 // per-`CircuitBreaker` required-`Duration` copy-invariant shape
22945 // — the accessor's returned `Duration` must outlive `&self`
22946 // (multiple calls must return equal values from a
22947 // dropped-`&self` copy, since the returned scalar carries no
22948 // borrow), and calling the accessor twice on the same
22949 // CircuitBreaker must yield the same `Duration` verbatim
22950 // (idempotent, no side effects on `&self`).
22951 //
22952 // Pins against a future silent detour that returned
22953 // `&Duration` (which would type-check but silently break every
22954 // downstream `Duration`-by-value consumer —
22955 // [`crate::render::require_positive_canonical_bounded_duration`]'s
22956 // first parameter is `Duration`, and `&Duration` would fold to
22957 // a detached copy at the call site with a `*` deref the sibling
22958 // accessors don't need), an accidental `.window + Duration::ZERO`
22959 // detour that returned a fresh copy through an arithmetic
22960 // no-op (breaking a future `const fn` regression), or a
22961 // one-arm-only accessor that returned a saturating value on
22962 // some sentinel input (breaking the pass-through invariant the
22963 // sibling required-scalar accessors carry).
22964 for window in [
22965 Duration::from_millis(1),
22966 POLICY_BREAKER_WINDOW_MAX,
22967 Duration::ZERO,
22968 Duration::from_secs(86_400),
22969 ] {
22970 let cb = CircuitBreaker {
22971 max_failures: 5,
22972 window,
22973 };
22974 let first = cb.window();
22975 let second = cb.window();
22976 assert_eq!(
22977 first, second,
22978 "CircuitBreaker::window must be idempotent — two \
22979 successive calls on the same &self must return the \
22980 same Duration",
22981 );
22982 assert_eq!(
22983 first, window,
22984 "CircuitBreaker::window must return :politicas \
22985 :circuit-breaker :window verbatim by copy — \
22986 got {first:?}, expected {window:?}",
22987 );
22988 }
22989 }
22990
22991 #[test]
22992 fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
22993 // Apex-identity pair-invariant pin composing both substrate-
22994 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
22995 // and [`WitContract::destination`] — at the emit-side call shape
22996 // every per-`(:de, :para)` CNP L4 port reader now takes. The
22997 // invariant, evaluated per-edge:
22998 //
22999 // spec.port_for_destination(c.destination()) == expected_port
23000 //
23001 // where `expected_port` is `entrada.port` when
23002 // `c.destination() == entrada.destination()` and
23003 // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
23004 // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
23005 // pin on the per-`:entrada` axis — that pin encodes the apex
23006 // ingress L4 identity via `entrada.destination()`; this pin
23007 // encodes the per-edge L4 identity via `c.destination()`, and
23008 // both compose on the same substrate-primitive resolver so a
23009 // future refactor that silently split either accessor's apex
23010 // behavior surfaces at caixa-core build time.
23011 let mut spec = three_member_spec();
23012 if let Some(e) = spec.entrada.as_mut() {
23013 e.para = "cart".into();
23014 e.port = 8443;
23015 }
23016 let apex_contract = WitContract {
23017 de: "checkout".into(),
23018 para: "cart".into(),
23019 wit: "wasi:http/proxy".into(),
23020 endpoint: Some("/hello".into()),
23021 subject: None,
23022 slot: None,
23023 };
23024 assert_eq!(
23025 spec.port_for_destination(apex_contract.destination()),
23026 8443,
23027 "`spec.port_for_destination(c.destination())` must equal \
23028 `entrada.port` when the contract callee names the ingress \
23029 apex — the CNP per-edge L4 port and the HTTPRoute apex \
23030 backendRef port share this substrate-primitive resolver.",
23031 );
23032 let non_apex_contract = WitContract {
23033 de: "cart".into(),
23034 para: "payment".into(),
23035 wit: "wasi:http/proxy".into(),
23036 endpoint: Some("/charge".into()),
23037 subject: None,
23038 slot: None,
23039 };
23040 assert_eq!(
23041 spec.port_for_destination(non_apex_contract.destination()),
23042 DEFAULT_SERVICO_PORT,
23043 "`spec.port_for_destination(c.destination())` must fall back \
23044 to the substrate-canonical port floor when the contract \
23045 callee is not the ingress apex — the resolver's non-apex \
23046 arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
23047 );
23048 }
23049
23050 #[test]
23051 fn membro_key_consts_are_lower_camel_case_shape() {
23052 // Shape-pin: every `MEMBRO_KEY_*` const must be a
23053 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23054 // `kebab-case` hyphens, no leading colon, no `PascalCase`
23055 // leading capital, no whitespace / dots) — the canonical shape
23056 // the `#[serde(rename_all = "camelCase")]` derive produces on
23057 // [`Membro`]. A future flip to a non-camelCase attribute at
23058 // the derive surfaces both here (this test fails on the
23059 // stale-constant shape) and at
23060 // `membro_serde_keys_match_lifted_membro_key_consts` (that test
23061 // fails on the mismatch between const and derive). Peer with
23062 // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
23063 // on the sibling `SupervisorSpec` top-level axis.
23064 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
23065 assert!(
23066 !key.is_empty(),
23067 "MEMBRO_KEY_* must be non-empty (got {key:?})"
23068 );
23069 let first = key.chars().next().unwrap();
23070 assert!(
23071 first.is_ascii_lowercase(),
23072 "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
23073 (got {key:?}, leads with {first:?})",
23074 );
23075 assert!(
23076 key.chars().all(|c| c.is_ascii_alphanumeric()),
23077 "MEMBRO_KEY_* must be ASCII-alphanumeric only \
23078 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23079 );
23080 }
23081 }
23082
23083 // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
23084
23085 #[test]
23086 fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
23087 // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
23088 // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
23089 // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
23090 // keys the `#[serde(rename_all = "camelCase")]` attribute on
23091 // [`WitContract`] emits for the required-triad. The three
23092 // sibling payload-arm keys already pin under
23093 // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
23094 // `STORE_FIELD_NAME` — pin all six alongside so a future
23095 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
23096 // verbatim-field-name flip at the derive attribute (any of which
23097 // would silently break every downstream JSON consumer that
23098 // reaches for one of the six via `Value::get(...)`) surfaces
23099 // here as a build-time test failure at `aplicacao.rs`, not as an
23100 // apply-time `.get(<stale-canonical-const>)` returning `None`
23101 // far from the derive-attr drift's commit. Peer with the sibling
23102 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
23103 // pin on the M3 `:membros` per-entry axis — same discipline the
23104 // `Membro` per-entry lift established, extended here to the
23105 // sibling M3 `WitContract` per-`:contratos` entry axis, the last
23106 // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
23107 // axis on the Aplicacao surface without a lifted serde-key peer.
23108 let c = WitContract {
23109 de: "cart".into(),
23110 para: "catalog".into(),
23111 wit: "wasi:http/proxy".into(),
23112 endpoint: Some("/lookup".into()),
23113 subject: None,
23114 slot: None,
23115 };
23116 let json = serde_json::to_string(&c).unwrap();
23117 for key in [
23118 crate::CONTRATO_KEY_DE,
23119 crate::CONTRATO_KEY_PARA,
23120 crate::CONTRATO_KEY_WIT,
23121 WitTarget::HTTP_FIELD_NAME,
23122 ] {
23123 let quoted = format!("\"{key}\"");
23124 assert!(
23125 json.contains("ed),
23126 "serialized WitContract must carry the lifted \
23127 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
23128 {quoted} verbatim in the JSON emission (got: {json})",
23129 );
23130 }
23131
23132 // Pin the two remaining payload-arm keys by round-tripping a
23133 // `WitContract` under each payload-shape (pub-sub, store) — the
23134 // required-triad appears on every emission but the payload arms
23135 // only surface when their `Option<String>` field is `Some`.
23136 let pubsub = WitContract {
23137 de: "cart".into(),
23138 para: "events".into(),
23139 wit: "nats:pub-sub".into(),
23140 endpoint: None,
23141 subject: Some("orders.placed".into()),
23142 slot: None,
23143 };
23144 let pubsub_json = serde_json::to_string(&pubsub).unwrap();
23145 let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
23146 assert!(
23147 pubsub_json.contains(&pubsub_quoted),
23148 "serialized pub-sub WitContract must carry the lifted \
23149 WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
23150 verbatim in the JSON emission (got: {pubsub_json})",
23151 );
23152 let store = WitContract {
23153 de: "cart".into(),
23154 para: "sessions".into(),
23155 wit: "wasi:keyvalue/store".into(),
23156 endpoint: None,
23157 subject: None,
23158 slot: Some("cart/$id".into()),
23159 };
23160 let store_json = serde_json::to_string(&store).unwrap();
23161 let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
23162 assert!(
23163 store_json.contains(&store_quoted),
23164 "serialized store WitContract must carry the lifted \
23165 WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
23166 verbatim in the JSON emission (got: {store_json})",
23167 );
23168 }
23169
23170 #[test]
23171 fn contrato_key_consts_are_pairwise_distinct() {
23172 // Cross-axis drift-detection pin: a future collapse of the six
23173 // canonical [`WitContract`] per-entry byte-strings onto the same
23174 // value (e.g. an accidental copy-paste flip of
23175 // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
23176 // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
23177 // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
23178 // every downstream probe on one axis onto the sibling axis's
23179 // overlay entry and pass every propagation-probe test that
23180 // expected only the stale axis's value. Peer of the sibling
23181 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
23182 // widened here to the six-way axis the `WitContract`
23183 // required-triad + `WitTarget` payload-triad jointly cover.
23184 let all = [
23185 crate::CONTRATO_KEY_DE,
23186 crate::CONTRATO_KEY_PARA,
23187 crate::CONTRATO_KEY_WIT,
23188 WitTarget::HTTP_FIELD_NAME,
23189 WitTarget::PUBSUB_FIELD_NAME,
23190 WitTarget::STORE_FIELD_NAME,
23191 ];
23192 for (i, a) in all.iter().enumerate() {
23193 for b in all.iter().skip(i + 1) {
23194 assert_ne!(
23195 a, b,
23196 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
23197 must be pairwise-distinct canonical byte-sequences \
23198 — got `{a}` == `{b}`",
23199 );
23200 }
23201 }
23202 }
23203
23204 #[test]
23205 fn contrato_key_consts_are_lower_camel_case_shape() {
23206 // Shape-pin: every `CONTRATO_KEY_*` (and every peer
23207 // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
23208 // byte-sequence (no `snake_case` underscores, no `kebab-case`
23209 // hyphens, no leading colon, no `PascalCase` leading capital, no
23210 // whitespace / dots) — the canonical shape the
23211 // `#[serde(rename_all = "camelCase")]` derive produces on
23212 // [`WitContract`]. A future flip to a non-camelCase attribute at
23213 // the derive surfaces both here (this test fails on the
23214 // stale-constant shape) and at
23215 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23216 // (that test fails on the mismatch between const and derive).
23217 // Peer with `membro_key_consts_are_lower_camel_case_shape`
23218 // (ce80ca0) on the sibling `Membro` per-entry axis.
23219 for key in [
23220 crate::CONTRATO_KEY_DE,
23221 crate::CONTRATO_KEY_PARA,
23222 crate::CONTRATO_KEY_WIT,
23223 WitTarget::HTTP_FIELD_NAME,
23224 WitTarget::PUBSUB_FIELD_NAME,
23225 WitTarget::STORE_FIELD_NAME,
23226 ] {
23227 assert!(
23228 !key.is_empty(),
23229 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
23230 non-empty (got {key:?})"
23231 );
23232 let first = key.chars().next().unwrap();
23233 assert!(
23234 first.is_ascii_lowercase(),
23235 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
23236 with an ASCII-lowercase byte (got {key:?}, leads with \
23237 {first:?})",
23238 );
23239 assert!(
23240 key.chars().all(|c| c.is_ascii_alphanumeric()),
23241 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
23242 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
23243 whitespace (got {key:?})",
23244 );
23245 }
23246 }
23247
23248 // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
23249
23250 #[test]
23251 fn entrada_serde_keys_match_lifted_entrada_key_consts() {
23252 // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
23253 // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
23254 // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
23255 // name the exact camelCase JSON keys the
23256 // `#[serde(rename_all = "camelCase")]` attribute on
23257 // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
23258 // pin that each canonical byte-sequence appears verbatim in the
23259 // JSON — a future accidental `rename_all = "snake_case"` /
23260 // `"kebab-case"` / verbatim-field-name flip at the derive
23261 // attribute (any of which would silently break every downstream
23262 // JSON consumer that reaches for one of the four consts via
23263 // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
23264 // emitter's per-Aplicacao hostname/paths/port projection, the
23265 // future `app-operator` reconciler's per-Aplicacao ingress
23266 // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
23267 // materializer's admission-time cross-check) surfaces here as
23268 // a build-time test failure at `aplicacao.rs`, not as an
23269 // apply-time `.get(<stale-canonical-const>)` returning `None`
23270 // far from the derive-attr drift's commit. Peer with the
23271 // sibling
23272 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23273 // (ca463a4) and
23274 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
23275 // pins on the M3 collection-slot atom axes — same discipline
23276 // both collection-slot lifts established, extended here to the
23277 // singleton `:entrada` mesh-slot atom axis, the last M3
23278 // typed-struct top-level `#[serde(rename_all = "camelCase")]`
23279 // axis on the Aplicacao surface without a lifted serde-key
23280 // peer.
23281 let e = Entrada {
23282 host: "checkout.quero.cloud".into(),
23283 para: "cart".into(),
23284 paths: vec!["/cart".into()],
23285 port: 8080,
23286 };
23287 let json = serde_json::to_string(&e).unwrap();
23288 for key in [
23289 crate::ENTRADA_KEY_HOST,
23290 crate::ENTRADA_KEY_PARA,
23291 crate::ENTRADA_KEY_PATHS,
23292 crate::ENTRADA_KEY_PORT,
23293 ] {
23294 let quoted = format!("\"{key}\"");
23295 assert!(
23296 json.contains("ed),
23297 "serialized Entrada must carry the lifted ENTRADA_KEY_* \
23298 byte-sequence {quoted} verbatim in the JSON emission \
23299 (got: {json})",
23300 );
23301 }
23302 }
23303
23304 #[test]
23305 fn entrada_key_consts_are_pairwise_distinct() {
23306 // Cross-axis drift-detection pin: a future collapse of the four
23307 // canonical [`Entrada`] singleton byte-strings onto the same
23308 // value (e.g. an accidental copy-paste flip of
23309 // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
23310 // silently reroute every downstream probe on one axis onto the
23311 // sibling axis's overlay entry and pass every propagation-probe
23312 // test that expected only the stale axis's value — the
23313 // Gateway/HTTPRoute emitter would read the hostname string
23314 // where the destination-Servico name was expected (or vice
23315 // versa), the admission-webhook cross-check would compare the
23316 // wrong pair of values, and the resulting Gateway resource
23317 // would either be admitted with garbage or rejected at the
23318 // controller far from the rebrand commit's source. Peer of the
23319 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
23320 // tetrad (40cc4e5), the two-way distinct pin on the
23321 // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
23322 // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
23323 // triad (ca463a4).
23324 let all = [
23325 crate::ENTRADA_KEY_HOST,
23326 crate::ENTRADA_KEY_PARA,
23327 crate::ENTRADA_KEY_PATHS,
23328 crate::ENTRADA_KEY_PORT,
23329 ];
23330 for (i, a) in all.iter().enumerate() {
23331 for b in all.iter().skip(i + 1) {
23332 assert_ne!(
23333 a, b,
23334 "ENTRADA_KEY_* consts must be pairwise-distinct \
23335 canonical byte-sequences — got `{a}` == `{b}`",
23336 );
23337 }
23338 }
23339 }
23340
23341 #[test]
23342 fn entrada_key_consts_are_lower_camel_case_shape() {
23343 // Shape-pin: every `ENTRADA_KEY_*` const must be a
23344 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23345 // `kebab-case` hyphens, no leading colon, no `PascalCase`
23346 // leading capital, no whitespace / dots) — the canonical shape
23347 // the `#[serde(rename_all = "camelCase")]` derive produces on
23348 // [`Entrada`]. A future flip to a non-camelCase attribute at
23349 // the derive surfaces both here (this test fails on the
23350 // stale-constant shape) and at
23351 // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
23352 // test fails on the mismatch between const and derive). Peer
23353 // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
23354 // and `contrato_key_consts_are_lower_camel_case_shape`
23355 // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
23356 // entry axes.
23357 for key in [
23358 crate::ENTRADA_KEY_HOST,
23359 crate::ENTRADA_KEY_PARA,
23360 crate::ENTRADA_KEY_PATHS,
23361 crate::ENTRADA_KEY_PORT,
23362 ] {
23363 assert!(
23364 !key.is_empty(),
23365 "ENTRADA_KEY_* must be non-empty (got {key:?})"
23366 );
23367 let first = key.chars().next().unwrap();
23368 assert!(
23369 first.is_ascii_lowercase(),
23370 "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
23371 (got {key:?}, leads with {first:?})",
23372 );
23373 assert!(
23374 key.chars().all(|c| c.is_ascii_alphanumeric()),
23375 "ENTRADA_KEY_* must be ASCII-alphanumeric only \
23376 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23377 );
23378 }
23379 }
23380
23381 // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
23382
23383 #[test]
23384 fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
23385 // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
23386 // ([`crate::POLITICAS_KEY_TIMEOUT`] /
23387 // [`crate::POLITICAS_KEY_RETRIES`] /
23388 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
23389 // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
23390 // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
23391 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
23392 // on [`MeshPolicy`] emits. Three of the five axes
23393 // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
23394 // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
23395 // camelCase transforms — the derive-attribute is load-bearing
23396 // on those, unlike the sibling `Entrada` / `Membro` /
23397 // `WitContract` structs whose fields are all lowercase-single-
23398 // word and where the derive is a no-op on every axis.
23399 // Serialize a fully-populated [`MeshPolicy`] (every axis
23400 // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
23401 // on none of the five slots) and pin that each canonical
23402 // byte-sequence appears verbatim in the JSON — a future
23403 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
23404 // verbatim-field-name flip at the derive attribute (any of
23405 // which would silently break every downstream JSON consumer
23406 // that reaches for one of the five consts via
23407 // `Value::get(...)` — the future M4 per-edge `:politicas`
23408 // overlay projection onto Cilium `L7Rules` and Gateway API
23409 // `HTTPRoute` backend timeouts, the future
23410 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23411 // admission-time mesh-policy cross-check, the future
23412 // `feira lint` per-`:politicas` bound-check gate) surfaces here
23413 // as a build-time test failure at `aplicacao.rs`, not as an
23414 // apply-time `.get(<stale-canonical-const>)` returning `None`
23415 // far from the derive-attr drift's commit. Peer with the
23416 // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
23417 // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23418 // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
23419 // (ce80ca0) pins on the M3 collection-slot / singleton-slot
23420 // atom axes — same discipline every M3 sibling lift
23421 // established, extended here to the singleton `:politicas`
23422 // mesh-slot atom axis, closing the last M3 typed-struct
23423 // top-level `#[serde(rename_all = "camelCase")]` axis on the
23424 // Aplicacao surface without a lifted serde-key peer.
23425 let p = MeshPolicy {
23426 timeout: Some(Duration::from_secs(30)),
23427 retries: Some(3),
23428 circuit_breaker: Some(CircuitBreaker {
23429 max_failures: 5,
23430 window: Duration::from_secs(60),
23431 }),
23432 mtls_required: Some(true),
23433 rate_limit: Some(RateLimit {
23434 rate: 100,
23435 window: Duration::from_secs(1),
23436 }),
23437 };
23438 let json = serde_json::to_string(&p).unwrap();
23439 for key in [
23440 crate::POLITICAS_KEY_TIMEOUT,
23441 crate::POLITICAS_KEY_RETRIES,
23442 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
23443 crate::POLITICAS_KEY_MTLS_REQUIRED,
23444 crate::POLITICAS_KEY_RATE_LIMIT,
23445 ] {
23446 let quoted = format!("\"{key}\"");
23447 assert!(
23448 json.contains("ed),
23449 "serialized MeshPolicy must carry the lifted \
23450 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
23451 JSON emission (got: {json})",
23452 );
23453 }
23454 }
23455
23456 #[test]
23457 fn politicas_key_consts_are_pairwise_distinct() {
23458 // Cross-axis drift-detection pin: a future collapse of the five
23459 // canonical [`MeshPolicy`] singleton byte-strings onto the same
23460 // value (e.g. an accidental copy-paste flip of
23461 // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
23462 // would silently reroute every downstream probe on one axis
23463 // onto the sibling axis's overlay entry and pass every
23464 // propagation-probe test that expected only the stale axis's
23465 // value — the M4 per-edge `:politicas` overlay projection would
23466 // read the retry-count string where the timeout duration was
23467 // expected (or vice versa), the CR materializer's admission
23468 // cross-check would compare the wrong pair of values, and the
23469 // resulting mesh reconciler would either bind the wrong axis
23470 // or reject the resource at reconcile far from the rebrand
23471 // commit's source. Peer of the sibling four-way distinct pin
23472 // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
23473 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
23474 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
23475 // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
23476 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23477 let all = [
23478 crate::POLITICAS_KEY_TIMEOUT,
23479 crate::POLITICAS_KEY_RETRIES,
23480 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
23481 crate::POLITICAS_KEY_MTLS_REQUIRED,
23482 crate::POLITICAS_KEY_RATE_LIMIT,
23483 ];
23484 for (i, a) in all.iter().enumerate() {
23485 for b in all.iter().skip(i + 1) {
23486 assert_ne!(
23487 a, b,
23488 "POLITICAS_KEY_* consts must be pairwise-distinct \
23489 canonical byte-sequences — got `{a}` == `{b}`",
23490 );
23491 }
23492 }
23493 }
23494
23495 #[test]
23496 fn politicas_key_consts_are_lower_camel_case_shape() {
23497 // Shape-pin: every `POLITICAS_KEY_*` const must be a
23498 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23499 // `kebab-case` hyphens, no leading colon, no `PascalCase`
23500 // leading capital, no whitespace / dots) — the canonical shape
23501 // the `#[serde(rename_all = "camelCase")]` derive produces on
23502 // [`MeshPolicy`]. A future flip to a non-camelCase attribute
23503 // at the derive surfaces both here (this test fails on the
23504 // stale-constant shape) and at
23505 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23506 // (that test fails on the mismatch between const and derive).
23507 // Peer with `entrada_key_consts_are_lower_camel_case_shape`
23508 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23509 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23510 // (ca463a4) on the sibling M3 typed-struct axes.
23511 for key in [
23512 crate::POLITICAS_KEY_TIMEOUT,
23513 crate::POLITICAS_KEY_RETRIES,
23514 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
23515 crate::POLITICAS_KEY_MTLS_REQUIRED,
23516 crate::POLITICAS_KEY_RATE_LIMIT,
23517 ] {
23518 assert!(
23519 !key.is_empty(),
23520 "POLITICAS_KEY_* must be non-empty (got {key:?})"
23521 );
23522 let first = key.chars().next().unwrap();
23523 assert!(
23524 first.is_ascii_lowercase(),
23525 "POLITICAS_KEY_* must lead with an ASCII-lowercase \
23526 byte (got {key:?}, leads with {first:?})",
23527 );
23528 assert!(
23529 key.chars().all(|c| c.is_ascii_alphanumeric()),
23530 "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
23531 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23532 );
23533 }
23534 }
23535
23536 // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
23537
23538 #[test]
23539 fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
23540 // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
23541 // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
23542 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
23543 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
23544 // [`CircuitBreaker`] emits inside the
23545 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
23546 // two axes (`max_failures` → `maxFailures`) is a non-trivial
23547 // camelCase transform — the derive-attribute is load-bearing on
23548 // that axis, unlike the sibling `window` field where the derive
23549 // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
23550 // pin that each canonical byte-sequence appears verbatim in the
23551 // JSON — a future accidental `rename_all = "snake_case"` /
23552 // `"kebab-case"` / verbatim-field-name flip at the derive
23553 // attribute (any of which would silently break every downstream
23554 // JSON consumer that reaches for one of the two consts via
23555 // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
23556 // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
23557 // per-edge `:politicas` overlay projection onto the mesh's
23558 // per-backend consecutive-failure-counter tripping threshold, the
23559 // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23560 // admission-time breaker cross-check, the future `feira lint`
23561 // per-`:politicas :circuit-breaker` bound-check gate) surfaces
23562 // here as a build-time test failure at `aplicacao.rs`, not as an
23563 // apply-time `.get(<stale-canonical-const>)` returning `None`
23564 // far from the derive-attr drift's commit. Peer with the sibling
23565 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23566 // (b55cca7) parent-axis pin — that test pins the outer
23567 // sub-block key the derive on [`MeshPolicy`] emits, this test
23568 // pins the inner keys the derive on the payload type emits, so
23569 // the two together lock the whole [`MeshPolicy`] breaker-tuning
23570 // shape end-to-end at build time.
23571 let cb = CircuitBreaker {
23572 max_failures: 5,
23573 window: Duration::from_secs(60),
23574 };
23575 let json = serde_json::to_string(&cb).unwrap();
23576 for key in [
23577 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23578 crate::CIRCUIT_BREAKER_KEY_WINDOW,
23579 ] {
23580 let quoted = format!("\"{key}\"");
23581 assert!(
23582 json.contains("ed),
23583 "serialized CircuitBreaker must carry the lifted \
23584 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
23585 in the JSON emission (got: {json})",
23586 );
23587 }
23588 }
23589
23590 #[test]
23591 fn circuit_breaker_key_consts_are_pairwise_distinct() {
23592 // Cross-axis drift-detection pin: a future collapse of the two
23593 // canonical [`CircuitBreaker`] sub-block byte-strings onto the
23594 // same value (e.g. an accidental copy-paste flip of
23595 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
23596 // `"maxFailures"`) would silently reroute every downstream
23597 // probe on one axis onto the sibling axis's overlay entry and
23598 // pass every propagation-probe test that expected only the
23599 // stale axis's value — the M4 per-edge `:politicas` overlay
23600 // projection would read the failure-count where the window
23601 // duration was expected (or vice versa), the CR materializer's
23602 // admission cross-check would compare the wrong pair of values,
23603 // and the resulting mesh reconciler would either bind the wrong
23604 // axis or reject the resource at reconcile far from the rebrand
23605 // commit's source. Peer of the sibling five-way distinct pin on
23606 // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
23607 // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
23608 // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
23609 // six-way distinct pin on the `CONTRATO_KEY_*` triad +
23610 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23611 let all = [
23612 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23613 crate::CIRCUIT_BREAKER_KEY_WINDOW,
23614 ];
23615 for (i, a) in all.iter().enumerate() {
23616 for b in all.iter().skip(i + 1) {
23617 assert_ne!(
23618 a, b,
23619 "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
23620 canonical byte-sequences — got `{a}` == `{b}`",
23621 );
23622 }
23623 }
23624 }
23625
23626 #[test]
23627 fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
23628 // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
23629 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23630 // `kebab-case` hyphens, no leading colon, no `PascalCase`
23631 // leading capital, no whitespace / dots) — the canonical shape
23632 // the `#[serde(rename_all = "camelCase")]` derive produces on
23633 // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
23634 // at the derive surfaces both here (this test fails on the
23635 // stale-constant shape) and at
23636 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
23637 // (that test fails on the mismatch between const and derive).
23638 // Peer with `politicas_key_consts_are_lower_camel_case_shape`
23639 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
23640 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23641 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23642 // (ca463a4) on the sibling M3 typed-struct axes.
23643 for key in [
23644 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23645 crate::CIRCUIT_BREAKER_KEY_WINDOW,
23646 ] {
23647 assert!(
23648 !key.is_empty(),
23649 "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
23650 );
23651 let first = key.chars().next().unwrap();
23652 assert!(
23653 first.is_ascii_lowercase(),
23654 "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
23655 byte (got {key:?}, leads with {first:?})",
23656 );
23657 assert!(
23658 key.chars().all(|c| c.is_ascii_alphanumeric()),
23659 "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
23660 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23661 );
23662 }
23663 }
23664
23665 // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
23666
23667 #[test]
23668 fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
23669 // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
23670 // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
23671 // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
23672 // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
23673 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
23674 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
23675 // [`Placement`] emits. One of the four axes (`shard_key` →
23676 // `shardKey`) is a non-trivial camelCase transform — the
23677 // derive-attribute is load-bearing on that axis, unlike the
23678 // sibling `estrategia` / `clusters` / `affinity` axes whose
23679 // source-side field names carry no `_` and where the derive is a
23680 // no-op. Serialize a fully-populated [`Placement`] (both
23681 // `Option`-carrying axes `Some(_)` so
23682 // `skip_serializing_if = "Option::is_none"` fires on neither of
23683 // the two optional slots) and pin that each canonical
23684 // byte-sequence appears verbatim in the JSON — a future
23685 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
23686 // verbatim-field-name flip at the derive attribute (any of which
23687 // would silently break every downstream consumer that reaches
23688 // for one of the four consts via
23689 // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
23690 // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
23691 // aggregator's per-cluster fanout filter keying off
23692 // `placement.clusters`, the M3 shard-pool dispatch materializer
23693 // keying off `placement.shardKey`, the M3 Adaptive compression
23694 // pass weighting off `placement.affinity`, every downstream
23695 // dispatcher branching on `placement.estrategia`, the future
23696 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23697 // admission-time placement cross-check, the future `feira lint`
23698 // per-`:placement` bound-check gate) surfaces here as a
23699 // build-time test failure at `aplicacao.rs`, not as an
23700 // apply-time `.get(<stale-canonical-const>)` returning `None`
23701 // far from the derive-attr drift's commit. Peer with the sibling
23702 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23703 // (b55cca7),
23704 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
23705 // (468e959),
23706 // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
23707 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23708 // (ca463a4), and
23709 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
23710 // pins on the M3 collection-slot / singleton-slot atom axes —
23711 // closes the last M3 typed-struct top-level
23712 // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
23713 // surface without a drift-detection pin.
23714 let p = Placement {
23715 estrategia: PlacementStrategy::Sharded,
23716 clusters: vec!["rio".into(), "mar".into()],
23717 affinity: Some("data-locality".into()),
23718 shard_key: Some("$tenantId".into()),
23719 };
23720 let json = serde_json::to_string(&p).unwrap();
23721 for key in [
23722 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23723 crate::M3_PLACEMENT_KEY_CLUSTERS,
23724 crate::M3_PLACEMENT_KEY_AFFINITY,
23725 crate::M3_PLACEMENT_KEY_SHARD_KEY,
23726 ] {
23727 let quoted = format!("\"{key}\"");
23728 assert!(
23729 json.contains("ed),
23730 "serialized Placement must carry the lifted \
23731 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
23732 the JSON emission (got: {json})",
23733 );
23734 }
23735 }
23736
23737 #[test]
23738 fn m3_placement_key_consts_are_pairwise_distinct() {
23739 // Cross-axis drift-detection pin: a future collapse of the four
23740 // canonical [`Placement`] sub-block byte-strings onto the same
23741 // value (e.g. an accidental copy-paste flip of
23742 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
23743 // `"affinity"`) would silently reroute every downstream probe on
23744 // one axis onto the sibling axis's overlay entry and pass every
23745 // propagation-probe test that expected only the stale axis's
23746 // value — the M3 shard-pool dispatch materializer would read the
23747 // affinity placement-hint where the shard-selection template was
23748 // expected (or vice versa), the M3 Adaptive compression pass's
23749 // cross-check would compare the wrong pair of values, and the
23750 // resulting placement engine would either bind the wrong axis or
23751 // reject the resource at reconcile far from the rebrand commit's
23752 // source. Peer of the sibling two-way distinct pin on the
23753 // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
23754 // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
23755 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
23756 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
23757 // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
23758 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23759 let all = [
23760 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23761 crate::M3_PLACEMENT_KEY_CLUSTERS,
23762 crate::M3_PLACEMENT_KEY_AFFINITY,
23763 crate::M3_PLACEMENT_KEY_SHARD_KEY,
23764 ];
23765 for (i, a) in all.iter().enumerate() {
23766 for b in all.iter().skip(i + 1) {
23767 assert_ne!(
23768 a, b,
23769 "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
23770 canonical byte-sequences — got `{a}` == `{b}`",
23771 );
23772 }
23773 }
23774 }
23775
23776 #[test]
23777 fn m3_placement_key_consts_are_lower_camel_case_shape() {
23778 // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
23779 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23780 // `kebab-case` hyphens, no leading colon, no `PascalCase`
23781 // leading capital, no whitespace / dots) — the canonical shape
23782 // the `#[serde(rename_all = "camelCase")]` derive produces on
23783 // [`Placement`]. A future flip to a non-camelCase attribute at
23784 // the derive surfaces both here (this test fails on the stale-
23785 // constant shape) and at
23786 // `placement_serde_keys_match_lifted_m3_placement_key_consts`
23787 // (that test fails on the mismatch between const and derive).
23788 // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
23789 // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
23790 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
23791 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23792 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23793 // (ca463a4) on the sibling M3 typed-struct axes.
23794 for key in [
23795 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23796 crate::M3_PLACEMENT_KEY_CLUSTERS,
23797 crate::M3_PLACEMENT_KEY_AFFINITY,
23798 crate::M3_PLACEMENT_KEY_SHARD_KEY,
23799 ] {
23800 assert!(
23801 !key.is_empty(),
23802 "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
23803 );
23804 let first = key.chars().next().unwrap();
23805 assert!(
23806 first.is_ascii_lowercase(),
23807 "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
23808 byte (got {key:?}, leads with {first:?})",
23809 );
23810 assert!(
23811 key.chars().all(|c| c.is_ascii_alphanumeric()),
23812 "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
23813 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23814 );
23815 }
23816 }
23817
23818 // ── AplicacaoSpec::port_for_destination — the substrate-canonical
23819 // destination-facing L4 port resolver every per-Aplicacao renderer
23820 // reaching for a per-destination Servico TCP port axis routes
23821 // through. The four pin tests below fix the four-way accept-set
23822 // the resolver must always honor: (:entrada-para-matches,
23823 // :entrada-para-mismatches, :entrada-none-so-fallback,
23824 // :entrada-port-non-default-honored) — drift on any arm surfaces
23825 // at caixa-core build time rather than at cluster-apply time.
23826
23827 #[test]
23828 fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
23829 // The typed `:entrada` block's `:para "cart"` matches the
23830 // queried destination, so the resolver returns the author-
23831 // declared `:port` scalar verbatim — the canonical "the
23832 // destination Servico IS the ingress apex, honor the typed
23833 // listener port" arm of the port-resolution dispatch.
23834 let mut spec = three_member_spec();
23835 if let Some(e) = spec.entrada.as_mut() {
23836 e.para = "cart".into();
23837 e.port = 9090;
23838 }
23839 assert_eq!(
23840 spec.port_for_destination("cart"),
23841 9090,
23842 "port_for_destination(entrada.para) must return entrada.port \
23843 verbatim, not the DEFAULT_SERVICO_PORT fallback"
23844 );
23845 }
23846
23847 #[test]
23848 fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
23849 // The typed `:entrada` block names `:para "cart"`, but the
23850 // queried destination is `"payment"` — a Servico that
23851 // participates in the mesh graph but is not the ingress apex.
23852 // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
23853 // canonical port floor, closing the "non-apex destination reads
23854 // the substrate default" arm. Same fixture the peer
23855 // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
23856 // pin at caixa-mesh exercises through the CNP emit-side path;
23857 // this pin exercises the shared underlying resolver directly.
23858 let spec = three_member_spec();
23859 assert_eq!(
23860 spec.port_for_destination("payment"),
23861 DEFAULT_SERVICO_PORT,
23862 "port_for_destination(non-apex-destination) must route \
23863 through the lifted DEFAULT_SERVICO_PORT canonical port floor"
23864 );
23865 }
23866
23867 #[test]
23868 fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
23869 // Internal-only Aplicacao — no `:entrada` block declared. Every
23870 // per-destination port query falls back to the lifted
23871 // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
23872 // the Aplicacao surface admits `:entrada None` (internal mesh
23873 // with no external gateway); every downstream renderer's per-
23874 // destination port axis must still resolve to a well-defined
23875 // scalar even without an ingress apex.
23876 let mut spec = three_member_spec();
23877 spec.entrada = None;
23878 assert_eq!(
23879 spec.port_for_destination("cart"),
23880 DEFAULT_SERVICO_PORT,
23881 "port_for_destination on an internal-only Aplicacao must \
23882 fall back to the lifted DEFAULT_SERVICO_PORT floor for \
23883 every destination"
23884 );
23885 assert_eq!(
23886 spec.port_for_destination("payment"),
23887 DEFAULT_SERVICO_PORT,
23888 "port_for_destination on an internal-only Aplicacao must \
23889 fall back uniformly across every destination — the fallback \
23890 is not entrada-shape-conditional"
23891 );
23892 }
23893
23894 #[test]
23895 fn port_for_destination_honors_non_default_entrada_port_verbatim() {
23896 // Structural pin against a hypothetical future refactor that
23897 // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
23898 // the resolver (a "normalize to the default when the author's
23899 // port matches the substrate default" collapse) — that would
23900 // break renderer sites that carry meaning on the emitted port
23901 // value beyond bare equality (a future per-cluster listener-
23902 // audit that keys off the author-declared port, not the
23903 // resolved-with-fallback port). Pin that a non-default
23904 // entrada.port is returned verbatim so drift here surfaces at
23905 // caixa-core build time.
23906 let mut spec = three_member_spec();
23907 if let Some(e) = spec.entrada.as_mut() {
23908 e.para = "cart".into();
23909 e.port = 8443;
23910 }
23911 assert_ne!(
23912 8443, DEFAULT_SERVICO_PORT,
23913 "test fixture must probe a port distinct from \
23914 DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
23915 );
23916 assert_eq!(
23917 spec.port_for_destination("cart"),
23918 8443,
23919 "port_for_destination(entrada.para) must return entrada.port \
23920 verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
23921 );
23922 }
23923
23924 #[test]
23925 fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
23926 // Apex-identity pair-invariant pin composing both substrate-
23927 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
23928 // and [`Entrada::destination`] — at the emit-side call shape
23929 // every per-Aplicacao renderer's ingress-apex L4 port reader
23930 // now takes. The invariant:
23931 //
23932 // spec.port_for_destination(entrada.destination()) == entrada.port
23933 //
23934 // holds by construction under today's single-destination
23935 // `:entrada` slot (`destination()` returns `entrada.para`, and
23936 // the resolver's apex arm matches `para == destination` and
23937 // returns `entrada.port`), and every downstream consumer that
23938 // composes the two accessors at the ingress apex — the
23939 // `caixa_mesh::gateway_routes` HTTPRoute per-rule
23940 // `backendRefs[0].port` emit-site path, the peer future M4 CR
23941 // materializer's admission-webhook that promotes the scalar to
23942 // a per-CR override overlay, every future per-Aplicacao snapshot
23943 // renderer's apex-facing L4 port reader — reaches through the
23944 // same composition. Pin the identity across four permutations
23945 // (`:para` × `:port` including a non-default port to exercise
23946 // the honor-verbatim arm and a non-cart `:para` to exercise
23947 // destination-agnostic identity) so a future refactor that
23948 // silently split either accessor's apex behavior surfaces at
23949 // caixa-core build time — a subtle `destination()` renaming
23950 // that returned `entrada.host.as_str()` instead of
23951 // `entrada.para.as_str()` would blow this pin loudly, closing
23952 // the last quiet failure mode the two lifts admit in composition.
23953 //
23954 // Peer discipline with the sibling caixa-mesh cross-crate pin
23955 // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
23956 // on the two-renderer pair-invariant axis; this pin encodes the
23957 // same two-consumer coherence rule at the substrate-primitive
23958 // level so the invariant survives even if every renderer is
23959 // deleted.
23960 for (para, port) in [
23961 ("cart", DEFAULT_SERVICO_PORT),
23962 ("cart", 8443u16),
23963 ("payment", 9090u16),
23964 ("catalog", 443u16),
23965 ] {
23966 let mut spec = three_member_spec();
23967 if let Some(e) = spec.entrada.as_mut() {
23968 e.para = para.into();
23969 e.port = port;
23970 }
23971 let expected_port = spec
23972 .entrada
23973 .as_ref()
23974 .expect("three_member_spec carries a typed `:entrada` block")
23975 .port;
23976 let composed_port = {
23977 let entrada = spec.entrada.as_ref().expect("entrada present");
23978 spec.port_for_destination(entrada.destination())
23979 };
23980 assert_eq!(
23981 composed_port, expected_port,
23982 "`spec.port_for_destination(entrada.destination())` must \
23983 equal `entrada.port` under today's single-destination \
23984 `:entrada` slot — this is the apex-identity contract \
23985 every downstream ingress-apex L4 port reader relies on. \
23986 Input :entrada :para: {para:?}, :entrada :port: {port}"
23987 );
23988 }
23989 }
23990
23991 #[test]
23992 fn port_for_destination_apex_arm_routes_through_destination_accessor() {
23993 // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
23994 // per-`:entrada` apex-arm membership probe must key off
23995 // [`Entrada::destination`], not the raw `.para` field access.
23996 // Structurally: setting ONLY the `:entrada :para` field to a
23997 // fresh non-cart destination on an otherwise-well-formed
23998 // Aplicacao must (1) leave `e.destination()` byte-equal to
23999 // `e.para.as_str()` (the accessor is byte-projective by
24000 // definition), and (2) cause the resolver's apex arm to fire
24001 // and return `entrada.port` at exactly that new destination
24002 // while every other destination string falls through to
24003 // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
24004 // membership check. Pins against a future silent detour that
24005 // (a) re-derived the apex-arm membership probe off
24006 // `e.para == destination` in `port_for_destination` instead of
24007 // `e.destination() == destination`, silently disagreeing with
24008 // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
24009 // consumers (`entrada.destination()` at
24010 // caixa-mesh/src/lib.rs:3173, `c.destination()` at
24011 // caixa-mesh/src/lib.rs:2739) that already reach through the
24012 // accessor, (b) accessor-side introduced a per-tenant alias
24013 // arm the caller was unaware of, silently rewriting an
24014 // author-declared `:para "cart"` value to a canary-aliased
24015 // form — the raw-field-access resolver would fall through to
24016 // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
24017 // while the peer emit-site consumers landed on the aliased
24018 // destination, splitting the ingress-apex L4 port at
24019 // cluster-apply time.
24020 //
24021 // Peer of the sibling
24022 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
24023 // (d0de220) composition pin on the per-`:membros` refusal-arm
24024 // axis — same "the shape-gate predicate must route through the
24025 // substrate-primitive typed dispatch" discipline extended onto
24026 // the per-`:entrada` apex-arm membership-probe axis. Closes
24027 // the last unlifted `.para` production-code read site on
24028 // `Entrada` in `caixa-core` — after this converge every
24029 // `caixa-core` `.para` field access outside the accessor's own
24030 // body and outside the `WitContract` per-`:contratos` sibling
24031 // axis is either a test-side field-setter or a doc-comment
24032 // reference.
24033 for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
24034 let mut spec = three_member_spec();
24035 if let Some(e) = spec.entrada.as_mut() {
24036 e.para = para.into();
24037 e.port = port;
24038 }
24039 let e = spec
24040 .entrada
24041 .as_ref()
24042 .expect("three_member_spec carries a typed `:entrada` block");
24043 assert_eq!(
24044 e.destination(),
24045 e.para.as_str(),
24046 "Entrada::destination must byte-equal the .para field \
24047 access — an accessor-side detour that no longer \
24048 projects the raw field would silently split this \
24049 drift-detection test from the port_for_destination \
24050 apex-arm membership probe",
24051 );
24052 assert_eq!(
24053 spec.port_for_destination(para),
24054 port,
24055 "port_for_destination must key off the accessor-projected \
24056 destination and return `entrada.port` on the apex arm — \
24057 input :entrada :para: {para:?}, :entrada :port: {port}",
24058 );
24059 assert_eq!(
24060 spec.port_for_destination("ghost-destination-never-a-member"),
24061 DEFAULT_SERVICO_PORT,
24062 "port_for_destination must fall through to \
24063 DEFAULT_SERVICO_PORT on a non-matching destination \
24064 under the accessor-projected membership check — input \
24065 :entrada :para: {para:?}, :entrada :port: {port}",
24066 );
24067 }
24068 }
24069
24070 #[test]
24071 fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
24072 // The canonical per-`:politicas :rate-limit` `:rate`
24073 // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
24074 // [`RateLimit::rate`] must return the `:politicas :rate-limit`
24075 // typed `u32` verbatim, byte-equal to the raw field access
24076 // across every representative value in the accept-set — `1` (the
24077 // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
24078 // the surrounding [`AplicacaoSpec::validate_politicas`] gate
24079 // carves out on the sibling `PolicyRateLimitZero` refusal),
24080 // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
24081 // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
24082 // `0` (a past-the-guard sentinel that pins the accessor doesn't
24083 // perform a silent bounds-collapse into `1` on the zero arm —
24084 // validate rejects zero but the accessor must ship the raw slot
24085 // verbatim so a validate-time gate regression surfaces at the
24086 // emit boundary rather than being silently absorbed), `u32::MAX`
24087 // (a past-the-guard sentinel that pins the accessor doesn't
24088 // perform a silent bounds-collapse through
24089 // `POLICY_RATE_LIMIT_MAX` at the return path).
24090 //
24091 // First sub-struct required-scalar accessor pin on the
24092 // `RateLimit` axis — sibling in shape to the peer
24093 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
24094 // required-`u32` accessor pin on the peer per-sub-struct
24095 // required-axis. Pins against a future silent detour that
24096 // re-derived the token capacity from a peer axis (an accidental
24097 // `self.window.as_secs() as u32` collapse that read the
24098 // rate-limit window duration as a token count), a `0 → 1`
24099 // cluster-default projection (which would silently absorb the
24100 // `PolicyRateLimitZero` refusal case at the accessor boundary),
24101 // or a bounds-collapsing accessor that clamped the return
24102 // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
24103 // gate owns the bounds; the accessor must ship the raw slot
24104 // verbatim).
24105 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
24106 let rl = RateLimit {
24107 rate,
24108 window: Duration::from_secs(1),
24109 };
24110 assert_eq!(
24111 rl.rate(),
24112 rate,
24113 "RateLimit::rate must return :politicas :rate-limit :rate \
24114 verbatim (got {}, expected {rate})",
24115 rl.rate(),
24116 );
24117 assert_eq!(
24118 rl.rate(),
24119 rl.rate,
24120 "RateLimit::rate must byte-equal the raw .rate field \
24121 access across every value in the u32 accept-set",
24122 );
24123 }
24124 }
24125
24126 #[test]
24127 fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
24128 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24129 // `:rate-limit :rate` zero-floor arm must key off
24130 // [`RateLimit::rate`], not the raw `.rate` field access.
24131 // Structurally: a `RateLimit { rate: 0, window:
24132 // Duration::from_secs(1) }` embedded in a `:politicas
24133 // :rate-limit` slot must surface the `PolicyRateLimitZero`
24134 // refusal exactly, and a `RateLimit { rate: 1, window:
24135 // Duration::from_secs(1) }` (the lower boundary of the
24136 // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
24137 // The pair jointly pins the accessor + validate-gate composition:
24138 // any future silent detour that had the accessor return a fresh
24139 // `1` on the zero arm (a `.rate().max(1)` collapse) would
24140 // silently absorb the `PolicyRateLimitZero` refusal at the
24141 // accessor boundary and the validate gate would accept a
24142 // struct-literal `RateLimit { rate: 0, .. }` — the composition
24143 // pin catches that at caixa-core build time.
24144 //
24145 // Peer of the sibling per-`CircuitBreaker`
24146 // [`CircuitBreaker::max_failures`] (3a74062) /
24147 // [`CircuitBreaker::window`] (373957f) accessor-composition
24148 // pins on the peer required-scalar axes — same "the validate /
24149 // shape-gate predicate must route through the substrate-primitive
24150 // typed dispatch" discipline extended onto the peer
24151 // per-`RateLimit` required-`u32` composition axis.
24152 let mut spec = three_member_spec();
24153 spec.politicas = MeshPolicy {
24154 rate_limit: Some(RateLimit {
24155 rate: 0,
24156 window: Duration::from_secs(1),
24157 }),
24158 ..MeshPolicy::default()
24159 };
24160 assert!(
24161 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
24162 "validate_politicas must reject rate == 0 with \
24163 PolicyRateLimitZero — the accessor and the validate gate \
24164 must route through the same substrate-primitive typed \
24165 dispatch on the :rate zero-floor arm",
24166 );
24167 spec.politicas = MeshPolicy {
24168 rate_limit: Some(RateLimit {
24169 rate: 1,
24170 window: Duration::from_secs(1),
24171 }),
24172 ..MeshPolicy::default()
24173 };
24174 assert!(
24175 spec.validate().is_ok(),
24176 "validate_politicas must accept rate == 1 (the lower \
24177 boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
24178 );
24179 }
24180
24181 #[test]
24182 fn rate_limit_rate_projects_u32_by_copy() {
24183 // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
24184 // `u32` is `Copy` and the accessor must return by value, not by
24185 // reference. Peer of the sibling per-`CircuitBreaker`
24186 // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
24187 // peer required-scalar `:max-failures` axis, extended onto the
24188 // peer per-`RateLimit` required-`u32` copy-invariant shape —
24189 // the accessor's returned `u32` must outlive `&self` (multiple
24190 // calls must return equal values from a dropped-`&self` copy,
24191 // since the returned scalar carries no borrow), and calling the
24192 // accessor twice on the same RateLimit must yield the same
24193 // `u32` verbatim (idempotent, no side effects on `&self`).
24194 //
24195 // Pins against a future silent detour that returned `&u32`
24196 // (which would type-check but silently break every downstream
24197 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
24198 // first parameter is `u32`, and `&u32` would fold to a detached
24199 // copy at the call site with a `*` deref the sibling accessors
24200 // don't need), an accidental `.rate.wrapping_add(0)` detour that
24201 // returned a fresh copy through an arithmetic no-op (breaking a
24202 // future `const fn` regression), or a one-arm-only accessor
24203 // that returned a saturating value on some sentinel input
24204 // (breaking the pass-through invariant the sibling required-
24205 // scalar accessors carry).
24206 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
24207 let rl = RateLimit {
24208 rate,
24209 window: Duration::from_secs(1),
24210 };
24211 let first = rl.rate();
24212 let second = rl.rate();
24213 assert_eq!(
24214 first, second,
24215 "RateLimit::rate must be idempotent — two successive \
24216 calls on the same &self must return the same u32",
24217 );
24218 assert_eq!(
24219 first, rate,
24220 "RateLimit::rate must return :politicas :rate-limit :rate \
24221 verbatim by copy — got {first}, expected {rate}",
24222 );
24223 }
24224 }
24225
24226 #[test]
24227 fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
24228 // The canonical per-`:politicas :rate-limit` `:window`
24229 // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
24230 // pin: [`RateLimit::window`] must return the
24231 // `:politicas :rate-limit :window` typed `Duration` verbatim,
24232 // byte-equal to the raw field access across every
24233 // representative value in the accept-set — `Duration::from_secs(1)`
24234 // (the `"s"` canonical window, the lower row of
24235 // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
24236 // [`AplicacaoSpec::validate_politicas`] gate accepts via
24237 // [`is_canonical_rate_limit_window`]),
24238 // `Duration::from_secs(60)` (the `"m"` canonical window, the
24239 // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
24240 // window, the upper row), `Duration::ZERO` (a past-the-guard
24241 // sentinel that pins the accessor doesn't perform a silent
24242 // bounds-collapse into `Duration::from_secs(1)` on the zero
24243 // arm — validate rejects an off-set window through
24244 // `PolicyRateLimitWindowNotCanonical` but the accessor must
24245 // ship the raw slot verbatim so a validate-time gate
24246 // regression surfaces at the emit boundary rather than being
24247 // silently absorbed), `Duration::from_millis(500)` (a
24248 // sub-canonical past-the-guard sentinel that pins the accessor
24249 // doesn't silently normalize a non-canonical fractional
24250 // magnitude onto the nearest canonical row).
24251 //
24252 // Second sub-struct required-scalar accessor pin on the
24253 // `RateLimit` axis — sibling in shape to the just-landed
24254 // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
24255 // accessor pin on the peer per-sub-struct required-axis,
24256 // extended onto the per-`RateLimit` required-`Duration` axis.
24257 // Pins against a future silent detour that re-derived the
24258 // refill period from a peer axis (an accidental
24259 // `Duration::from_secs(self.rate as u64)` collapse that read
24260 // the rate-limit token capacity as a refill-interval
24261 // duration), a `Duration::ZERO → Duration::from_secs(1)`
24262 // canonical-default projection (which would silently absorb
24263 // the `PolicyRateLimitWindowNotCanonical` refusal case at the
24264 // accessor boundary), or a canonical-set-collapsing accessor
24265 // that clamped the return through [`rate_limit_window_unit`]
24266 // (the `AplicacaoSpec::validate` gate owns the canonical-set
24267 // membership; the accessor must ship the raw slot verbatim).
24268 for window in [
24269 Duration::from_secs(1),
24270 Duration::from_secs(60),
24271 Duration::from_secs(3600),
24272 Duration::ZERO,
24273 Duration::from_millis(500),
24274 ] {
24275 let rl = RateLimit { rate: 100, window };
24276 assert_eq!(
24277 rl.window(),
24278 window,
24279 "RateLimit::window must return :politicas :rate-limit :window \
24280 verbatim (got {:?}, expected {window:?})",
24281 rl.window(),
24282 );
24283 assert_eq!(
24284 rl.window(),
24285 rl.window,
24286 "RateLimit::window must byte-equal the raw .window field \
24287 access across every value in the Duration accept-set",
24288 );
24289 }
24290 }
24291
24292 #[test]
24293 fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
24294 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24295 // `:rate-limit :window` canonical-set arm must key off
24296 // [`RateLimit::window`], not the raw `.window` field access.
24297 // Structurally: a `RateLimit { window: Duration::from_millis(500),
24298 // .. }` embedded in a `:politicas :rate-limit` slot must
24299 // surface the `PolicyRateLimitWindowNotCanonical` refusal
24300 // exactly (with the sub-canonical `Duration::from_millis(500)`
24301 // magnitude carried through verbatim), and a `RateLimit
24302 // { window: Duration::from_secs(1), .. }` (the lower row of
24303 // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
24304 // The pair jointly pins the accessor + validate-gate
24305 // composition: any future silent detour that had the accessor
24306 // normalize the off-set window to the nearest canonical row
24307 // (a `.window().max(Duration::from_secs(1))` collapse, or a
24308 // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
24309 // collapse) would silently absorb the
24310 // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
24311 // boundary — including a drift in the error's `window` payload
24312 // (the emit-side diagnostic reader keys off the offending
24313 // magnitude verbatim, so a normalization at the accessor
24314 // boundary would silently pin the wrong magnitude in the
24315 // refusal). The composition pin catches that at caixa-core
24316 // build time.
24317 //
24318 // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
24319 // (7f81a60) accessor-composition pin on the peer required-
24320 // scalar `:rate` axis — same "the validate / shape-gate
24321 // predicate must route through the substrate-primitive typed
24322 // dispatch, and the error payload must project through the
24323 // same accessor" discipline extended onto the peer
24324 // per-`RateLimit` required-`Duration` composition axis.
24325 let mut spec = three_member_spec();
24326 spec.politicas = MeshPolicy {
24327 rate_limit: Some(RateLimit {
24328 rate: 100,
24329 window: Duration::from_millis(500),
24330 }),
24331 ..MeshPolicy::default()
24332 };
24333 match spec.validate() {
24334 Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
24335 assert_eq!(
24336 window,
24337 Duration::from_millis(500),
24338 "PolicyRateLimitWindowNotCanonical must carry the \
24339 offending :window magnitude verbatim through the \
24340 accessor — got {window:?}, expected 500ms",
24341 );
24342 }
24343 other => panic!(
24344 "validate_politicas must reject non-canonical :window \
24345 with PolicyRateLimitWindowNotCanonical — the accessor \
24346 and the validate gate must route through the same \
24347 substrate-primitive typed dispatch on the :window \
24348 canonical-set arm; got {other:?}",
24349 ),
24350 }
24351 spec.politicas = MeshPolicy {
24352 rate_limit: Some(RateLimit {
24353 rate: 100,
24354 window: Duration::from_secs(1),
24355 }),
24356 ..MeshPolicy::default()
24357 };
24358 assert!(
24359 spec.validate().is_ok(),
24360 "validate_politicas must accept window == Duration::from_secs(1) \
24361 (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
24362 );
24363 }
24364
24365 #[test]
24366 fn rate_limit_window_projects_duration_by_copy() {
24367 // The by-copy pin: [`RateLimit::window`] returns `Duration`
24368 // by copy — `Duration` is `Copy` and the accessor must return
24369 // by value, not by reference. Peer of the sibling per-`RateLimit`
24370 // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
24371 // required-scalar `:rate` axis, extended onto the peer
24372 // per-`RateLimit` required-`Duration` copy-invariant shape —
24373 // the accessor's returned `Duration` must outlive `&self`
24374 // (multiple calls must return equal values from a
24375 // dropped-`&self` copy, since the returned scalar carries no
24376 // borrow), and calling the accessor twice on the same
24377 // RateLimit must yield the same `Duration` verbatim
24378 // (idempotent, no side effects on `&self`).
24379 //
24380 // Pins against a future silent detour that returned
24381 // `&Duration` (which would type-check but silently break every
24382 // downstream `Duration`-by-value consumer —
24383 // [`is_canonical_rate_limit_window`]'s first parameter is
24384 // `Duration`, and `&Duration` would fold to a detached copy at
24385 // the call site with a `*` deref the sibling accessors don't
24386 // need), an accidental `.window + Duration::ZERO` detour that
24387 // returned a fresh copy through an arithmetic no-op (breaking
24388 // a future `const fn` regression), or a one-arm-only accessor
24389 // that returned a canonical fallback on some sentinel input
24390 // (breaking the pass-through invariant the sibling required-
24391 // scalar accessors carry).
24392 for window in [
24393 Duration::from_secs(1),
24394 Duration::from_secs(60),
24395 Duration::from_secs(3600),
24396 Duration::ZERO,
24397 Duration::from_millis(500),
24398 ] {
24399 let rl = RateLimit { rate: 100, window };
24400 let first = rl.window();
24401 let second = rl.window();
24402 assert_eq!(
24403 first, second,
24404 "RateLimit::window must be idempotent — two successive \
24405 calls on the same &self must return the same Duration",
24406 );
24407 assert_eq!(
24408 first, window,
24409 "RateLimit::window must return :politicas :rate-limit :window \
24410 verbatim by copy — got {first:?}, expected {window:?}",
24411 );
24412 }
24413 }
24414}