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 /// Canonical camelCase-schema discriminator scalar this variant
4135 /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
4136 /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
4137 /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4138 /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
4139 /// every substrate consumer that dispatches on the strategy (the
4140 /// `lareira-fleet-programs` aggregator, the future `app-operator`
4141 /// reconciler, the M3 Adaptive compression pass) reads the same
4142 /// byte-string the `Serialize` derive emits — the pin test in
4143 /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
4144 /// asserts the two paths agree.
4145 #[must_use]
4146 pub const fn as_str(self) -> &'static str {
4147 match self {
4148 Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
4149 Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
4150 Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
4151 }
4152 }
4153}
4154
4155/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
4156/// the pretty-printed byte-string every consumer that formats the strategy
4157/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
4158/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
4159/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
4160/// per-Aplicacao strategy line, the future M4 CR materializer's per-
4161/// admission-webhook rejection body) reaches for the same lifted
4162/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4163/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4164/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
4165/// `Serialize` derive already emits under
4166/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
4167/// [`PlacementStrategy::as_str`] helper already returns.
4168///
4169/// Until this lift landed the sibling OTP-shape typed enums —
4170/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
4171/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
4172/// so [`std::fmt::Display`] routes through the same discriminant string
4173/// the wire format emits) — carried a stable [`std::fmt::Display`]
4174/// surface but [`PlacementStrategy`] did not; every consumer reaching
4175/// for a strategy byte-string past the wire format had to pick between
4176/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
4177/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
4178/// derive), any two of which a future variant rename or
4179/// `#[serde(rename_all = "kebab-case")]` attribute would silently
4180/// desynchronize — with the failure surfacing as a downstream renderer /
4181/// operator's per-strategy dispatch reading one spelling while the wire
4182/// format emitted another, far from the source rebrand commit and with
4183/// no field naming the drift. Routing `Display` through
4184/// [`PlacementStrategy::as_str`] makes the three paths
4185/// (`Debug` for structural inspection, `Display` for user-facing text,
4186/// `Serialize` for the wire format) converge on the same lifted
4187/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
4188/// the diagnostic byte-string, and the pretty-printed byte-string move
4189/// as a single unit through one canonical declaration each, by
4190/// construction. Same trajectory as [`PlacementStrategy::as_str`]
4191/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
4192/// closes the third path.
4193///
4194/// Pin tests
4195/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
4196/// and
4197/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
4198/// assert the three paths agree byte-for-byte on every variant, so a
4199/// future variant rename or per-arm serde attribute drift is a build
4200/// error visible at caixa-core test time, not a silent per-consumer
4201/// dispatch miss at apply / reconcile time.
4202impl std::fmt::Display for PlacementStrategy {
4203 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4204 f.write_str(self.as_str())
4205 }
4206}
4207
4208/// Where the Aplicacao runs.
4209#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4210#[serde(rename_all = "camelCase")]
4211pub struct Placement {
4212 /// Distribution strategy.
4213 #[serde(default)]
4214 pub estrategia: PlacementStrategy,
4215
4216 /// Named clusters that host this Aplicacao. Required for
4217 /// `Replicated` and `SingleNode`; for `Sharded` declares the
4218 /// shard pool.
4219 #[serde(default)]
4220 pub clusters: Vec<String>,
4221
4222 /// Optional hint to the placement engine: `"data-locality"`,
4223 /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
4224 #[serde(default, skip_serializing_if = "Option::is_none")]
4225 pub affinity: Option<String>,
4226
4227 /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
4228 #[serde(default, skip_serializing_if = "Option::is_none")]
4229 pub shard_key: Option<String>,
4230}
4231
4232impl Placement {
4233 /// Substrate-canonical per-`:placement` Akka-cluster-sharding
4234 /// `:shard-key` extractor-expression scalar accessor every consumer
4235 /// of the Aplicacao's hash-keyed distribution routing keys off —
4236 /// returns the author-declared `:placement :shard-key` byte-string
4237 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
4238 /// own `Option<String>` storage; `None` when the slot is absent
4239 /// (the canonical shape under `:estrategia Replicated` /
4240 /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
4241 /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
4242 /// partition — `validate` refuses any `Placement` past this call
4243 /// that lands `Some` on a non-`Sharded` strategy or `None` on
4244 /// `Sharded`).
4245 ///
4246 /// The `:placement :shard-key` slot carries the Akka-style
4247 /// cluster-sharding entity-id extractor expression
4248 /// (MESH-COMPOSITION §II.4) — validated by
4249 /// [`validate_placement_shard_key`] to be a non-empty printable-
4250 /// ASCII single-token reference (`tenantId`, `$tenantId`,
4251 /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
4252 /// future M4 Akka-style cluster-sharding reconciler hashes without
4253 /// re-validating at the runtime layer), and every downstream
4254 /// consumer that reads the key keys off this scalar (the
4255 /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
4256 /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4257 /// declared-but-inert refusal diagnostic, the caixa-mesh
4258 /// per-Aplicacao `placement.shardKey` emit path the substrate
4259 /// operator's per-entity hash-routing reader consumes, the future
4260 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4261 /// per-shard-key resolver).
4262 ///
4263 /// Prior to this lift the `.shard_key` field was accessed inline at
4264 /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
4265 /// `Sharded` arm's `match &self.placement.shard_key { None => …,
4266 /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
4267 /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
4268 /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
4269 /// — two open-coded field-accesses that expressed no compile-time
4270 /// link back to the typed slot. A future extension of the
4271 /// `:placement :shard-key` axis to a richer author surface — a
4272 /// per-cluster override the operator pins through a future
4273 /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
4274 /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
4275 /// alias table the M4 CR materializer resolves per-CR, a
4276 /// per-Aplicacao dynamic `:shard-key` derivation the future
4277 /// adaptive placement engine computes from `:affinity` weights —
4278 /// would have had to be threaded through both open-coded copies in
4279 /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
4280 /// arm refusal would silently disagree on which extractor
4281 /// expression a given Placement resolves to. Lifting the resolution
4282 /// rule to a typed method on the substrate primitive means every
4283 /// downstream consumer of the Aplicacao's per-`:placement`
4284 /// hash-key surface reaches for exactly one typed dispatch — the
4285 /// resolver's accept-set migrates as a unit on any future axis
4286 /// addition.
4287 ///
4288 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
4289 /// [`WitContract::destination`] / [`WitContract::world_ref`]
4290 /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
4291 /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
4292 /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
4293 /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
4294 /// typed dispatch on the substrate primitive, thin projections at
4295 /// each consumer" discipline extended onto the per-`:placement`
4296 /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
4297 /// First `Option<&str>`-return accessor on the M3 mesh-slot family
4298 /// — opens the "optional per-slot scalar" projection pattern the
4299 /// sibling per-`:placement` `:affinity`, per-`:politicas`
4300 /// `:rate-limit` future lifts fold on. Named `shard_key()` to
4301 /// match the storage field's name; the accessor's identity name
4302 /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
4303 /// slot's docstring already carries.
4304 #[must_use]
4305 pub fn shard_key(&self) -> Option<&str> {
4306 self.shard_key.as_deref()
4307 }
4308
4309 /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
4310 /// compression-hint scalar accessor every weighting-consumer of the
4311 /// Aplicacao's per-hint routing surface keys off — returns the
4312 /// author-declared `:placement :affinity` byte-string verbatim as
4313 /// an `Option<&str>`, borrowed from the typed slot's own
4314 /// `Option<String>` storage; `None` when the slot is absent (the
4315 /// canonical shape of an Aplicacao that leaves the compression
4316 /// weighting up to the placement engine's cluster-default arm — no
4317 /// author-authored `data-locality` / `low-latency` / etc. hint
4318 /// biases the routing).
4319 ///
4320 /// The `:placement :affinity` slot carries the M3 Adaptive-
4321 /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
4322 /// by [`validate_placement_affinity`] to be a DNS-1123 label
4323 /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
4324 /// K8s-conformant label-selector shape every apiserver-side pod-
4325 /// affinity / node-affinity materializer already gates on
4326 /// admission), and every downstream consumer that reads the hint
4327 /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
4328 /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
4329 /// `placement.affinity` overlay emit path the substrate operator's
4330 /// per-hint weighting-consumer reads, the future M4
4331 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
4332 /// pod-affinity / node-affinity selector resolver).
4333 ///
4334 /// Prior to this lift the `.affinity` field was accessed inline at
4335 /// the sole caixa-core site — the
4336 /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
4337 /// `if let Some(a) = &self.placement.affinity { …
4338 /// validate_placement_affinity(a)? … }` cascade — one open-coded
4339 /// field-access that expressed no compile-time link back to the
4340 /// typed slot. A future extension of the `:placement :affinity`
4341 /// axis to a richer author surface — a per-cluster override the
4342 /// operator pins through a future `:placement :affinity-overrides`
4343 /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
4344 /// tenant hint alias table the M4 CR materializer resolves per-CR,
4345 /// a per-Aplicacao dynamic `:affinity` derivation the future
4346 /// adaptive placement engine computes from `:clusters` topology —
4347 /// would have had to be threaded through the open-coded copy in
4348 /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
4349 /// materializer reader that landed on the axis, or the per-hint
4350 /// value-shape gate and its downstream weighting consumers would
4351 /// silently disagree on which hint a given Placement resolves to.
4352 /// Lifting the resolution rule to a typed method on the substrate
4353 /// primitive means every downstream consumer of the Aplicacao's
4354 /// per-`:placement` compression-hint surface reaches for exactly
4355 /// one typed dispatch — the resolver's accept-set migrates as a
4356 /// unit on any future axis addition.
4357 ///
4358 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
4359 /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
4360 /// optional-scalar axis — same "one typed dispatch on the substrate
4361 /// primitive, thin projections at each consumer" discipline extended
4362 /// onto the per-`:placement` M3-Adaptive-compression-hint
4363 /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
4364 /// return accessor on the M3 mesh-slot family; closes the last
4365 /// un-lifted per-`:placement` `Option<String>` axis. Named
4366 /// `affinity()` to match the storage field's name; the accessor's
4367 /// identity name maps onto the canonical MESH-COMPOSITION §II.4
4368 /// vocabulary the slot's docstring already carries.
4369 #[must_use]
4370 pub fn affinity(&self) -> Option<&str> {
4371 self.affinity.as_deref()
4372 }
4373
4374 /// Substrate-canonical per-`:placement` `:estrategia` distribution-
4375 /// strategy scalar accessor every consumer that dispatches on the
4376 /// Aplicacao's per-cluster distribution shape keys off — returns the
4377 /// author-declared `:placement :estrategia` variant verbatim as a
4378 /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
4379 /// `PlacementStrategy` storage.
4380 ///
4381 /// The `:placement :estrategia` slot carries the closed-set
4382 /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
4383 /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
4384 /// `Replicated` — active-active across every named cluster; `Sharded`
4385 /// — Akka-style hash-keyed entity distribution across the cluster pool
4386 /// per §II.4) that every downstream consumer of the Aplicacao's
4387 /// per-cluster fan-out shape keys off. Validated by
4388 /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
4389 /// the sibling `:shard-key` axis (`shard_key.is_some() ==
4390 /// matches!(estrategia, Sharded)` — the cross-slot partition the
4391 /// [`Placement::shard_key`] accessor's docstring pins), and every
4392 /// downstream consumer that reads the strategy keys off this scalar
4393 /// (the [`AplicacaoSpec::validate_placement`]
4394 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
4395 /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
4396 /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
4397 /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4398 /// declared-but-inert refusal's
4399 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
4400 /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
4401 /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
4402 /// emit path the substrate operator's per-strategy fan-out reader
4403 /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4404 /// materializer's per-strategy admission-webhook resolver).
4405 ///
4406 /// Prior to this lift the `.estrategia` field was accessed inline at
4407 /// four sites — the [`AplicacaoSpec::validate_placement`]
4408 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
4409 /// `estrategia: self.placement.estrategia`, the same method's
4410 /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
4411 /// partition dispatch, the non-`Sharded`-arm
4412 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
4413 /// `estrategia: self.placement.estrategia`, and the `feira app graph`
4414 /// per-Aplicacao strategy print line at
4415 /// `println!("… {} …", spec.placement.estrategia, …)`
4416 /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
4417 /// expressed no compile-time link back to the typed slot. A future
4418 /// extension of the `:placement :estrategia` axis to a richer author
4419 /// surface (a per-cluster override the operator pins through a future
4420 /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
4421 /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
4422 /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
4423 /// derivation the future adaptive placement engine computes from
4424 /// `:affinity` + `:clusters` topology) would have had to be threaded
4425 /// through every open-coded copy in lockstep — one consumer reading
4426 /// the raw variant while a peer read the operator-resolved variant
4427 /// would silently split the `PlacementWithoutClusters` /
4428 /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
4429 /// partition-dispatch input, a two-consumer split at the validator
4430 /// far from the source `caixa.lisp` with no field naming the
4431 /// strategy-drift root cause. Lifting the resolution rule to a typed
4432 /// method on the substrate primitive means every downstream consumer
4433 /// of the Aplicacao's per-`:placement` distribution-strategy surface
4434 /// reaches for exactly one typed dispatch — the resolver's accept-set
4435 /// migrates as a unit on any future axis addition.
4436 ///
4437 /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
4438 /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
4439 /// same "one typed dispatch on the substrate primitive, thin
4440 /// projections at each consumer" discipline extended onto the
4441 /// per-`:placement` distribution-strategy `Copy`-composite-enum
4442 /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
4443 /// family; first `Copy`-return accessor on the M3 mesh-slot
4444 /// `Placement` type — companion to the sibling per-`:placement`
4445 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4446 /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
4447 /// optional-scalar axes, closing the last unlifted per-`:placement`
4448 /// scalar-value axis (the closed-set `PlacementStrategy`
4449 /// distribution-strategy discriminator) so every downstream
4450 /// per-`:placement` reader now routes through a typed dispatch on
4451 /// the substrate primitive. Named `estrategia()` to match the storage
4452 /// field's name; the accessor's identity name maps onto the
4453 /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
4454 /// already carries.
4455 #[must_use]
4456 pub fn estrategia(&self) -> PlacementStrategy {
4457 self.estrategia
4458 }
4459
4460 /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
4461 /// per-cluster distribution-target slice accessor every consumer that
4462 /// walks the Aplicacao's declared cluster-pool keys off — returns the
4463 /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
4464 /// `&[String]` slice-view, borrowed from the typed slot's own
4465 /// `Vec<String>` storage (a zero-copy slice-view over the same
4466 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
4467 /// through). Non-optional: the empty slice is the load-bearing
4468 /// pre-validation sentinel every downstream consumer of the paired
4469 /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
4470 /// off — every strategy in the closed
4471 /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
4472 /// requires a non-empty list (`SingleNode` / `Replicated` use the
4473 /// list as hosting / takeover candidates per Erlang/OTP distributed-
4474 /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
4475 /// shard pool per Akka cluster-sharding convention, §II.4), so the
4476 /// `.is_empty()` probe is the shared pre-condition every
4477 /// [`AplicacaoSpec::validate_placement`] arm heads on.
4478 ///
4479 /// The `:placement :clusters` slot carries the K8s-conformant DNS-
4480 /// 1123-label per-cluster distribution-target list — the same
4481 /// set-not-multiset shape the sibling `:membros :caixa` /
4482 /// `:children :caixa` axes carry (`validate_placement`'s per-entry
4483 /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
4484 /// pins the shape). Every downstream consumer that fans on the list
4485 /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
4486 /// pre-flight `.is_empty()` probe that trips
4487 /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
4488 /// per-cluster value-shape + duplicate-detection fan-out loop, the
4489 /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
4490 /// that materializes the list verbatim onto every
4491 /// programs.yaml entry the substrate operator's per-cluster
4492 /// `placement.clusters | contains .Values.cluster` filter reads,
4493 /// the `feira app graph` per-Aplicacao cluster print line, the
4494 /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4495 /// per-cluster admission-webhook fan-out, the future M5 adaptive-
4496 /// placement engine's cluster-topology reader).
4497 ///
4498 /// Prior to this lift the `.clusters` `Vec<String>` was accessed
4499 /// inline at three production sites — the
4500 /// [`AplicacaoSpec::validate_placement`] pre-flight
4501 /// `self.placement.clusters.is_empty()` refusal probe, the same
4502 /// method's per-cluster validate loop's
4503 /// `for c in &self.placement.clusters` traversal head, and the
4504 /// `feira app graph` per-Aplicacao print line's
4505 /// `spec.placement.clusters` `{:?}` formatter argument
4506 /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
4507 /// that expressed no compile-time link back to the typed slot. A
4508 /// future extension of the `:placement :clusters` axis to a richer
4509 /// author surface (a per-tenant cluster-pool overlay the operator
4510 /// pins through a future `:placement :clusters-overrides` slot the
4511 /// MESH-COMPOSITION §V cross-cluster-federation roadmap
4512 /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
4513 /// the future M5 adaptive-placement engine computes from
4514 /// `:affinity` weights + live cluster-topology probes, a promotion
4515 /// of the plain `Vec<String>` to a richer `{static, dynamic}`
4516 /// partition once the substrate operator's cluster-membership
4517 /// reconciler comes into typed scope) would have had to be threaded
4518 /// through all three open-coded copies in lockstep or one consumer
4519 /// would silently disagree with the peers on which cluster-pool a
4520 /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
4521 /// reading the raw slot while the peer per-cluster validate loop
4522 /// read an operator-resolved slot would silently split the paired
4523 /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
4524 /// `PlacementClusterDuplicate` refusal cascade's actual traversal
4525 /// input from the pre-flight input, a three-consumer split at the
4526 /// validator and formatter far from the source `caixa.lisp` with
4527 /// no field naming the cluster-pool-drift root cause. Lifting the
4528 /// resolution rule to a typed method on the substrate primitive
4529 /// means every downstream consumer of the Aplicacao's
4530 /// per-`:placement` cluster-pool surface reaches for exactly one
4531 /// typed dispatch — the resolver's accept-set migrates as a unit
4532 /// on any future axis addition.
4533 ///
4534 /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
4535 /// slot — sibling to the seed M2
4536 /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
4537 /// slice-return accessor on the peer per-`:supervisor` static-
4538 /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
4539 /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
4540 /// primitive, thin projections at each consumer" discipline. The
4541 /// three peer `Vec`-carry axes still unlifted at the time of this
4542 /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
4543 /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
4544 /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
4545 /// [`crate::UpgradeFromEntry::instructions`]
4546 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4547 /// — inherit this accessor's discipline as future compounding runs
4548 /// migrate their consumers onto the shared slice-return shape.
4549 /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
4550 /// type, sibling to the two `Option<&str>`-return
4551 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
4552 /// (74ec2d3) accessors and the `Copy`-return
4553 /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
4554 /// unlifted per-`:placement` field axis (the `Vec<String>`
4555 /// distribution-target-list carrier) so every downstream
4556 /// per-`:placement` reader now routes through a typed dispatch on
4557 /// the substrate primitive. Named `clusters()` to match the storage
4558 /// field's name verbatim and the tatara-lisp author-surface term
4559 /// (`:clusters`) the field's own docstring already carries; the
4560 /// accessor's identity maps onto the canonical MESH-COMPOSITION
4561 /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
4562 /// for. Returns `&[String]` (not `&Vec<String>`) because every
4563 /// downstream consumer of the cluster list treats it as a read-only
4564 /// sequence — the slice-view is the narrowest borrow that supports
4565 /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
4566 /// `.len()`) without leaking the backing `Vec`'s
4567 /// grow/push/reserve surface that no consumer of the typed view
4568 /// reaches for (the storage-side `Vec` remains reachable through
4569 /// the `pub clusters` field for the mutation-carrying serde
4570 /// round-trip and per-test fixture-mutation paths).
4571 #[must_use]
4572 pub fn clusters(&self) -> &[String] {
4573 self.clusters.as_slice()
4574 }
4575}
4576
4577impl Default for Placement {
4578 fn default() -> Self {
4579 Self {
4580 estrategia: PlacementStrategy::default(),
4581 clusters: Vec::new(),
4582 affinity: None,
4583 shard_key: None,
4584 }
4585 }
4586}
4587
4588// ── external entry point ─────────────────────────────────────────────
4589
4590/// External entry point — what an outside caller sees. Renders to a
4591/// Gateway / Ingress + a route to the named member Servico.
4592#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4593#[serde(rename_all = "camelCase")]
4594pub struct Entrada {
4595 /// Public hostname (e.g. `"checkout.quero.cloud"`).
4596 pub host: String,
4597
4598 /// Member Servico the gateway routes to. Must be in `:membros`.
4599 pub para: String,
4600
4601 /// Optional path filter — if set, only matching paths route to
4602 /// this Aplicacao (the rest fall through to other route rules).
4603 #[serde(default)]
4604 pub paths: Vec<String>,
4605
4606 /// Default port on the destination Servico (the trigger.service.port).
4607 #[serde(default = "default_port")]
4608 pub port: u16,
4609}
4610
4611impl Entrada {
4612 /// Substrate-canonical per-`:entrada` URL-path fallback resolver
4613 /// every HTTPRoute-aware renderer keys off — returns the author-
4614 /// declared `:entrada :paths` list verbatim when non-empty, and the
4615 /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
4616 /// all fallback otherwise (so an Aplicacao author who declares an
4617 /// external `:entrada` block but no per-path rule surface still
4618 /// gets a route whose sole `HTTPPathMatch` matches every incoming
4619 /// request under the paired
4620 /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
4621 ///
4622 /// Prior to this lift the "if `:entrada :paths` is empty use the
4623 /// substrate catch-all; else return each declared path verbatim"
4624 /// cascade lived inline at
4625 /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
4626 /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
4627 /// per-Aplicacao HTTPRoute per-rule path-list emit site the
4628 /// substrate ships today, with no typed method on the substrate
4629 /// primitive that named the rule. A future path-resolution axis
4630 /// addition — a per-cluster `:entrada :default-path` override the
4631 /// operator pins through a future `:placement`-scoped slot, an
4632 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
4633 /// admission-webhook floor that materializes the catch-all before
4634 /// the CR lands, a future per-`:entrada :paths` overlay from a
4635 /// per-cluster policy the future `feira app deploy` pipeline
4636 /// consumes — would have to be threaded through every renderer's
4637 /// inline copy of the cascade in lockstep or one consumer would
4638 /// silently disagree with the peers on which path list a given
4639 /// `:entrada` block resolves to. Lifting the rule to a typed
4640 /// method on the substrate primitive means every downstream
4641 /// HTTPRoute-aware consumer (the M4 CR materializer, the future
4642 /// per-cluster overlay resolver, every future per-Aplicacao
4643 /// snapshot renderer) reaches for exactly one typed dispatch —
4644 /// the resolver's accept-set moves as a unit on any future axis
4645 /// addition.
4646 ///
4647 /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
4648 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
4649 /// per-`:entrada` scalar-value axes — extends the "one typed
4650 /// dispatch on the substrate primitive, thin projections at each
4651 /// consumer" discipline onto the per-`:entrada` path-list
4652 /// resolution axis every HTTPRoute-aware renderer consumes. Same
4653 /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
4654 /// sibling `:politicas` primitive — one typed method on the
4655 /// substrate primitive that names the cascade every renderer
4656 /// otherwise re-inlines.
4657 #[must_use]
4658 pub fn resolved_paths(&self) -> Vec<&str> {
4659 // Route the internal cascade-head + per-entry projection reads
4660 // through the lifted [`Self::paths`] slice accessor rather than
4661 // the raw `self.paths` field access — the substrate-primitive
4662 // per-`:entrada` path-list resolver's two internal reads now
4663 // key off the canonical raw-slot surface every downstream
4664 // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
4665 // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
4666 // entrada summary line's `{:?}` Debug print) routes through, so
4667 // any future rebrand on the typed slot's raw-slot reader lands
4668 // at exactly one place. Same two-consumer coherence discipline
4669 // the sibling `Placement::clusters` (a6e18d7) accessor pins on
4670 // the peer M3 mesh-slot `Vec<String>`-carry axis.
4671 if self.paths().is_empty() {
4672 vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
4673 } else {
4674 self.paths().iter().map(String::as_str).collect()
4675 }
4676 }
4677
4678 /// Substrate-canonical per-`:entrada` DNS-hostname singular
4679 /// accessor every Gateway-API `Listener.hostname` reader keys off
4680 /// — returns the author-declared `:entrada :host` byte-string
4681 /// verbatim as a `&str`, borrowed from the typed slot's own
4682 /// [`String`] storage.
4683 ///
4684 /// Named the "singular" half of the DNS-hostname resolver pair on
4685 /// the substrate primitive: the parent-Gateway per-listener
4686 /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
4687 /// (`Listener.hostname: Option<PreciseHostname>` — at most one
4688 /// hostname per listener), and this accessor is the typed dispatch
4689 /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
4690 /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
4691 /// the per-HTTPRoute `spec.hostnames[]` list axis the same
4692 /// per-Aplicacao ingress-hostname surface projects onto.
4693 ///
4694 /// Prior to this lift the `entrada.host.clone()` byte-string was
4695 /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
4696 /// per-listener singular `hostname:` axis
4697 /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
4698 /// per-HTTPRoute plural `spec.hostnames[]` axis
4699 /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
4700 /// consumers read the same `entrada.host` field but the two-site
4701 /// duplication expressed no compile-time contract that the singular
4702 /// Gateway-listener filter and the plural `HTTPRoute` filter list
4703 /// stay in lockstep on future extensions of the `:entrada` slot to
4704 /// a multi-hostname author surface (an `:entrada :alt-hosts` list
4705 /// overlay, a per-cluster SNI fan-out the operator pins through a
4706 /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
4707 /// Aplicacao` CR materializer's per-listener virtual-host filter
4708 /// admission-webhook overlay). Any such extension would have to be
4709 /// threaded through every renderer's inline copy of the resolution
4710 /// in lockstep or the Gateway listener's `hostname:` filter would
4711 /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
4712 /// — a Gateway-API-conformance divergence whose apply-time symptom
4713 /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
4714 /// `NoMatchingParent` — the API server rejects the route because
4715 /// its `hostnames[]` filter doesn't intersect the parent listener's
4716 /// `hostname` filter) is far from the source `caixa.lisp` and never
4717 /// surfaces in the emitted YAML. Lifting the singular and plural
4718 /// resolvers to typed methods on the substrate primitive means
4719 /// every consumer of the Aplicacao's ingress-hostname surface
4720 /// reaches for exactly one typed dispatch, and the pair-invariant
4721 /// `hostnames() == vec![hostname()]` pinned by the sibling
4722 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
4723 /// keeps the two axes in lockstep by construction.
4724 ///
4725 /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
4726 /// (1449891) path-list resolver on the per-HTTPRoute per-rule
4727 /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
4728 /// the substrate primitive, thin projections at each consumer"
4729 /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
4730 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
4731 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
4732 /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
4733 /// `:entrada` scalar-value + list-value axes.
4734 #[must_use]
4735 pub fn hostname(&self) -> &str {
4736 self.host.as_str()
4737 }
4738
4739 /// Substrate-canonical per-`:entrada` DNS-hostname plural
4740 /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
4741 /// keys off — returns the singleton `[hostname()]` list under
4742 /// today's single-hostname-per-Aplicacao author surface, and the
4743 /// authoritative multi-hostname list under a future
4744 /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
4745 ///
4746 /// Plural half of the DNS-hostname resolver pair — see the
4747 /// companion [`Entrada::hostname`] docstring for the two-consumer
4748 /// lift + pair-invariant discipline (`hostnames() ==
4749 /// vec![hostname()]`, pinned load-bearing by the sibling
4750 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
4751 /// test).
4752 ///
4753 /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
4754 /// per-`:entrada` plural-list resolver on the per-HTTPRoute
4755 /// per-rule path-list axis — same `Vec<&str>` shape, same
4756 /// substrate-primitive-owns-the-resolver discipline extended to
4757 /// the per-HTTPRoute virtual-host filter-list axis.
4758 #[must_use]
4759 pub fn hostnames(&self) -> Vec<&str> {
4760 vec![self.hostname()]
4761 }
4762
4763 /// Substrate-canonical per-`:entrada` destination-Servico scalar
4764 /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
4765 /// the author-declared `:entrada :para` byte-string verbatim as a
4766 /// `&str`, borrowed from the typed slot's own [`String`] storage.
4767 ///
4768 /// The `:entrada :para` slot names the single member Servico the
4769 /// external Gateway routes to (validated by
4770 /// [`AplicacaoSpec::validate`] to be a
4771 /// [`Membro::caixa`] the Aplicacao declares — a stray
4772 /// `:para` that doesn't name a member is
4773 /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
4774 /// backend-attachment miss at cluster-apply time). Under today's
4775 /// single-destination author surface `:entrada :para` is the ingress
4776 /// apex Servico's canonical identity; under a hypothetical
4777 /// future multi-backend author surface (a `:entrada
4778 /// :split :backends` weighted-fan-out overlay for canary /
4779 /// blue-green traffic-split rollouts, per-path override for
4780 /// path-based per-Servico routing beyond the single-apex model,
4781 /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4782 /// per-CR admission-webhook that promotes the scalar to a
4783 /// weighted list) this accessor is the substrate primitive's typed
4784 /// dispatch every downstream `HTTPRoute`-aware consumer routes
4785 /// through, so the resolution shape migrates as a unit on one
4786 /// caixa-core edit rather than a coordinated rewrite across every
4787 /// renderer's inline field-access.
4788 ///
4789 /// Prior to this lift the `entrada.para` byte-string was accessed
4790 /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
4791 /// `metadata.name` composer's per-destination discriminator arg
4792 /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
4793 /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
4794 /// per-HTTPRoute per-rule `backendRefs[0].name` axis
4795 /// (`entrada.para.clone()`,
4796 /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
4797 /// consumers read the same `entrada.para` field but the two-site
4798 /// duplication expressed no compile-time contract that the HTTPRoute
4799 /// name-discriminator and the per-rule backend name stay in
4800 /// lockstep on future extensions of the `:entrada` slot to a
4801 /// multi-destination author surface. Any such extension would have
4802 /// to be threaded through every renderer's inline copy of the
4803 /// destination projection in lockstep or the HTTPRoute
4804 /// `metadata.name` would silently reference a different destination
4805 /// than its own `backendRefs[]` — an operator-side
4806 /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
4807 /// grep-by-name lookup would land on a route whose `backendRefs[]`
4808 /// silently point at a peer Servico, dropping every external
4809 /// `:entrada` flow at the gateway with the destination-drift root
4810 /// cause invisible in the emitted YAML.
4811 ///
4812 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
4813 /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
4814 /// the per-listener singular / per-HTTPRoute plural filter axes and
4815 /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
4816 /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
4817 /// typed dispatch on the substrate primitive, thin projections at
4818 /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
4819 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
4820 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
4821 /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
4822 /// sibling per-`:entrada` scalar-value + list-value axes — this
4823 /// accessor closes the last unlifted per-`:entrada` scalar axis
4824 /// (the destination-Servico byte-string) so every downstream
4825 /// per-`:entrada` reader now routes through a typed dispatch on
4826 /// the substrate primitive.
4827 #[must_use]
4828 pub fn destination(&self) -> &str {
4829 self.para.as_str()
4830 }
4831
4832 /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
4833 /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
4834 /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
4835 /// reader keys off — returns the author-declared `:entrada :port`
4836 /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
4837 /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
4838 /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
4839 /// [`AplicacaoError::EntradaPortZero`], not a silent
4840 /// admission-webhook rejection at cluster-apply time).
4841 ///
4842 /// The `:entrada :port` slot carries the destination Servico's
4843 /// canonical in-cluster L4 listener port (`trigger.service.port` on
4844 /// the `pleme-computeunit` library chart), and every downstream
4845 /// consumer that reads the port keys off this scalar (the
4846 /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
4847 /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
4848 /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
4849 /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4850 /// CR materializer's per-Aplicacao gateway port resolver).
4851 ///
4852 /// Prior to this lift the `.port` field was accessed inline at two
4853 /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
4854 /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
4855 /// the [`AplicacaoSpec::port_for_destination`] resolver's
4856 /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
4857 /// open-coded field-accesses that expressed no compile-time link
4858 /// back to the typed slot. A future extension of the `:entrada :port`
4859 /// axis to a richer author surface — a per-cluster override the
4860 /// operator pins through a future `:placement :default-port` slot the
4861 /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
4862 /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
4863 /// heterogeneous listener ports, an M4
4864 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
4865 /// admission-webhook floor that promotes the scalar to a
4866 /// per-destination map — would have had to be threaded through both
4867 /// open-coded copies in lockstep or the structural-floor validator
4868 /// and the [`AplicacaoSpec::port_for_destination`] resolver would
4869 /// silently disagree on which port a given [`Entrada`] resolves to.
4870 /// Lifting the resolution rule to a typed method on the substrate
4871 /// primitive means every downstream consumer of the Aplicacao's
4872 /// per-`:entrada` L4-port surface reaches for exactly one typed
4873 /// dispatch — the resolver's accept-set migrates as a unit on any
4874 /// future axis addition.
4875 ///
4876 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
4877 /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
4878 /// accessors on the per-`:entrada` scalar-value axis — same "one
4879 /// typed dispatch on the substrate primitive, thin projections at
4880 /// each consumer" discipline extended onto the per-`:entrada`
4881 /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
4882 /// the M3 mesh-slot `Entrada` type — closes the last unlifted
4883 /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
4884 /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
4885 /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
4886 /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
4887 /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
4888 /// storage field's name; the accessor's identity name maps onto the
4889 /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
4890 /// already carries.
4891 #[must_use]
4892 pub fn port(&self) -> u16 {
4893 self.port
4894 }
4895
4896 /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
4897 /// slice accessor every HTTPRoute-aware renderer keys off when it
4898 /// wants the raw author-declared path-list (not the fallback-
4899 /// applied projection [`Self::resolved_paths`] returns) — returns
4900 /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
4901 /// borrowed from the typed slot's own [`Vec<String>`] storage.
4902 ///
4903 /// Named the "raw slot" half of the per-`:entrada` path-list resolver
4904 /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
4905 /// (1449891) closes the fallback-applying arm every per-Aplicacao
4906 /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
4907 /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
4908 /// catch-all; non-empty slot → per-entry verbatim projection); this
4909 /// accessor closes the raw-slot arm every consumer that must see the
4910 /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
4911 /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
4912 /// not `Err(EntradaPathEmpty)`, so it cannot route through the
4913 /// fallback-applying sibling; the `feira app graph` per-Aplicacao
4914 /// external-gateway summary line's `{:?}` Debug print — which must
4915 /// name the author's declaration, not the substrate's fallback, so
4916 /// an author reading their graph output can grep their caixa.lisp
4917 /// for the exact list they authored) routes through.
4918 ///
4919 /// Prior to this lift the `.paths` field was accessed inline at four
4920 /// production sites: the two internal reads in [`Self::resolved_paths`]
4921 /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
4922 /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
4923 /// value-shape gate's `for p in &e.paths` traversal head, and the
4924 /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
4925 /// Debug print — four open-coded field-accesses that expressed no
4926 /// compile-time link back to the typed slot. A future extension of
4927 /// the `:entrada :paths` axis to a richer author surface — a
4928 /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
4929 /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
4930 /// spec supports through `matches[].method`), a per-path per-header
4931 /// filter overlay (`matches[].headers[]`), a per-cluster override
4932 /// the operator pins through a future `:placement :path-overlay`
4933 /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4934 /// per-CR admission-webhook that normalized the list at admission
4935 /// time — would have had to be threaded through every open-coded
4936 /// copy in lockstep or the validator's per-entry gate would silently
4937 /// disagree with the renderer's per-entry emit on which list a given
4938 /// `:entrada` block resolves to. Lifting the resolution to a typed
4939 /// method on the substrate primitive means every downstream consumer
4940 /// of the Aplicacao's per-`:entrada` path-list surface reaches for
4941 /// exactly one typed dispatch — the resolver's accept-set migrates
4942 /// as a unit on any future axis addition.
4943 ///
4944 /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
4945 /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
4946 /// carry axis — same "one typed dispatch on the substrate primitive,
4947 /// thin projections at each consumer" discipline extended onto the
4948 /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
4949 /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
4950 /// carrier) so every downstream per-`:entrada` reader now routes
4951 /// through a typed dispatch on the substrate primitive. Returns
4952 /// `&[String]` (not `&Vec<String>`) because every downstream consumer
4953 /// treats the list as a read-only sequence — the slice-view is the
4954 /// narrowest borrow that supports every present + roadmapped consumer
4955 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
4956 /// `Vec`'s grow/push/reserve surface that no consumer of the typed
4957 /// view reaches for (the storage-side `Vec` remains reachable through
4958 /// the `pub paths` field for the mutation-carrying serde round-trip
4959 /// and per-test fixture-mutation paths).
4960 #[must_use]
4961 pub fn paths(&self) -> &[String] {
4962 self.paths.as_slice()
4963 }
4964}
4965
4966/// Canonical default L4 port every typed Servico exposes on its
4967/// in-cluster K8s Service (the `trigger.service.port` axis the
4968/// `pleme-computeunit` library chart emits, the `:entrada :port` author
4969/// surface defaults to when the author omits the slot, and the
4970/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
4971/// `:entrada` block matches the per-`:contratos` destination Servico).
4972/// The single source of truth all three typed-port consumers reach for:
4973///
4974/// - [`Entrada::port`]'s serde default (via the
4975/// [`default_port`] helper this constant feeds); the author surface
4976/// `(:entrada (:host … :para …))` without an explicit `:port` slot
4977/// reads back as a typed [`Entrada`] carrying this exact value;
4978/// - the
4979/// [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
4980/// emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
4981/// fallback, fired when the typed `:entrada` block doesn't name
4982/// the per-`:contratos` destination Servico — the typed
4983/// `:contratos` graph carries no per-destination port axis (the
4984/// destination port is the destination Servico's
4985/// `lareira-<nome>` chart's `trigger.service.port`, which the
4986/// Aplicacao-level renderer has no visibility into without a
4987/// resolver round-trip), so the renderer falls back to the
4988/// substrate's canonical Servico-port assumption — by
4989/// construction the same value the destination's own
4990/// `pleme-computeunit` chart emits, the same value the
4991/// destination's own typed `:entrada :port` slot defaults to;
4992/// - every future per-Servico renderer the absorption-roadmap
4993/// acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4994/// CR materializer's per-edge port resolver, the future
4995/// per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
4996/// emitter's per-route bucket key, the future caixa-otel
4997/// collector-pipeline emitter's per-Servico scrape port).
4998///
4999/// Until this lift landed the value `8080` lived at two production-code
5000/// call-sites: the [`default_port`] helper at
5001/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
5002/// and the `.unwrap_or(8080)` literal at
5003/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
5004/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
5005/// resolver). A future Servico-port rebrand — the substrate moving the
5006/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
5007/// gateway grows direct `:80` listeners, to `8443` once the substrate
5008/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
5009/// override the operator pins through a future
5010/// `:placement :default-port` slot — without a coordinated edit on
5011/// both sides would silently emit Servicos listening on one port and
5012/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
5013/// The CNP's apply-time symptom (the policy is admitted but every L4
5014/// flow on the destination Servico's actual port silently drops because
5015/// it doesn't match the whitelisted port) is far from the rebrand
5016/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
5017/// in hubble traces, not in `kubectl describe`. Lifting the literal to
5018/// a shared constant closes the drift footgun structurally — both
5019/// consumers read from the same `u16`, so any rebrand reaches both
5020/// sites by construction.
5021///
5022/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
5023/// per-renderer canonical-K8s-axis constant — the namespace string
5024/// and the canonical Servico port both lived as duplicated literals
5025/// across caixa-core / caixa-mesh / caixa-flux before their respective
5026/// lifts. Same "the typed constant lives in one place" discipline the
5027/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
5028/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
5029/// shared-string axes.
5030///
5031/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
5032pub const DEFAULT_SERVICO_PORT: u16 = 8080;
5033
5034/// Structural floor for the typed `:entrada :port` axis — every
5035/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
5036/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
5037///
5038/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
5039/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
5040/// interprets as "let the kernel pick a free port at bind time", not a
5041/// well-defined destination the substrate's per-`:entrada` Gateway API
5042/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
5043/// carrying `port: 0` degenerates to a nominal-only routing target: the
5044/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
5045/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
5046/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
5047/// at build time rather than at `kubectl apply` time), and the
5048/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
5049/// (caixa-mesh/src/lib.rs:2657 through
5050/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
5051/// [`Entrada::port`] typed value — silently emits a policy whose
5052/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
5053/// actual listener, dropping every L4 flow at the eBPF data plane far
5054/// from the source caixa.lisp with no field naming the port-zero-drift
5055/// root cause.
5056///
5057/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
5058/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
5059/// on the top edge (unlike the peer capped-`u32` `:politicas` /
5060/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
5061/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
5062/// well below `u32::MAX` and therefore need explicit typed caps).
5063///
5064/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
5065/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
5066/// scalar every `(:entrada (:host … :para …))` slot without an explicit
5067/// `:port` inherits through the serde default hook; this constant names
5068/// the accept-set floor every declared port must satisfy. The pair is
5069/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
5070/// substrate's default must satisfy its own accept-set floor by
5071/// construction) — a future rebrand that accidentally moved
5072/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
5073/// negative-cast typo, a per-cluster override the operator pins through
5074/// a future `:placement :default-port` slot that lands out-of-range)
5075/// would silently invalidate the serde-default emission at every
5076/// author-side `(:entrada (:host … :para …))` slot — the compile-time
5077/// invariant pin
5078/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
5079/// closes the drift footgun at caixa-core build time.
5080///
5081/// Lifted as a typed `pub const` (rather than an inline `0` literal at
5082/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
5083/// has exactly one source of truth — the future M4
5084/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
5085/// gateway resolver, the future per-Servico
5086/// `computeunit.trigger.service.port` renderer's per-CR port-value
5087/// validator, and every downstream test-fixture navigator asserting
5088/// the accept-set floor all read from one place. Same shape every
5089/// other typed bracket-floor / bracket-ceiling in this crate carries
5090/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5091/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
5092/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5093/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
5094/// [`POLICY_RATE_LIMIT_MAX`]).
5095pub const SERVICO_PORT_MIN: u16 = 1;
5096
5097const fn default_port() -> u16 {
5098 DEFAULT_SERVICO_PORT
5099}
5100
5101// ── the typed view ───────────────────────────────────────────────────
5102
5103/// Typed composition view of the flat Aplicacao slots on
5104/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
5105/// validation + downstream renderer consumption.
5106#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5107#[serde(rename_all = "camelCase")]
5108pub struct AplicacaoSpec {
5109 pub membros: Vec<Membro>,
5110 pub contratos: Vec<WitContract>,
5111 pub politicas: MeshPolicy,
5112 pub placement: Placement,
5113 pub entrada: Option<Entrada>,
5114}
5115
5116impl AplicacaoSpec {
5117 /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
5118 /// per-Aplicacao member-list slice-return accessor every
5119 /// per-Aplicacao member-list reader keys off — returns the author-
5120 /// declared `:membros` list verbatim as a `&[Membro]` slice-view
5121 /// over the same backing buffer the raw `self.membros.as_slice()`
5122 /// field access borrows from.
5123 ///
5124 /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
5125 /// member list — the load-bearing identity of the application graph
5126 /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
5127 /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
5128 /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
5129 /// accessor) with a `:versao` semver-requirement string (through
5130 /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
5131 /// and every downstream consumer that fans on the member-set keys
5132 /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
5133 /// membership-lookup `HashSet<&str>` seed's collect input, the
5134 /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
5135 /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
5136 /// per-member DNS-1123 / semver-requirement / duplicate-detection
5137 /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
5138 /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
5139 /// programs.yaml per-`:membros` fan-out emitter's per-entry
5140 /// mapping-composition loop, the `feira app graph` per-Aplicacao
5141 /// member-count print line and per-member tree traversal,
5142 /// every future wasm-operator (M4) per-Aplicacao CR materializer's
5143 /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
5144 /// placement engine's per-member weight-topology reader).
5145 ///
5146 /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
5147 /// inline at six production sites — the [`AplicacaoSpec::validate`]
5148 /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
5149 /// [`AplicacaoSpec::validate_membros`]'s pre-flight
5150 /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
5151 /// probe, the same method's per-member `for m in &self.membros`
5152 /// validate-loop traversal head, the
5153 /// [`AplicacaoSpec::detect_sync_cycles`]'s
5154 /// `for m in &self.membros` adjacency-list seed, the
5155 /// [`caixa_mesh::programs_for_aplicacao`] emitter's
5156 /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
5157 /// paired with the peer `for m in &spec.membros` per-entry fan-out
5158 /// loop, and the `feira app graph` per-Aplicacao print line's
5159 /// `spec.membros.len()` count formatter argument paired with the
5160 /// peer `for m in &spec.membros` per-member tree traversal — six
5161 /// open-coded field-accesses that expressed no compile-time link
5162 /// back to the typed slot. A future extension of the `:membros`
5163 /// axis to a richer author surface (a per-cluster member-set
5164 /// overlay the operator pins through a future
5165 /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
5166 /// roadmap acknowledges, a per-tenant member-alias table the M4
5167 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
5168 /// CR at admission time, a per-Aplicacao dynamic member-set
5169 /// derivation the future adaptive-placement engine computes from
5170 /// weighted membership topology, a promotion of the plain
5171 /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
5172 /// Orleans-style virtual-actor dynamic-membership comes into typed
5173 /// scope) would have had to be threaded through all six open-coded
5174 /// copies in lockstep or one consumer would silently disagree with
5175 /// the peers on which member-set a given Aplicacao resolves to —
5176 /// the `HashSet<&str>` name-set seed reading the raw slot while
5177 /// the peer `.is_empty()` refusal probe read an operator-resolved
5178 /// slot would silently split the `:contratos` membership-lookup
5179 /// input from the pre-flight-refusal input, a six-consumer split
5180 /// at the validator + programs.yaml emitter + graph printer far
5181 /// from the source `caixa.lisp` with no field naming the member-
5182 /// set-drift root cause. Lifting the resolution rule to a typed
5183 /// method on the substrate primitive means every downstream
5184 /// consumer of the Aplicacao's per-`:membros` member-list surface
5185 /// reaches for exactly one typed dispatch — the resolver's accept-
5186 /// set migrates as a unit on any future axis addition.
5187 ///
5188 /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
5189 /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5190 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5191 /// static-child-list `Vec`-carry axis, and to the M3
5192 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5193 /// on the peer per-`:placement` distribution-target-list `Vec`-
5194 /// carry axis. Same "one typed dispatch on the substrate primitive,
5195 /// thin projections at each consumer" discipline. The two peer
5196 /// `Vec`-carry axes still unlifted at the time of this lift —
5197 /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
5198 /// WIT-typed edge list) and
5199 /// [`crate::UpgradeFromEntry::instructions`]
5200 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5201 /// — inherit this accessor's discipline as future compounding runs
5202 /// migrate their consumers onto the shared slice-return shape.
5203 /// First `&[T]`-return accessor on the top-level M3 mesh-slot
5204 /// `AplicacaoSpec` type itself, extending the discipline beyond
5205 /// the inner per-slot types ([`crate::Placement`],
5206 /// [`crate::SupervisorSpec`]) onto the outermost typed composition
5207 /// view every renderer consumes. Named `membros()` to match the
5208 /// storage field's name verbatim and the tatara-lisp author-
5209 /// surface term (`:membros`) the field's own docstring already
5210 /// carries; the accessor's identity maps onto the canonical
5211 /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
5212 /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
5213 /// every downstream consumer of the member list treats it as a
5214 /// read-only sequence — the slice-view is the narrowest borrow
5215 /// that supports every present + roadmapped consumer
5216 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5217 /// backing `Vec`'s grow/push/reserve surface that no consumer of
5218 /// the typed view reaches for (the storage-side `Vec` remains
5219 /// reachable through the `pub membros` field for the mutation-
5220 /// carrying serde round-trip and per-test fixture-mutation paths).
5221 #[must_use]
5222 pub fn membros(&self) -> &[Membro] {
5223 self.membros.as_slice()
5224 }
5225
5226 /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
5227 /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
5228 /// accessor every per-Aplicacao contract-list reader keys off —
5229 /// returns the author-declared `:contratos` list verbatim as a
5230 /// `&[WitContract]` slice-view over the same backing buffer the raw
5231 /// `self.contratos.as_slice()` field access borrows from.
5232 ///
5233 /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
5234 /// WIT-typed edge list — the load-bearing set of directed edges
5235 /// on the application graph whose nodes are the `:membros` entries
5236 /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
5237 /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
5238 /// six-tuple is the edge identity every downstream duplicate gate
5239 /// keys off). Every per-`:contratos` entry pairs a `:de` source-
5240 /// Servico caller name + a `:para` destination-Servico callee name
5241 /// (through the lifted [`WitContract::source`] +
5242 /// [`WitContract::destination`] (7f0fd43) accessor pair on the
5243 /// caller/callee-Servico axis) with a `:wit` world-reference
5244 /// (through the lifted [`WitContract::world_ref`] (0804823)
5245 /// accessor) and the target-shape-appropriate payload-carrier
5246 /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
5247 /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
5248 /// (ed22b66) accessor on the per-target-shape payload-carrier
5249 /// axis). Every downstream consumer that fans on the edge-set
5250 /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
5251 /// name-set / self-edge / target-shape / dedup fan-out loop, the
5252 /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
5253 /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
5254 /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
5255 /// grouping loop, the `feira app graph` per-Aplicacao contract-
5256 /// count print line and per-contract tree traversal, every future
5257 /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
5258 /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
5259 /// mesh-policy overlay resolver's per-contract typed-edge weight
5260 /// reader).
5261 ///
5262 /// Prior to this lift the `.contratos` `Vec<WitContract>` was
5263 /// accessed inline at four production sites — the
5264 /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
5265 /// per-edge validate-loop traversal head (which drives every
5266 /// per-edge name-set membership lookup, self-edge check,
5267 /// target-shape dispatch, and dedup `HashSet` insert), the
5268 /// [`AplicacaoSpec::detect_sync_cycles`]'s
5269 /// `for c in &self.contratos` adjacency-list seed head (which
5270 /// drives every per-edge sync-vs-pub-sub partition and per-edge
5271 /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
5272 /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
5273 /// `BTreeMap` grouping loop head (which drives every per-CNP
5274 /// fan-out emit), and the `feira app graph` per-Aplicacao print
5275 /// line's `spec.contratos.len()` count formatter argument paired
5276 /// with the peer `for c in &spec.contratos` per-contract tree
5277 /// traversal — four open-coded field-accesses that expressed no
5278 /// compile-time link back to the typed slot. A future extension
5279 /// of the `:contratos` axis to a richer author surface (a
5280 /// per-cluster contract overlay the operator pins through a
5281 /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
5282 /// federation roadmap acknowledges, a per-tenant edge-policy
5283 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5284 /// materializer resolves per-CR at admission time, a per-edge
5285 /// weight scalar the future adaptive-placement engine reads to
5286 /// bias sync-subgraph routing, a promotion of the plain
5287 /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
5288 /// once virtual-actor-style dynamic-edge composition comes into
5289 /// typed scope) would have had to be threaded through all four
5290 /// open-coded copies in lockstep or one consumer would silently
5291 /// disagree with the peers on which edge-set a given Aplicacao
5292 /// resolves to — the validator's per-edge dedup `HashSet` seed
5293 /// reading the raw slot while the peer sync-cycle adjacency-list
5294 /// seed read an operator-resolved slot would silently split the
5295 /// build-time edge-set gate from the runtime deadlock-detection
5296 /// gate, a four-consumer split at the validator, the cycle
5297 /// detector, the CNP emitter, and the graph printer far from
5298 /// the source `caixa.lisp` with no field naming the edge-set-
5299 /// drift root cause. Lifting the resolution rule to a typed method on the
5300 /// substrate primitive means every downstream consumer of the
5301 /// Aplicacao's per-`:contratos` edge-list surface reaches for
5302 /// exactly one typed dispatch — the resolver's accept-set
5303 /// migrates as a unit on any future axis addition.
5304 ///
5305 /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
5306 /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5307 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5308 /// static-child-list `Vec`-carry axis, to the M3
5309 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5310 /// on the peer per-`:placement` distribution-target-list `Vec`-
5311 /// carry axis, and to the immediately-adjacent sibling M3
5312 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
5313 /// the peer per-`:membros` node-list `Vec`-carry axis — the
5314 /// per-`:contratos` edge-list accessor is the natural pair of
5315 /// the per-`:membros` node-list accessor (graph edges over graph
5316 /// nodes; every graph-shaped consumer reads both). Same "one
5317 /// typed dispatch on the substrate primitive, thin projections
5318 /// at each consumer" discipline. The last remaining `Vec`-carry
5319 /// axis still unlifted at the time of this lift —
5320 /// [`crate::UpgradeFromEntry::instructions`]
5321 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
5322 /// list) — inherits this accessor's discipline as future
5323 /// compounding runs migrate its consumers onto the shared slice-
5324 /// return shape. Second `&[T]`-return accessor on the top-level
5325 /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
5326 /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
5327 /// `:contratos` are the two `Vec` fields on the outer typed
5328 /// composition view — `:politicas`, `:placement`, `:entrada` are
5329 /// scalar/option-shaped and already route through their per-slot
5330 /// accessor families). Named `contratos()` to match the storage
5331 /// field's name verbatim and the tatara-lisp author-surface term
5332 /// (`:contratos`) the field's own docstring already carries; the
5333 /// accessor's identity maps onto the canonical MESH-COMPOSITION
5334 /// §III.1 vocabulary the slot's docstring already reaches for.
5335 /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
5336 /// every downstream consumer of the contract list treats it as a
5337 /// read-only sequence — the slice-view is the narrowest borrow
5338 /// that supports every present + roadmapped consumer
5339 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5340 /// backing `Vec`'s grow/push/reserve surface that no consumer of
5341 /// the typed view reaches for (the storage-side `Vec` remains
5342 /// reachable through the `pub contratos` field for the mutation-
5343 /// carrying serde round-trip and per-test fixture-mutation paths).
5344 #[must_use]
5345 pub fn contratos(&self) -> &[WitContract] {
5346 self.contratos.as_slice()
5347 }
5348
5349 /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
5350 /// per-Aplicacao mesh-policy composite-reference accessor every
5351 /// per-Aplicacao policy-block reader keys off — returns the author-
5352 /// declared `:politicas` composite verbatim as a `&MeshPolicy`
5353 /// reference over the same backing storage the raw `&self.politicas`
5354 /// field access borrows from.
5355 ///
5356 /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
5357 /// mesh-policy composite — the load-bearing container of every
5358 /// mesh-level operational-policy axis every downstream mesh-artifact
5359 /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
5360 /// mesh-policy overlay is the single typed surface a
5361 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
5362 /// from). Every per-`:politicas` axis threads through a lifted
5363 /// per-slot accessor on the [`MeshPolicy`] type: the
5364 /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
5365 /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
5366 /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
5367 /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
5368 /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
5369 /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
5370 /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
5371 /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
5372 /// accessor. Every downstream consumer that reaches for a policy
5373 /// axis first passes through this outer accessor onto the composite
5374 /// and then dispatches onto the per-axis accessor — the two-level
5375 /// dispatch means every per-`:politicas` reader now routes through
5376 /// a typed dispatch on the substrate primitive at both altitudes.
5377 ///
5378 /// Prior to this lift the `.politicas` `MeshPolicy` composite was
5379 /// accessed inline at four production sites — the
5380 /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
5381 /// &self.politicas;` traversal seed (which drives every per-axis
5382 /// zero-floor + upper-cap + canonical-form bracket dispatch through
5383 /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
5384 /// `p.rate_limit()` on the axis-level lifted accessors), the
5385 /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
5386 /// emitter's `spec.politicas.mtls_required()` field-then-accessor
5387 /// chain (which drives every per-`(:de, :para)` CNP
5388 /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
5389 /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
5390 /// timeout + retry overlay emitter's paired
5391 /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
5392 /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
5393 /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
5394 /// open-coded outer-field accesses that expressed no compile-time
5395 /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
5396 /// future extension of the `:politicas` outer axis to a richer
5397 /// author surface (a per-cluster policy overlay the operator pins
5398 /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
5399 /// §V federation roadmap acknowledges, a per-tenant policy-alias
5400 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5401 /// resolves per-CR at admission time, a per-Aplicacao dynamic
5402 /// policy-composite derivation the future adaptive-placement engine
5403 /// computes from a per-cluster load-topology reader, a promotion of
5404 /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
5405 /// partition once virtual-actor-style dynamic-mesh-policy
5406 /// composition comes into typed scope) would have had to be threaded
5407 /// through all four open-coded copies in lockstep or one consumer
5408 /// would silently disagree with the peers on which mesh-policy
5409 /// composite a given Aplicacao resolves to — the validator's
5410 /// per-axis bracket-dispatch seed reading the raw slot while the
5411 /// peer CNP mTLS-overlay emitter read an operator-resolved slot
5412 /// would silently split the build-time policy-shape gate from the
5413 /// runtime CNP-emission gate, a four-consumer split at the
5414 /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
5415 /// the source `caixa.lisp` with no field naming the policy-drift
5416 /// root cause. Lifting the resolution rule to a typed method on the
5417 /// substrate primitive means every downstream consumer of the
5418 /// Aplicacao's per-`:politicas` mesh-policy composite surface
5419 /// reaches for exactly one typed dispatch — the resolver's accept-
5420 /// set migrates as a unit on any future axis addition.
5421 ///
5422 /// First `&Composite`-return accessor on the top-level M3 mesh-slot
5423 /// `AplicacaoSpec` type itself — sibling to the seed slice-return
5424 /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5425 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
5426 /// close the two `Vec`-carry axes on the outer typed composition
5427 /// view; the outer `:politicas` composite-reference axis is the
5428 /// natural pair to the paired outer `Vec`-carry accessors on the
5429 /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
5430 /// emitter reads all four axes as one unit (graph nodes + graph
5431 /// edges + mesh policy + placement pool). Peer to the same
5432 /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
5433 /// slot: every M2 `SupervisorSpec`-scoped composite reader
5434 /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
5435 /// `restart_window`, `children`) already routes through the M2
5436 /// `SupervisorSpec` accessor family — this lift extends the same
5437 /// "one typed dispatch on the substrate primitive at the outer
5438 /// composition altitude" discipline to the M3 mesh-slot
5439 /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
5440 /// remaining peer outer-composite axes still unlifted at the time
5441 /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
5442 /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
5443 /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
5444 /// inherit this accessor's discipline as future compounding runs
5445 /// migrate their consumers onto the shared reference-return shape.
5446 /// Named `politicas()` to match the storage field's name verbatim
5447 /// and the tatara-lisp author-surface term (`:politicas`) the
5448 /// field's own docstring already carries; the accessor's identity
5449 /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
5450 /// slot's docstring already reaches for. Returns `&MeshPolicy`
5451 /// (not the owning composite by copy or clone) because every
5452 /// downstream consumer of the mesh-policy composite treats it as a
5453 /// read-only per-axis dispatch source — the reference-view is the
5454 /// narrowest borrow that supports every present + roadmapped
5455 /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
5456 /// emptiness probe) without cloning the composite through every
5457 /// consumer's fast path.
5458 #[must_use]
5459 pub fn politicas(&self) -> &MeshPolicy {
5460 &self.politicas
5461 }
5462
5463 /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
5464 /// per-Aplicacao distribution-composite composite-reference accessor
5465 /// every per-Aplicacao placement-block reader keys off — returns the
5466 /// author-declared `:placement` composite verbatim as a `&Placement`
5467 /// reference over the same backing storage the raw `&self.placement`
5468 /// field access borrows from.
5469 ///
5470 /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
5471 /// distribution composite — the load-bearing container of every
5472 /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
5473 /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
5474 /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
5475 /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
5476 /// hosting-pool identity, §V for the `M3-Adaptive`-compression
5477 /// `:affinity` hint). Every per-`:placement` axis threads through a
5478 /// lifted per-slot accessor on the [`Placement`] type: the
5479 /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
5480 /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
5481 /// per-cluster distribution-target slice-return accessor, the
5482 /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
5483 /// optional-scalar accessor, and the [`Placement::shard_key`]
5484 /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
5485 /// downstream consumer that reaches for a placement axis first passes
5486 /// through this outer accessor onto the composite and then dispatches
5487 /// onto the per-axis accessor — the two-level dispatch means every
5488 /// per-`:placement` reader now routes through a typed dispatch on the
5489 /// substrate primitive at both altitudes.
5490 ///
5491 /// Prior to this lift the `.placement` `Placement` composite was
5492 /// accessed inline at three production sites — the
5493 /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
5494 /// seed (six `self.placement.<axis>()` field-then-inner-accessor
5495 /// chains: the pre-flight `.clusters().is_empty()` refusal probe
5496 /// paired with the `.estrategia()` diagnostic-carry copy, the per-
5497 /// cluster `.clusters()` validate-loop traversal head, the per-
5498 /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
5499 /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
5500 /// paired with the shape-gate cascade's `.shard_key()` /
5501 /// `.estrategia()` diagnostic-carry pair), the
5502 /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
5503 /// per-entry placement-block emitter's outer
5504 /// `serde_yaml::to_value(&spec.placement)` composite-serialization
5505 /// seed (which fans onto every per-cluster `programs[]` entry as a
5506 /// self-describing distribution overlay the aggregator filters by),
5507 /// and the `feira app graph` per-Aplicacao print line's paired
5508 /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
5509 /// then-inner-accessor chains (which drive the human-readable
5510 /// distribution summary of the typed Aplicacao view) — three open-
5511 /// coded outer-field accesses that expressed no compile-time link
5512 /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
5513 /// extension of the `:placement` outer axis to a richer author surface
5514 /// (a per-cluster placement overlay the operator pins through a
5515 /// future `:placement-overrides` slot the MESH-COMPOSITION §V
5516 /// federation roadmap acknowledges, a per-tenant placement-alias
5517 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
5518 /// resolves per-CR at admission time, a per-Aplicacao dynamic
5519 /// placement-composite derivation the future M5 adaptive-placement
5520 /// engine computes from a per-cluster load-topology reader, a
5521 /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
5522 /// partition once Orleans-style virtual-actor dynamic-placement comes
5523 /// into typed scope) would have had to be threaded through all three
5524 /// open-coded copies in lockstep or one consumer would silently
5525 /// disagree with the peers on which placement composite a given
5526 /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
5527 /// seed reading the raw slot while the peer
5528 /// `programs_for_aplicacao` emitter read an operator-resolved slot
5529 /// would silently split the build-time distribution-shape gate from
5530 /// the runtime programs.yaml distribution-annotation gate, a three-
5531 /// consumer split at the validator, the programs.yaml emitter, and
5532 /// the `feira app graph` printer far from the source `caixa.lisp`
5533 /// with no field naming the placement-drift root cause. Lifting the
5534 /// resolution rule to a typed method on the substrate primitive
5535 /// means every downstream consumer of the Aplicacao's per-
5536 /// `:placement` distribution composite surface reaches for exactly
5537 /// one typed dispatch — the resolver's accept-set migrates as a unit
5538 /// on any future axis addition.
5539 ///
5540 /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
5541 /// `AplicacaoSpec` type itself — sibling to the seed
5542 /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
5543 /// composite-reference accessor on the peer per-`:politicas` outer-
5544 /// composite axis, and to the paired slice-return accessors
5545 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
5546 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
5547 /// the two `Vec`-carry axes on the outer typed composition view; the
5548 /// outer `:placement` composite-reference axis is the natural pair
5549 /// to the peer `:politicas` composite-reference axis on the two
5550 /// operationally-symmetric M3 mesh slots (`:politicas` carries the
5551 /// how-to-run policy overlay, `:placement` carries the where-to-run
5552 /// distribution composite — every whole-Aplicacao mesh-artifact
5553 /// emitter reads both as one unit). Same "one typed dispatch on the
5554 /// substrate primitive, thin projections at each consumer"
5555 /// discipline the peer per-`:politicas` composite-reference axis
5556 /// already routes through. The one remaining outer-composite axis
5557 /// still unlifted at the time of this lift —
5558 /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
5559 /// external-gateway composite) — inherits this accessor's discipline
5560 /// as the next compounding run migrates its consumers onto the shared
5561 /// reference-return shape, closing the outer-composite altitude on
5562 /// every M3 mesh-slot axis. Named `placement()` to match the storage
5563 /// field's name verbatim and the tatara-lisp author-surface term
5564 /// (`:placement`) the field's own docstring already carries; the
5565 /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
5566 /// vocabulary the slot's docstring already reaches for. Returns
5567 /// `&Placement` (not the owning composite by copy or clone) because
5568 /// every downstream consumer of the placement composite treats it as
5569 /// a read-only per-axis dispatch source — the reference-view is the
5570 /// narrowest borrow that supports every present + roadmapped consumer
5571 /// (per-axis accessor dispatch, serde composite-serialization) without
5572 /// cloning the composite through every consumer's fast path.
5573 #[must_use]
5574 pub fn placement(&self) -> &Placement {
5575 &self.placement
5576 }
5577
5578 /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
5579 /// per-Aplicacao external-gateway composite optional-composite-
5580 /// reference accessor every per-Aplicacao gateway-block reader
5581 /// keys off — returns the author-declared `:entrada` composite
5582 /// verbatim as an `Option<&Entrada>` reference over the same
5583 /// backing storage the raw `self.entrada.as_ref()` field access
5584 /// borrows from, with `None` naming the internal-only mesh shape
5585 /// (the author-omitted `:entrada` slot the K8s Gateway API v1
5586 /// gateway_routes emitter treats as "emit nothing" and the peer
5587 /// `feira app graph` printer treats as "internal-only mesh").
5588 ///
5589 /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
5590 /// external-gateway composite — the load-bearing container of
5591 /// every does-this-Aplicacao-expose-a-public-endpoint axis every
5592 /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
5593 /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
5594 /// hostname axis, §III.4 for the `:para` destination-Servico
5595 /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
5596 /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
5597 /// axis threads through a lifted per-slot accessor on the
5598 /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
5599 /// Gateway-API `Listener.hostname` scalar accessor, the paired
5600 /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
5601 /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
5602 /// backendRefs destination-Servico scalar accessor, the
5603 /// [`Entrada::resolved_paths`] path-fallback resolver, and the
5604 /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
5605 /// scalar accessor. Every downstream consumer that reaches for
5606 /// an entrada axis first passes through this outer accessor onto
5607 /// the composite and then dispatches onto the per-axis accessor
5608 /// — the two-level dispatch means every per-`:entrada` reader
5609 /// now routes through a typed dispatch on the substrate primitive
5610 /// at both altitudes.
5611 ///
5612 /// Prior to this lift the `.entrada` `Option<Entrada>` composite
5613 /// was accessed inline at four production sites — the
5614 /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
5615 /// gate's `if let Some(e) = &self.entrada { … }` traversal head
5616 /// (which drives every per-axis refusal on the composite: the
5617 /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
5618 /// `EntradaMemberMissing` membership lookup against the
5619 /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
5620 /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
5621 /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
5622 /// per-path shape gate on each entry of `e.paths`), the
5623 /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
5624 /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
5625 /// composite-projection seed (which drives the destination-
5626 /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
5627 /// backendRefs port emitter fans on), the
5628 /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
5629 /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
5630 /// early-return seed (which drives the "no `:entrada` ⇒ no
5631 /// external artifacts" partition on the whole-Aplicacao Gateway-
5632 /// API emitter's fan-out), and the `feira app graph` per-
5633 /// Aplicacao print line's `if let Some(e) = &spec.entrada`
5634 /// external-gateway summary emitter (which drives the human-
5635 /// readable `entrada: host → para (paths=…, port=…)` /
5636 /// `entrada: (internal-only mesh)` partition on the typed
5637 /// Aplicacao view) — four open-coded outer-field accesses that
5638 /// expressed no compile-time link back to the typed slot at the
5639 /// [`AplicacaoSpec`] altitude. A future extension of the
5640 /// `:entrada` outer axis to a richer author surface (a
5641 /// multi-`:entrada` list the M4 CR materializer resolves per-CR
5642 /// at admission time so an Aplicacao can expose a public-web +
5643 /// admin-web pair, a per-cluster `:entrada-overrides` slot the
5644 /// MESH-COMPOSITION §V federation roadmap acknowledges so an
5645 /// operator can pin a per-cluster hostname override without
5646 /// re-authoring the `caixa.lisp`, a promotion of the plain
5647 /// `Option<Entrada>` to a richer `{single, multi}` partition once
5648 /// the multi-`:entrada` roadmap lands) would have had to be
5649 /// threaded through all four open-coded copies in lockstep or one
5650 /// consumer would silently disagree with the peers on which
5651 /// entrada composite a given Aplicacao resolves to — the
5652 /// validator's per-axis bracket-dispatch seed reading the raw
5653 /// slot while the peer `gateway_routes` emitter read an
5654 /// operator-resolved slot would silently split the build-time
5655 /// gateway-shape gate from the runtime Gateway + HTTPRoute
5656 /// emission gate, a four-consumer split at the validator, the
5657 /// `port_for_destination` L4-port resolver, the `gateway_routes`
5658 /// emitter, and the `feira app graph` printer far from the
5659 /// source `caixa.lisp` with no field naming the entrada-drift
5660 /// root cause. Lifting the resolution rule to a typed method on
5661 /// the substrate primitive means every downstream consumer of
5662 /// the Aplicacao's per-`:entrada` external-gateway composite
5663 /// surface reaches for exactly one typed dispatch — the
5664 /// resolver's accept-set migrates as a unit on any future axis
5665 /// addition.
5666 ///
5667 /// Third and final `&Composite`-return accessor on the top-level
5668 /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
5669 /// unlifted outer-composite axis on the outer typed composition
5670 /// view, sibling to the seed [`AplicacaoSpec::politicas`]
5671 /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
5672 /// accessor on the per-`:politicas` outer-composite axis and to
5673 /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
5674 /// distribution-composite composite-reference accessor on the
5675 /// per-`:placement` outer-composite axis; extends the outer-
5676 /// composite reference-return discipline the two peers already
5677 /// route through onto the last unlifted per-`AplicacaoSpec`
5678 /// outer-composite axis. The `:entrada` outer-composite axis is
5679 /// the natural pair to the two peer outer-composite axes on the
5680 /// three operationally-symmetric M3 mesh-slot outer composites
5681 /// (`:politicas` carries the how-to-run policy overlay,
5682 /// `:placement` carries the where-to-run distribution composite,
5683 /// `:entrada` carries the who-can-reach-it external-gateway
5684 /// composite — every whole-Aplicacao mesh-artifact emitter reads
5685 /// all three as one unit). Same "one typed dispatch on the
5686 /// substrate primitive, thin projections at each consumer"
5687 /// discipline the peer outer-composite axes already route through.
5688 /// Named `entrada()` to match the storage field's name verbatim
5689 /// and the tatara-lisp author-surface term (`:entrada`) the
5690 /// field's own docstring already carries; the accessor's
5691 /// identity maps onto the canonical MESH-COMPOSITION §III.4
5692 /// vocabulary the slot's docstring already reaches for. Returns
5693 /// `Option<&Entrada>` (not the owning composite by copy or
5694 /// clone) because every downstream consumer of the entrada
5695 /// composite treats it as a read-only per-axis dispatch source
5696 /// — the reference-view is the narrowest borrow that supports
5697 /// every present + roadmapped consumer (per-axis accessor
5698 /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
5699 /// port-fallback projection, early-return partition on the
5700 /// `None` arm) without cloning the composite through every
5701 /// consumer's fast path. The `Option` half of the return-type
5702 /// preserves the load-bearing "author-omitted `:entrada` ⇒
5703 /// internal-only mesh" partition (not a default composite the
5704 /// downstream must reject on emptiness) — the accessor projects
5705 /// the raw `Option<Entrada>` slot's presence bit through the
5706 /// reference-return unchanged.
5707 #[must_use]
5708 pub fn entrada(&self) -> Option<&Entrada> {
5709 self.entrada.as_ref()
5710 }
5711
5712 /// Validate the typed shape:
5713 /// - `:membros` is non-empty; every entry has a non-empty `:caixa`
5714 /// and a non-empty `:versao`; no two entries share the same
5715 /// `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
5716 /// not a multiset)
5717 /// - every `:contratos` :de + :para must be in `:membros`
5718 /// - no `:contratos` edge is a self-edge (`:de == :para`) — a
5719 /// contract is an inter-Servico edge, so a Servico contracting
5720 /// with itself is a build error under every WIT shape
5721 /// (MESH-COMPOSITION §III.1)
5722 /// - no two `:contratos` entries agree on
5723 /// `(de, para, wit, endpoint, subject, slot)` — the typed-graph
5724 /// edges are a set, not a multiset (peer of the `:membros` /
5725 /// `:placement :clusters` / `:entrada :paths` duplicate gates)
5726 /// - `:entrada :para` must be in `:membros`
5727 /// - `:placement Sharded` must declare `:shard-key` (non-empty);
5728 /// `:placement Replicated`/`SingleNode` must NOT declare
5729 /// `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
5730 /// consumes it (MESH-COMPOSITION §II.4), and the typed partition
5731 /// between strategy and shard-key is symmetric: every validated
5732 /// `Placement` has `shard_key.is_some()` iff `estrategia ==
5733 /// Sharded`
5734 /// - every `:placement` strategy must declare ≥1 `:clusters` entry —
5735 /// `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
5736 /// the shard pool (MESH-COMPOSITION §III.1)
5737 /// - every `:clusters` entry is non-empty and unique
5738 /// - `:placement :affinity`, when set, is non-empty
5739 /// - the synchronous-`:contratos` subgraph is acyclic
5740 /// (MESH-COMPOSITION §III.3)
5741 /// - every declared `:politicas` value is operationally meaningful
5742 /// (zero timeout, zero retries, zero breaker thresholds, zero rate
5743 /// limit are all build errors — MESH-COMPOSITION §V CSE invariants;
5744 /// omit the field instead to express "no policy on this axis")
5745 pub fn validate(&self) -> Result<(), AplicacaoError> {
5746 self.validate_membros()?;
5747 let names: std::collections::HashSet<&str> =
5748 self.membros().iter().map(Membro::nome).collect();
5749
5750 // Identity key for the typed-edge duplicate gate below: every
5751 // field that distinguishes one contract from another. Two
5752 // entries that agree on all six are *the same edge declared
5753 // twice*, the typed-graph analogue of duplicate `:membros` /
5754 // `:placement :clusters` / `:entrada :paths` entries (which
5755 // are already build errors at this layer). Rejecting it at the
5756 // validate gate closes a renderer-side footgun: caixa-mesh's
5757 // `cilium_network_policies` keys each emitted policy by
5758 // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
5759 // (de, para) and identical payload would land as two K8s
5760 // objects with colliding `metadata.name`, rejected at apply
5761 // time far from the source caixa.lisp.
5762 let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
5763 std::collections::HashSet::new();
5764 for c in self.contratos() {
5765 // Per-axis value-shape gate on every `:contratos` name
5766 // reference, before any graph-membership lookup. Empty +
5767 // DNS-1123-malformed `:de`/`:para` values silently fell
5768 // through to `ContratoMemberMissing` at the lookup arm
5769 // because every `:membros :caixa` is shape-validated
5770 // (3f9d7a0), so the `names` set structurally cannot contain
5771 // an empty / malformed string and the membership-lookup
5772 // diagnostic always misframed the root cause as
5773 // "this caixa is not in `:membros`". The shape gate runs
5774 // ahead of the lookup so structurally-impossible-to-match
5775 // inputs route through the narrower self-locating
5776 // diagnostic, preserving the legitimate "well-shaped
5777 // phantom reference" arm. `:de` runs before `:para` per
5778 // the canonical edge-direction order the existing
5779 // membership lookup, self-edge check, target dispatch,
5780 // and diagnostic strings already use.
5781 // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
5782 // + the paired [`AplicacaoError::ContratoMemberMissing`]
5783 // diagnostic's `caixa:` carrier through the lifted
5784 // [`WitContract::source`] / [`WitContract::destination`]
5785 // scalar accessors rather than the raw `&c.de` / `&c.para`
5786 // `&String`-borrow arg site + the raw `c.de.clone()` /
5787 // `c.para.clone()` field-access `String`-carry sites — the
5788 // last unlifted per-`:contratos` raw-field-access sites in
5789 // the M3 mesh-slot validator's per-edge per-arm shape-gate
5790 // arg + phantom-name diagnostic wrap-envelope emit surface.
5791 // `c.source()` is byte-identical to `&c.de` (pinned by the
5792 // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
5793 // + `wit_contract_source_borrows_from_de_storage` accessor
5794 // tests) and `c.destination()` is byte-identical to `&c.para`
5795 // (pinned by the sibling
5796 // `wit_contract_destination_returns_para_byte_equal_across_permutations`
5797 // + `wit_contract_destination_borrows_from_para_storage`
5798 // accessor tests) — so a future rebrand of either underlying
5799 // storage flows through the accessor's one body without a
5800 // coordinated per-consumer rewrite across the M3 mesh
5801 // validator's per-edge shape-gate + phantom-name refusal
5802 // arms. Peer of the sibling per-`:contratos` self-loop
5803 // arm's `.source().to_string()` / `.world_ref().to_string()`
5804 // `String`-carry sites the earlier convergence lifted onto
5805 // the same accessor pair.
5806 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
5807 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
5808 if !names.contains(c.source()) {
5809 return Err(AplicacaoError::ContratoMemberMissing {
5810 caixa: c.source().to_string(),
5811 });
5812 }
5813 if !names.contains(c.destination()) {
5814 return Err(AplicacaoError::ContratoMemberMissing {
5815 caixa: c.destination().to_string(),
5816 });
5817 }
5818 // A `:contratos` entry is an *inter*-Servico contract
5819 // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
5820 // typed edge between two distinct graph nodes. An edge whose
5821 // `:de` equals its `:para` is a Servico contracting with
5822 // itself — a degenerate edge under every WIT shape. The
5823 // synchronous shapes were caught only incidentally, and with
5824 // a misleading diagnostic: `detect_sync_cycles` reported
5825 // `cart → cart` as a `ContratoCycle` whose path is
5826 // `["cart", "cart"]` — framing a self-edge as a multi-node
5827 // deadlock. The pub-sub shape slipped through entirely
5828 // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
5829 // `nats:pub-sub` edge from a member to itself silently
5830 // validated, then rendered a `CiliumNetworkPolicy` whose
5831 // endpointSelector and fromEndpoints both name the same
5832 // program — a self-allow rule that is a no-op, since
5833 // intra-pod traffic never traverses the mesh). A self-edge's
5834 // runtime meaning is an in-process call, which doesn't go
5835 // through the mesh at all, so no `:contratos` edge can carry
5836 // it. Firing the gate before the `:wit`/`target()` shape
5837 // checks means the structural "this edge can't exist" error
5838 // precedes the narrower payload-shape diagnostics, and shape-
5839 // agnostically covers all four `WitTarget` arms (HTTP / Store
5840 // / Capability / PubSub) at one point — closing the pub-sub
5841 // hole and replacing the misleading cycle diagnostic in one
5842 // gate. Peer of the duplicate-`:contratos` / duplicate-
5843 // `:membros` set gates: both reject a structurally
5844 // ill-formed graph at the typed surface, before the renderer
5845 // emits a K8s object that fails or no-ops far from the source
5846 // caixa.lisp.
5847 // Route the per-`:contratos` structural self-edge probe
5848 // through the lifted [`WitContract::is_self_loop`] typed
5849 // predicate rather than the raw `c.de == c.para` field-
5850 // equality check — the one production consumer of the per-
5851 // `:contratos` caller-equals-callee endpoint-equality axis
5852 // now keys off exactly one typed dispatch on the substrate
5853 // primitive, so any future rebrand of the axis (an M4-typed-
5854 // caller enum whose identity comparison rule the predicate
5855 // could route through, a per-cluster caller/callee-alias
5856 // table the M4 CR materializer resolves per-CR before the
5857 // equality probe) migrates as a single caixa-core edit
5858 // rather than a coordinated rewrite of the gate + every
5859 // downstream self-edge consumer. Peer of the sibling
5860 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
5861 // [`WitContract::is_store`] shape-predicate routing on the
5862 // `:wit` world-ref axis, extended onto the per-edge
5863 // endpoint-equality axis.
5864 //
5865 // Route the paired [`AplicacaoError::ContratoSelfLoop`]
5866 // diagnostic's `caixa:` / `wit:` carriers through the
5867 // lifted [`WitContract::source`] / [`WitContract::world_ref`]
5868 // scalar accessors rather than the raw `c.de.clone()` /
5869 // `c.wit.clone()` field-access `String`-carry sites — the
5870 // last unlifted per-`:contratos` raw-field-access
5871 // `.clone()` sites in the M3 mesh-slot validator's self-
5872 // edge refusal arm. `.source().to_string()` is byte-
5873 // identical to `.de.clone()` (pinned by the sibling
5874 // `source_returns_de_byte_equal_across_permutations` accessor
5875 // test), and `.world_ref().to_string()` is byte-identical
5876 // to `.wit.clone()` (pinned by the sibling
5877 // `world_ref_returns_wit_byte_equal_across_permutations`
5878 // accessor test) — so a future rebrand of either underlying
5879 // storage flows through the accessor's one body without a
5880 // coordinated per-consumer rewrite across the M3 mesh
5881 // validator.
5882 if c.is_self_loop() {
5883 return Err(AplicacaoError::ContratoSelfLoop {
5884 caixa: c.source().to_string(),
5885 wit: c.world_ref().to_string(),
5886 });
5887 }
5888 if c.world_ref().is_empty() {
5889 let (de, para) = c.edge_pair();
5890 return Err(AplicacaoError::EmptyWit { de, para });
5891 }
5892 // Shape ↔ target consistency — surfaces "HTTP wit without
5893 // :endpoint", "NATS wit with :endpoint set", etc. as named
5894 // build errors instead of silent renderer drops. Threaded
5895 // through the duplicate-edge diagnostic below (via
5896 // [`WitTarget::label`]) so the "which typed target arm did
5897 // the duplicate carry" question is answered by the typed
5898 // enum's variant discriminator, not by re-probing the raw
5899 // `Option<String>` payload fields.
5900 let target_view = c.target()?;
5901 // Contract identity: (de, para, wit, endpoint, subject, slot).
5902 // Two contracts that match on all six are the same typed edge
5903 // declared twice — author error, not a legitimate variant of
5904 // "same caller-callee pair, different payload" (e.g.
5905 // cart→catalog at /products vs /search), which keeps distinct
5906 // identity keys via the differing endpoint payloads.
5907 //
5908 // Route the six-axis dedup key through the lifted
5909 // [`WitContract::identity`] composite-projection accessor
5910 // rather than the inline six-tuple builder — the two
5911 // substrate primitives on the per-`:contratos` identity axis
5912 // (the [`ContratoIdentity`] type alias's six axes, this
5913 // dedup-key's six tuple arms) now migrate as a unit on any
5914 // future axis addition. Peer of the sibling per-`:contratos`
5915 // composite-projection [`WitContract::edge_pair`] /
5916 // [`WitContract::edge_triple`] accessors on the
5917 // caller-callee / caller-callee-wit prefix axes; extends
5918 // the discipline onto the full-identity axis that carries
5919 // the three payload-shape arms too.
5920 let key = c.identity();
5921 crate::render::insert_first_seen(&mut seen_contracts, key, || {
5922 // Route the per-`:contratos` duplicate-gate diagnostic's
5923 // `(de, para, wit)` triple through the lifted
5924 // [`WitContract::edge_triple`] typed accessor rather
5925 // than pairing `edge_pair()` for the `(de, para)` prefix
5926 // with a raw `c.wit.clone()` for the `wit:` tail — the
5927 // paired-with-raw-field-access shape was the last
5928 // per-`:contratos` diagnostic constructor bypassing the
5929 // substrate-primitive composite projection, sibling to
5930 // the eight [`AplicacaoError::Contrato*`] triple-
5931 // carrying constructors [`WitContract::target`]'s edge
5932 // closure feeds through the same accessor.
5933 let (de, para, wit) = c.edge_triple();
5934 AplicacaoError::ContratoDuplicate {
5935 de,
5936 para,
5937 wit,
5938 target: target_view.label(),
5939 }
5940 })?;
5941 }
5942
5943 // Cycles in the synchronous-edge subgraph are build errors
5944 // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
5945 // are "acyclic by construction" because the publisher fires
5946 // and forgets, so no caller blocks on a downstream that loops
5947 // back to it.
5948 self.detect_sync_cycles()?;
5949
5950 if let Some(e) = self.entrada() {
5951 // Route the per-`:entrada` composite-reference read
5952 // through the lifted [`AplicacaoSpec::entrada`] accessor
5953 // rather than the raw `&self.entrada` field access — the
5954 // shape-and-membership gate's traversal head is now the
5955 // canonical read-side surface every per-Aplicacao entrada
5956 // consumer routes through, closing the fourth of four
5957 // open-coded outer-field accesses on the per-`:entrada`
5958 // outer-composite axis.
5959 //
5960 // Shape gate on `:entrada :para` runs ahead of the
5961 // membership lookup. Every `:membros :caixa` past
5962 // `validate_membro_caixa` is a valid DNS-1123 label
5963 // (3f9d7a0), so the `names` set structurally cannot
5964 // contain an empty / malformed string and the membership-
5965 // lookup diagnostic always misframed the root cause as
5966 // "this caixa is not in `:membros`". The shape gate
5967 // routes structurally-impossible-to-match inputs through
5968 // the narrower self-locating diagnostic, preserving the
5969 // legitimate "well-shaped phantom reference" arm — the
5970 // same trajectory the peer `:membros :caixa` (3f9d7a0),
5971 // `:placement :clusters` (6c8c00b), and `:contratos :de`
5972 // / `:para` (8d5af6b) axes already follow. This closes
5973 // the fourth and last Aplicacao-level Servico-name
5974 // reference axis on the canonical DNS-1123 floor.
5975 // Route the per-`:entrada :para` byte-string reads through
5976 // the lifted [`Entrada::destination`] accessor rather than
5977 // the raw `e.para` field access — the three
5978 // per-`AplicacaoSpec::validate` `:entrada :para` consumers
5979 // (shape-gate `validate_entrada_para` arg, membership
5980 // lookup, `EntradaMemberMissing` diagnostic carry) now key
5981 // off exactly one typed dispatch on the substrate
5982 // primitive, closing the last unlifted per-`:entrada :para`
5983 // raw-field-access axis on the M3 mesh-slot validator.
5984 // The `.destination().to_string()` at the diagnostic site
5985 // is byte-identical to `.para.clone()` — pinned by the
5986 // sibling `destination_returns_entrada_para_byte_equal` +
5987 // `destination_borrows_from_entrada_para_storage` accessor
5988 // tests — so a future rebrand of the underlying `:para`
5989 // storage (a lift from `String` to a typed
5990 // `ServicoName(String)` newtype, a per-Aplicacao interning
5991 // arena the M4 CR materializer authors, a
5992 // `smol_str::SmolStr` inline-buffer swap) flows through
5993 // the accessor's one body without a coordinated
5994 // per-consumer rewrite across the M3 mesh validator.
5995 validate_entrada_para(e.destination())?;
5996 if !names.contains(e.destination()) {
5997 return Err(AplicacaoError::EntradaMemberMissing {
5998 para: e.destination().to_string(),
5999 });
6000 }
6001 // Route the per-`:entrada :host` byte-string reads through
6002 // the lifted [`Entrada::hostname`] accessor rather than
6003 // the raw `e.host` field access — the emptiness gate and
6004 // the shape-gate `validate_entrada_host` arg now key off
6005 // exactly one typed dispatch on the substrate primitive,
6006 // closing the last unlifted per-`:entrada :host` raw-
6007 // field-access axis on the M3 mesh-slot validator. Peer
6008 // of the sibling per-`:entrada :para` convergence above
6009 // and pinned by the existing
6010 // `hostname_returns_entrada_host_byte_equal` +
6011 // `hostnames_returns_singleton_of_hostname_accessor`
6012 // accessor tests, so any future
6013 // Gateway-API-shaped host renormalization (a wildcard-
6014 // label lift, a trailing-`.` FQDN substitution, an IDNA
6015 // Punycode round-trip the SNI fan-out overlay authors)
6016 // flows through the accessor's one body without a
6017 // coordinated per-consumer rewrite across the M3 mesh
6018 // validator.
6019 if e.hostname().is_empty() {
6020 return Err(AplicacaoError::EmptyEntradaHost);
6021 }
6022 // The `:host` lands verbatim as a K8s Gateway API v1
6023 // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
6024 // both apiserver-validated against the same restrictive
6025 // pattern: lowercase RFC 1123 DNS subdomain, optional
6026 // single leading wildcard label (`*.`), max length 253,
6027 // per-label max length 63, no IP literals, no scheme,
6028 // no port. Until this gate landed `validate()` only
6029 // refused the empty string (`EmptyEntradaHost`); a
6030 // structurally invalid hostname (`"https://example.com"`,
6031 // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
6032 // `"_underscored.example.com"`, `"FOO.example.com"`,
6033 // `"checkout.quero.cloud."`) silently passed validate
6034 // and the apiserver `field is invalid` error surfaced at
6035 // `kubectl apply` time, far from the source caixa.lisp.
6036 // Lifting the gate to caixa-build time mirrors the
6037 // `:entrada :paths` value-shape trajectory (eb3456d) and
6038 // closes the last unstructured `:entrada` axis.
6039 validate_entrada_host(e.hostname())?;
6040 // Structural-floor gate on `:entrada :port`: every
6041 // validated `Entrada::port` past this gate lies in
6042 // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
6043 // type-inferred ceiling closes the top edge, so no companion
6044 // upper-cap arm is needed here — unlike the peer capped-
6045 // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
6046 // `require_positive_bounded_u32` bracket covers both edges).
6047 // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
6048 // accept-set-floor const rather than the prior inline
6049 // `if e.port == 0` byte-check so a future rebrand of the
6050 // accept-set floor (a hypothetical unprivileged-only
6051 // migration lifting the floor to `1024`, a per-cluster
6052 // scoping the operator pins through a future
6053 // `:placement :port-floor` slot as the M4 typed-slot
6054 // trajectory adds it, the future
6055 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6056 // per-Aplicacao gateway resolver reaching for the same
6057 // floor) is a one-line edit on the canonical
6058 // [`SERVICO_PORT_MIN`] declaration, not a coordinated
6059 // rewrite across the emit site + the pin test + every
6060 // future per-target renderer the substrate adds.
6061 if e.port() < SERVICO_PORT_MIN {
6062 return Err(AplicacaoError::EntradaPortZero);
6063 }
6064 // Each `:entrada :paths` entry becomes a K8s Gateway API
6065 // HTTPRoute `matches[].path.value`. The Gateway API rejects
6066 // values that don't start with `/` for `type: PathPrefix`,
6067 // and an empty value is meaningless. Surface those as build
6068 // errors (MESH-COMPOSITION §III.3) rather than apply-time
6069 // failures. Empty `:paths` itself is fine — caixa-mesh
6070 // falls back to a single `/` catch-all.
6071 let mut seen = std::collections::HashSet::new();
6072 // Route the per-entry value-shape gate's traversal head
6073 // through the lifted [`Entrada::paths`] slice accessor
6074 // rather than the raw `&e.paths` field access — the
6075 // per-Aplicacao `:entrada :paths` validate loop now keys
6076 // off the canonical raw-slot surface every downstream
6077 // per-`:entrada` path-list consumer (the sibling
6078 // [`Entrada::resolved_paths`] fallback-applying resolver
6079 // internal reads, `feira app graph`'s per-Aplicacao entrada
6080 // summary line's `{:?}` Debug print) routes through, so any
6081 // future rebrand on the typed slot's raw-slot reader lands
6082 // at exactly one place. Same convergence discipline as the
6083 // sibling [`Placement::clusters`] (a6e18d7) reader-site
6084 // convergences on the peer M3 mesh-slot `Vec<String>`-carry
6085 // axis.
6086 for p in e.paths() {
6087 if p.is_empty() {
6088 return Err(AplicacaoError::EntradaPathEmpty);
6089 }
6090 if !p.starts_with('/') {
6091 return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
6092 }
6093 // Per-entry value-shape gate: the path lands verbatim
6094 // as a K8s Gateway API HTTPRoute `matches[].path.value`
6095 // (caixa-mesh/src/lib.rs:498), apiserver-validated
6096 // against `maxLength: 1024` + the Gateway API webhook's
6097 // path-grammar rules (no `//`, no `/./`, no `/../`, no
6098 // query/fragment separators, no whitespace, no control
6099 // characters, no non-ASCII bytes). Until this gate
6100 // landed `validate` only refused the empty string and
6101 // missing-leading-slash (eb3456d); a structurally
6102 // invalid path (`"/api?q=1"`, `"/api#frag"`,
6103 // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
6104 // 1025-byte URL-shaped slug) silently passed validate
6105 // and the failure surfaced at `kubectl apply` time as
6106 // a Gateway API webhook rejection, far from the source
6107 // caixa.lisp, with no field naming the offending
6108 // `:paths` entry. Lifting the gate to caixa-build time
6109 // mirrors the `:entrada :host` value-shape trajectory
6110 // (c7d05ec) on the sibling axis — every author surface
6111 // that emits a Gateway API field now matches the
6112 // apiserver's accepted set at validate time.
6113 validate_entrada_path(p)?;
6114 crate::render::insert_first_seen(&mut seen, p.as_str(), || {
6115 AplicacaoError::EntradaPathDuplicate { path: p.clone() }
6116 })?;
6117 }
6118 }
6119
6120 self.validate_placement()?;
6121
6122 self.validate_politicas()?;
6123
6124 Ok(())
6125 }
6126
6127 /// Reject `:membros` values that are operationally meaningless. The
6128 /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
6129 /// every entry names a Servico that participates in the Aplicacao,
6130 /// and the rendered programs.yaml fan-out emits one entry per
6131 /// `:membros`. Three authoring footguns are closed here:
6132 ///
6133 /// - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
6134 /// a `programs:` entry whose `name:` is the empty string, which
6135 /// downstream `lareira-fleet-programs` rejects at template time
6136 /// with a non-localized error;
6137 /// - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
6138 /// an empty semver constraint, so the failure surfaces far from
6139 /// the source caixa.lisp;
6140 /// - duplicate `:caixa` names — two entries with the same name
6141 /// produce duplicate programs.yaml entries (one silently
6142 /// overwrites the other in the cluster's HelmRelease values), and
6143 /// contract membership lookups against `:contratos` collapse the
6144 /// two onto one node, masking authoring mistakes.
6145 ///
6146 /// Same value-shape discipline as `:placement :clusters` (where empty
6147 /// + duplicate cluster names are rejected) and `:entrada :paths`
6148 /// (where empty + duplicate path entries are rejected). Lifting these
6149 /// invariants to the typed surface mirrors the MESH-COMPOSITION
6150 /// §III.3 promise that the `:membros` set — the load-bearing identity
6151 /// of the application graph — is well-formed by construction.
6152 fn validate_membros(&self) -> Result<(), AplicacaoError> {
6153 if self.membros().is_empty() {
6154 return Err(AplicacaoError::NoMembros);
6155 }
6156 let mut seen = std::collections::HashSet::new();
6157 for m in self.membros() {
6158 // Route the `MembroCaixaEmpty` refusal-arm's per-member
6159 // empty-`:caixa` shape-gate through the typed
6160 // [`Membro::nome`] accessor rather than the raw `.caixa`
6161 // field access — the last un-lifted `.caixa` production-
6162 // code read site on the per-`:membros` member-caixa `:nome`
6163 // axis, sibling to the six caixa-core validator read sites
6164 // (member-set collector, per-member value-shape gate,
6165 // duplicate dedup key, cycle-detector adjacency-map seed,
6166 // self-loop gate) the 4a32abf lift already routed through
6167 // the accessor and the peer 54bf2f3 caixa-mesh emit-side
6168 // per-`programs[]` entry-`name:` `String`-carry converge.
6169 // Prior to this converge the `MembroCaixaEmpty` refusal
6170 // arm was the solitary consumer bypassing the typed
6171 // dispatch — the same-loop iteration's very next call
6172 // `validate_membro_caixa(m.nome())` already routed through
6173 // the accessor, so an author landing an empty-`:caixa`
6174 // entry hit the accessor on the shape-gate line but
6175 // bypassed it on the emptiness line one line above. A
6176 // future extension of the `:membros :caixa` axis to a
6177 // richer author surface (a per-cluster alias table pinned
6178 // through a future `:placement`-scoped slot, a namespace-
6179 // qualified rewrite the M4 CR materializer applies per-CR,
6180 // a per-member overlay from the future `:membros
6181 // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
6182 // that lands on the accessor would silently disagree
6183 // between the emptiness gate and every peer consumer —
6184 // an author-declared `:caixa "checkout"` value the
6185 // accessor rewrote to `""` under a future alias arm would
6186 // pass the raw `.is_empty()` gate here while the peer
6187 // `validate_membro_caixa(m.nome())` call one line below
6188 // (and every downstream emit-side consumer routing through
6189 // the accessor) tripped on the empty-value shape far from
6190 // this diagnostic. Pinned by the drift-detection test
6191 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
6192 // below.
6193 if m.nome().is_empty() {
6194 return Err(AplicacaoError::MembroCaixaEmpty);
6195 }
6196 // Every emitted cluster artifact's `metadata.name` derives
6197 // from a `:membros :caixa` value verbatim — the rendered
6198 // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
6199 // the [`crate::LABEL_PROGRAM`] label value on every CNP
6200 // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
6201 // 272), the composed `CiliumNetworkPolicy` `metadata.name`
6202 // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
6203 // `metadata.name` when the member is the `:entrada :para`
6204 // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
6205 // schema enforces the DNS-1123 label rule on admission;
6206 // a structurally invalid member name (`"Cart"`, `"my_cart"`,
6207 // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
6208 // mistaken-identity slug) silently passes the prior empty-/
6209 // duplicate-only gate and the failure surfaces at `kubectl
6210 // apply` time as a `metadata.name: Invalid value` rejection,
6211 // far from the source caixa.lisp, with no field naming the
6212 // offending `:membros` entry. Lifting the gate to caixa-build
6213 // time mirrors the `:entrada :host` value-shape trajectory
6214 // (c7d05ec) on the peer axis — every author surface that
6215 // emits a K8s name now matches the apiserver's accepted set
6216 // at validate time.
6217 validate_membro_caixa(m.nome())?;
6218 // The author surface for `:versao` is the same Cargo-shaped
6219 // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
6220 // `"*"`) every `:deps` entry carries — and the lacre pipeline
6221 // resolves both axes through the same
6222 // [`crate::version::parse_requirement`] entry-point. The
6223 // shared [`crate::render::require_valid_versao_requirement`]
6224 // helper brackets the empty-first + parse cascade both peer
6225 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
6226 // [`crate::SupervisorSpec::validate`] on `:children :versao`)
6227 // route through, so drift between the three axes' accepted
6228 // requirement sets is structurally impossible and the parse-
6229 // side no-op the empty-first arm closes (semver's empty
6230 // parse yields an implicit `*`) lives in exactly one
6231 // predicate.
6232 crate::render::require_valid_versao_requirement(
6233 m.versao_requirement(),
6234 || AplicacaoError::MembroVersaoEmpty {
6235 caixa: m.nome().to_string(),
6236 },
6237 |reason| AplicacaoError::MembroVersaoInvalid {
6238 caixa: m.nome().to_string(),
6239 versao: m.versao_requirement().to_string(),
6240 reason,
6241 },
6242 )?;
6243 crate::render::insert_first_seen(&mut seen, m.nome(), || {
6244 AplicacaoError::MembroDuplicate {
6245 caixa: m.nome().to_string(),
6246 }
6247 })?;
6248 }
6249 Ok(())
6250 }
6251
6252 /// Reject `:placement` values that are operationally meaningless or
6253 /// internally contradictory. Each strategy variant has the same
6254 /// invariants on `:clusters` (non-empty list, non-empty unique
6255 /// entries) — the §III.1 author surface is uniform on this axis,
6256 /// even though the *meaning* of the list differs by strategy
6257 /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
6258 /// shard pool).
6259 ///
6260 /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
6261 /// are the same authoring footgun closed for `:politicas` zero
6262 /// values and `:entrada` empty paths: the field is *declared* but
6263 /// carries no meaning, so downstream renderers either skip it
6264 /// silently (cluster-fanout drops the empty entry, no diagnostic)
6265 /// or apply it literally and fail at admission time. Lifting both
6266 /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
6267 /// violation is a build error" promise.
6268 ///
6269 /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
6270 /// is required exactly when `:estrategia Sharded` (hash-keyed
6271 /// distribution, Akka cluster-sharding convention, §II.4) and
6272 /// refused on `:estrategia Replicated`/`SingleNode` (where no
6273 /// hash-keyed routing axis consumes it). The partition closes the
6274 /// "I think I configured sharding" footgun where an author writes
6275 /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
6276 /// the typed slot's value silently vanishes at the renderer layer
6277 /// — every validated `Placement` past this call satisfies
6278 /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
6279 fn validate_placement(&self) -> Result<(), AplicacaoError> {
6280 // Every strategy needs at least one named cluster: `Replicated`
6281 // and `SingleNode` use the list as hosting/takeover candidates
6282 // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
6283 // §II.1), while `Sharded` uses it as the shard pool
6284 // (Akka cluster-sharding convention — §II.4). An empty list is
6285 // meaningless under any of the three.
6286 //
6287 // Route the paired pre-flight `.is_empty()` refusal probe and
6288 // the per-cluster validate loop's traversal head through the
6289 // lifted [`Placement::clusters`] slice-return accessor rather
6290 // than the raw `self.placement.clusters` field access — the
6291 // two production consumers of the per-`:placement` cluster-
6292 // pool `Vec`-carry now key off exactly one typed dispatch on
6293 // the substrate primitive, so any future rebrand on the axis
6294 // (a per-tenant cluster-pool overlay the operator pins through
6295 // a future `:placement :clusters-overrides` slot, a per-
6296 // Aplicacao dynamic cluster-pool derivation the future M5
6297 // adaptive-placement engine computes from `:affinity` weights)
6298 // migrates as a single caixa-core edit rather than a
6299 // coordinated rewrite of the paired arms — sibling of the
6300 // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
6301 // arm migration on the per-`:supervisor` static-child-list
6302 // `Vec`-carry axis.
6303 //
6304 // Route the per-`:placement` outer-composite reference read
6305 // through the lifted [`AplicacaoSpec::placement`] outer accessor
6306 // rather than the raw `&self.placement` field access — the
6307 // per-axis bracket-dispatch fan-out below (`p.clusters()`,
6308 // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
6309 // axis-level lifted accessor family) now routes through the
6310 // substrate-primitive typed dispatch at the outer composition
6311 // altitude, the same shape the peer caixa-mesh
6312 // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
6313 // and the sibling `feira app graph` per-Aplicacao print line
6314 // now key off after this accessor lift.
6315 let p = self.placement();
6316 if p.clusters().is_empty() {
6317 return Err(AplicacaoError::PlacementWithoutClusters {
6318 estrategia: p.estrategia(),
6319 });
6320 }
6321 let mut seen = std::collections::HashSet::new();
6322 for c in p.clusters() {
6323 // Per-entry value-shape gate: the cluster name lands in
6324 // every K8s context / `lareira-fleet-programs` aggregator
6325 // filter / future M4 CR materializer's per-cluster axis
6326 // a validated `:clusters` entry passes through, each
6327 // enforcing the DNS-1123 label rule on admission. Same
6328 // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
6329 // on the peer name axis — both axes' validated values
6330 // are guaranteed-accepted by the apiserver without
6331 // re-validation at any downstream renderer or admission
6332 // layer.
6333 validate_placement_cluster(c)?;
6334 crate::render::insert_first_seen(&mut seen, c.as_str(), || {
6335 AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
6336 })?;
6337 }
6338 // Route the per-`:placement :affinity` per-hint value-shape
6339 // gate through the typed [`Placement::affinity`] accessor rather
6340 // than the raw `&self.placement.affinity` field access — the
6341 // sole open-coded field-access site on the per-`:placement`
6342 // M3-Adaptive-compression-hint axis the accessor lift now owns.
6343 // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
6344 // the accessor's `Option<&str>` return type;
6345 // [`validate_placement_affinity`]'s `&str` parameter accepts
6346 // the narrower borrow without a re-allocation, so the routing
6347 // change is byte-for-byte in the pass arm and remains
6348 // byte-for-byte in every failure diagnostic
6349 // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
6350 // String` field is populated inside
6351 // [`validate_placement_affinity`] via the peer `.to_string()`
6352 // path on the same borrowed slice). Peer of the sibling
6353 // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
6354 // routing through [`Placement::shard_key`] at the caixa-core
6355 // site above — extends the "read `:placement` optional-scalars
6356 // through the typed accessor" discipline to the second
6357 // `Option<String>`-shape slot on the M3 mesh-slot family.
6358 //
6359 // Per-hint value-shape gate: the `:affinity` value lands
6360 // verbatim in the M3 Adaptive compression overlay
6361 // (caixa-mesh's `placement.affinity` emission) and every
6362 // future M4 placement-engine routing axis keying off the
6363 // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
6364 // selector — each enforces the DNS-1123 label rule on
6365 // admission. Same typed-shape trajectory as `:placement
6366 // :clusters` (6c8c00b) on the sibling slot and the four
6367 // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
6368 // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
6369 // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
6370 // on the Aplicacao surface to land on the canonical
6371 // [`crate::render::is_dns_1123_label`] floor.
6372 if let Some(a) = p.affinity() {
6373 validate_placement_affinity(a)?;
6374 }
6375 match p.estrategia() {
6376 // Route the `Sharded`-arm shape-gate cascade through the
6377 // typed [`Placement::shard_key`] accessor rather than the
6378 // raw `&self.placement.shard_key` field access — one of the
6379 // two open-coded field-access sites on the per-`:placement`
6380 // Akka-cluster-sharding-key axis the accessor lift now
6381 // owns. The `Some(k)`-bound `k` narrows from `&String` to
6382 // `&str` under the accessor's `Option<&str>` return type;
6383 // `str::is_empty` and [`validate_placement_shard_key`]'s
6384 // `&str` parameter both accept the narrower borrow without
6385 // a re-allocation.
6386 PlacementStrategy::Sharded => match p.shard_key() {
6387 None => return Err(AplicacaoError::ShardedWithoutKey),
6388 Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
6389 // Per-axis value-shape gate on the Akka-cluster-sharding
6390 // `:shard-key` extractor expression. The shape gate runs
6391 // after the more self-locating `ShardedKeyEmpty` arm so
6392 // a `:shard-key ""` surfaces the narrower empty
6393 // diagnostic first; every non-empty `:shard-key` past
6394 // this call is guaranteed to be a printable-ASCII
6395 // single-token reference the future M4 Akka-style
6396 // cluster-sharding reconciler can hash without
6397 // re-validating at the runtime layer. Mirrors the
6398 // payload-axis shape gates on the peer `:contratos`
6399 // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
6400 // 63e18a0 / c4213a4) — each lifts the runtime parser's
6401 // intersection-floor to a caixa-build-time gate.
6402 Some(k) => validate_placement_shard_key(k)?,
6403 },
6404 // `:shard-key` is the Akka-cluster-sharding axis
6405 // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
6406 // across the cluster pool. `Replicated` (active-active across
6407 // every named cluster) and `SingleNode` (Erlang/OTP
6408 // distributed-app takeover/failover, §II.1) have no hash-keyed
6409 // routing axis to consume the slot; downstream renderers
6410 // (caixa-mesh's `placement.shardKey` overlay at
6411 // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
6412 // sharding reconciler) ignore `:shard-key` outside the
6413 // `Sharded` arm by construction. Until this gate landed an
6414 // author who wrote `:placement (:estrategia Replicated
6415 // :shard-key "tenantId")` (an off-by-one strategy typo, a
6416 // copy-paste from a Sharded sibling caixa, the "I think I
6417 // configured sharding" footgun) silently passed validate and
6418 // the typed slot's value vanished at the renderer layer with
6419 // no diagnostic — the canonical "declared-but-inert" footgun
6420 // the empty-:affinity / empty-shard-key / zero-:politicas /
6421 // empty-:contratos-target gates already close on every other
6422 // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
6423 // Lifting the rejection to a build-time gate closes the
6424 // Sharded ↔ non-Sharded partition over the typed
6425 // `:placement` slot: every validated `Placement` past this
6426 // call has `shard_key.is_some()` iff `estrategia ==
6427 // Sharded`, structurally — the future Akka reconciler can
6428 // reach for `placement.shard_key` knowing it's `Some` exactly
6429 // when the strategy consumes it, without re-deriving the
6430 // partition from inline strategy probes.
6431 PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
6432 // Route the non-`Sharded`-arm declared-but-inert refusal
6433 // through the typed [`Placement::shard_key`] accessor —
6434 // the second of the two open-coded field-access sites the
6435 // accessor lift now owns. The `Some(k)`-bound `k` narrows
6436 // from `&String` to `&str`; the `AplicacaoError::
6437 // ShardKeyOnNonSharded { shard_key: String }` diagnostic
6438 // materializes the owned `String` via `k.to_string()`
6439 // (peer to the sibling per-Membro `String`-carry sites
6440 // 4127bb6 routed through `m.nome().to_string()` /
6441 // `m.versao_requirement().to_string()`), so the whole
6442 // `Sharded` ↔ non-`Sharded` partition on the
6443 // `:shard-key` axis now flows through the same typed
6444 // dispatch as the sibling `Sharded`-arm shape gate.
6445 if let Some(k) = p.shard_key() {
6446 return Err(AplicacaoError::ShardKeyOnNonSharded {
6447 estrategia: p.estrategia(),
6448 shard_key: k.to_string(),
6449 });
6450 }
6451 }
6452 }
6453 Ok(())
6454 }
6455
6456 /// Reject `:politicas` values that are operationally meaningless.
6457 /// Each axis is optional — omitting it expresses "no policy on this
6458 /// axis". Carrying a *zero* value for a declared axis is the bug
6459 /// this function rejects: zero is either
6460 ///
6461 /// - re-interpreted as "infinite" by downstream proxies (Envoy's
6462 /// `RouteAction.timeout = 0s` disables the timeout entirely),
6463 /// directly contradicting MESH-COMPOSITION §V CSE invariant
6464 /// "every Aplicacao declares :politicas :timeout (no infinite
6465 /// blocking)", or
6466 /// - a renderer footgun (a 0-failure circuit breaker trips on the
6467 /// first call; a 0-rate rate-limit denies every request).
6468 ///
6469 /// Lifting these "0 means the opposite of what you think" idioms to
6470 /// the typed Aplicacao surface as build errors mirrors the §III.3
6471 /// promise that contract drift, capability leaks, and cycles are all
6472 /// build errors — not runtime surprises.
6473 fn validate_politicas(&self) -> Result<(), AplicacaoError> {
6474 // Route the per-`:politicas` composite-reference read through
6475 // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
6476 // than the raw `&self.politicas` field access — the per-axis
6477 // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
6478 // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
6479 // the substrate-primitive typed dispatch at the outer
6480 // composition altitude AND at every per-axis altitude, matching
6481 // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
6482 // timeout/retry-overlay emitters that already key off the same
6483 // per-axis accessor family. The four-axis fan-out is now
6484 // uniformly `p.<axis>()` — the last two raw `p.timeout` /
6485 // `p.retries` field-access sites (co-resident with the peer
6486 // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
6487 // b0e741a / 21a6c3b already lifted) now route through
6488 // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
6489 // the per-`:politicas` bracket-dispatch fan-out's raw-field-
6490 // access axis on the M3 mesh-slot family.
6491 let p = self.politicas();
6492 if let Some(t) = p.timeout() {
6493 // Zero-floor + integer-millisecond canonical-form +
6494 // upper-cap bracket on the typed `:timeout` axis. See
6495 // [`crate::render::require_positive_canonical_bounded_duration`]
6496 // for the full three-arm ordering discipline (zero-floor
6497 // strictly precedes the canonical-form arm so
6498 // `Duration::ZERO` surfaces the self-locating
6499 // `PolicyTimeoutZero` diagnostic naming the omit-axis
6500 // remediation; canonical-form strictly precedes the cap
6501 // arm so a sub-millisecond above-cap `Duration` surfaces
6502 // the more fundamental round-trip-shape diagnostic first)
6503 // and the four peer typed-`Duration` sites that now share
6504 // this canonical bracket. Every validated value lies in
6505 // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
6506 // granularity — the same top-and-bottom-edge discipline
6507 // [`POLICY_RETRIES_MAX`] and
6508 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
6509 // capped-`u32` `:politicas` axes.
6510 crate::render::require_positive_canonical_bounded_duration(
6511 t,
6512 POLICY_TIMEOUT_MAX,
6513 || AplicacaoError::PolicyTimeoutZero,
6514 |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
6515 |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
6516 )?;
6517 }
6518 if let Some(r) = p.retries() {
6519 // Zero-floor + upper-cap bracket on the typed `:retries`
6520 // axis. See [`crate::render::require_positive_bounded_u32`]
6521 // for the ordering discipline (zero-floor arm strictly
6522 // precedes cap arm so `Some(0)` surfaces the self-locating
6523 // `PolicyRetriesZero` diagnostic with its omit-axis
6524 // remediation directly named, not the misleading
6525 // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
6526 // this bracket landed the top edge ran all the way to
6527 // `u32::MAX` and a struct-literal `MeshPolicy { retries:
6528 // Some(100_000), .. }` (or the equivalent author-surface
6529 // `(:retries 100000)` / `(:retries 4294967295)` typo
6530 // landing in the slot) silently passed validate. The
6531 // runtime substrate consuming the value (Envoy's
6532 // `retry_policy.num_retries`, the future
6533 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6534 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6535 // policy into a thundering-herd amplification vector —
6536 // the caller's one request fans out to `retries`
6537 // server-side calls per edge per traversal, multiplying
6538 // load by `(retries+1)^depth` across the
6539 // synchronous-`:contratos` subgraph at the precise moment
6540 // the substrate is already failing (transient failure is
6541 // the trigger), exactly the failure mode AWS App Mesh's
6542 // explicit `maxRetries ≤ 10` schema cap exists to prevent.
6543 // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
6544 // the sibling capped-`u32` `:politicas` axes
6545 // (`max_failures`, `rate_limit.rate`) and the peer capped-
6546 // `u32` axes in `:supervisor :max-restarts` +
6547 // `:limits :cpu`; all five now route through the same
6548 // canonical bracket helper.
6549 crate::render::require_positive_bounded_u32(
6550 r,
6551 POLICY_RETRIES_MAX,
6552 || AplicacaoError::PolicyRetriesZero,
6553 |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
6554 )?;
6555 }
6556 if let Some(cb) = p.circuit_breaker() {
6557 // Zero-floor + upper-cap bracket on the typed
6558 // `:max-failures` axis. See
6559 // [`crate::render::require_positive_bounded_u32`] for the
6560 // ordering discipline (zero-floor arm strictly precedes
6561 // cap arm so `max_failures == 0` surfaces the
6562 // self-locating `PolicyBreakerZeroFailures` diagnostic
6563 // with its omit-axis remediation directly named, not the
6564 // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
6565 // false` cap-arm miss). Until this bracket landed the top
6566 // edge ran all the way to `u32::MAX` and a struct-literal
6567 // `CircuitBreaker { max_failures: 100_000, .. }` (or the
6568 // equivalent author-surface `(:max-failures 100000)` /
6569 // `(:max-failures 4294967295)` typo landing in the slot)
6570 // silently passed validate. The runtime substrate
6571 // consuming the value (Envoy's
6572 // `outlier_detection.consecutive_5xx`, the future
6573 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6574 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6575 // breaker policy into a no-op — the trip threshold is
6576 // structurally so high that no realistic
6577 // failures-per-`:window` traffic shape can reach it, the
6578 // breaker never trips, and every typed-slot consumer
6579 // emits an Envoy / Cilium L7 overlay carrying a
6580 // protection that is structurally never enforced. The
6581 // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
6582 // peer with `retries` and `rate_limit.rate` on the same
6583 // helper.
6584 crate::render::require_positive_bounded_u32(
6585 cb.max_failures(),
6586 POLICY_BREAKER_MAX_FAILURES_MAX,
6587 || AplicacaoError::PolicyBreakerZeroFailures,
6588 |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
6589 )?;
6590 // Zero-floor + integer-millisecond canonical-form +
6591 // upper-cap bracket on the typed `:window` axis. See
6592 // [`crate::render::require_positive_canonical_bounded_duration`]
6593 // for the full three-arm ordering discipline (peer to the
6594 // `:timeout` site immediately above); every validated
6595 // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
6596 // (1ms..=1h), integer-millisecond granularity — the same
6597 // top-and-bottom-edge discipline
6598 // [`POLICY_TIMEOUT_MAX`] applies on the sibling
6599 // duration-typed `:politicas :timeout` axis.
6600 crate::render::require_positive_canonical_bounded_duration(
6601 cb.window(),
6602 POLICY_BREAKER_WINDOW_MAX,
6603 || AplicacaoError::PolicyBreakerZeroWindow,
6604 |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
6605 |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
6606 )?;
6607 }
6608 if let Some(rl) = p.rate_limit() {
6609 // Zero-floor + upper-cap bracket on the typed
6610 // `:rate-limit` rate axis. See
6611 // [`crate::render::require_positive_bounded_u32`] for the
6612 // ordering discipline (zero-floor arm strictly precedes
6613 // cap arm so `rl.rate == 0` surfaces the self-locating
6614 // `PolicyRateLimitZero` diagnostic with its omit-axis
6615 // remediation directly named, not the misleading
6616 // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
6617 // Until this bracket landed the top edge ran all the way
6618 // to `u32::MAX` and a struct-literal
6619 // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
6620 // author-surface `(:rate-limit "4294967295/s")` /
6621 // `(:rate-limit "100000000/m")` typo landing in the slot)
6622 // silently passed validate. The runtime substrate
6623 // consuming the value (Envoy's
6624 // `local_rate_limit.token_bucket.max_tokens`, the future
6625 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
6626 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
6627 // rate-limit policy into a no-op limiter: the bucket
6628 // capacity is structurally so high that no realistic
6629 // per-edge traffic shape can drain it, the limiter never
6630 // trips, and every typed-slot consumer emits a "rate
6631 // declared" L7 overlay carrying enforcement that is
6632 // structurally never reached — the canonical
6633 // declared-but-inert footgun the sibling
6634 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
6635 // the peer no-op-breaker shape. The bracket set is
6636 // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
6637 // `max_failures` on the same helper. The rate bracket
6638 // strictly precedes the window-canonical gate so a
6639 // structurally absurd rate magnitude surfaces the more
6640 // fundamental amplification-shape diagnostic before the
6641 // narrower codec-round-trip-shape diagnostic on `:window`.
6642 crate::render::require_positive_bounded_u32(
6643 rl.rate(),
6644 POLICY_RATE_LIMIT_MAX,
6645 || AplicacaoError::PolicyRateLimitZero,
6646 |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
6647 )?;
6648 // The `:rate-limit` author surface is the canonical
6649 // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
6650 // accepts exactly the three-unit set (1s/60s/3600s) the
6651 // [`rate_limit_codec::render`] formatter emits the canonical
6652 // unit suffix for. A `RateLimit` whose `:window` is anything
6653 // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
6654 // programmatically (struct literals in Rust + the typed
6655 // `Duration` field) but renders to a `<n>/<k>s` fragment
6656 // (the codec's fall-through) the parser then rejects on
6657 // round-trip — silently breaking the THEORY.md §V.2.7
6658 // render-determinism contract for any consumer that
6659 // serializes-then-deserializes the typed slot. Lifting the
6660 // canonical-window invariant to a build-time gate at
6661 // `validate_politicas` makes the codec's round-trip property
6662 // a structural property of the validated typed value:
6663 // every `RateLimit` past `AplicacaoSpec::validate` has a
6664 // window the codec round-trips losslessly, so the next
6665 // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
6666 // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
6667 // §III.2 #3) reaches for `rate_limit.window` knowing the
6668 // value is in the codec's accepted set without re-validating
6669 // at the renderer layer. Same trajectory as c4213a4 (typed
6670 // WitContract endpoint/subject/slot value-shape gates) and
6671 // the b0c8389 :behavior + :upgrade-from script-path lifts:
6672 // the typed slot's valid set matches its codec's accepted
6673 // set, structurally.
6674 // Route the canonical-window shape-gate through the substrate
6675 // primitive [`RateLimit::canonical_unit`] rather than the free
6676 // module-private [`is_canonical_rate_limit_window`] predicate:
6677 // both projections resolve `Duration → Option<RateLimitUnit>`
6678 // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
6679 // arm on the closed-set typed enum), but the accessor is the
6680 // typed method every downstream consumer of the validated slot
6681 // ([`rate_limit_codec::render`]'s canonical arm above, the
6682 // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6683 // per-`:politicas :rate-limit` admission webhook, the future
6684 // per-`:contratos`-edge rate-limit-override overlay
6685 // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
6686 // production consumers of the canonical-unit axis (the codec
6687 // render and this validate gate) now key off exactly one typed
6688 // dispatch on the substrate primitive, so any future extension
6689 // to `canonical_unit` (a per-cluster canonical-window overlay
6690 // the operator pins through a future `:contratos :rate-limit
6691 // -unit-overrides` slot, a per-tenant unit-alias table the M4
6692 // CR materializer resolves per-CR) reaches both consumers by
6693 // construction rather than a coordinated rewrite of every
6694 // free-helper call site.
6695 if rl.canonical_unit().is_none() {
6696 return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
6697 window: rl.window(),
6698 });
6699 }
6700 }
6701 Ok(())
6702 }
6703
6704 /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
6705 /// A synchronous edge is any contract whose typed [`WitTarget`] is
6706 /// `Http`, `Store`, or `Capability` — the caller blocks on the
6707 /// callee, so a cycle would deadlock at runtime. Pub-sub edges
6708 /// (`WitTarget::PubSub`) are skipped: an event publisher does not
6709 /// block on its subscribers, so they can never close a sync loop.
6710 ///
6711 /// Iterative DFS with three-coloring; the reported cycle is the
6712 /// path of caixa names traversed from the back-edge target around
6713 /// to itself, in declaration order. Adjacency lists and DFS roots
6714 /// are visited in `BTreeMap` key order so the diagnostic is
6715 /// deterministic across runs.
6716 fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
6717 use std::collections::{BTreeMap, BTreeSet};
6718
6719 #[derive(Clone, Copy, PartialEq, Eq)]
6720 enum Mark {
6721 White,
6722 Gray,
6723 Black,
6724 }
6725
6726 let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
6727 for m in self.membros() {
6728 adj.entry(m.nome()).or_default();
6729 }
6730 for c in self.contratos() {
6731 // target() was already called by validate(); re-running here
6732 // keeps detect_sync_cycles self-contained for callers that
6733 // reuse it (M4 per-edge policy resolver) without revalidating.
6734 //
6735 // The pub-sub-arm check routes through the lifted
6736 // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
6737 // arm-discriminator predicate rather than a raw `matches!(…,
6738 // WitTarget::PubSub { .. })` on the variant so a future
6739 // rebrand on the axis (an M4 per-edge WIT registry split of
6740 // [`WitTarget::PubSub`] into shape-specific peers, a
6741 // per-consumer rename that the accept-set already carries)
6742 // reaches this call site through the derive rather than a
6743 // scattered per-arm `matches!` rewrite — same
6744 // `IsVariant`-derived-arm-discriminator discipline the
6745 // peer closed-set typed enums ([`crate::CaixaKind`] via
6746 // f5bba80, [`PlacementStrategy`] via 766ec63,
6747 // [`crate::supervisor::RestartStrategy`] +
6748 // [`crate::supervisor::RestartPolicy`],
6749 // [`crate::upgrade::UpgradeInstruction`] via 915a934)
6750 // already route through on the substrate's other typed-enum
6751 // arm-discriminator axes.
6752 if c.target()?.is_pubsub() {
6753 continue;
6754 }
6755 adj.entry(c.source()).or_default().insert(c.destination());
6756 }
6757
6758 let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
6759 let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
6760
6761 // Stable DFS root order — BTreeMap iteration is sorted by key.
6762 let roots: Vec<&str> = adj.keys().copied().collect();
6763
6764 // Frame: (node, sorted-neighbours snapshot, next-edge index).
6765 for root in roots {
6766 if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
6767 continue;
6768 }
6769 let root_neighbors: Vec<&str> = adj
6770 .get(root)
6771 .map(|s| s.iter().copied().collect())
6772 .unwrap_or_default();
6773 let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
6774 color.insert(root, Mark::Gray);
6775
6776 loop {
6777 // Read+advance the top frame in one borrow scope so we
6778 // can later mutate the stack (push/pop) without holding
6779 // a borrow across.
6780 let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
6781 let node = top.0;
6782 if top.2 >= top.1.len() {
6783 (node, None)
6784 } else {
6785 let nxt = top.1[top.2];
6786 top.2 += 1;
6787 (node, Some(nxt))
6788 }
6789 });
6790 let Some((node, nxt_opt)) = step else { break };
6791 let Some(nxt) = nxt_opt else {
6792 color.insert(node, Mark::Black);
6793 stack.pop();
6794 continue;
6795 };
6796 let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
6797 match nxt_color {
6798 Mark::Gray => {
6799 // Reconstruct the cycle from `node` back through
6800 // the parent chain to `nxt`, then close.
6801 let mut cycle = Vec::new();
6802 let mut cur = node;
6803 cycle.push(cur.to_string());
6804 while cur != nxt {
6805 match parent.get(cur).copied() {
6806 Some(p) => {
6807 cur = p;
6808 cycle.push(cur.to_string());
6809 }
6810 None => break,
6811 }
6812 }
6813 cycle.reverse();
6814 cycle.push(nxt.to_string());
6815 return Err(AplicacaoError::ContratoCycle { cycle });
6816 }
6817 Mark::White => {
6818 parent.insert(nxt, node);
6819 color.insert(nxt, Mark::Gray);
6820 let nxt_neighbors: Vec<&str> = adj
6821 .get(nxt)
6822 .map(|s| s.iter().copied().collect())
6823 .unwrap_or_default();
6824 stack.push((nxt, nxt_neighbors, 0));
6825 }
6826 Mark::Black => {}
6827 }
6828 }
6829 }
6830 Ok(())
6831 }
6832
6833 /// Substrate-canonical destination-facing TCP port every emitted
6834 /// per-Aplicacao artifact must key `destination`-shaped port axes
6835 /// off. Returns the typed `:entrada :port` scalar when this
6836 /// Aplicacao's `:entrada` block names `destination` under its
6837 /// `:para` axis (the destination Servico *is* the ingress apex, so
6838 /// the substrate honors the author-declared listener port
6839 /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
6840 /// fallback otherwise (every non-apex destination — the internal
6841 /// mesh Servicos `:contratos` reach across, the future per-edge
6842 /// policy resolver's per-destination probe targets, the
6843 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
6844 /// L4 port resolver — reads the same substrate-canonical port floor
6845 /// by construction).
6846 ///
6847 /// Prior to this lift the "if :entrada matches this destination use
6848 /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
6849 /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
6850 /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
6851 /// prior to this lift), with no typed method on the substrate primitive
6852 /// that named the rule. A future per-destination port axis addition
6853 /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
6854 /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
6855 /// per-Servico listener ports land, a per-cluster override the operator
6856 /// pins through a future `:placement :default-port` slot — would have
6857 /// to be threaded through every renderer's inline cascade in lockstep
6858 /// or one consumer would silently disagree on which port a given
6859 /// destination Servico's ingress lands at. Lifting the rule to a
6860 /// typed method on the substrate primitive means the M4 CR
6861 /// materializer, the future per-edge policy resolver, and every
6862 /// downstream test-fixture navigator reach for exactly one typed
6863 /// dispatch — the resolver's accept-set moves as a unit on any
6864 /// future axis addition.
6865 ///
6866 /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
6867 /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
6868 /// the typed primitive, thin projections at each consumer"
6869 /// discipline lifts on the sibling `:contratos` payload / `:politicas
6870 /// :rate-limit` unit-suffix axes; extends the discipline onto the
6871 /// destination-facing port-resolution axis every per-Aplicacao
6872 /// L4-fallback renderer consumes.
6873 #[must_use]
6874 pub fn port_for_destination(&self, destination: &str) -> u16 {
6875 // Route the per-`:entrada` composite-reference read through
6876 // the lifted [`AplicacaoSpec::entrada`] accessor rather than
6877 // the raw `self.entrada.as_ref()` field access — the
6878 // per-destination L4-port fallback resolver's composite-
6879 // projection seed is now the canonical read-side surface
6880 // every per-Aplicacao entrada consumer routes through, peer
6881 // of the sibling `validate` per-`:entrada` shape-and-
6882 // membership gate migration on the same outer-composite
6883 // axis.
6884 // Route the per-`:entrada` apex-destination membership probe
6885 // through the lifted [`Entrada::destination`] accessor rather
6886 // than the raw `e.para == destination` field access — the last
6887 // un-lifted `.para` production-code read site on the per-
6888 // `:entrada` `:para` axis, sibling to the four caixa-core
6889 // consumer sites the peer 15ddd8c converge already routed
6890 // through the accessor (the three
6891 // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
6892 // membership gate sites: the `validate_entrada_para` DNS-1123
6893 // shape gate, the per-`:membros` membership lookup, and the
6894 // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
6895 // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
6896 // `entrada.para`-projection converge at
6897 // caixa-core/src/render.rs (the `gateway_api_http_route_name`
6898 // route-name projection site). Prior to this converge the
6899 // `port_for_destination` resolver was the solitary consumer
6900 // bypassing the typed dispatch on the `.para` axis — the two
6901 // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
6902 // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
6903 // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
6904 // reach through the same accessor family compose with this
6905 // resolver at the emit boundary via the apex-identity
6906 // invariant `spec.port_for_destination(entrada.destination())
6907 // == entrada.port` the sibling
6908 // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
6909 // pin pins across four permutations. A future extension of the
6910 // `:entrada :para` axis to a richer author surface (a per-
6911 // cluster alias overlay the operator pins through a future
6912 // `:placement`-scoped slot, a namespace-qualified rewrite the
6913 // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
6914 // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
6915 // §III.2 acknowledges) that lands on the accessor would silently
6916 // disagree between this resolver and the two `caixa-mesh` emit
6917 // sites — an author-declared `:para "cart"` value the accessor
6918 // rewrote to `"cart-v2"` under a future canary arm would leave
6919 // the resolver's membership arm falling through to
6920 // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
6921 // `.para`) while the peer emit-site consumers landed on the
6922 // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
6923 // silently disagreed on which destination port a given typed
6924 // `:entrada` resolves to at cluster-apply time. Pinned by the
6925 // drift-detection test
6926 // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
6927 // below.
6928 self.entrada()
6929 .filter(|e| e.destination() == destination)
6930 .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
6931 }
6932}
6933
6934/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
6935/// entry may name the Aplicacao's own `:nome`.
6936///
6937/// An Aplicacao that lists itself as a member is a degenerate self-edge in
6938/// the typed graph — the application graph is a DAG rooted at the Aplicacao
6939/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
6940/// Servicos that compose the app; an Aplicacao is never its own constituent),
6941/// and the lacre pipeline's closure-resolution would otherwise be handed a
6942/// node that is its own parent: a one-node cycle it either rejects far from
6943/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
6944/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
6945/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
6946/// label + lacre closure root), a member whose `:caixa` equals the
6947/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
6948/// peer.
6949///
6950/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
6951/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
6952/// gate `validate_upgrade_from_against_versao` and the supervision-tree
6953/// self-parent gate `crate::supervisor::validate_no_self_supervision`
6954/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
6955/// not a tree/mesh edge" discipline, here on the second typed-graph axis
6956/// (the Aplicacao :membros set; the supervision-tree :children list was the
6957/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
6958/// every validated Supervisor's children are distinct from its `:nome`,
6959/// every validated Aplicacao's membros are distinct from its `:nome`. The
6960/// transitive consequence is that `:entrada :para` and `:contratos`
6961/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
6962/// name the Aplicacao itself, without re-deriving the partition.
6963pub fn validate_no_self_membership(
6964 membros: &[Membro],
6965 parent_nome: &str,
6966) -> Result<(), AplicacaoError> {
6967 for m in membros {
6968 if m.nome() == parent_nome {
6969 return Err(AplicacaoError::MembroIsSelfAplicacao {
6970 caixa: parent_nome.to_string(),
6971 });
6972 }
6973 }
6974 Ok(())
6975}
6976
6977#[derive(Debug, Error, PartialEq, Eq)]
6978pub enum AplicacaoError {
6979 #[error("Aplicacao must declare at least one :membros entry")]
6980 NoMembros,
6981 #[error(
6982 ":membros entry has empty :caixa (every member must name a Servico; \
6983 omit the entry instead of carrying an empty name)"
6984 )]
6985 MembroCaixaEmpty,
6986 #[error(
6987 ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
6988 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
6989 name / label value the member name lands in; use a lowercase \
6990 alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
6991 )]
6992 MembroCaixaInvalid { caixa: String, reason: String },
6993 #[error(
6994 ":membros entry {caixa:?} has empty :versao (every member must pin a \
6995 semver constraint that resolves through the lacre pipeline)"
6996 )]
6997 MembroVersaoEmpty { caixa: String },
6998 #[error(
6999 ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
7000 requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
7001 `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
7002 carries; the lacre pipeline resolves both through the same parser)"
7003 )]
7004 MembroVersaoInvalid {
7005 caixa: String,
7006 versao: String,
7007 reason: String,
7008 },
7009 #[error(
7010 ":membros entry {caixa:?} appears more than once (the graph node set \
7011 is a set, not a multiset; duplicate members produce duplicate \
7012 programs.yaml entries and ambiguous :contratos membership lookups)"
7013 )]
7014 MembroDuplicate { caixa: String },
7015 #[error(
7016 "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
7017 never its own constituent Servico (the application graph is a DAG rooted \
7018 at the Aplicacao; :membros names the *other* caixas that compose the \
7019 app, not the app itself). Since every :nome is a globally-unique \
7020 substrate identity, a member naming the Aplicacao's own :nome is a \
7021 one-node lacre-closure recursion, not a coincidentally-named peer; \
7022 drop the self-referential :membros entry or rename it to the actual \
7023 constituent caixa."
7024 )]
7025 MembroIsSelfAplicacao { caixa: String },
7026 #[error(
7027 "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
7028 caixa declared in :membros; omit the contract or fill the {slot} field with a \
7029 member name)"
7030 )]
7031 ContratoCaixaEmpty { slot: &'static str },
7032 #[error(
7033 "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
7034 :contratos {slot} value names a member of :membros, which is itself a \
7035 DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
7036 object the member name lands in — Service, Pod, identity-based Cilium \
7037 selector; use a lowercase alphanumeric + hyphen identifier like \
7038 `\"checkout\"` or `\"cart-v2\"`)"
7039 )]
7040 ContratoCaixaInvalid {
7041 slot: &'static str,
7042 caixa: String,
7043 reason: String,
7044 },
7045 #[error("contrato references caixa {caixa:?} not declared in :membros")]
7046 ContratoMemberMissing { caixa: String },
7047 #[error(
7048 "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
7049 entry is an inter-Servico contract whose :de and :para must name distinct \
7050 :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
7051 the contract, or point :para at the member it actually calls)"
7052 )]
7053 ContratoSelfLoop { caixa: String, wit: String },
7054 #[error("contrato {de:?} → {para:?} has empty :wit")]
7055 EmptyWit { de: String, para: String },
7056 #[error(
7057 "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
7058 {reason} (the substrate dispatches `:wit` values on the canonical \
7059 lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
7060 `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
7061 demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
7062 kebab-case identifier per segment)"
7063 )]
7064 ContratoWitInvalid {
7065 de: String,
7066 para: String,
7067 wit: String,
7068 reason: String,
7069 },
7070 #[error(
7071 ":entrada :para is empty (every :entrada must route to a caixa declared in \
7072 :membros; fill the :para field with a member name)"
7073 )]
7074 EntradaParaEmpty,
7075 #[error(
7076 ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
7077 :entrada :para value names a member of :membros, which is itself a DNS-1123 \
7078 label per the K8s apiserver's `metadata.name` rule on every object the \
7079 member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
7080 Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
7081 `\"checkout\"` or `\"cart-v2\"`)"
7082 )]
7083 EntradaParaInvalid { para: String, reason: String },
7084 #[error(":entrada routes to caixa {para:?} not declared in :membros")]
7085 EntradaMemberMissing { para: String },
7086 #[error(":entrada must declare a non-empty :host")]
7087 EmptyEntradaHost,
7088 #[error(
7089 ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
7090 (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
7091 `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
7092 like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
7093 )]
7094 EntradaHostInvalid { host: String, reason: String },
7095 #[error(":entrada :port must be in 1..=65535, got 0")]
7096 EntradaPortZero,
7097 #[error(":entrada :paths entry is empty (use the empty list to match all)")]
7098 EntradaPathEmpty,
7099 #[error(
7100 ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
7101 )]
7102 EntradaPathNotAbsolute { path: String },
7103 #[error(
7104 ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
7105 value: {reason} (the K8s apiserver enforces the same shape on \
7106 `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
7107 single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
7108 requires percent-encoding `%XX` for non-ASCII and whitespace)"
7109 )]
7110 EntradaPathInvalid { path: String, reason: String },
7111 #[error(":entrada :paths entry {path:?} appears more than once")]
7112 EntradaPathDuplicate { path: String },
7113 #[error(
7114 ":placement {estrategia} requires at least one :clusters entry \
7115 (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
7116 )]
7117 PlacementWithoutClusters { estrategia: PlacementStrategy },
7118 #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
7119 PlacementClusterEmpty,
7120 #[error(
7121 ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
7122 (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
7123 in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
7124 future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
7125 — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
7126 identifier like `\"rio\"` or `\"mar-east\"`)"
7127 )]
7128 PlacementClusterInvalid { cluster: String, reason: String },
7129 #[error(":placement :clusters entry {cluster:?} appears more than once")]
7130 PlacementClusterDuplicate { cluster: String },
7131 #[error(
7132 ":placement :affinity must be non-empty when set (omit :affinity to express \
7133 `no placement hint`)"
7134 )]
7135 PlacementAffinityEmpty,
7136 #[error(
7137 ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
7138 (placement hints land verbatim in the M3 Adaptive compression overlay's \
7139 `placement.affinity` field and in every future M4 placement-engine routing \
7140 axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
7141 selector — both enforce the DNS-1123 label rule on admission; use a \
7142 lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
7143 `\"low-latency\"`, or `\"anti-affinity\"`)"
7144 )]
7145 PlacementAffinityInvalid { affinity: String, reason: String },
7146 #[error(":placement Sharded requires :shard-key")]
7147 ShardedWithoutKey,
7148 #[error(
7149 ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
7150 hashes every entity onto the same shard, defeating sharding entirely)"
7151 )]
7152 ShardedKeyEmpty,
7153 #[error(
7154 ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
7155 entity-id extractor expression: {reason} (the future M4 Akka-style \
7156 cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
7157 as a single-token property reference and hashes the extracted entity ID \
7158 to compute shard placement; use a printable-ASCII extractor expression \
7159 like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
7160 `\"${{tenant}}\"`)"
7161 )]
7162 ShardKeyInvalid { shard_key: String, reason: String },
7163 #[error(
7164 ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
7165 Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
7166 convention); :estrategia Replicated runs every cluster active-active and \
7167 :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
7168 distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
7169 to :estrategia Sharded if hash-keyed routing is the intent"
7170 )]
7171 ShardKeyOnNonSharded {
7172 estrategia: PlacementStrategy,
7173 shard_key: String,
7174 },
7175 #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
7176 ContratoMissingTarget {
7177 de: String,
7178 para: String,
7179 wit: String,
7180 expected: &'static str,
7181 },
7182 #[error(
7183 "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
7184 expected `:{expected}` only"
7185 )]
7186 ContratoWrongTarget {
7187 de: String,
7188 para: String,
7189 wit: String,
7190 expected: &'static str,
7191 },
7192 #[error(
7193 "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
7194 like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
7195 that matches no traffic and silently drops every request)"
7196 )]
7197 ContratoEndpointEmpty { de: String, para: String },
7198 #[error(
7199 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
7200 (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
7201 :entrada :paths)"
7202 )]
7203 ContratoEndpointNotAbsolute {
7204 de: String,
7205 para: String,
7206 endpoint: String,
7207 },
7208 #[error(
7209 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
7210 Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
7211 emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
7212 caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
7213 shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
7214 like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
7215 and whitespace)"
7216 )]
7217 ContratoEndpointInvalid {
7218 de: String,
7219 para: String,
7220 endpoint: String,
7221 reason: String,
7222 },
7223 #[error(
7224 "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
7225 subject is a no-op subscribe; omit :subject only if the WIT world is not \
7226 pub-sub-shaped)"
7227 )]
7228 ContratoSubjectEmpty { de: String, para: String },
7229 #[error(
7230 "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
7231 NATS subject: {reason} (the NATS server's subject parser enforces the \
7232 same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
7233 single-token and `>` multi-token wildcards — at publish/subscribe time; \
7234 use a token-by-token form like `\"checkout.events.charge.failed\"` or \
7235 `\"orders.*.completed\"` — a malformed subject silently drops every \
7236 message at runtime far from the source caixa.lisp)"
7237 )]
7238 ContratoSubjectInvalid {
7239 de: String,
7240 para: String,
7241 subject: String,
7242 reason: String,
7243 },
7244 #[error(
7245 "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
7246 addresses the bucket root, defeating the per-key isolation the slot exists \
7247 for; omit :slot only if the WIT world is not store-shaped)"
7248 )]
7249 ContratoSlotEmpty { de: String, para: String },
7250 #[error(
7251 "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
7252 WASI keyvalue store slot template: {reason} (the substrate enforces \
7253 the printable-ASCII intersection-floor every kv backend admits — \
7254 use a single-token path / template expression like `\"checkout/$orderId\"`, \
7255 `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
7256 percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
7257 slot either gets rejected on write by strict backends or silently \
7258 corrupts the next read on permissive ones, far from the source caixa.lisp)"
7259 )]
7260 ContratoSlotInvalid {
7261 de: String,
7262 para: String,
7263 slot: String,
7264 reason: String,
7265 },
7266 #[error(
7267 "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
7268 or an event-sourced indirection (MESH-COMPOSITION §III.3)",
7269 cycle.join(" → ")
7270 )]
7271 ContratoCycle { cycle: Vec<String> },
7272 #[error(
7273 ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
7274 than once (the typed graph edges are a set, not a multiset; duplicate \
7275 contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
7276 values that K8s admission rejects far from the source caixa.lisp)"
7277 )]
7278 ContratoDuplicate {
7279 de: String,
7280 para: String,
7281 wit: String,
7282 target: String,
7283 },
7284 #[error(
7285 ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
7286 contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
7287 express `no per-call deadline on this axis`"
7288 )]
7289 PolicyTimeoutZero,
7290 #[error(
7291 ":politicas :retries must be > 0 when set; omit :retries to express \
7292 `no retries on transient failure`"
7293 )]
7294 PolicyRetriesZero,
7295 #[error(
7296 ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
7297 (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
7298 retry policy into a thundering-herd amplification vector on transient \
7299 failure (one caller request fans out to `(retries+1)^depth` server-side \
7300 calls across the synchronous-:contratos subgraph), exactly the failure \
7301 mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
7302 Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
7303 or omit :retries to disable retries entirely"
7304 )]
7305 PolicyRetriesExceedsCap { retries: u32 },
7306 #[error(
7307 ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
7308 breaker trips on the first call); omit :circuit-breaker to disable it"
7309 )]
7310 PolicyBreakerZeroFailures,
7311 #[error(
7312 ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
7313 mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
7314 above this cap turns the typed breaker policy into a no-op: the trip \
7315 threshold is structurally so high that no realistic failures-per-:window \
7316 traffic shape can reach it, so the breaker never trips and every typed-slot \
7317 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
7318 Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
7319 structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
7320 Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
7321 omit :circuit-breaker to disable the breaker entirely"
7322 )]
7323 PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
7324 #[error(
7325 ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
7326 tracks no failures); omit :circuit-breaker to disable it"
7327 )]
7328 PolicyBreakerZeroWindow,
7329 #[error(
7330 ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
7331 request); omit :rate-limit to disable rate limiting"
7332 )]
7333 PolicyRateLimitZero,
7334 #[error(
7335 ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
7336 (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
7337 rate-limit policy into a no-op limiter: the token-bucket capacity is \
7338 structurally so high that no realistic per-edge traffic shape can drain it, \
7339 so the limiter never trips and every typed-slot consumer (the future \
7340 CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7341 local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
7342 that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
7343 Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
7344 Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
7345 Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
7346 to disable rate limiting entirely"
7347 )]
7348 PolicyRateLimitExceedsCap { rate: u32 },
7349 #[error(
7350 ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
7351 the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
7352 rate-limit codec round-trips losslessly; got {window:?} which renders to a \
7353 non-round-trippable form (omit :rate-limit to disable, or pick one of the \
7354 three canonical windows)"
7355 )]
7356 PolicyRateLimitWindowNotCanonical { window: Duration },
7357 #[error(
7358 ":politicas :timeout must be an integer number of milliseconds — the canonical \
7359 authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
7360 duration codec round-trips losslessly; got {timeout:?} which carries a \
7361 sub-millisecond residue that either truncates to a different `Duration` on \
7362 re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
7363 to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
7364 zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
7365 (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
7366 )]
7367 PolicyTimeoutNotCanonical { timeout: Duration },
7368 #[error(
7369 ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
7370 (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
7371 per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
7372 overlays carry a deadline so long no realistic synchronous-:contratos \
7373 traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
7374 CSE invariant degenerates to enforcement only at the per-Servico \
7375 `:limits :wall-clock` layer — far above the per-edge granularity the typed \
7376 `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
7377 (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
7378 ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
7379 maxes out at the same `3600s` ceiling) or omit :timeout to express \
7380 `no per-call deadline on this axis` (the synchronous-call deadline then \
7381 relies entirely on the per-Servico `:limits :wall-clock` axis)"
7382 )]
7383 PolicyTimeoutExceedsCap { timeout: Duration },
7384 #[error(
7385 ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
7386 the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
7387 the shared duration codec round-trips losslessly; got {window:?} which carries a \
7388 sub-millisecond residue that either truncates to a different `Duration` on \
7389 re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
7390 Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
7391 )]
7392 PolicyBreakerWindowNotCanonical { window: Duration },
7393 #[error(
7394 ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
7395 (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
7396 rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
7397 is structurally so long that transient failures are never forgotten, the breaker \
7398 trips once and stays tripped for the lifetime of the component, and every typed-slot \
7399 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7400 outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
7401 Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
7402 default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
7403 the breaker entirely"
7404 )]
7405 PolicyBreakerWindowExceedsCap { window: Duration },
7406}
7407
7408#[cfg(test)]
7409mod tests {
7410 use super::*;
7411
7412 fn membro(name: &str, ver: &str) -> Membro {
7413 Membro {
7414 caixa: name.into(),
7415 versao: ver.into(),
7416 }
7417 }
7418
7419 fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
7420 WitContract {
7421 de: de.into(),
7422 para: para.into(),
7423 wit: "wasi:http/proxy".into(),
7424 endpoint: Some(ep.into()),
7425 subject: None,
7426 slot: None,
7427 }
7428 }
7429
7430 fn three_member_spec() -> AplicacaoSpec {
7431 AplicacaoSpec {
7432 membros: vec![
7433 membro("catalog", "^0.1"),
7434 membro("cart", "^0.1"),
7435 membro("payment", "^0.2"),
7436 ],
7437 contratos: vec![
7438 contract_http("cart", "catalog", "/products/:id"),
7439 contract_http("cart", "payment", "/charge"),
7440 ],
7441 politicas: MeshPolicy {
7442 timeout: Some(Duration::from_secs(30)),
7443 retries: Some(3),
7444 mtls_required: Some(true),
7445 ..Default::default()
7446 },
7447 placement: Placement {
7448 estrategia: PlacementStrategy::Replicated,
7449 clusters: vec!["rio".into(), "mar".into()],
7450 affinity: Some("data-locality".into()),
7451 shard_key: None,
7452 },
7453 entrada: Some(Entrada {
7454 host: "checkout.quero.cloud".into(),
7455 para: "cart".into(),
7456 paths: vec!["/api/cart".into(), "/api/products".into()],
7457 port: 8080,
7458 }),
7459 }
7460 }
7461
7462 #[test]
7463 fn happy_path_validates() {
7464 three_member_spec().validate().unwrap();
7465 }
7466
7467 #[test]
7468 fn rejects_empty_membros() {
7469 let mut s = three_member_spec();
7470 s.membros = vec![];
7471 assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
7472 }
7473
7474 #[test]
7475 fn rejects_empty_membro_caixa() {
7476 // A `:caixa ""` entry has no name to render into programs.yaml
7477 // and no caixa.lisp to resolve at lacre time.
7478 let mut s = three_member_spec();
7479 s.membros[1].caixa = String::new();
7480 assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
7481 }
7482
7483 #[test]
7484 fn rejects_empty_membro_versao() {
7485 // A `:versao ""` entry can't pin a semver constraint, so the
7486 // lacre pipeline fails far from the source.
7487 let mut s = three_member_spec();
7488 s.membros[2].versao = String::new();
7489 let err = s.validate().unwrap_err();
7490 assert!(
7491 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
7492 "got {err:?}"
7493 );
7494 }
7495
7496 #[test]
7497 fn rejects_duplicate_membro_caixa() {
7498 // Two `:membros` entries with the same `:caixa` collapse to one
7499 // node in the membership HashSet, which masks `:contratos`
7500 // membership errors and produces duplicate programs.yaml entries.
7501 let mut s = three_member_spec();
7502 s.membros.push(membro("cart", "^0.2"));
7503 let err = s.validate().unwrap_err();
7504 assert!(
7505 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7506 "got {err:?}"
7507 );
7508 }
7509
7510 #[test]
7511 fn rejects_invalid_membro_versao_requirement() {
7512 // The fail-before-pass-after pin: a non-empty but malformed
7513 // semver requirement (`"^bad-version"`) silently passed
7514 // `validate()` on every pre-gate codebase because the prior
7515 // shape only refused the empty string. The parse failure
7516 // surfaced far downstream at lacre-resolve time with a
7517 // `semver::Error` that didn't name which `:membros` entry
7518 // carried the typo. The new gate moves the check to caixa-build
7519 // time at the source caixa.lisp.
7520 let mut s = three_member_spec();
7521 s.membros[2].versao = "^bad-version".into();
7522 let err = s.validate().unwrap_err();
7523 assert!(
7524 matches!(
7525 err,
7526 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7527 if caixa == "payment" && versao == "^bad-version"
7528 ),
7529 "got {err:?}"
7530 );
7531 }
7532
7533 #[test]
7534 fn rejects_membro_versao_with_double_caret_typo() {
7535 // `"^^0.1"` is the canonical doubled-caret typo — looks like a
7536 // Cargo-shaped requirement on first glance but fails the parser
7537 // because semver doesn't accept stacked operators. Pin this
7538 // adjacent-shape footgun explicitly so a future relaxation that
7539 // accepts "looks-canonical-but-isn't" forms surfaces here.
7540 let mut s = three_member_spec();
7541 s.membros[0].versao = "^^0.1".into();
7542 let err = s.validate().unwrap_err();
7543 assert!(
7544 matches!(
7545 err,
7546 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7547 if caixa == "catalog" && versao == "^^0.1"
7548 ),
7549 "got {err:?}"
7550 );
7551 }
7552
7553 #[test]
7554 fn rejects_membro_versao_with_v_prefixed_tag() {
7555 // `"v0.1"` is the canonical "git-tag-shape leaking into the
7556 // semver requirement slot" typo — an author copies the
7557 // publish-side git-tag string verbatim into `:versao`, but
7558 // Cargo's semver parser rejects the leading `v` (only digits +
7559 // canonical operators are valid in the major-version
7560 // position). The gate's diagnostic names which member entry
7561 // carried the v-prefix so the fix is one edit, not a grep
7562 // through every member's `:versao`. (Note: bare `x`-glob
7563 // shorthands like `^0.1.x` are *accepted* by the semver crate
7564 // as an `*` wildcard on the patch axis — they're a Cargo-side
7565 // valid shape, not a typo, so the gate intentionally lets them
7566 // through.)
7567 let mut s = three_member_spec();
7568 s.membros[1].versao = "v0.1".into();
7569 let err = s.validate().unwrap_err();
7570 assert!(
7571 matches!(
7572 err,
7573 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
7574 if caixa == "cart" && versao == "v0.1"
7575 ),
7576 "got {err:?}"
7577 );
7578 }
7579
7580 #[test]
7581 fn accepts_canonical_membro_versao_forms() {
7582 // The four Cargo-shaped requirement forms `:deps :versao`
7583 // already accepts via `crate::parse_requirement` must pass the
7584 // membros gate without re-validating at the resolver layer.
7585 // Pin every leg so a future tightening of the canonical set
7586 // surfaces here as a test failure.
7587 for form in [
7588 "^0.1", // caret — minor-range pin (the most common shape)
7589 "~0.1.2", // tilde — patch-range pin
7590 "0.1.0", // exact — single-version pin
7591 "*", // wildcard — explicitly any-version (semver::VersionReq::STAR)
7592 ">=0.1, <2", // multi-range — comma-separated comparators
7593 ] {
7594 let mut s = three_member_spec();
7595 for m in &mut s.membros {
7596 m.versao = form.into();
7597 }
7598 s.validate()
7599 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7600 }
7601 }
7602
7603 #[test]
7604 fn membro_versao_empty_takes_precedence_over_invalid() {
7605 // Order pin: the existing `MembroVersaoEmpty` diagnostic
7606 // (which doesn't try to parse) fires before the new
7607 // `MembroVersaoInvalid` parse-side diagnostic, so an empty
7608 // `:versao` keeps its narrower error message — `parse_requirement`
7609 // would also reject `""`, but the empty-string arm is the more
7610 // self-locating diagnostic for the author.
7611 let mut s = three_member_spec();
7612 s.membros[1].versao = String::new();
7613 let err = s.validate().unwrap_err();
7614 assert!(
7615 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
7616 "got {err:?}"
7617 );
7618 }
7619
7620 #[test]
7621 fn membro_versao_invalid_fires_before_duplicate_check() {
7622 // Order pin: a malformed requirement on a non-duplicate entry
7623 // surfaces *its own* diagnostic (which names the offending
7624 // `:versao` string), even when a later entry would otherwise
7625 // collapse onto an earlier name. The per-entry shape gate runs
7626 // inline before the duplicate-key insert, parallel to
7627 // `membros_validation_runs_before_contratos_membership_check`
7628 // and `duplicate_contrato_gate_runs_after_target_shape_check`.
7629 let mut s = three_member_spec();
7630 s.membros[0].versao = "^bad".into();
7631 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
7632 let err = s.validate().unwrap_err();
7633 assert!(
7634 matches!(
7635 err,
7636 AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
7637 ),
7638 "got {err:?}"
7639 );
7640 }
7641
7642 #[test]
7643 fn membro_versao_invalid_diagnostic_carries_offending_versao() {
7644 // The diagnostic-shape pin: the error names the offending
7645 // `:versao` value verbatim so the author can grep their
7646 // caixa.lisp without re-running the build, and carries a
7647 // non-empty `reason` from `semver::VersionReq::parse` so the
7648 // parser's own wording flows through to the diagnostic.
7649 let mut s = three_member_spec();
7650 s.membros[2].versao = "not-a-req".into();
7651 let err = s.validate().unwrap_err();
7652 let AplicacaoError::MembroVersaoInvalid {
7653 caixa,
7654 versao,
7655 reason,
7656 } = err
7657 else {
7658 panic!("expected MembroVersaoInvalid, got other variant");
7659 };
7660 assert_eq!(caixa, "payment");
7661 assert_eq!(versao, "not-a-req");
7662 assert!(
7663 !reason.is_empty(),
7664 "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
7665 );
7666 }
7667
7668 #[test]
7669 fn membro_versao_invalid_runs_before_contratos_check() {
7670 // A malformed `:versao` on any member must surface its own
7671 // diagnostic (which names *which* member to fix) before any
7672 // `:contratos` membership lookup raises `ContratoMemberMissing`.
7673 // The `:contratos` gate runs after `validate_membros`, so this
7674 // is structurally guaranteed — pin it explicitly so a future
7675 // refactor that reorders the gates surfaces here.
7676 let mut s = three_member_spec();
7677 s.membros[1].versao = "^^0.1".into();
7678 // Add a contrato whose `:para` doesn't exist — would normally
7679 // raise ContratoMemberMissing at the membership lookup, but
7680 // the membros gate must fire first.
7681 s.contratos
7682 .push(contract_http("cart", "phantom", "/never-reached"));
7683 let err = s.validate().unwrap_err();
7684 assert!(
7685 matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
7686 "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
7687 );
7688 }
7689
7690 #[test]
7691 fn membros_validation_runs_before_contratos_membership_check() {
7692 // If `:membros` carries a duplicate, the membership-collapse
7693 // would silently accept a `:contratos :para "phantom"` so long
7694 // as some entry hashes to "phantom". Pinning order: the
7695 // duplicate-membros error fires first, regardless of whether
7696 // contratos reference real members.
7697 let mut s = three_member_spec();
7698 s.membros = vec![
7699 membro("cart", "^0.1"),
7700 membro("cart", "^0.2"),
7701 membro("catalog", "^0.1"),
7702 membro("payment", "^0.1"),
7703 ];
7704 let err = s.validate().unwrap_err();
7705 assert!(
7706 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
7707 "got {err:?}"
7708 );
7709 }
7710
7711 #[test]
7712 fn distinct_membros_validate() {
7713 // Pin the happy-path: every `:membros` entry has a non-empty
7714 // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
7715 // The fixture already satisfies this; this test makes the
7716 // invariant explicit so a future refactor of the fixture can't
7717 // silently break the guarantee.
7718 three_member_spec().validate().unwrap();
7719 }
7720
7721 // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
7722
7723 #[test]
7724 fn rejects_membro_caixa_with_uppercase() {
7725 // The canonical "I copied the Servico's display name verbatim"
7726 // typo — caixa names are lowercase per K8s DNS-1123 label rule,
7727 // but author tools often round-trip a TitleCase or CamelCase
7728 // identifier from an ADR or a sketch. Pin the diagnostic names
7729 // the offending name and suggests the lower-cased fix in one
7730 // edit, mirroring the `rejects_entrada_host_with_uppercase`
7731 // gate's shape (c7d05ec).
7732 let mut s = three_member_spec();
7733 s.membros[1].caixa = "Cart".into();
7734 let err = s.validate().unwrap_err();
7735 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7736 panic!("expected MembroCaixaInvalid, got other variant");
7737 };
7738 assert_eq!(caixa, "Cart");
7739 assert!(
7740 reason.contains("uppercase"),
7741 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
7742 );
7743 assert!(
7744 reason.contains("\"cart\""),
7745 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
7746 );
7747 }
7748
7749 #[test]
7750 fn rejects_membro_caixa_with_underscore() {
7751 // The canonical "I'm thinking of a Python module / Postgres
7752 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
7753 // label schema. K8s rejects `metadata.name: my_cart` at admission
7754 // time with an opaque `field is invalid` (no source-citing
7755 // diagnostic). The gate moves it to caixa-build time.
7756 let mut s = three_member_spec();
7757 s.membros[0].caixa = "my_cart".into();
7758 let err = s.validate().unwrap_err();
7759 assert!(
7760 matches!(
7761 err,
7762 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7763 if caixa == "my_cart" && reason.contains('_')
7764 ),
7765 "got {err:?}"
7766 );
7767 }
7768
7769 #[test]
7770 fn rejects_membro_caixa_with_dot() {
7771 // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
7772 // subdomain — even though K8s `metadata.name` itself accepts
7773 // dots (DNS-1123 subdomain rule), this string also lands as a
7774 // K8s Service name (DNS-1035 label — no dots) and as a label
7775 // value on identity-based Cilium selectors. The strictest floor
7776 // among the use sites wins. The "I want to namespace my member
7777 // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
7778 let mut s = three_member_spec();
7779 s.membros[2].caixa = "team.cart".into();
7780 let err = s.validate().unwrap_err();
7781 assert!(
7782 matches!(
7783 err,
7784 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7785 if caixa == "team.cart" && reason.contains('.')
7786 ),
7787 "got {err:?}"
7788 );
7789 }
7790
7791 #[test]
7792 fn rejects_membro_caixa_with_leading_hyphen() {
7793 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
7794 // with an alphanumeric. The K8s apiserver rejects `-cart`
7795 // outright; the renderer would emit a `metadata.name: "-cart"`
7796 // that fails admission far from the source caixa.lisp.
7797 let mut s = three_member_spec();
7798 s.membros[0].caixa = "-cart".into();
7799 let err = s.validate().unwrap_err();
7800 assert!(
7801 matches!(
7802 err,
7803 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
7804 if caixa == "-cart" && reason.contains("start and end")
7805 ),
7806 "got {err:?}"
7807 );
7808 }
7809
7810 #[test]
7811 fn rejects_membro_caixa_with_trailing_hyphen() {
7812 // The symmetric arm of the boundary rule. Pin separately so
7813 // both ends of the label are covered against a future relaxation
7814 // that only checks one boundary.
7815 let mut s = three_member_spec();
7816 s.membros[1].caixa = "cart-".into();
7817 let err = s.validate().unwrap_err();
7818 assert!(
7819 matches!(
7820 err,
7821 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7822 if caixa == "cart-"
7823 ),
7824 "got {err:?}"
7825 );
7826 }
7827
7828 #[test]
7829 fn rejects_membro_caixa_with_unicode() {
7830 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
7831 // (`xn--…`) by the author before it reaches K8s. The byte-by-
7832 // byte ASCII validity check rejects multi-byte UTF-8 sequences
7833 // by the first byte that fails the `[a-z0-9-]` predicate.
7834 let mut s = three_member_spec();
7835 s.membros[2].caixa = "café".into();
7836 let err = s.validate().unwrap_err();
7837 assert!(
7838 matches!(
7839 err,
7840 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7841 if caixa == "café"
7842 ),
7843 "got {err:?}"
7844 );
7845 }
7846
7847 #[test]
7848 fn rejects_membro_caixa_with_whitespace() {
7849 // Whitespace is the canonical "I pasted from a sketch / doc"
7850 // footgun. The apiserver rejects every `metadata.name` value
7851 // carrying whitespace; pin the gate fires at the right boundary.
7852 let mut s = three_member_spec();
7853 s.membros[0].caixa = "my cart".into();
7854 let err = s.validate().unwrap_err();
7855 assert!(
7856 matches!(
7857 err,
7858 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
7859 if caixa == "my cart"
7860 ),
7861 "got {err:?}"
7862 );
7863 }
7864
7865 #[test]
7866 fn rejects_membro_caixa_too_long() {
7867 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
7868 // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
7869 // exactly. The gate's reason names both the cap and the actual
7870 // length so the author can shorten in one edit.
7871 let mut s = three_member_spec();
7872 let too_long = "a".repeat(64);
7873 s.membros[1].caixa = too_long.clone();
7874 let err = s.validate().unwrap_err();
7875 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
7876 panic!("expected MembroCaixaInvalid");
7877 };
7878 assert_eq!(caixa, too_long);
7879 assert!(
7880 reason.contains("63") && reason.contains("64"),
7881 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
7882 );
7883 }
7884
7885 #[test]
7886 fn membro_caixa_max_length_validates() {
7887 // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
7888 // so a future tightening (e.g. dropping to 62) surfaces here as
7889 // a regression, mirroring `entrada_host_max_length_validates`
7890 // (c7d05ec).
7891 let mut s = three_member_spec();
7892 s.membros[2].caixa = "a".repeat(63);
7893 s.entrada.as_mut().unwrap().para = "a".repeat(63);
7894 // remove contratos referencing the renamed member; they'd
7895 // raise ContratoMemberMissing otherwise
7896 s.contratos
7897 .retain(|c| c.de != "payment" && c.para != "payment");
7898 s.validate().unwrap();
7899 }
7900
7901 #[test]
7902 fn accepts_canonical_membro_caixa_forms() {
7903 // The DNS-1123 label shapes a caixa author is realistically
7904 // going to write: single-word lowercase, hyphen-joined, ending
7905 // in a digit-suffixed version (`cart-v2`), starting with a
7906 // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
7907 // DNS-1035 which requires a letter at position 0), single-
7908 // character (`a` — boundary). Pin every leg so a future
7909 // tightening that bans (e.g.) digit-start identifiers surfaces
7910 // here.
7911 for form in [
7912 "checkout",
7913 "cart",
7914 "cart-v2",
7915 "a",
7916 "c0",
7917 "3rd-party-shim",
7918 "x-1-2-3-4",
7919 ] {
7920 let mut s = three_member_spec();
7921 // Renaming a member also requires updating downstream refs;
7922 // drop everything else and rebuild a minimal spec around
7923 // just the one renamed member.
7924 s.membros = vec![membro(form, "^0.1")];
7925 s.contratos = vec![];
7926 s.entrada = None;
7927 s.validate()
7928 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
7929 }
7930 }
7931
7932 #[test]
7933 fn membro_caixa_empty_takes_precedence_over_invalid() {
7934 // Order pin: the existing `MembroCaixaEmpty` diagnostic
7935 // (which doesn't try to parse) fires before the new
7936 // `MembroCaixaInvalid` parse-side diagnostic, so an empty
7937 // `:caixa` keeps its narrower error message — the new gate
7938 // would also reject `""`, but the empty-string arm is the more
7939 // self-locating diagnostic for the author. Mirrors the
7940 // `entrada_host_empty_takes_precedence_over_invalid` pin
7941 // (c7d05ec).
7942 let mut s = three_member_spec();
7943 s.membros[1].caixa = String::new();
7944 let err = s.validate().unwrap_err();
7945 assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
7946 }
7947
7948 #[test]
7949 fn membro_caixa_invalid_fires_before_versao_check() {
7950 // Order pin: an invalid-shape `:caixa` surfaces *its own*
7951 // diagnostic (which names the offending caixa name), even when
7952 // the same entry's `:versao` is also empty/invalid. The shape
7953 // gate runs first because the diagnostic is more self-locating —
7954 // an empty/invalid `:versao` on an invalid-shape caixa name is
7955 // a downstream-fix-after-the-caixa-rename concern.
7956 let mut s = three_member_spec();
7957 s.membros[1].caixa = "Cart".into();
7958 s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
7959 let err = s.validate().unwrap_err();
7960 assert!(
7961 matches!(
7962 err,
7963 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
7964 ),
7965 "got {err:?}"
7966 );
7967 }
7968
7969 #[test]
7970 fn membro_caixa_invalid_fires_before_duplicate_check() {
7971 // Order pin: a malformed-shape `:caixa` on an earlier entry
7972 // surfaces *its own* diagnostic, even when a later entry would
7973 // otherwise collapse onto a duplicate name. The per-entry shape
7974 // gate runs inline before the duplicate-key insert, parallel
7975 // to `membro_versao_invalid_fires_before_duplicate_check`.
7976 let mut s = three_member_spec();
7977 s.membros[0].caixa = "Catalog".into();
7978 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
7979 let err = s.validate().unwrap_err();
7980 assert!(
7981 matches!(
7982 err,
7983 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
7984 ),
7985 "got {err:?}"
7986 );
7987 }
7988
7989 #[test]
7990 fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
7991 // The diagnostic-shape pin: the error names the offending
7992 // `:caixa` value verbatim so the author can grep their
7993 // caixa.lisp without re-running the build, and carries a
7994 // non-empty `reason` naming the specific violation. Same
7995 // shape every typed-shape gate enshrines (c7d05ec's
7996 // `entrada_host_diagnostic_carries_offending_host`,
7997 // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
7998 let mut s = three_member_spec();
7999 s.membros[2].caixa = "BAD_NAME".into();
8000 let err = s.validate().unwrap_err();
8001 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8002 panic!("expected MembroCaixaInvalid");
8003 };
8004 assert_eq!(caixa, "BAD_NAME");
8005 assert!(
8006 !reason.is_empty(),
8007 "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
8008 );
8009 }
8010
8011 #[test]
8012 fn rejects_contrato_with_unknown_de() {
8013 let mut s = three_member_spec();
8014 s.contratos.push(contract_http("phantom", "catalog", "/x"));
8015 let err = s.validate().unwrap_err();
8016 assert!(
8017 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8018 );
8019 }
8020
8021 #[test]
8022 fn rejects_contrato_with_unknown_para() {
8023 let mut s = three_member_spec();
8024 s.contratos.push(contract_http("cart", "phantom", "/x"));
8025 let err = s.validate().unwrap_err();
8026 assert!(
8027 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8028 );
8029 }
8030
8031 #[test]
8032 fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
8033 // The read-path pin: the phantom-`:de` refusal arm's
8034 // `ContratoMemberMissing.caixa` carrier must be observed through
8035 // the lifted [`WitContract::source`] accessor, not the raw
8036 // `.de.clone()` field-access `String`-carry. Peer of the sibling
8037 // per-`:contratos` self-loop arm's `.source().to_string()` /
8038 // `.world_ref().to_string()` `String`-carry sites the earlier
8039 // convergence lifted onto the same accessor pair. A future
8040 // silent detour that reintroduced the raw `.de.clone()` at the
8041 // wrap envelope while the shape-gate and membership lookup
8042 // routed through the accessor would surface here as a byte-equal
8043 // miss between the fired diagnostic's `caixa:` field and the
8044 // offending edge's `.source()` — pinning the accessor as the
8045 // sole read path across the phantom-name refusal arm's arg +
8046 // wrap-envelope emit surface.
8047 let mut s = three_member_spec();
8048 let phantom = contract_http("phantom", "catalog", "/x");
8049 s.contratos.push(phantom.clone());
8050 let err = s.validate().unwrap_err();
8051 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8052 panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
8053 };
8054 assert_eq!(
8055 caixa,
8056 phantom.source(),
8057 "ContratoMemberMissing.caixa on the phantom-:de arm must \
8058 byte-equal WitContract::source — the wrap envelope must \
8059 route through the lifted accessor rather than the raw \
8060 .de.clone() field-access String-carry"
8061 );
8062 }
8063
8064 #[test]
8065 fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8066 // The symmetric read-path pin on the `:para` phantom-name
8067 // refusal arm — same shape as the sibling `:de` pin above but
8068 // on the callee-Servico axis. Pins the wrap envelope's
8069 // `caixa:` field is observed through the lifted
8070 // [`WitContract::destination`] accessor, not the raw
8071 // `.para.clone()` field-access `String`-carry.
8072 let mut s = three_member_spec();
8073 let phantom = contract_http("cart", "phantom", "/x");
8074 s.contratos.push(phantom.clone());
8075 let err = s.validate().unwrap_err();
8076 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8077 panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
8078 };
8079 assert_eq!(
8080 caixa,
8081 phantom.destination(),
8082 "ContratoMemberMissing.caixa on the phantom-:para arm must \
8083 byte-equal WitContract::destination — the wrap envelope \
8084 must route through the lifted accessor rather than the raw \
8085 .para.clone() field-access String-carry"
8086 );
8087 }
8088
8089 #[test]
8090 fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
8091 // The read-path pin on the `:de` DNS-1123-malformed shape-gate
8092 // refusal arm — the `validate_contrato_caixa` arg must be
8093 // observed through the lifted [`WitContract::source`] accessor,
8094 // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
8095 // value routes through the shared
8096 // [`crate::render::require_valid_dns_1123_label`] floor with the
8097 // accessor-projected value; the fired
8098 // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
8099 // the offending edge's `.source()`, pinning that the arg + the
8100 // downstream `caixa: caixa.to_string()` wrap route through the
8101 // same accessor's read path.
8102 let mut s = three_member_spec();
8103 let malformed = contract_http("BAD_NAME", "catalog", "/x");
8104 s.contratos.push(malformed.clone());
8105 let err = s.validate().unwrap_err();
8106 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8107 panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
8108 };
8109 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8110 assert_eq!(
8111 caixa,
8112 malformed.source(),
8113 "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
8114 byte-equal WitContract::source — the shape-gate arg + wrap \
8115 envelope must route through the lifted accessor rather \
8116 than the raw &c.de &String-borrow"
8117 );
8118 }
8119
8120 #[test]
8121 fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8122 // Symmetric arm to the sibling `:de` malformed-shape pin above,
8123 // on the `:para` axis. Pins the shape-gate arg + wrap envelope
8124 // route through the lifted [`WitContract::destination`]
8125 // accessor. `:para` runs after the `:de` shape gate in the
8126 // canonical edge-direction order, so the `:de` value must be
8127 // well-shaped for the `:para` gate to fire — the `cart` :de is
8128 // canonical.
8129 let mut s = three_member_spec();
8130 let malformed = contract_http("cart", "BAD_NAME", "/x");
8131 s.contratos.push(malformed.clone());
8132 let err = s.validate().unwrap_err();
8133 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8134 panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
8135 };
8136 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8137 assert_eq!(
8138 caixa,
8139 malformed.destination(),
8140 "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
8141 byte-equal WitContract::destination — the shape-gate arg + \
8142 wrap envelope must route through the lifted accessor \
8143 rather than the raw &c.para &String-borrow"
8144 );
8145 }
8146
8147 // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
8148
8149 #[test]
8150 fn rejects_contrato_de_empty() {
8151 // `:de ""` previously fell through to `ContratoMemberMissing`
8152 // (with `caixa: ""`) because the validated `:membros :caixa`
8153 // set never contains the empty string. The narrower
8154 // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
8155 // the offending slot.
8156 let mut s = three_member_spec();
8157 s.contratos.push(contract_http("", "catalog", "/x"));
8158 let err = s.validate().unwrap_err();
8159 assert_eq!(
8160 err,
8161 AplicacaoError::ContratoCaixaEmpty {
8162 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8163 },
8164 "got {err:?}"
8165 );
8166 }
8167
8168 #[test]
8169 fn rejects_contrato_para_empty() {
8170 // Symmetric arm to `:de ""` — `:para ""` previously fell
8171 // through to `ContratoMemberMissing { caixa: "" }`.
8172 let mut s = three_member_spec();
8173 s.contratos.push(contract_http("cart", "", "/x"));
8174 let err = s.validate().unwrap_err();
8175 assert_eq!(
8176 err,
8177 AplicacaoError::ContratoCaixaEmpty {
8178 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8179 },
8180 "got {err:?}"
8181 );
8182 }
8183
8184 #[test]
8185 fn rejects_contrato_de_with_uppercase() {
8186 // The canonical "I copied the Servico's TitleCase display
8187 // name from an ADR" typo. Until this gate landed `:de "Cart"`
8188 // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
8189 // as "this caixa isn't in `:membros`" when the root cause is
8190 // "this `:de` value's shape can never legitimately match a
8191 // validated member (DNS-1123 labels are lowercase)". The
8192 // narrower diagnostic names the offending slot, the value
8193 // verbatim, and the parser-shaped reason.
8194 let mut s = three_member_spec();
8195 s.contratos.push(contract_http("Cart", "catalog", "/x"));
8196 let err = s.validate().unwrap_err();
8197 let AplicacaoError::ContratoCaixaInvalid {
8198 slot,
8199 caixa,
8200 reason,
8201 } = err
8202 else {
8203 panic!("expected ContratoCaixaInvalid, got other variant");
8204 };
8205 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8206 assert_eq!(caixa, "Cart");
8207 assert!(
8208 reason.contains("uppercase"),
8209 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8210 );
8211 }
8212
8213 #[test]
8214 fn rejects_contrato_para_with_underscore() {
8215 // The canonical "I'm thinking of a Python module" leak —
8216 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8217 // Pin the `:para` axis surfaces the same diagnostic shape as
8218 // the `:de` axis on the underscore violation.
8219 let mut s = three_member_spec();
8220 s.contratos.push(contract_http("cart", "my_catalog", "/x"));
8221 let err = s.validate().unwrap_err();
8222 assert!(
8223 matches!(
8224 err,
8225 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8226 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
8227 ),
8228 "got {err:?}"
8229 );
8230 }
8231
8232 #[test]
8233 fn rejects_contrato_de_with_dot() {
8234 // A `:contratos :de` value is a single DNS-1123 *label*, not
8235 // a subdomain — mirroring the `:membros :caixa` floor. The
8236 // strictest floor among the use sites wins.
8237 let mut s = three_member_spec();
8238 s.contratos
8239 .push(contract_http("team.cart", "catalog", "/x"));
8240 let err = s.validate().unwrap_err();
8241 assert!(
8242 matches!(
8243 err,
8244 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8245 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
8246 ),
8247 "got {err:?}"
8248 );
8249 }
8250
8251 #[test]
8252 fn rejects_contrato_para_with_unicode() {
8253 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8254 // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
8255 // validity check rejects multi-byte UTF-8 by the first
8256 // non-`[a-z0-9-]` byte.
8257 let mut s = three_member_spec();
8258 s.contratos.push(contract_http("cart", "café", "/x"));
8259 let err = s.validate().unwrap_err();
8260 assert!(
8261 matches!(
8262 err,
8263 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8264 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
8265 ),
8266 "got {err:?}"
8267 );
8268 }
8269
8270 #[test]
8271 fn rejects_contrato_de_with_leading_hyphen() {
8272 // DNS-1123 boundary rule: labels must start and end with an
8273 // alphanumeric. K8s rejects `-cart` outright; the narrower
8274 // shape diagnostic now names the violation at caixa-build
8275 // time rather than the misframed membership-lookup arm.
8276 let mut s = three_member_spec();
8277 s.contratos.push(contract_http("-cart", "catalog", "/x"));
8278 let err = s.validate().unwrap_err();
8279 assert!(
8280 matches!(
8281 err,
8282 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8283 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
8284 ),
8285 "got {err:?}"
8286 );
8287 }
8288
8289 #[test]
8290 fn contrato_de_empty_takes_precedence_over_invalid() {
8291 // Order pin: the `ContratoCaixaEmpty` arm fires before the
8292 // `ContratoCaixaInvalid` parse-side arm — same empty-first
8293 // cascade `validate_membro_caixa` / `validate_placement_cluster`
8294 // / `validate_entrada_host` already establish on their peer
8295 // name axes. The empty string is a structurally distinct
8296 // authoring footgun (the author left the field blank, vs.
8297 // typed a malformed value), so it gets its own diagnostic.
8298 let mut s = three_member_spec();
8299 s.contratos.push(contract_http("", "catalog", "/x"));
8300 let err = s.validate().unwrap_err();
8301 assert_eq!(
8302 err,
8303 AplicacaoError::ContratoCaixaEmpty {
8304 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8305 }
8306 );
8307 }
8308
8309 #[test]
8310 fn contrato_de_shape_fires_before_para_shape() {
8311 // Per-axis order pin: within one `:contratos` entry, the `:de`
8312 // shape gate fires before the `:para` shape gate — same
8313 // edge-direction order the existing `ContratoMemberMissing` /
8314 // `ContratoSelfLoop` / target-dispatch checks use, so the
8315 // diagnostic for a contract with both `:de` and `:para`
8316 // malformed is stable. Authors fixing the surfaced `:de`
8317 // first will see `:para`'s diagnostic on re-run.
8318 let mut s = three_member_spec();
8319 s.contratos.push(contract_http("Cart", "Catalog", "/x"));
8320 let err = s.validate().unwrap_err();
8321 assert!(
8322 matches!(
8323 err,
8324 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8325 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8326 ),
8327 "got {err:?}"
8328 );
8329 }
8330
8331 #[test]
8332 fn contrato_shape_fires_before_membership_lookup() {
8333 // The load-bearing pin: an invalid-shape `:de` surfaces its
8334 // *own* diagnostic, not the misframed `ContratoMemberMissing`.
8335 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8336 // an invalid-shape `:de` could never legitimately match any
8337 // member — the prior `ContratoMemberMissing` diagnostic was
8338 // a structural impossibility framed as a graph-membership
8339 // failure. The shape gate now routes every such input through
8340 // the narrower self-locating diagnostic.
8341 let mut s = three_member_spec();
8342 s.contratos.push(contract_http("Cart", "catalog", "/x"));
8343 let err = s.validate().unwrap_err();
8344 assert!(
8345 matches!(
8346 err,
8347 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
8348 ),
8349 "got {err:?}"
8350 );
8351 // And the symmetric case: an invalid-shape `:para` surfaces
8352 // its own diagnostic too, even when `:de` is well-shaped.
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, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
8360 ),
8361 "got {err:?}"
8362 );
8363 }
8364
8365 #[test]
8366 fn contrato_shape_fires_before_self_edge_check() {
8367 // A `:de "Cart" :para "Cart"` entry is two distinct authoring
8368 // bugs: the shape violation (uppercase) and the self-edge
8369 // violation. The narrower per-axis shape diagnostic surfaces
8370 // first because fixing the shape may reveal that the author
8371 // also meant to point `:para` at a different member — the
8372 // self-edge framing is only useful once both endpoints have
8373 // valid shape.
8374 let mut s = three_member_spec();
8375 s.contratos.push(contract_http("Cart", "Cart", "/x"));
8376 let err = s.validate().unwrap_err();
8377 assert!(
8378 matches!(
8379 err,
8380 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8381 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8382 ),
8383 "got {err:?}"
8384 );
8385 }
8386
8387 #[test]
8388 fn contrato_well_shaped_phantom_still_raises_member_missing() {
8389 // Strict-improvement pin: a well-shaped `:de` that simply
8390 // isn't in `:membros` (a phantom reference — author meant
8391 // to add the member but didn't, or renamed and missed an
8392 // update) still surfaces `ContratoMemberMissing`, unchanged.
8393 // The shape gate only intercepts inputs that could never
8394 // legitimately match a validated member; legitimately-shaped
8395 // phantom references remain on the graph-membership axis.
8396 let mut s = three_member_spec();
8397 s.contratos
8398 .push(contract_http("phantom-shim", "catalog", "/x"));
8399 let err = s.validate().unwrap_err();
8400 assert!(
8401 matches!(
8402 err,
8403 AplicacaoError::ContratoMemberMissing { ref caixa }
8404 if caixa == "phantom-shim"
8405 ),
8406 "got {err:?}"
8407 );
8408 }
8409
8410 #[test]
8411 fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
8412 // The diagnostic-shape pin: the error names the offending
8413 // slot (`:de` or `:para`) verbatim and the offending value
8414 // verbatim plus a non-empty parser-shaped reason, so the
8415 // author can grep their caixa.lisp for `:de "<name>"` /
8416 // `:para "<name>"` and fix it in one edit. Same diagnostic
8417 // shape as `MembroCaixaInvalid` (3f9d7a0) and
8418 // `PlacementClusterInvalid` (6c8c00b).
8419 let mut s = three_member_spec();
8420 s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
8421 let err = s.validate().unwrap_err();
8422 let AplicacaoError::ContratoCaixaInvalid {
8423 slot,
8424 caixa,
8425 reason,
8426 } = err
8427 else {
8428 panic!("expected ContratoCaixaInvalid, got {err:?}");
8429 };
8430 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8431 assert_eq!(caixa, "BAD_NAME");
8432 assert!(
8433 !reason.is_empty(),
8434 "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
8435 );
8436 }
8437
8438 #[test]
8439 fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
8440 // Scalar-value pin: the two author-facing kebab-case labels the
8441 // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
8442 // admits on the `:contratos` per-entry endpoint-shape axis,
8443 // one arm per typed sub-slot. Mirrors the peer scalar-value
8444 // pin the sibling top-level M2 / M3 / Supervisor
8445 // author-facing-label consts carry
8446 // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
8447 // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
8448 // slot itself), so every altitude of the typed-slot algebra
8449 // shares the same "one canonical byte-string per arm"
8450 // discipline. A future rebrand (`:de` → `:from` matching the
8451 // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
8452 // sibling, `:para` → `:to` matching the same, or
8453 // `:de`/`:para` → `:source`/`:target` matching the WIT
8454 // world's `import`/`export` half-vocabulary) lands as an
8455 // edit to exactly one const, and every consumer that reaches
8456 // for the label picks it up at build time rather than at
8457 // runtime as a downstream `ContratoCaixaEmpty` /
8458 // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
8459 // diagnostic mismatch far from the rename's commit.
8460 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
8461 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
8462 }
8463
8464 #[test]
8465 fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
8466 // Production-through-const pin: the two per-axis labels the
8467 // per-`:contratos` entry endpoint-shape gate at
8468 // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
8469 // argument to [`validate_contrato_caixa`] route through the
8470 // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
8471 // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
8472 // future rebrand that reaches the const but not the gate (or
8473 // vice versa) surfaces here at build time rather than at
8474 // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
8475 // `slot: <stale-kebab-case>` diagnostic far from the rename's
8476 // commit. Mirror of the peer
8477 // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
8478 // pin (882f498) on the sibling M3 top-level slot axis.
8479 let mut s = three_member_spec();
8480 s.contratos.push(contract_http("", "catalog", "/x"));
8481 assert_eq!(
8482 s.validate().unwrap_err(),
8483 AplicacaoError::ContratoCaixaEmpty {
8484 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8485 }
8486 );
8487 let mut s = three_member_spec();
8488 s.contratos.push(contract_http("cart", "", "/x"));
8489 assert_eq!(
8490 s.validate().unwrap_err(),
8491 AplicacaoError::ContratoCaixaEmpty {
8492 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8493 }
8494 );
8495 }
8496
8497 #[test]
8498 fn accepts_canonical_contrato_caixa_forms() {
8499 // The DNS-1123 label shapes a caixa author is realistically
8500 // going to write on a `:contratos :de` / `:para`. Pin every
8501 // leg so a future tightening that bans (e.g.) digit-start
8502 // identifiers surfaces here, mirroring
8503 // `accepts_canonical_membro_caixa_forms` on the peer name
8504 // axis.
8505 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8506 let mut s = three_member_spec();
8507 s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
8508 s.contratos = vec![contract_http("checkout", form, "/x")];
8509 s.entrada = None;
8510 s.validate().unwrap_or_else(|e| {
8511 panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
8512 });
8513
8514 let mut s = three_member_spec();
8515 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8516 s.contratos = vec![contract_http(form, "catalog", "/x")];
8517 s.entrada = None;
8518 s.validate().unwrap_or_else(|e| {
8519 panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
8520 });
8521 }
8522 }
8523
8524 #[test]
8525 fn rejects_empty_wit() {
8526 let mut s = three_member_spec();
8527 s.contratos.push(WitContract {
8528 de: "cart".into(),
8529 para: "catalog".into(),
8530 wit: "".into(),
8531 endpoint: None,
8532 subject: None,
8533 slot: None,
8534 });
8535 let err = s.validate().unwrap_err();
8536 assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
8537 }
8538
8539 #[test]
8540 fn rejects_entrada_to_unknown_member() {
8541 let mut s = three_member_spec();
8542 s.entrada.as_mut().unwrap().para = "phantom".into();
8543 assert!(matches!(
8544 s.validate().unwrap_err(),
8545 AplicacaoError::EntradaMemberMissing { .. }
8546 ));
8547 }
8548
8549 // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
8550
8551 #[test]
8552 fn rejects_entrada_para_empty() {
8553 // `:para ""` previously fell through to
8554 // `EntradaMemberMissing { para: "" }` because the validated
8555 // `:membros :caixa` set never contains the empty string. The
8556 // narrower `EntradaParaEmpty` diagnostic now names the
8557 // offending slot directly — same empty-first cascade
8558 // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
8559 // `ContratoCaixaEmpty` establish on the peer name axes.
8560 let mut s = three_member_spec();
8561 s.entrada.as_mut().unwrap().para = String::new();
8562 let err = s.validate().unwrap_err();
8563 assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
8564 }
8565
8566 #[test]
8567 fn rejects_entrada_para_with_uppercase() {
8568 // The canonical "I copied the Servico's TitleCase display
8569 // name from an ADR" typo. Until this gate landed `:para "Cart"`
8570 // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
8571 // as "this caixa isn't in `:membros`" when the root cause is
8572 // "this `:para` value's shape can never legitimately match a
8573 // validated member (DNS-1123 labels are lowercase)". The
8574 // narrower diagnostic names the value verbatim plus the
8575 // parser-shaped reason.
8576 let mut s = three_member_spec();
8577 s.entrada.as_mut().unwrap().para = "Cart".into();
8578 let err = s.validate().unwrap_err();
8579 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8580 panic!("expected EntradaParaInvalid, got other variant");
8581 };
8582 assert_eq!(para, "Cart");
8583 assert!(
8584 reason.contains("uppercase"),
8585 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8586 );
8587 }
8588
8589 #[test]
8590 fn rejects_entrada_para_with_underscore() {
8591 // The canonical "I'm thinking of a Python module" leak —
8592 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8593 let mut s = three_member_spec();
8594 s.entrada.as_mut().unwrap().para = "my_cart".into();
8595 let err = s.validate().unwrap_err();
8596 assert!(
8597 matches!(
8598 err,
8599 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8600 if para == "my_cart" && reason.contains('_')
8601 ),
8602 "got {err:?}"
8603 );
8604 }
8605
8606 #[test]
8607 fn rejects_entrada_para_with_dot() {
8608 // An `:entrada :para` value is a single DNS-1123 *label*, not
8609 // a subdomain — mirroring the `:membros :caixa` floor. The
8610 // strictest floor among the use sites wins.
8611 let mut s = three_member_spec();
8612 s.entrada.as_mut().unwrap().para = "team.cart".into();
8613 let err = s.validate().unwrap_err();
8614 assert!(
8615 matches!(
8616 err,
8617 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8618 if para == "team.cart" && reason.contains('.')
8619 ),
8620 "got {err:?}"
8621 );
8622 }
8623
8624 #[test]
8625 fn rejects_entrada_para_with_unicode() {
8626 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8627 // (`xn--…`) before it reaches K8s.
8628 let mut s = three_member_spec();
8629 s.entrada.as_mut().unwrap().para = "café".into();
8630 let err = s.validate().unwrap_err();
8631 assert!(
8632 matches!(
8633 err,
8634 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
8635 ),
8636 "got {err:?}"
8637 );
8638 }
8639
8640 #[test]
8641 fn rejects_entrada_para_with_leading_hyphen() {
8642 // DNS-1123 boundary rule: labels must start and end with an
8643 // alphanumeric. K8s rejects `-cart` outright.
8644 let mut s = three_member_spec();
8645 s.entrada.as_mut().unwrap().para = "-cart".into();
8646 let err = s.validate().unwrap_err();
8647 assert!(
8648 matches!(
8649 err,
8650 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8651 if para == "-cart" && reason.contains("start and end")
8652 ),
8653 "got {err:?}"
8654 );
8655 }
8656
8657 #[test]
8658 fn rejects_entrada_para_with_trailing_hyphen() {
8659 // Symmetric boundary arm.
8660 let mut s = three_member_spec();
8661 s.entrada.as_mut().unwrap().para = "cart-".into();
8662 let err = s.validate().unwrap_err();
8663 assert!(
8664 matches!(
8665 err,
8666 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8667 if para == "cart-" && reason.contains("start and end")
8668 ),
8669 "got {err:?}"
8670 );
8671 }
8672
8673 #[test]
8674 fn rejects_entrada_para_too_long() {
8675 // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
8676 // bytes per label. K8s rejects longer names at admission on
8677 // every `metadata.name` axis.
8678 let mut s = three_member_spec();
8679 s.entrada.as_mut().unwrap().para = "a".repeat(64);
8680 let err = s.validate().unwrap_err();
8681 assert!(
8682 matches!(
8683 err,
8684 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
8685 if para.len() == 64 && reason.contains("max length")
8686 ),
8687 "got {err:?}"
8688 );
8689 }
8690
8691 #[test]
8692 fn entrada_para_empty_takes_precedence_over_invalid() {
8693 // Order pin: the `EntradaParaEmpty` arm fires before the
8694 // `EntradaParaInvalid` parse-side arm — same empty-first
8695 // cascade `validate_membro_caixa` / `validate_placement_cluster`
8696 // / `validate_contrato_caixa` already establish.
8697 let mut s = three_member_spec();
8698 s.entrada.as_mut().unwrap().para = String::new();
8699 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
8700 }
8701
8702 #[test]
8703 fn entrada_para_shape_fires_before_membership_lookup() {
8704 // The load-bearing pin: an invalid-shape `:para` surfaces its
8705 // *own* diagnostic, not the misframed `EntradaMemberMissing`.
8706 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8707 // an invalid-shape `:para` could never legitimately match any
8708 // member — the prior `EntradaMemberMissing` diagnostic framed
8709 // a structural impossibility as a graph-membership failure.
8710 let mut s = three_member_spec();
8711 s.entrada.as_mut().unwrap().para = "Cart".into();
8712 let err = s.validate().unwrap_err();
8713 assert!(
8714 matches!(
8715 err,
8716 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
8717 ),
8718 "got {err:?}"
8719 );
8720 }
8721
8722 #[test]
8723 fn entrada_para_shape_fires_before_host_gate() {
8724 // Per-`:entrada` order pin: the `:para` shape gate fires
8725 // before the `:host` gate, mirroring the existing
8726 // `entrada_host_member_missing_takes_precedence_over_host_invalid`
8727 // ordering where the member-lookup arm preceded the host gate.
8728 // The shape gate slots ahead of that, so a malformed `:para`
8729 // surfaces its own diagnostic even when `:host` is also wrong.
8730 let mut s = three_member_spec();
8731 let e = s.entrada.as_mut().unwrap();
8732 e.para = "Cart".into();
8733 e.host = "BAD HOST".into();
8734 let err = s.validate().unwrap_err();
8735 assert!(
8736 matches!(
8737 err,
8738 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
8739 ),
8740 "got {err:?}"
8741 );
8742 }
8743
8744 #[test]
8745 fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
8746 // Strict-improvement pin: a well-shaped `:para` that simply
8747 // isn't in `:membros` (a phantom reference — author meant to
8748 // add the member but didn't, or renamed and missed an
8749 // update) still surfaces `EntradaMemberMissing`, unchanged.
8750 // The shape gate only intercepts inputs that could never
8751 // legitimately match a validated member.
8752 let mut s = three_member_spec();
8753 s.entrada.as_mut().unwrap().para = "phantom-shim".into();
8754 let err = s.validate().unwrap_err();
8755 assert!(
8756 matches!(
8757 err,
8758 AplicacaoError::EntradaMemberMissing { ref para }
8759 if para == "phantom-shim"
8760 ),
8761 "got {err:?}"
8762 );
8763 }
8764
8765 #[test]
8766 fn entrada_para_invalid_diagnostic_carries_offending_para() {
8767 // The diagnostic-shape pin: the error names the offending
8768 // `:para` value verbatim plus a non-empty parser-shaped
8769 // reason, so the author can grep their caixa.lisp for
8770 // `:para "<name>"` and fix it in one edit. Same diagnostic
8771 // shape as `MembroCaixaInvalid` (3f9d7a0),
8772 // `PlacementClusterInvalid` (6c8c00b), and
8773 // `ContratoCaixaInvalid` (8d5af6b).
8774 let mut s = three_member_spec();
8775 s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
8776 let err = s.validate().unwrap_err();
8777 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
8778 panic!("expected EntradaParaInvalid, got {err:?}");
8779 };
8780 assert_eq!(para, "BAD_NAME");
8781 assert!(
8782 !reason.is_empty(),
8783 "EntradaParaInvalid `reason` must carry a parser-shaped wording"
8784 );
8785 }
8786
8787 #[test]
8788 fn accepts_canonical_entrada_para_forms() {
8789 // Positive-control sweep covering the DNS-1123 label shapes a
8790 // caixa author is realistically going to write on `:entrada
8791 // :para`. Pin every leg so a future tightening that bans
8792 // (e.g.) digit-start identifiers surfaces here, mirroring
8793 // `accepts_canonical_membro_caixa_forms` and
8794 // `accepts_canonical_contrato_caixa_forms` on the peer name
8795 // axes.
8796 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
8797 let mut s = three_member_spec();
8798 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
8799 s.contratos = vec![contract_http(form, "catalog", "/x")];
8800 s.entrada = Some(Entrada {
8801 host: "checkout.quero.cloud".into(),
8802 para: form.into(),
8803 paths: vec!["/api".into()],
8804 port: 8080,
8805 });
8806 s.validate().unwrap_or_else(|e| {
8807 panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
8808 });
8809 }
8810 }
8811
8812 #[test]
8813 fn rejects_replicated_without_clusters() {
8814 let mut s = three_member_spec();
8815 s.placement.clusters = vec![];
8816 assert!(matches!(
8817 s.validate().unwrap_err(),
8818 AplicacaoError::PlacementWithoutClusters { .. }
8819 ));
8820 }
8821
8822 #[test]
8823 fn rejects_sharded_without_key() {
8824 let mut s = three_member_spec();
8825 s.placement.estrategia = PlacementStrategy::Sharded;
8826 s.placement.shard_key = None;
8827 s.placement.clusters = vec!["rio".into()];
8828 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
8829 }
8830
8831 #[test]
8832 fn sharded_with_key_validates() {
8833 let mut s = three_member_spec();
8834 s.placement.estrategia = PlacementStrategy::Sharded;
8835 s.placement.shard_key = Some("$tenantId".into());
8836 s.validate().unwrap();
8837 }
8838
8839 #[test]
8840 fn round_trip_via_json_preserves_shape() {
8841 let s = three_member_spec();
8842 let json = serde_json::to_string(&s.membros).unwrap();
8843 let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
8844 assert_eq!(back, s.membros);
8845
8846 let json = serde_json::to_string(&s.contratos).unwrap();
8847 let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
8848 assert_eq!(back, s.contratos);
8849
8850 let json = serde_json::to_string(&s.placement).unwrap();
8851 let back: Placement = serde_json::from_str(&json).unwrap();
8852 assert_eq!(back, s.placement);
8853
8854 let json = serde_json::to_string(&s.entrada).unwrap();
8855 let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
8856 assert_eq!(back, s.entrada);
8857 }
8858
8859 #[test]
8860 fn rate_limit_round_trip_seconds() {
8861 let policy = MeshPolicy {
8862 rate_limit: Some(RateLimit {
8863 rate: 100,
8864 window: Duration::from_secs(1),
8865 }),
8866 ..Default::default()
8867 };
8868 let json = serde_json::to_string(&policy).unwrap();
8869 assert!(json.contains("\"100/s\""));
8870 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
8871 assert_eq!(back.rate_limit.unwrap().rate, 100);
8872 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
8873 }
8874
8875 #[test]
8876 fn rate_limit_round_trip_minutes() {
8877 let policy = MeshPolicy {
8878 rate_limit: Some(RateLimit {
8879 rate: 5000,
8880 window: Duration::from_secs(60),
8881 }),
8882 ..Default::default()
8883 };
8884 let json = serde_json::to_string(&policy).unwrap();
8885 assert!(json.contains("\"5000/m\""));
8886 }
8887
8888 #[test]
8889 fn circuit_breaker_round_trip() {
8890 let policy = MeshPolicy {
8891 circuit_breaker: Some(CircuitBreaker {
8892 max_failures: 5,
8893 window: Duration::from_secs(60),
8894 }),
8895 ..Default::default()
8896 };
8897 let json = serde_json::to_string(&policy).unwrap();
8898 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
8899 assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
8900 assert_eq!(
8901 back.circuit_breaker.unwrap().window,
8902 Duration::from_secs(60)
8903 );
8904 }
8905
8906 #[test]
8907 fn rejects_http_contrato_without_endpoint() {
8908 let mut s = three_member_spec();
8909 s.contratos.push(WitContract {
8910 de: "cart".into(),
8911 para: "catalog".into(),
8912 wit: "wasi:http/proxy".into(),
8913 endpoint: None,
8914 subject: None,
8915 slot: None,
8916 });
8917 let err = s.validate().unwrap_err();
8918 assert!(matches!(
8919 err,
8920 AplicacaoError::ContratoMissingTarget {
8921 expected: WitTarget::HTTP_FIELD_NAME,
8922 ..
8923 }
8924 ));
8925 }
8926
8927 #[test]
8928 fn rejects_http_contrato_with_subject() {
8929 let mut s = three_member_spec();
8930 s.contratos.push(WitContract {
8931 de: "cart".into(),
8932 para: "catalog".into(),
8933 wit: "wasi:http/proxy".into(),
8934 endpoint: Some("/x".into()),
8935 subject: Some("not.allowed.here".into()),
8936 slot: None,
8937 });
8938 let err = s.validate().unwrap_err();
8939 assert!(matches!(
8940 err,
8941 AplicacaoError::ContratoWrongTarget {
8942 expected: WitTarget::HTTP_FIELD_NAME,
8943 ..
8944 }
8945 ));
8946 }
8947
8948 #[test]
8949 fn rejects_pubsub_contrato_without_subject() {
8950 let mut s = three_member_spec();
8951 s.contratos.push(WitContract {
8952 de: "cart".into(),
8953 para: "catalog".into(),
8954 wit: "nats:pub-sub".into(),
8955 endpoint: None,
8956 subject: None,
8957 slot: None,
8958 });
8959 let err = s.validate().unwrap_err();
8960 assert!(matches!(
8961 err,
8962 AplicacaoError::ContratoMissingTarget {
8963 expected: WitTarget::PUBSUB_FIELD_NAME,
8964 ..
8965 }
8966 ));
8967 }
8968
8969 #[test]
8970 fn rejects_pubsub_contrato_with_endpoint() {
8971 let mut s = three_member_spec();
8972 s.contratos.push(WitContract {
8973 de: "cart".into(),
8974 para: "catalog".into(),
8975 wit: "kafka:topic".into(),
8976 endpoint: Some("/wrong".into()),
8977 subject: Some("topic.x".into()),
8978 slot: None,
8979 });
8980 let err = s.validate().unwrap_err();
8981 assert!(matches!(
8982 err,
8983 AplicacaoError::ContratoWrongTarget {
8984 expected: WitTarget::PUBSUB_FIELD_NAME,
8985 ..
8986 }
8987 ));
8988 }
8989
8990 #[test]
8991 fn rejects_store_contrato_without_slot() {
8992 let mut s = three_member_spec();
8993 s.contratos.push(WitContract {
8994 de: "cart".into(),
8995 para: "catalog".into(),
8996 wit: "wasi:keyvalue/store".into(),
8997 endpoint: None,
8998 subject: None,
8999 slot: None,
9000 });
9001 let err = s.validate().unwrap_err();
9002 assert!(matches!(
9003 err,
9004 AplicacaoError::ContratoMissingTarget {
9005 expected: WitTarget::STORE_FIELD_NAME,
9006 ..
9007 }
9008 ));
9009 }
9010
9011 // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
9012
9013 #[test]
9014 fn rejects_http_contrato_with_empty_endpoint() {
9015 // `Some("")` for an HTTP endpoint passes the presence check
9016 // (target() previously returned WitTarget::Http { endpoint: "" })
9017 // but renders as a `path: ""` Cilium L7 rule that matches no
9018 // traffic. Same value-shape footgun closed for :entrada :paths
9019 // entries (eb3456d).
9020 let mut s = three_member_spec();
9021 s.contratos.push(WitContract {
9022 de: "cart".into(),
9023 para: "catalog".into(),
9024 wit: "wasi:http/proxy".into(),
9025 endpoint: Some(String::new()),
9026 subject: None,
9027 slot: None,
9028 });
9029 let err = s.validate().unwrap_err();
9030 assert!(
9031 matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
9032 if de == "cart" && para == "catalog"),
9033 "got {err:?}"
9034 );
9035 }
9036
9037 #[test]
9038 fn rejects_http_contrato_with_relative_endpoint() {
9039 // Cilium L7 :path + Gateway API PathPrefix both require a
9040 // leading `/`. Same shape required of :entrada :paths
9041 // (eb3456d). Lifted into target() so every consumer of the
9042 // typed WitTarget view inherits the guarantee.
9043 let mut s = three_member_spec();
9044 s.contratos.push(WitContract {
9045 de: "cart".into(),
9046 para: "catalog".into(),
9047 wit: "wasi:http/proxy".into(),
9048 endpoint: Some("products/:id".into()),
9049 subject: None,
9050 slot: None,
9051 });
9052 let err = s.validate().unwrap_err();
9053 assert!(
9054 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9055 if endpoint == "products/:id"),
9056 "got {err:?}"
9057 );
9058 }
9059
9060 #[test]
9061 fn rejects_pubsub_contrato_with_empty_subject() {
9062 // NATS / Kafka publish without a subject is a no-op subscribe;
9063 // never the author's intent. Same empty-string rejection as
9064 // :membros :caixa, :placement :clusters entries, :entrada
9065 // :paths entries — every value carried by every typed slot is
9066 // value-shape-checked at validate().
9067 let mut s = three_member_spec();
9068 s.contratos.push(WitContract {
9069 de: "cart".into(),
9070 para: "catalog".into(),
9071 wit: "nats:pub-sub".into(),
9072 endpoint: None,
9073 subject: Some(String::new()),
9074 slot: None,
9075 });
9076 let err = s.validate().unwrap_err();
9077 assert!(
9078 matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
9079 if de == "cart" && para == "catalog"),
9080 "got {err:?}"
9081 );
9082 }
9083
9084 #[test]
9085 fn rejects_store_contrato_with_empty_slot() {
9086 // An empty slot template addresses the bucket root, defeating
9087 // the per-key isolation the slot exists for — a footgun on
9088 // `wasi:keyvalue/store` whose closest analog is the empty
9089 // shard-key rejected on :placement Sharded (c7c7799).
9090 let mut s = three_member_spec();
9091 s.contratos.push(WitContract {
9092 de: "cart".into(),
9093 para: "catalog".into(),
9094 wit: "wasi:keyvalue/store".into(),
9095 endpoint: None,
9096 subject: None,
9097 slot: Some(String::new()),
9098 });
9099 let err = s.validate().unwrap_err();
9100 assert!(
9101 matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
9102 if de == "cart" && para == "catalog"),
9103 "got {err:?}"
9104 );
9105 }
9106
9107 #[test]
9108 fn http_contrato_root_endpoint_validates() {
9109 // Pin the boundary case: a single-`/` endpoint is the catch-all
9110 // form the Gateway HTTPRoute renderer falls back to when
9111 // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
9112 // must remain a valid contrato endpoint too.
9113 let mut s = three_member_spec();
9114 s.contratos.push(contract_http("cart", "catalog", "/"));
9115 s.validate().unwrap();
9116 }
9117
9118 // ── :contratos :endpoint value-shape gate ────────────────────────────
9119 //
9120 // Mirrors the `:entrada :paths` value-shape suite on the peer
9121 // HTTP-path axis. Until this gate landed `WitContract::target()`
9122 // only refused the empty string + the missing-leading-`/` form
9123 // (c4213a4); a structurally invalid endpoint passed validate and
9124 // landed verbatim as a Cilium L7 `path:` rule
9125 // (caixa-mesh/src/lib.rs:311) that either silently dropped all
9126 // traffic or was rejected at apply time by Cilium policy admission.
9127 // Every authoring footgun the K8s Gateway API webhook / Cilium
9128 // policy validator would catch on admission now becomes a caixa-
9129 // build-time `ContratoEndpointInvalid` with the offending
9130 // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
9131 // shape as `EntradaPathInvalid` on the sibling axis; same shared
9132 // predicate (`crate::render::is_gateway_api_http_path`) ensures
9133 // drift between the two axes' rule enforcement is a build error
9134 // at the predicate.
9135
9136 fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
9137 // Fresh spec per call so the would-be-duplicate edge
9138 // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
9139 // `three_member_spec`'s pre-existing
9140 // `(cart, catalog, …, /products/:id)` entry — only the
9141 // endpoint payload differs.
9142 let mut s = three_member_spec();
9143 s.contratos.push(contract_http("cart", "catalog", ep));
9144 s.validate().unwrap_err()
9145 }
9146
9147 #[test]
9148 fn rejects_http_contrato_endpoint_with_query() {
9149 // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
9150 // silently rendered as a Cilium L7 `path: "/charge?token=X"`
9151 // rule the L7 matcher would never satisfy.
9152 let err = contrato_endpoint_err("/charge?token=X");
9153 assert!(
9154 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9155 if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
9156 "got {err:?}"
9157 );
9158 }
9159
9160 #[test]
9161 fn rejects_http_contrato_endpoint_with_fragment() {
9162 let err = contrato_endpoint_err("/charge#frag");
9163 assert!(
9164 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9165 if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
9166 "got {err:?}"
9167 );
9168 }
9169
9170 #[test]
9171 fn rejects_http_contrato_endpoint_with_whitespace() {
9172 let err = contrato_endpoint_err("/foo bar");
9173 assert!(
9174 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9175 if endpoint == "/foo bar" && reason.contains("whitespace")),
9176 "got {err:?}"
9177 );
9178 }
9179
9180 #[test]
9181 fn rejects_http_contrato_endpoint_with_control_char() {
9182 let err = contrato_endpoint_err("/api/\x01bar");
9183 assert!(
9184 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9185 if endpoint == "/api/\x01bar" && reason.contains("control character")),
9186 "got {err:?}"
9187 );
9188 }
9189
9190 #[test]
9191 fn rejects_http_contrato_endpoint_with_non_ascii() {
9192 let err = contrato_endpoint_err("/api/café");
9193 assert!(
9194 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9195 if endpoint == "/api/café" && reason.contains("non-ASCII")),
9196 "got {err:?}"
9197 );
9198 }
9199
9200 #[test]
9201 fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
9202 let err = contrato_endpoint_err("/api//cart");
9203 assert!(
9204 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9205 if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
9206 "got {err:?}"
9207 );
9208 }
9209
9210 #[test]
9211 fn rejects_http_contrato_endpoint_with_dot_segment() {
9212 let err = contrato_endpoint_err("/api/./cart");
9213 assert!(
9214 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9215 if endpoint == "/api/./cart" && reason.contains("`.` segment")),
9216 "got {err:?}"
9217 );
9218 }
9219
9220 #[test]
9221 fn rejects_http_contrato_endpoint_with_parent_segment() {
9222 // Path-traversal in a contrato endpoint is the canonical
9223 // "L7 rule that the workload's HTTP server's path-resolution
9224 // logic interprets differently than the policy enforcer"
9225 // footgun. Rejected outright at validate time.
9226 let err = contrato_endpoint_err("/api/../etc");
9227 assert!(
9228 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9229 if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
9230 "got {err:?}"
9231 );
9232 }
9233
9234 #[test]
9235 fn rejects_http_contrato_endpoint_too_long() {
9236 // 1025-byte endpoint — one over the Gateway API
9237 // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
9238 // path matcher has no inherent length limit but the policy
9239 // CR itself rides through the K8s apiserver, which enforces
9240 // ConfigMap-shaped limits; sharing the Gateway API cap is the
9241 // conservative floor.
9242 let big = format!("/api/{}", "a".repeat(1020));
9243 assert_eq!(big.len(), 1025);
9244 let err = contrato_endpoint_err(&big);
9245 assert!(
9246 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9247 if endpoint == &big && reason.contains("max length of 1024")),
9248 "got {err:?}"
9249 );
9250 }
9251
9252 #[test]
9253 fn http_contrato_endpoint_max_length_validates() {
9254 // 1024-byte endpoint — exactly the cap. Boundary pin: drift
9255 // in the cap surfaces here and at
9256 // `rejects_http_contrato_endpoint_too_long` simultaneously,
9257 // mirroring `entrada_path_max_length_validates` on the peer
9258 // axis.
9259 let big = format!("/api/{}", "a".repeat(1019));
9260 assert_eq!(big.len(), 1024);
9261 let mut s = three_member_spec();
9262 s.contratos.push(contract_http("cart", "catalog", &big));
9263 s.validate().unwrap();
9264 }
9265
9266 #[test]
9267 fn http_contrato_endpoint_accepts_canonical_forms() {
9268 // Positive-set sweep: every canonical HTTP-path shape the
9269 // sibling `:entrada :paths` axis accepts (the bare-root `/`,
9270 // plain paths, hidden-file-style `.config` segments distinct
9271 // from the `.` segment, digit-bearing segments, the canonical
9272 // route-template `:param` form, trailing-slash form,
9273 // percent-encoded segments, the `/foo..bar` interior-`..`-
9274 // substring forms that are NOT `..` segments) must remain a
9275 // valid contrato endpoint too. Drift between this list and
9276 // the entrada path positive sweep surfaces at the shared
9277 // `is_gateway_api_http_path` substrate-side suite — one
9278 // source of truth. Uses a fresh `(payment, catalog)` edge so
9279 // none of the swept endpoints collide with the pre-existing
9280 // `(cart, catalog, /products/:id)` / `(cart, payment,
9281 // /charge)` entries in `three_member_spec`.
9282 for ep in [
9283 "/",
9284 "/charge",
9285 "/v1/charge",
9286 "/api/.config",
9287 "/products/:id",
9288 "/api/cart/",
9289 "/api/caf%C3%A9",
9290 "/foo..bar",
9291 "/...",
9292 ] {
9293 let mut s = three_member_spec();
9294 s.contratos.push(contract_http("payment", "catalog", ep));
9295 s.validate()
9296 .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
9297 }
9298 }
9299
9300 #[test]
9301 fn contrato_endpoint_empty_takes_precedence_over_invalid() {
9302 // Ordering pin: `ContratoEndpointEmpty` is the more self-
9303 // locating diagnostic on `""` and must lead — the value-
9304 // shape gate is only reached after the empty-check fires.
9305 // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
9306 // on the peer axis.
9307 let mut s = three_member_spec();
9308 s.contratos.push(WitContract {
9309 de: "cart".into(),
9310 para: "catalog".into(),
9311 wit: "wasi:http/proxy".into(),
9312 endpoint: Some(String::new()),
9313 subject: None,
9314 slot: None,
9315 });
9316 let err = s.validate().unwrap_err();
9317 assert!(
9318 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
9319 "got {err:?}"
9320 );
9321 }
9322
9323 #[test]
9324 fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
9325 // Ordering pin: an endpoint without a leading `/` surfaces the
9326 // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
9327 // value-shape gate is only consulted on endpoints that already
9328 // satisfy the absolute-prefix invariant. Mirrors
9329 // `entrada_path_not_absolute_takes_precedence_over_invalid`.
9330 let err = contrato_endpoint_err("bad path");
9331 assert!(
9332 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9333 if endpoint == "bad path"),
9334 "got {err:?}"
9335 );
9336 }
9337
9338 #[test]
9339 fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
9340 // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
9341 // `:para` + a non-empty reason flow through verbatim so the
9342 // author can grep their caixa.lisp for the offending contrato
9343 // block and fix it in one edit. Same shape as
9344 // `entrada_path_diagnostic_carries_offending_path`.
9345 let err = contrato_endpoint_err("/api?q=1");
9346 match err {
9347 AplicacaoError::ContratoEndpointInvalid {
9348 de,
9349 para,
9350 endpoint,
9351 reason,
9352 } => {
9353 assert_eq!(de, "cart");
9354 assert_eq!(para, "catalog");
9355 assert_eq!(endpoint, "/api?q=1");
9356 assert!(!reason.is_empty(), "reason field must be non-empty");
9357 }
9358 other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
9359 }
9360 }
9361
9362 #[test]
9363 fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
9364 // The compounding theorem: every &str inside a WitTarget
9365 // returned by target() is non-empty (and absolute, for Http).
9366 // Renderers downstream of typed_view() can rely on this
9367 // without re-checking — the type system carries the proof.
9368 let http = contract_http("cart", "catalog", "/x");
9369 match http.target().unwrap() {
9370 WitTarget::Http { endpoint } => {
9371 assert!(!endpoint.is_empty());
9372 assert!(endpoint.starts_with('/'));
9373 }
9374 other => panic!("expected Http, got {other:?}"),
9375 }
9376 let nats = WitContract {
9377 de: "a".into(),
9378 para: "b".into(),
9379 wit: "nats:pub-sub".into(),
9380 endpoint: None,
9381 subject: Some("topic.x".into()),
9382 slot: None,
9383 };
9384 match nats.target().unwrap() {
9385 WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
9386 other => panic!("expected PubSub, got {other:?}"),
9387 }
9388 let kv = WitContract {
9389 de: "a".into(),
9390 para: "b".into(),
9391 wit: "wasi:keyvalue/store".into(),
9392 endpoint: None,
9393 subject: None,
9394 slot: Some("checkout/$orderId".into()),
9395 };
9396 match kv.target().unwrap() {
9397 WitTarget::Store { slot } => assert!(!slot.is_empty()),
9398 other => panic!("expected Store, got {other:?}"),
9399 }
9400 }
9401
9402 #[test]
9403 fn target_diagnostic_names_offending_endpoint_value() {
9404 // When the malformed endpoint string is non-trivial, the
9405 // diagnostic carries the actual value back to the author —
9406 // not a generic "endpoint malformed" error.
9407 let bad = WitContract {
9408 de: "src".into(),
9409 para: "dst".into(),
9410 wit: "wasi:http/proxy".into(),
9411 endpoint: Some("api/v1/charge".into()),
9412 subject: None,
9413 slot: None,
9414 };
9415 match bad.target().unwrap_err() {
9416 AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
9417 assert_eq!(de, "src");
9418 assert_eq!(para, "dst");
9419 assert_eq!(endpoint, "api/v1/charge");
9420 }
9421 other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
9422 }
9423 }
9424
9425 #[test]
9426 fn rejects_unknown_wit_with_target_set() {
9427 let mut s = three_member_spec();
9428 s.contratos.push(WitContract {
9429 de: "cart".into(),
9430 para: "catalog".into(),
9431 wit: "custom:exchange".into(),
9432 endpoint: Some("/leaked".into()),
9433 subject: None,
9434 slot: None,
9435 });
9436 let err = s.validate().unwrap_err();
9437 assert!(matches!(
9438 err,
9439 AplicacaoError::ContratoWrongTarget {
9440 expected: WitTarget::CAPABILITY_EXPECTED,
9441 ..
9442 }
9443 ));
9444 }
9445
9446 #[test]
9447 fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
9448 // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
9449 // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
9450 // fourth arm of the same "which payload field name goes in the
9451 // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
9452 // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
9453 // consts cover on the peer HTTP / PubSub / Store arms
9454 // (`wit_target_field_name_pins_per_variant`). Until this lift
9455 // landed the byte-string sat twice — once inline in the
9456 // [`WitContract::target`] Capability-arm rejection at the
9457 // production dispatch, once in `rejects_unknown_wit_with_target_set`
9458 // pinning against the same literal — with no compile-time link
9459 // between them. Same "one canonical declaration, next to the
9460 // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
9461 // lift established for the payload-less arm's human-readable
9462 // label axis; this test is the shape peer of
9463 // `wit_target_label_pins_per_variant`'s Capability-arm assertion
9464 // pair (routes-through-const + scalar-value pin) on the
9465 // wrong-target diagnostic-scalar axis.
9466 //
9467 // Fail-before-pass-after was verified locally by mutating the
9468 // const declaration to `"capability"` — the scalar-value pin
9469 // below fires (`"capability" != "none"`) and the routes-through
9470 // assertion below still holds (production and const walk in
9471 // lockstep), which is the correct behavior: a rename on the
9472 // const drifts here first, not at a downstream consumer.
9473 assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
9474
9475 let mut s = three_member_spec();
9476 s.contratos.push(WitContract {
9477 de: "cart".into(),
9478 para: "catalog".into(),
9479 wit: "custom:exchange".into(),
9480 endpoint: Some("/leaked".into()),
9481 subject: None,
9482 slot: None,
9483 });
9484 match s.validate().unwrap_err() {
9485 AplicacaoError::ContratoWrongTarget { expected, .. } => {
9486 assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
9487 }
9488 other => panic!("expected ContratoWrongTarget, got {other:?}"),
9489 }
9490 }
9491
9492 #[test]
9493 fn unknown_wit_capability_only_validates() {
9494 let mut s = three_member_spec();
9495 s.contratos.push(WitContract {
9496 de: "cart".into(),
9497 para: "catalog".into(),
9498 // A WIT world we haven't yet shaped — accept it as a typed
9499 // capability edge so authors aren't blocked while the WIT
9500 // registry catches up. No payload field may be carried.
9501 wit: "custom:exchange".into(),
9502 endpoint: None,
9503 subject: None,
9504 slot: None,
9505 });
9506 s.validate().unwrap();
9507 let added = s.contratos.last().unwrap();
9508 assert_eq!(added.target().unwrap(), WitTarget::Capability);
9509 }
9510
9511 #[test]
9512 fn target_typed_view_round_trips_each_shape() {
9513 let http = contract_http("cart", "catalog", "/products/:id");
9514 assert_eq!(
9515 http.target().unwrap(),
9516 WitTarget::Http {
9517 endpoint: "/products/:id"
9518 }
9519 );
9520 let nats = WitContract {
9521 de: "a".into(),
9522 para: "b".into(),
9523 wit: "nats:pub-sub".into(),
9524 endpoint: None,
9525 subject: Some("topic.x".into()),
9526 slot: None,
9527 };
9528 assert_eq!(
9529 nats.target().unwrap(),
9530 WitTarget::PubSub { subject: "topic.x" }
9531 );
9532 let kv = WitContract {
9533 de: "a".into(),
9534 para: "b".into(),
9535 wit: "wasi:keyvalue/store".into(),
9536 endpoint: None,
9537 subject: None,
9538 slot: Some("checkout/$orderId".into()),
9539 };
9540 assert_eq!(
9541 kv.target().unwrap(),
9542 WitTarget::Store {
9543 slot: "checkout/$orderId"
9544 }
9545 );
9546 }
9547
9548 #[test]
9549 fn wit_contract_kind_predicates() {
9550 let http = contract_http("a", "b", "/x");
9551 assert!(http.is_http());
9552 assert!(!http.is_pubsub());
9553 assert!(!http.is_store());
9554
9555 let nats = WitContract {
9556 de: "a".into(),
9557 para: "b".into(),
9558 wit: "nats:pub-sub".into(),
9559 endpoint: None,
9560 subject: Some("topic.x".into()),
9561 slot: None,
9562 };
9563 assert!(nats.is_pubsub());
9564 assert!(!nats.is_http());
9565
9566 let kv = WitContract {
9567 de: "a".into(),
9568 para: "b".into(),
9569 wit: "wasi:keyvalue/store".into(),
9570 endpoint: None,
9571 subject: None,
9572 slot: Some("checkout/$orderId".into()),
9573 };
9574 assert!(kv.is_store());
9575 assert!(!kv.is_http());
9576 }
9577
9578 // ── :contratos :wit value-shape gate ─────────────────────────────────
9579 //
9580 // Mirrors the `:contratos :endpoint` value-shape suite on the peer
9581 // dispatch-discriminator axis. Until this gate landed
9582 // `WitContract::target()` accepted any non-empty string and
9583 // silently demoted unrecognized shapes to a capability-only L4
9584 // edge — the canonical "I thought I had L7 HTTP routing, got
9585 // L4-only" footgun. Every authoring footgun the WIT registry's
9586 // own grammar rejects (uppercase, hyphen-for-colon typo,
9587 // whitespace, empty package, doubled `@`, …) now becomes a
9588 // caixa-build-time `ContratoWitInvalid` with the offending
9589 // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
9590 // as `ContratoEndpointInvalid` on the sibling axis; same shared
9591 // predicate (`crate::render::is_wit_world_ref`) ensures drift
9592 // between any two axes' rule enforcement is a build error at the
9593 // predicate, not piecemeal across renderers.
9594
9595 fn contrato_wit_err(wit: &str) -> AplicacaoError {
9596 // Fresh spec per call so the new contract doesn't collide on
9597 // identity with `three_member_spec`'s pre-existing entries.
9598 // The new edge uses `(payment, catalog)` — a pair the fixture
9599 // doesn't already declare — with no payload field set, so the
9600 // wit-shape gate fires before any payload-shape arm.
9601 let mut s = three_member_spec();
9602 s.contratos.push(WitContract {
9603 de: "payment".into(),
9604 para: "catalog".into(),
9605 wit: wit.into(),
9606 endpoint: None,
9607 subject: None,
9608 slot: None,
9609 });
9610 s.validate().unwrap_err()
9611 }
9612
9613 #[test]
9614 fn rejects_wit_with_uppercase_namespace() {
9615 // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
9616 // didn't match the lowercase `wasi:http/` prefix is_http() keys
9617 // off, so the dispatch fell through to the capability arm and
9618 // the contract silently rendered as an L4-only Cilium edge.
9619 // The new gate surfaces the uppercase typo at validate time
9620 // with the offending `:wit` named.
9621 let err = contrato_wit_err("WASI:http/proxy");
9622 assert!(
9623 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9624 if wit == "WASI:http/proxy" && reason.contains("lowercase")),
9625 "got {err:?}"
9626 );
9627 }
9628
9629 #[test]
9630 fn rejects_wit_with_hyphen_for_colon_typo() {
9631 // The canonical "I forgot the `:` separator" typo — pre-gate
9632 // this passed as Capability silently, so the renderer emitted
9633 // an L4-only policy where the author expected L7 HTTP rules.
9634 let err = contrato_wit_err("wasi-http/proxy");
9635 assert!(
9636 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9637 if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
9638 "got {err:?}"
9639 );
9640 }
9641
9642 #[test]
9643 fn rejects_wit_with_multiple_colons() {
9644 // Doubled `:` — the namespace/package split has nowhere to
9645 // anchor, so the dispatch silently demotes to Capability.
9646 let err = contrato_wit_err("wasi:http:proxy");
9647 assert!(
9648 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9649 if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
9650 "got {err:?}"
9651 );
9652 }
9653
9654 #[test]
9655 fn rejects_wit_with_empty_package() {
9656 // `wasi:` — namespace alone with no package. Pre-gate this
9657 // failed neither the is_http nor is_pubsub nor is_store
9658 // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
9659 // a bare `wasi:`), so it silently demoted to Capability.
9660 let err = contrato_wit_err("wasi:");
9661 assert!(
9662 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9663 if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
9664 "got {err:?}"
9665 );
9666 }
9667
9668 #[test]
9669 fn rejects_wit_with_underscore() {
9670 // Underscore — WIT identifiers are kebab-case, same rule
9671 // DNS-1123 enforces on its peer axes. The diagnostic carries
9672 // the explicit "use `-` instead" remediation.
9673 let err = contrato_wit_err("wasi:http_proxy");
9674 assert!(
9675 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9676 if wit == "wasi:http_proxy" && reason.contains('_')),
9677 "got {err:?}"
9678 );
9679 }
9680
9681 #[test]
9682 fn rejects_wit_with_whitespace() {
9683 // Whitespace mid-token — the prefix check matches but the
9684 // package-and-onward parse silently demoted to Capability.
9685 let err = contrato_wit_err("wasi:http proxy");
9686 assert!(
9687 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9688 if wit == "wasi:http proxy" && reason.contains("whitespace")),
9689 "got {err:?}"
9690 );
9691 }
9692
9693 #[test]
9694 fn rejects_wit_with_non_ascii() {
9695 // Un-percent-encoded non-ASCII byte — the canonical "I copied
9696 // the package name from a doc with smart quotes / accented
9697 // characters" footgun.
9698 let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
9699 assert!(
9700 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9701 if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
9702 "got {err:?}"
9703 );
9704 }
9705
9706 #[test]
9707 fn rejects_wit_with_consecutive_hyphens() {
9708 // `pub--sub` — WIT identifiers join words with single hyphens.
9709 let err = contrato_wit_err("nats:pub--sub");
9710 assert!(
9711 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9712 if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
9713 "got {err:?}"
9714 );
9715 }
9716
9717 #[test]
9718 fn rejects_wit_with_trailing_at_no_version() {
9719 // `wasi:http/proxy@` — the version-suffix author started to
9720 // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
9721 // parser would reject this; surface it at validate time.
9722 let err = contrato_wit_err("wasi:http/proxy@");
9723 assert!(
9724 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9725 if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
9726 "got {err:?}"
9727 );
9728 }
9729
9730 #[test]
9731 fn rejects_wit_too_long() {
9732 // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
9733 // The legitimate-shape arms all pass (lowercase, single `:`,
9734 // kebab-case identifiers); only the cap arm fires. Surfaces
9735 // the paste-from-binary / accidental-multi-line-blob landing
9736 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
9737 // on the peer axis.
9738 let big = format!("wasi:{}", "a".repeat(124));
9739 assert_eq!(big.len(), 129);
9740 let err = contrato_wit_err(&big);
9741 assert!(
9742 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
9743 if wit == &big && reason.contains("max length of 128")),
9744 "got {err:?}"
9745 );
9746 }
9747
9748 #[test]
9749 fn wit_max_length_validates() {
9750 // 128-byte WIT reference — exactly the cap. Boundary pin:
9751 // drift in the cap surfaces here and at `rejects_wit_too_long`
9752 // simultaneously, mirroring
9753 // `http_contrato_endpoint_max_length_validates` on the peer
9754 // axis.
9755 let big = format!("wasi:{}", "a".repeat(123));
9756 assert_eq!(big.len(), 128);
9757 let mut s = three_member_spec();
9758 s.contratos.push(WitContract {
9759 de: "payment".into(),
9760 para: "catalog".into(),
9761 wit: big,
9762 endpoint: None,
9763 subject: None,
9764 slot: None,
9765 });
9766 s.validate().unwrap();
9767 }
9768
9769 #[test]
9770 fn wit_accepts_canonical_forms_at_aplicacao_layer() {
9771 // Positive-set sweep through the AplicacaoSpec::validate
9772 // surface (rather than the substrate-side predicate directly)
9773 // — pins every shape the existing test fixtures + the
9774 // checkout-aplicacao example carry, so the gate's accept-set
9775 // matches the substrate's emit-set. Drift between this list
9776 // and `render::tests::wit_world_ref_accepts_canonical_forms`
9777 // surfaces at the substrate layer's positive sweep — one
9778 // source of truth for the rule.
9779 for wit in [
9780 "wasi:http/proxy",
9781 "wasi:keyvalue/store",
9782 "nats:pub-sub",
9783 "kafka:topic",
9784 "custom:exchange",
9785 "pleme:cap/audit",
9786 "wasi:http/proxy@0.2.0",
9787 ] {
9788 // Payload field paired to the dispatched WIT shape so the
9789 // shape-↔-target arm doesn't fire instead of the wit-shape
9790 // arm we're exercising. Routes off the same
9791 // `wit_shape_is_http` / `wit_shape_is_pubsub` /
9792 // `wit_shape_is_store` free functions the production
9793 // `WitContract::is_http` / `is_pubsub` / `is_store`
9794 // methods delegate to (both consult the lifted
9795 // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
9796 // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
9797 // future prefix addition to the routing accept-set
9798 // reaches this test's payload-dispatch arm by
9799 // construction — no per-test-site drift can hide a
9800 // shape-→-target-slot mismatch that would silently
9801 // demote a canonical `:wit` value to the
9802 // `(None, None, None)` capability-only arm and let the
9803 // `AplicacaoSpec::validate` positive sweep pass on a
9804 // shape it should exercise as HTTP / pub-sub / store.
9805 let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
9806 (Some("/x".into()), None, None)
9807 } else if wit_shape_is_pubsub(wit) {
9808 (None, Some("topic.x".into()), None)
9809 } else if wit_shape_is_store(wit) {
9810 (None, None, Some("bucket/$key".into()))
9811 } else {
9812 (None, None, None)
9813 };
9814 let mut s = three_member_spec();
9815 s.contratos.push(WitContract {
9816 de: "payment".into(),
9817 para: "catalog".into(),
9818 wit: wit.into(),
9819 endpoint,
9820 subject,
9821 slot,
9822 });
9823 s.validate()
9824 .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
9825 }
9826 }
9827
9828 #[test]
9829 fn wit_shape_predicates_accept_canonical_prefix_set() {
9830 // Positive-set sweep pinning every prefix in
9831 // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
9832 // WIT_STORE_SHAPE_PREFIXES against the three free-function
9833 // dispatch predicates. The six prefixes are the load-bearing
9834 // routing keys the substrate's WIT-shape dispatch consults
9835 // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
9836 // key/value-store-slot admission); any drift between the
9837 // free-function accept-set and this list surfaces here
9838 // rather than at apply time as a silent
9839 // shape-→-capability-only demotion.
9840 assert!(wit_shape_is_http("wasi:http/proxy"));
9841 assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
9842 assert!(wit_shape_is_http("http:incoming"));
9843
9844 assert!(wit_shape_is_pubsub("nats:pub-sub"));
9845 assert!(wit_shape_is_pubsub("kafka:topic"));
9846
9847 assert!(wit_shape_is_store("wasi:keyvalue/store"));
9848 assert!(wit_shape_is_store("kv:cache/session"));
9849 }
9850
9851 #[test]
9852 fn wit_shape_predicates_reject_uncanonical_forms() {
9853 // Negative-set pin: the six canonical prefixes are
9854 // lowercase-only (mirrors the `is_wit_world_ref` substrate
9855 // predicate's lowercase invariant — see its docstring on the
9856 // "I thought I had L7 HTTP routing, got L4-only" footgun).
9857 // The empty string, an uppercase-prefixed form, a hyphen-
9858 // instead-of-colon typo, and a bare kebab identifier all miss
9859 // every shape arm — reachable-by-construction only via the
9860 // `is_wit_world_ref` gate that admission-checks the `:wit`
9861 // value first, but pinned here so any future
9862 // free-function change (e.g. a case-insensitive
9863 // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
9864 // this unit level.
9865 for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
9866 assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
9867 assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
9868 assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
9869 }
9870 }
9871
9872 #[test]
9873 fn wit_shape_predicates_partition_canonical_set() {
9874 // Every canonical prefix routes to exactly one shape arm —
9875 // the three prefix sets are pairwise disjoint. Pins the
9876 // routing property [`WitContract::target`] relies on: an
9877 // `is_http()` return of `true` guarantees `is_pubsub()` and
9878 // `is_store()` return `false`, so the shape-→-target-slot
9879 // dispatch (endpoint vs subject vs slot) is unambiguous.
9880 // Drift (e.g. a future `"kv:"` moved into the HTTP set
9881 // without removal from the store set) would silently route
9882 // one prefix to two arms and the first-matching-arm order
9883 // becomes load-bearing — this pin surfaces it as a build
9884 // error instead.
9885 for prefix in WIT_HTTP_SHAPE_PREFIXES {
9886 let sample = format!("{prefix}x");
9887 assert!(wit_shape_is_http(&sample));
9888 assert!(!wit_shape_is_pubsub(&sample));
9889 assert!(!wit_shape_is_store(&sample));
9890 }
9891 for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
9892 let sample = format!("{prefix}x");
9893 assert!(!wit_shape_is_http(&sample));
9894 assert!(wit_shape_is_pubsub(&sample));
9895 assert!(!wit_shape_is_store(&sample));
9896 }
9897 for prefix in WIT_STORE_SHAPE_PREFIXES {
9898 let sample = format!("{prefix}x");
9899 assert!(!wit_shape_is_http(&sample));
9900 assert!(!wit_shape_is_pubsub(&sample));
9901 assert!(wit_shape_is_store(&sample));
9902 }
9903 }
9904
9905 #[test]
9906 fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
9907 // Positive pin: [`wit_shape_matches`] is exactly the
9908 // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
9909 // parameterized on the accept-set. Two-prefix accept-set,
9910 // one-prefix accept-set, and empty accept-set (which must
9911 // reject everything, including the empty string — an empty
9912 // `any()` fold returns `false`) all pinned so a future
9913 // reimplementation that swaps `starts_with` for `contains`,
9914 // `==`, or a case-folded comparator surfaces at unit-test
9915 // time.
9916 let two = &["wasi:http/", "http:"];
9917 assert!(wit_shape_matches("wasi:http/proxy", two));
9918 assert!(wit_shape_matches("http:incoming", two));
9919 assert!(!wit_shape_matches("wasi:keyvalue/store", two));
9920
9921 let one = &["nats:"];
9922 assert!(wit_shape_matches("nats:pub-sub", one));
9923 assert!(!wit_shape_matches("kafka:topic", one));
9924
9925 // Empty accept-set matches nothing — the identity element
9926 // for the disjunctive `any()` fold across the prefix set.
9927 // Reachable via a future `wit_shape_is_<name>` const paired
9928 // to a still-empty prefix table on a nascent shape-arm draft.
9929 let empty: &[&str] = &[];
9930 assert!(!wit_shape_matches("wasi:http/proxy", empty));
9931 assert!(!wit_shape_matches("", empty));
9932
9933 // starts_with, not contains: a prefix embedded mid-string
9934 // never matches. Pins the routing invariant [`WitContract::target`]
9935 // relies on (an authored `:wit "custom:wasi:http/"` string
9936 // does not silently route through the HTTP arm just because
9937 // it happens to contain the canonical HTTP prefix).
9938 assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
9939 }
9940
9941 #[test]
9942 fn wit_shape_predicates_delegate_to_wit_shape_matches() {
9943 // Equivalence pin: each per-shape predicate is exactly
9944 // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
9945 // every canonical prefix + the empty string + one negative
9946 // sample against every peer so a future predicate that grew
9947 // its own inline `iter().any(starts_with)` (rather than
9948 // delegating through the lifted combinator) drifts loudly here
9949 // — the peer-const table's contents must agree with the
9950 // predicate's accept-set by construction.
9951 let samples = [
9952 String::new(),
9953 "wasi:http/proxy".to_string(),
9954 "http:incoming".to_string(),
9955 "nats:pub-sub".to_string(),
9956 "kafka:topic".to_string(),
9957 "wasi:keyvalue/store".to_string(),
9958 "kv:cache/session".to_string(),
9959 "custom-shape".to_string(),
9960 "WASI:HTTP/proxy".to_string(),
9961 ];
9962 for wit in &samples {
9963 assert_eq!(
9964 wit_shape_is_http(wit),
9965 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
9966 "wit_shape_is_http drifted from combinator on {wit:?}",
9967 );
9968 assert_eq!(
9969 wit_shape_is_pubsub(wit),
9970 wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
9971 "wit_shape_is_pubsub drifted from combinator on {wit:?}",
9972 );
9973 assert_eq!(
9974 wit_shape_is_store(wit),
9975 wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
9976 "wit_shape_is_store drifted from combinator on {wit:?}",
9977 );
9978 }
9979 }
9980
9981 #[test]
9982 fn wit_contract_shape_methods_delegate_to_free_functions() {
9983 // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
9984 // `is_store` are `&self` conveniences on top of the free
9985 // functions — for every canonical prefix the method's return
9986 // matches its free-function peer. Sweeps the union of the
9987 // three prefix sets so a future method that grew its own
9988 // inline prefix logic (rather than delegating) drifts loudly
9989 // here on the first prefix the free function accepts and the
9990 // method doesn't.
9991 for shape_set in [
9992 WIT_HTTP_SHAPE_PREFIXES,
9993 WIT_PUBSUB_SHAPE_PREFIXES,
9994 WIT_STORE_SHAPE_PREFIXES,
9995 ] {
9996 for prefix in shape_set {
9997 let c = WitContract {
9998 de: "cart".into(),
9999 para: "catalog".into(),
10000 wit: format!("{prefix}x"),
10001 endpoint: None,
10002 subject: None,
10003 slot: None,
10004 };
10005 assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
10006 assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
10007 assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
10008 }
10009 }
10010 }
10011
10012 #[test]
10013 fn empty_wit_takes_precedence_over_invalid() {
10014 // Ordering pin: `EmptyWit` is the more self-locating
10015 // diagnostic on `""` and must lead — the value-shape gate is
10016 // only reached after the empty-check fires. Mirrors
10017 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10018 // the peer payload axis.
10019 let mut s = three_member_spec();
10020 s.contratos.push(WitContract {
10021 de: "payment".into(),
10022 para: "catalog".into(),
10023 wit: String::new(),
10024 endpoint: None,
10025 subject: None,
10026 slot: None,
10027 });
10028 let err = s.validate().unwrap_err();
10029 assert!(
10030 matches!(err, AplicacaoError::EmptyWit { .. }),
10031 "got {err:?}"
10032 );
10033 }
10034
10035 #[test]
10036 fn wit_invalid_fires_before_payload_shape_arm() {
10037 // Ordering pin: a malformed `:wit` surfaces *its own*
10038 // diagnostic (which names the offending wit verbatim) before
10039 // any payload-field check — a contrato whose wit is
10040 // structurally invalid AND carries a wrong target field
10041 // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
10042 // because the dispatch on the wit is what decides which
10043 // payload field is "right" in the first place. Without this
10044 // ordering, the author would see "wrong target field" for a
10045 // wit that hasn't even been parsed, which doesn't name the
10046 // root cause.
10047 let mut s = three_member_spec();
10048 s.contratos.push(WitContract {
10049 de: "payment".into(),
10050 para: "catalog".into(),
10051 // Hyphen-for-colon typo + endpoint set: pre-gate this
10052 // raised `ContratoWrongTarget { expected: "none" }` (the
10053 // Capability arm rejecting the endpoint), masking the
10054 // real authoring mistake (the wit isn't `wasi:http/proxy`).
10055 wit: "wasi-http/proxy".into(),
10056 endpoint: Some("/x".into()),
10057 subject: None,
10058 slot: None,
10059 });
10060 let err = s.validate().unwrap_err();
10061 assert!(
10062 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
10063 if wit == "wasi-http/proxy"),
10064 "got {err:?}"
10065 );
10066 }
10067
10068 #[test]
10069 fn wit_invalid_diagnostic_carries_offending_wit() {
10070 // Diagnostic-shape pin — the offending `:wit` + `:de` +
10071 // `:para` + a non-empty reason flow through verbatim so the
10072 // author can grep their caixa.lisp for the offending contrato
10073 // block and fix it in one edit. Same shape as
10074 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
10075 let err = contrato_wit_err("WASI:HTTP/proxy");
10076 match err {
10077 AplicacaoError::ContratoWitInvalid {
10078 de,
10079 para,
10080 wit,
10081 reason,
10082 } => {
10083 assert_eq!(de, "payment");
10084 assert_eq!(para, "catalog");
10085 assert_eq!(wit, "WASI:HTTP/proxy");
10086 assert!(!reason.is_empty(), "reason field must be non-empty");
10087 }
10088 other => panic!("expected ContratoWitInvalid, got {other:?}"),
10089 }
10090 }
10091
10092 // ── :contratos :subject value-shape gate ─────────────────────────────
10093 //
10094 // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
10095 // suites on the peer payload axes. Until this gate landed
10096 // `WitContract::target()` only refused the empty string; a
10097 // structurally invalid subject silently passed validate and the
10098 // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
10099 // Subject'` on publish / subscribe, or as a silent message drop,
10100 // far from the source caixa.lisp. Every authoring footgun the
10101 // NATS server's subject parser would catch on admission now
10102 // becomes a caixa-build-time `ContratoSubjectInvalid` with the
10103 // offending `:subject` + `:de` + `:para` named verbatim. Same
10104 // diagnostic shape as `ContratoEndpointInvalid` /
10105 // `ContratoWitInvalid` on the peer payload axes; same shared
10106 // predicate (`crate::render::is_nats_subject`) ensures drift
10107 // between any two axes' rule enforcement is a build error at the
10108 // predicate, not piecemeal across renderers.
10109
10110 fn contrato_subject_err(subject: &str) -> AplicacaoError {
10111 // Fresh spec per call so the new contract doesn't collide on
10112 // identity with `three_member_spec`'s pre-existing entries.
10113 // The new edge uses `(payment, catalog)` — a pair the fixture
10114 // doesn't already declare — with `:wit "nats:pub-sub"` and the
10115 // varying `:subject`, so the subject-shape gate fires cleanly
10116 // after the wit-shape gate (which `"nats:pub-sub"` passes).
10117 let mut s = three_member_spec();
10118 s.contratos.push(WitContract {
10119 de: "payment".into(),
10120 para: "catalog".into(),
10121 wit: "nats:pub-sub".into(),
10122 endpoint: None,
10123 subject: Some(subject.into()),
10124 slot: None,
10125 });
10126 s.validate().unwrap_err()
10127 }
10128
10129 #[test]
10130 fn rejects_pubsub_contrato_subject_with_whitespace() {
10131 // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
10132 // landed at the NATS server as a malformed subject the parser
10133 // rejects with `-ERR 'Invalid Subject'`. Now caught at the
10134 // source caixa.lisp.
10135 let err = contrato_subject_err("foo bar");
10136 assert!(
10137 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10138 if subject == "foo bar" && reason.contains("whitespace")),
10139 "got {err:?}"
10140 );
10141 }
10142
10143 #[test]
10144 fn rejects_pubsub_contrato_subject_with_control_char() {
10145 let err = contrato_subject_err("foo\x01bar");
10146 assert!(
10147 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10148 if subject == "foo\x01bar" && reason.contains("control character")),
10149 "got {err:?}"
10150 );
10151 }
10152
10153 #[test]
10154 fn rejects_pubsub_contrato_subject_with_non_ascii() {
10155 // Un-percent-encoded non-ASCII byte — the canonical "I copied
10156 // the subject from a doc with smart quotes / accented
10157 // characters" footgun.
10158 let err = contrato_subject_err("foo.caf\u{e9}");
10159 assert!(
10160 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10161 if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
10162 "got {err:?}"
10163 );
10164 }
10165
10166 #[test]
10167 fn rejects_pubsub_contrato_subject_with_leading_dot() {
10168 // Empty leading token — NATS rejects.
10169 let err = contrato_subject_err(".foo");
10170 assert!(
10171 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10172 if subject == ".foo" && reason.contains("must not start with `.`")),
10173 "got {err:?}"
10174 );
10175 }
10176
10177 #[test]
10178 fn rejects_pubsub_contrato_subject_with_trailing_dot() {
10179 // Empty trailing token — NATS rejects. The remediation
10180 // (use `>` instead) is in the reason string.
10181 let err = contrato_subject_err("foo.");
10182 assert!(
10183 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10184 if subject == "foo." && reason.contains("must not end with `.`")),
10185 "got {err:?}"
10186 );
10187 }
10188
10189 #[test]
10190 fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
10191 // The canonical "I forgot to fill in the middle segment"
10192 // typo — `"foo..bar"`. NATS rejects empty tokens.
10193 let err = contrato_subject_err("foo..bar");
10194 assert!(
10195 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10196 if subject == "foo..bar" && reason.contains("consecutive `.`")),
10197 "got {err:?}"
10198 );
10199 }
10200
10201 #[test]
10202 fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
10203 // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
10204 // as the final segment. Pre-gate this passed as a typed edge
10205 // and surfaced at runtime as a NATS subscribe rejection.
10206 let err = contrato_subject_err("foo.>.bar");
10207 assert!(
10208 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10209 if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
10210 "got {err:?}"
10211 );
10212 }
10213
10214 #[test]
10215 fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
10216 // `foo*.bar` — NATS wildcards are standalone tokens. The
10217 // remediation is in the reason string.
10218 let err = contrato_subject_err("foo*.bar");
10219 assert!(
10220 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10221 if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
10222 "got {err:?}"
10223 );
10224 }
10225
10226 #[test]
10227 fn rejects_pubsub_contrato_subject_with_invalid_char() {
10228 // `foo,bar` — comma is not a valid NATS subject character.
10229 // Pinned separately from the wildcard arms so the invalid-
10230 // character diagnostic is in force.
10231 let err = contrato_subject_err("foo,bar");
10232 assert!(
10233 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10234 if subject == "foo,bar" && reason.contains("invalid character")),
10235 "got {err:?}"
10236 );
10237 }
10238
10239 #[test]
10240 fn rejects_pubsub_contrato_subject_too_long() {
10241 // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
10242 // The legitimate-shape arms all pass (one all-`a` token, no
10243 // `.`, no wildcards); only the cap arm fires. Surfaces the
10244 // paste-from-binary / accidental-multi-line-blob landing
10245 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10246 // on the peer axis.
10247 let big = "a".repeat(257);
10248 assert_eq!(big.len(), 257);
10249 let err = contrato_subject_err(&big);
10250 assert!(
10251 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
10252 if subject == &big && reason.contains("max length of 256")),
10253 "got {err:?}"
10254 );
10255 }
10256
10257 #[test]
10258 fn pubsub_contrato_subject_max_length_validates() {
10259 // 256-byte subject — exactly the cap. Boundary pin: drift in
10260 // the cap surfaces here and at
10261 // `rejects_pubsub_contrato_subject_too_long` simultaneously,
10262 // mirroring `http_contrato_endpoint_max_length_validates` and
10263 // `wit_max_length_validates` on the peer axes.
10264 let big = "a".repeat(256);
10265 assert_eq!(big.len(), 256);
10266 let mut s = three_member_spec();
10267 s.contratos.push(WitContract {
10268 de: "payment".into(),
10269 para: "catalog".into(),
10270 wit: "nats:pub-sub".into(),
10271 endpoint: None,
10272 subject: Some(big),
10273 slot: None,
10274 });
10275 s.validate().unwrap();
10276 }
10277
10278 #[test]
10279 fn pubsub_contrato_subject_accepts_canonical_forms() {
10280 // Positive-set sweep: every canonical NATS subject shape the
10281 // substrate-side `is_nats_subject` predicate accepts (the
10282 // multi-dot `events.order.charged`, the snake_case / kebab-
10283 // case / mixed-case tokens, the digit-bearing tokens, the
10284 // single-token wildcard `*` at every segment position, and
10285 // the trailing `>` multi-token wildcard) must remain a valid
10286 // contrato subject too. Drift between this list and the
10287 // substrate-side `nats_subject_accepts_canonical_forms` sweep
10288 // surfaces at the shared predicate — one source of truth.
10289 // Uses a fresh `(payment, catalog)` edge so none of the swept
10290 // subjects collide with the pre-existing entries in
10291 // `three_member_spec`.
10292 for subject in [
10293 "checkout.events.charge.failed",
10294 "rio.events.order.charged",
10295 "orders",
10296 "orders.123",
10297 "snake_case.token",
10298 "kebab-case.token",
10299 "MixedCase.Token",
10300 "orders.*.charged",
10301 "*.events.*",
10302 "orders.>",
10303 ] {
10304 let mut s = three_member_spec();
10305 s.contratos.push(WitContract {
10306 de: "payment".into(),
10307 para: "catalog".into(),
10308 wit: "nats:pub-sub".into(),
10309 endpoint: None,
10310 subject: Some(subject.into()),
10311 slot: None,
10312 });
10313 s.validate()
10314 .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
10315 }
10316 }
10317
10318 #[test]
10319 fn contrato_subject_empty_takes_precedence_over_invalid() {
10320 // Ordering pin: `ContratoSubjectEmpty` is the more self-
10321 // locating diagnostic on `""` and must lead — the value-shape
10322 // gate is only reached after the empty-check fires. Mirrors
10323 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10324 // the peer payload axis.
10325 let mut s = three_member_spec();
10326 s.contratos.push(WitContract {
10327 de: "payment".into(),
10328 para: "catalog".into(),
10329 wit: "nats:pub-sub".into(),
10330 endpoint: None,
10331 subject: Some(String::new()),
10332 slot: None,
10333 });
10334 let err = s.validate().unwrap_err();
10335 assert!(
10336 matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
10337 "got {err:?}"
10338 );
10339 }
10340
10341 #[test]
10342 fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
10343 // Diagnostic-shape pin — the offending `:subject` + `:de` +
10344 // `:para` + a non-empty reason flow through verbatim so the
10345 // author can grep their caixa.lisp for the offending contrato
10346 // block and fix it in one edit. Same shape as
10347 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10348 // and `wit_invalid_diagnostic_carries_offending_wit`.
10349 let err = contrato_subject_err("foo..bar");
10350 match err {
10351 AplicacaoError::ContratoSubjectInvalid {
10352 de,
10353 para,
10354 subject,
10355 reason,
10356 } => {
10357 assert_eq!(de, "payment");
10358 assert_eq!(para, "catalog");
10359 assert_eq!(subject, "foo..bar");
10360 assert!(!reason.is_empty(), "reason field must be non-empty");
10361 }
10362 other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
10363 }
10364 }
10365
10366 #[test]
10367 fn target_view_pubsub_subject_passes_through_to_typed_view() {
10368 // The compounding theorem on the pub-sub axis: every
10369 // `WitTarget::PubSub { subject }` returned by `target()` carries
10370 // a NATS-server-accepted subject. Renderers downstream of
10371 // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
10372 // NATS Stream/Consumer CR emitter, the future `feira app graph`
10373 // view's subject labeller) can rely on this without re-checking
10374 // — the type system carries the proof. Mirrors
10375 // `target_view_payload_is_guaranteed_nonempty_after_target_call`
10376 // on the peer axes.
10377 let nats = WitContract {
10378 de: "a".into(),
10379 para: "b".into(),
10380 wit: "nats:pub-sub".into(),
10381 endpoint: None,
10382 subject: Some("orders.events.*.charged".into()),
10383 slot: None,
10384 };
10385 match nats.target().unwrap() {
10386 WitTarget::PubSub { subject } => {
10387 assert_eq!(subject, "orders.events.*.charged");
10388 }
10389 other => panic!("expected PubSub, got {other:?}"),
10390 }
10391 }
10392
10393 // ── :contratos :slot value-shape gate ────────────────────────────────
10394 //
10395 // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
10396 // (63e18a0) value-shape suites on the peer payload axes. Until this
10397 // gate landed `WitContract::target()` only refused the empty string
10398 // for the Store arm; a structurally invalid slot (raw whitespace,
10399 // control character, non-ASCII byte, paste-from-binary multi-line
10400 // blob) silently passed validate and surfaced at runtime as a
10401 // per-backend kv write rejection or a silent next-read corruption,
10402 // far from the source caixa.lisp with no field naming which
10403 // `:contratos` edge carried the typo. Every authoring footgun the
10404 // kv backend intersection-floor would catch on write now becomes a
10405 // caixa-build-time `ContratoSlotInvalid` with the offending
10406 // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
10407 // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
10408 // peer payload axes; same shared predicate
10409 // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
10410 // any two axes' rule enforcement is a build error at the
10411 // predicate, not piecemeal across renderers. Closes the typed
10412 // payload-axis value-shape trajectory across all three legs of the
10413 // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
10414
10415 fn contrato_slot_err(slot: &str) -> AplicacaoError {
10416 // Fresh spec per call so the new contract doesn't collide on
10417 // identity with `three_member_spec`'s pre-existing entries
10418 // and doesn't close a synchronous cycle the cycle detector
10419 // would reject before the slot-shape gate fires. The new edge
10420 // uses `(payment, catalog)` — a pair the fixture doesn't
10421 // already declare in either direction (the fixture carries
10422 // `cart -> catalog` and `cart -> payment`, so `payment ->
10423 // catalog` doesn't form a cycle on the sync subgraph) — with
10424 // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
10425 // slot-shape gate fires cleanly after the wit-shape gate
10426 // (which `"wasi:keyvalue/store"` passes). Same edge pair the
10427 // peer `contrato_subject_err` helper uses (63e18a0).
10428 let mut s = three_member_spec();
10429 s.contratos.push(WitContract {
10430 de: "payment".into(),
10431 para: "catalog".into(),
10432 wit: "wasi:keyvalue/store".into(),
10433 endpoint: None,
10434 subject: None,
10435 slot: Some(slot.into()),
10436 });
10437 s.validate().unwrap_err()
10438 }
10439
10440 #[test]
10441 fn rejects_store_contrato_slot_with_whitespace() {
10442 // Fail-before-pass-after pin — pre-gate `"check out/$order"`
10443 // silently landed at the kv backend with whitespace whose
10444 // runtime behavior varies unpredictably across backends (etcd
10445 // accepts, Redis accepts then breaks on next CLI op, DynamoDB
10446 // rejects on write). Now caught at the source caixa.lisp.
10447 let err = contrato_slot_err("check out/$order");
10448 assert!(
10449 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10450 if slot == "check out/$order" && reason.contains("whitespace")),
10451 "got {err:?}"
10452 );
10453 }
10454
10455 #[test]
10456 fn rejects_store_contrato_slot_with_tab() {
10457 // Tab byte arm-pinned separately from the space arm so a
10458 // future relaxation that admits one but not the other surfaces
10459 // here.
10460 let err = contrato_slot_err("check\tout");
10461 assert!(
10462 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10463 if slot == "check\tout" && reason.contains("whitespace")),
10464 "got {err:?}"
10465 );
10466 }
10467
10468 #[test]
10469 fn rejects_store_contrato_slot_with_control_char() {
10470 // SOH (0x01) — distinct from the whitespace arm. Redis admits
10471 // and corrupts on RESP protocol framing; DynamoDB rejects on
10472 // write.
10473 let err = contrato_slot_err("checkout/\x01order");
10474 assert!(
10475 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10476 if slot == "checkout/\x01order" && reason.contains("control character")),
10477 "got {err:?}"
10478 );
10479 }
10480
10481 #[test]
10482 fn rejects_store_contrato_slot_with_newline() {
10483 // Embedded newline — the canonical "the paste-from-binary slug
10484 // spans multiple lines" footgun. Distinct from the whitespace
10485 // arm because `\n` is a control character (0x0A).
10486 let err = contrato_slot_err("checkout\norder");
10487 assert!(
10488 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10489 if slot == "checkout\norder" && reason.contains("control character")),
10490 "got {err:?}"
10491 );
10492 }
10493
10494 #[test]
10495 fn rejects_store_contrato_slot_with_non_ascii() {
10496 // Un-percent-encoded non-ASCII byte — the canonical "I copied
10497 // the slot from a doc with accented characters" footgun. Each
10498 // kv backend re-encodes non-ASCII differently (etcd preserves
10499 // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
10500 // rejects), so the typed slot's value set is the intersection-
10501 // floor every backend admits identically (printable ASCII).
10502 let err = contrato_slot_err("ch\u{e9}ckout/$order");
10503 assert!(
10504 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10505 if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
10506 "got {err:?}"
10507 );
10508 }
10509
10510 #[test]
10511 fn rejects_store_contrato_slot_too_long() {
10512 // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
10513 // legitimate-shape arms all pass (a single all-`a` token, no
10514 // separators); only the cap arm fires. Surfaces the paste-
10515 // from-binary / accidental-multi-line-blob landing footgun.
10516 // Mirrors `rejects_pubsub_contrato_subject_too_long` and
10517 // `rejects_http_contrato_endpoint_too_long` on the peer
10518 // payload axes.
10519 let big = "a".repeat(513);
10520 assert_eq!(big.len(), 513);
10521 let err = contrato_slot_err(&big);
10522 assert!(
10523 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
10524 if slot == &big && reason.contains("max length of 512")),
10525 "got {err:?}"
10526 );
10527 }
10528
10529 #[test]
10530 fn store_contrato_slot_max_length_validates() {
10531 // 512-byte slot — exactly the cap. Boundary pin: drift in the
10532 // cap surfaces here and at `rejects_store_contrato_slot_too_long`
10533 // simultaneously, mirroring
10534 // `pubsub_contrato_subject_max_length_validates` and
10535 // `http_contrato_endpoint_max_length_validates` on the peer
10536 // payload axes.
10537 let big = "a".repeat(512);
10538 assert_eq!(big.len(), 512);
10539 let mut s = three_member_spec();
10540 s.contratos.push(WitContract {
10541 de: "payment".into(),
10542 para: "catalog".into(),
10543 wit: "wasi:keyvalue/store".into(),
10544 endpoint: None,
10545 subject: None,
10546 slot: Some(big),
10547 });
10548 s.validate().unwrap();
10549 }
10550
10551 #[test]
10552 fn store_contrato_slot_accepts_canonical_forms() {
10553 // Positive-set sweep: every canonical kv slot template the
10554 // substrate-side `is_wasi_keyvalue_slot` predicate accepts
10555 // (single-token identifiers, path-namespaced `$`-templates,
10556 // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
10557 // snake_case / kebab-case / MixedCase tokens, digit-bearing
10558 // tokens, percent-encoded fragments) must remain valid
10559 // contrato slots too. Drift between this list and the
10560 // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
10561 // surfaces at the shared predicate — one source of truth.
10562 // Uses a fresh `(payment, catalog)` edge so none of the swept
10563 // slots collide with the pre-existing entries in
10564 // `three_member_spec`.
10565 for slot in [
10566 "checkout",
10567 "checkout/$orderId",
10568 "users:{tenant}/{id}",
10569 "session.<sid>",
10570 "session.tokens.<sid>",
10571 "snake_case_key",
10572 "kebab-case-key",
10573 "MixedCase",
10574 "shard0",
10575 "v2/key",
10576 "users/caf%C3%A9",
10577 ] {
10578 let mut s = three_member_spec();
10579 s.contratos.push(WitContract {
10580 de: "payment".into(),
10581 para: "catalog".into(),
10582 wit: "wasi:keyvalue/store".into(),
10583 endpoint: None,
10584 subject: None,
10585 slot: Some(slot.into()),
10586 });
10587 s.validate()
10588 .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
10589 }
10590 }
10591
10592 #[test]
10593 fn contrato_slot_empty_takes_precedence_over_invalid() {
10594 // Ordering pin: `ContratoSlotEmpty` is the more self-locating
10595 // diagnostic on `""` and must lead — the value-shape gate is
10596 // only reached after the empty-check fires. Mirrors
10597 // `contrato_subject_empty_takes_precedence_over_invalid` and
10598 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10599 // the peer payload axes.
10600 let mut s = three_member_spec();
10601 s.contratos.push(WitContract {
10602 de: "payment".into(),
10603 para: "catalog".into(),
10604 wit: "wasi:keyvalue/store".into(),
10605 endpoint: None,
10606 subject: None,
10607 slot: Some(String::new()),
10608 });
10609 let err = s.validate().unwrap_err();
10610 assert!(
10611 matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
10612 "got {err:?}"
10613 );
10614 }
10615
10616 #[test]
10617 fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
10618 // Diagnostic-shape pin — the offending `:slot` + `:de` +
10619 // `:para` + a non-empty reason flow through verbatim so the
10620 // author can grep their caixa.lisp for the offending contrato
10621 // block and fix it in one edit. Same shape as
10622 // `contrato_subject_invalid_diagnostic_carries_offending_subject`
10623 // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
10624 // on the peer payload axes.
10625 let err = contrato_slot_err("check out/$order");
10626 match err {
10627 AplicacaoError::ContratoSlotInvalid {
10628 de,
10629 para,
10630 slot,
10631 reason,
10632 } => {
10633 assert_eq!(de, "payment");
10634 assert_eq!(para, "catalog");
10635 assert_eq!(slot, "check out/$order");
10636 assert!(!reason.is_empty(), "reason field must be non-empty");
10637 }
10638 other => panic!("expected ContratoSlotInvalid, got {other:?}"),
10639 }
10640 }
10641
10642 #[test]
10643 fn target_view_store_slot_passes_through_to_typed_view() {
10644 // The compounding theorem on the store axis: every
10645 // `WitTarget::Store { slot }` returned by `target()` carries a
10646 // kv-backend-accepted slot template. Renderers downstream of
10647 // `typed_view()` (the future per-Servico `:capabilities
10648 // wasi:keyvalue/store` axis emitter, the future `feira app
10649 // graph` view's slot labeller, the future kv-provider CR
10650 // materializer) can rely on this without re-checking — the
10651 // type system carries the proof. Mirrors
10652 // `target_view_pubsub_subject_passes_through_to_typed_view` on
10653 // the peer payload axis.
10654 let store = WitContract {
10655 de: "a".into(),
10656 para: "b".into(),
10657 wit: "wasi:keyvalue/store".into(),
10658 endpoint: None,
10659 subject: None,
10660 slot: Some("checkout/$orderId".into()),
10661 };
10662 match store.target().unwrap() {
10663 WitTarget::Store { slot } => {
10664 assert_eq!(slot, "checkout/$orderId");
10665 }
10666 other => panic!("expected Store, got {other:?}"),
10667 }
10668 }
10669
10670 #[test]
10671 fn rejects_self_loop_in_synchronous_contratos() {
10672 // A synchronous self-edge (`cart → cart` over HTTP) is now
10673 // rejected by the dedicated `ContratoSelfLoop` gate — a precise
10674 // "this edge is degenerate" diagnostic — rather than incidentally
10675 // by the cycle detector framing it as a `["cart", "cart"]`
10676 // multi-node deadlock.
10677 let mut s = three_member_spec();
10678 s.contratos.push(contract_http("cart", "cart", "/loop"));
10679 let err = s.validate().unwrap_err();
10680 match err {
10681 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10682 assert_eq!(caixa, "cart");
10683 assert_eq!(wit, "wasi:http/proxy");
10684 }
10685 other => panic!("expected ContratoSelfLoop, got {other:?}"),
10686 }
10687 }
10688
10689 #[test]
10690 fn rejects_self_loop_in_pubsub_contratos() {
10691 // The cycle detector excludes pub-sub edges (acyclic by
10692 // construction), so before the explicit gate a `nats:pub-sub`
10693 // self-edge silently validated and rendered a self-allow CNP.
10694 // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
10695 let mut s = three_member_spec();
10696 s.contratos.push(WitContract {
10697 de: "payment".into(),
10698 para: "payment".into(),
10699 wit: "nats:pub-sub".into(),
10700 endpoint: None,
10701 subject: Some("rio.events.payment".into()),
10702 slot: None,
10703 });
10704 let err = s.validate().unwrap_err();
10705 match err {
10706 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
10707 assert_eq!(caixa, "payment");
10708 assert_eq!(wit, "nats:pub-sub");
10709 }
10710 other => panic!("expected ContratoSelfLoop, got {other:?}"),
10711 }
10712 }
10713
10714 #[test]
10715 fn self_loop_fires_before_payload_shape_check() {
10716 // The structural "this edge can't exist" error precedes the
10717 // narrower payload-shape diagnostics: a self-edge carrying an
10718 // otherwise-malformed endpoint still reports ContratoSelfLoop,
10719 // not ContratoEndpointInvalid.
10720 let mut s = three_member_spec();
10721 s.contratos.push(WitContract {
10722 de: "cart".into(),
10723 para: "cart".into(),
10724 wit: "wasi:http/proxy".into(),
10725 endpoint: Some("not-absolute".into()),
10726 subject: None,
10727 slot: None,
10728 });
10729 match s.validate().unwrap_err() {
10730 AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
10731 other => panic!("expected ContratoSelfLoop, got {other:?}"),
10732 }
10733 }
10734
10735 #[test]
10736 fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
10737 // A self-edge naming a non-member reports the more fundamental
10738 // ContratoMemberMissing first (the member doesn't exist), so the
10739 // self-loop gate is reached only once both endpoints resolve.
10740 let mut s = three_member_spec();
10741 s.contratos.push(contract_http("ghost", "ghost", "/loop"));
10742 match s.validate().unwrap_err() {
10743 AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
10744 other => panic!("expected ContratoMemberMissing, got {other:?}"),
10745 }
10746 }
10747
10748 #[test]
10749 fn rejects_two_node_synchronous_cycle() {
10750 let mut s = three_member_spec();
10751 // existing edges: cart → catalog, cart → payment
10752 // adding catalog → cart closes a 2-cycle on the HTTP subgraph
10753 s.contratos
10754 .push(contract_http("catalog", "cart", "/refresh"));
10755 let err = s.validate().unwrap_err();
10756 match err {
10757 AplicacaoError::ContratoCycle { cycle } => {
10758 // Cycle traversal should mention both endpoints, with
10759 // the back-edge target appearing as both first and last
10760 // element to close the loop.
10761 assert!(cycle.len() >= 3);
10762 assert_eq!(cycle.first(), cycle.last());
10763 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
10764 assert!(body.contains("cart"));
10765 assert!(body.contains("catalog"));
10766 }
10767 other => panic!("expected ContratoCycle, got {other:?}"),
10768 }
10769 }
10770
10771 #[test]
10772 fn rejects_three_node_synchronous_cycle() {
10773 let mut s = three_member_spec();
10774 // Reset to a clean 3-cycle: catalog → cart → payment → catalog
10775 s.contratos = vec![
10776 contract_http("catalog", "cart", "/x"),
10777 contract_http("cart", "payment", "/y"),
10778 contract_http("payment", "catalog", "/z"),
10779 ];
10780 let err = s.validate().unwrap_err();
10781 match err {
10782 AplicacaoError::ContratoCycle { cycle } => {
10783 assert_eq!(cycle.first(), cycle.last());
10784 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
10785 assert_eq!(body.len(), 3);
10786 assert!(body.contains("cart"));
10787 assert!(body.contains("catalog"));
10788 assert!(body.contains("payment"));
10789 }
10790 other => panic!("expected ContratoCycle, got {other:?}"),
10791 }
10792 }
10793
10794 #[test]
10795 fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
10796 // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
10797 // "acyclic by construction" — so a cycle whose closing edge
10798 // is pub-sub should NOT raise ContratoCycle.
10799 let mut s = three_member_spec();
10800 s.contratos = vec![
10801 contract_http("catalog", "cart", "/x"),
10802 contract_http("cart", "payment", "/y"),
10803 // Closing edge is pub-sub — async; not a sync deadlock.
10804 WitContract {
10805 de: "payment".into(),
10806 para: "catalog".into(),
10807 wit: "nats:pub-sub".into(),
10808 endpoint: None,
10809 subject: Some("checkout.events.charge.completed".into()),
10810 slot: None,
10811 },
10812 ];
10813 s.validate().expect("pub-sub edge breaks the sync cycle");
10814 }
10815
10816 #[test]
10817 fn store_edge_counts_as_synchronous_for_cycle_detection() {
10818 // wasi:keyvalue/store is request/response; a cycle through one
10819 // *is* a sync deadlock, just like HTTP.
10820 let mut s = three_member_spec();
10821 s.contratos = vec![
10822 contract_http("catalog", "cart", "/x"),
10823 WitContract {
10824 de: "cart".into(),
10825 para: "catalog".into(),
10826 wit: "wasi:keyvalue/store".into(),
10827 endpoint: None,
10828 subject: None,
10829 slot: Some("session/$id".into()),
10830 },
10831 ];
10832 let err = s.validate().unwrap_err();
10833 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
10834 }
10835
10836 #[test]
10837 fn capability_edge_counts_as_synchronous_for_cycle_detection() {
10838 // Capability-only edges (unknown WIT shape, no payload) default
10839 // to synchronous — safer; authors with truly async capability
10840 // semantics can model them as pub-sub explicitly.
10841 let mut s = three_member_spec();
10842 s.contratos = vec![
10843 contract_http("catalog", "cart", "/x"),
10844 WitContract {
10845 de: "cart".into(),
10846 para: "catalog".into(),
10847 wit: "custom:exchange".into(),
10848 endpoint: None,
10849 subject: None,
10850 slot: None,
10851 },
10852 ];
10853 let err = s.validate().unwrap_err();
10854 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
10855 }
10856
10857 #[test]
10858 fn long_acyclic_chain_validates() {
10859 // A long sync chain (no back-edges) must validate even when
10860 // every node is reachable from the first.
10861 let mut s = three_member_spec();
10862 s.membros = vec![
10863 membro("a", "^0.1"),
10864 membro("b", "^0.1"),
10865 membro("c", "^0.1"),
10866 membro("d", "^0.1"),
10867 membro("e", "^0.1"),
10868 ];
10869 s.contratos = vec![
10870 contract_http("a", "b", "/1"),
10871 contract_http("b", "c", "/2"),
10872 contract_http("c", "d", "/3"),
10873 contract_http("d", "e", "/4"),
10874 ];
10875 s.entrada.as_mut().unwrap().para = "a".into();
10876 s.validate().unwrap();
10877 }
10878
10879 #[test]
10880 fn diamond_acyclic_validates() {
10881 // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
10882 let mut s = three_member_spec();
10883 s.membros = vec![
10884 membro("a", "^0.1"),
10885 membro("b", "^0.1"),
10886 membro("c", "^0.1"),
10887 membro("d", "^0.1"),
10888 ];
10889 s.contratos = vec![
10890 contract_http("a", "b", "/1"),
10891 contract_http("a", "c", "/2"),
10892 contract_http("b", "d", "/3"),
10893 contract_http("c", "d", "/4"),
10894 ];
10895 s.entrada.as_mut().unwrap().para = "a".into();
10896 s.validate().unwrap();
10897 }
10898
10899 // ── duplicate-`:contratos` build-error gate ──────────────────────────
10900
10901 #[test]
10902 fn rejects_duplicate_http_contrato() {
10903 // Fail-before-pass-after pin: the fixture's `cart → catalog`
10904 // HTTP edge appears once. Push an identical entry — same
10905 // (de, para, wit, endpoint) — and validate() must reject it.
10906 // Until this gate landed the typed surface accepted the
10907 // duplicate silently and caixa-mesh's `cilium_network_policies`
10908 // emitted two ``CiliumNetworkPolicy`` objects with identical
10909 // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
10910 // admission rejects on `kubectl apply` far from the source.
10911 let mut s = three_member_spec();
10912 s.contratos
10913 .push(contract_http("cart", "catalog", "/products/:id"));
10914 let err = s.validate().unwrap_err();
10915 assert!(
10916 matches!(
10917 err,
10918 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10919 if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
10920 ),
10921 "got {err:?}"
10922 );
10923 }
10924
10925 #[test]
10926 fn rejects_duplicate_pubsub_contrato() {
10927 // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
10928 // edges with identical (de, para, subject) are degenerate;
10929 // pin that the typed surface refuses both at validate time.
10930 let mut s = three_member_spec();
10931 let pubsub = WitContract {
10932 de: "payment".into(),
10933 para: "cart".into(),
10934 wit: "nats:pub-sub".into(),
10935 endpoint: None,
10936 subject: Some("checkout.events.charge.failed".into()),
10937 slot: None,
10938 };
10939 s.contratos.push(pubsub.clone());
10940 s.contratos.push(pubsub);
10941 let err = s.validate().unwrap_err();
10942 assert!(
10943 matches!(
10944 err,
10945 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10946 if de == "payment" && para == "cart" && wit == "nats:pub-sub"
10947 ),
10948 "got {err:?}"
10949 );
10950 }
10951
10952 #[test]
10953 fn rejects_duplicate_store_contrato() {
10954 // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
10955 // edges with identical (de, para, slot) collapse to one mesh-
10956 // policy edge; pin the build error.
10957 let mut s = three_member_spec();
10958 let store = WitContract {
10959 de: "cart".into(),
10960 para: "payment".into(),
10961 wit: "wasi:keyvalue/store".into(),
10962 endpoint: None,
10963 subject: None,
10964 slot: Some("checkout/$orderId".into()),
10965 };
10966 // Drop the conflicting HTTP `cart → payment` edge from the
10967 // fixture so the duplicate-store pair is the only one
10968 // distinguishable on this pair.
10969 s.contratos
10970 .retain(|c| !(c.de == "cart" && c.para == "payment"));
10971 s.contratos.push(store.clone());
10972 s.contratos.push(store);
10973 let err = s.validate().unwrap_err();
10974 assert!(
10975 matches!(
10976 err,
10977 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
10978 if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
10979 ),
10980 "got {err:?}"
10981 );
10982 }
10983
10984 #[test]
10985 fn rejects_duplicate_capability_contrato() {
10986 // Same gate on the pure-capability axis (no payload selector).
10987 // Two contracts with identical (de, para, wit) and no
10988 // endpoint/subject/slot are duplicate edges; pin so a future
10989 // `target_label` change can't accidentally collapse the
10990 // capability arm into a None-shaped key that compares equal
10991 // to a populated one.
10992 let mut s = three_member_spec();
10993 let capability = WitContract {
10994 de: "cart".into(),
10995 para: "catalog".into(),
10996 wit: "pleme:cap/audit".into(),
10997 endpoint: None,
10998 subject: None,
10999 slot: None,
11000 };
11001 s.contratos.push(capability.clone());
11002 s.contratos.push(capability);
11003 let err = s.validate().unwrap_err();
11004 match err {
11005 AplicacaoError::ContratoDuplicate {
11006 de,
11007 para,
11008 wit,
11009 target,
11010 } => {
11011 assert_eq!(de, "cart");
11012 assert_eq!(para, "catalog");
11013 assert_eq!(wit, "pleme:cap/audit");
11014 assert!(
11015 target.contains("capability"),
11016 "capability-edge duplicate diagnostic must surface the \
11017 no-payload shape (got target = {target:?})"
11018 );
11019 }
11020 other => panic!("expected ContratoDuplicate, got {other:?}"),
11021 }
11022 }
11023
11024 #[test]
11025 fn accepts_distinct_http_paths_between_same_pair() {
11026 // Negative pin: two HTTP contracts cart → catalog at distinct
11027 // endpoints (`/products/:id` and `/search`) are *not*
11028 // duplicates — they're distinct typed edges differing on the
11029 // payload axis. The duplicate-gate must not over-match here,
11030 // since the cart-calls-catalog-on-multiple-paths shape is the
11031 // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
11032 // example: cart calls catalog at /products/:id, payment at
11033 // /charge — same shape extends to two paths on one para).
11034 let mut s = three_member_spec();
11035 s.contratos
11036 .push(contract_http("cart", "catalog", "/search"));
11037 s.validate()
11038 .expect("distinct endpoints between same (de, para) must validate");
11039 }
11040
11041 #[test]
11042 fn accepts_same_endpoint_on_different_pairs() {
11043 // Negative pin: the same `/charge` endpoint reused on two
11044 // different (de, para) pairs is two distinct edges, not a
11045 // duplicate. Pinning this shape so the gate's identity key
11046 // includes both `de` and `para` (not just `(wit, endpoint)`).
11047 let mut s = three_member_spec();
11048 s.contratos
11049 .push(contract_http("payment", "catalog", "/charge"));
11050 s.validate()
11051 .expect("same endpoint reused on distinct (de, para) must validate");
11052 }
11053
11054 #[test]
11055 fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
11056 // Pin the diagnostic shape: the duplicate-edge error names
11057 // *which* target field carried the conflict, so the author
11058 // doesn't have to re-grep the source caixa.lisp to find it.
11059 // Same self-locating diagnostic discipline as
11060 // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
11061 let mut s = three_member_spec();
11062 s.contratos
11063 .push(contract_http("cart", "catalog", "/products/:id"));
11064 let err = s.validate().unwrap_err();
11065 let msg = format!("{err}");
11066 assert!(
11067 msg.contains("\"/products/:id\""),
11068 "duplicate-contrato diagnostic must name the offending \
11069 :endpoint payload (got: {msg:?})"
11070 );
11071 assert!(
11072 msg.contains("cart") && msg.contains("catalog"),
11073 "diagnostic must name both endpoints of the duplicate edge \
11074 (got: {msg:?})"
11075 );
11076 }
11077
11078 #[test]
11079 fn duplicate_contrato_gate_runs_after_membership_check() {
11080 // Order pin: a duplicate contract whose `:de` is *also* not in
11081 // `:membros` surfaces the membership error first — the
11082 // missing-member diagnostic is more locating than the
11083 // duplicate-edge one (the author has to fix the membership
11084 // before the duplicate is meaningful). Same ordering
11085 // discipline as `membros_validation_runs_before_contratos_membership_check`.
11086 let mut s = three_member_spec();
11087 s.contratos.push(contract_http("phantom", "catalog", "/x"));
11088 s.contratos.push(contract_http("phantom", "catalog", "/x"));
11089 let err = s.validate().unwrap_err();
11090 assert!(
11091 matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
11092 "membership-missing must fire before duplicate-edge (got {err:?})"
11093 );
11094 }
11095
11096 #[test]
11097 fn duplicate_contrato_gate_runs_after_target_shape_check() {
11098 // Order pin: a contract with a malformed target (e.g. an HTTP
11099 // wit world with an empty :endpoint) surfaces the target-shape
11100 // error first, not the duplicate one. Even when two such
11101 // malformed entries are identical, the per-contract `target()`
11102 // check fires inside the loop *before* the duplicate-key
11103 // insert, so the diagnostic remains the most-locating one.
11104 let mut s = three_member_spec();
11105 let malformed = WitContract {
11106 de: "cart".into(),
11107 para: "catalog".into(),
11108 wit: "wasi:http/proxy".into(),
11109 endpoint: Some(String::new()),
11110 subject: None,
11111 slot: None,
11112 };
11113 s.contratos.push(malformed.clone());
11114 s.contratos.push(malformed);
11115 let err = s.validate().unwrap_err();
11116 assert!(
11117 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
11118 "endpoint-empty must fire before duplicate-edge (got {err:?})"
11119 );
11120 }
11121
11122 #[test]
11123 fn wit_target_label_pins_per_variant_format() {
11124 // Label format is the single source of truth every duplicate-
11125 // `:contratos` diagnostic + every future `feira app graph`
11126 // consumer routes through. Pin the shape per variant so a
11127 // future edit to `WitTarget::label` (e.g. a JSON emitter that
11128 // strips the leading `:`, or a rename from `endpoint` →
11129 // `path`) surfaces as a red-red test rather than as a silent
11130 // downstream diagnostic drift. Together with the exhaustive
11131 // `match` on `WitTarget` inside `label()`, adding a future
11132 // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
11133 // peer, per-edge WIT registry variants) is a compile error at
11134 // the label site — not a fall-through into the `Capability`
11135 // "no payload" default the prior raw-field-probe helper
11136 // silently landed on.
11137 assert_eq!(
11138 WitTarget::Http {
11139 endpoint: "/charge",
11140 }
11141 .label(),
11142 "\
11143:endpoint \"/charge\""
11144 );
11145 assert_eq!(
11146 WitTarget::PubSub {
11147 subject: "events.checkout.paid",
11148 }
11149 .label(),
11150 "\
11151:subject \"events.checkout.paid\""
11152 );
11153 assert_eq!(
11154 WitTarget::Store {
11155 slot: "checkout/$order",
11156 }
11157 .label(),
11158 "\
11159:slot \"checkout/$order\""
11160 );
11161 assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
11162 // Capability-arm label routes through the lifted
11163 // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
11164 // declaration per arm, next to the variant" discipline the
11165 // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
11166 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11167 // consts already carry extends to the payload-less arm; the
11168 // byte-string equality pin below plus this label-routes-
11169 // through-the-const pin make a future rebrand on either the
11170 // const declaration or the `label()` template a build error
11171 // here rather than a downstream consumer surprise.
11172 assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
11173 assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
11174 }
11175
11176 #[test]
11177 fn wit_target_display_routes_through_label_helper() {
11178 // Fail-before-pass-after pin on the fourth (and only remaining)
11179 // typed-shape-discriminator axis to converge onto the
11180 // three-path-convergence discipline the sibling M3
11181 // [`PlacementStrategy`] (0a2f653) and M2
11182 // [`crate::supervisor::RestartStrategy`] /
11183 // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
11184 // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
11185 // through [`WitTarget::label`], so every consumer reaching for
11186 // `format!("{v}")` on a typed payload target lands on the same
11187 // stable author-facing byte-string [`WitTarget::label`] returns
11188 // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
11189 // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
11190 // `:contratos` gate seeds via [`WitTarget::label`] at
11191 // aplicacao.rs:5491 already threads through.
11192 //
11193 // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
11194 // through to the `Debug` derive's structural output
11195 // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
11196 // rather than the [`WitTarget::label`] helper's stable byte-
11197 // string (`:endpoint "/charge"` — the author-facing `:contratos`
11198 // keyword form). Every future consumer that reaches for
11199 // `format!("{target}")` — the canonical shape every user-facing
11200 // pretty-print site on the sibling typed-enum axes
11201 // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
11202 // [`crate::supervisor::RestartPolicy`]) already uses — would
11203 // silently land under a different byte-string than the
11204 // [`WitTarget::label`] callers that the duplicate-`:contratos`
11205 // diagnostic already threads through, with the mismatch
11206 // surfacing as a downstream diagnostic / graph / audit line
11207 // reading one spelling while the substrate's own gate emitted
11208 // another.
11209 //
11210 // Pin the routing here so a future
11211 // `impl std::fmt::Display for WitTarget<'_>` reimplementation
11212 // that hand-rolls the per-arm formatting instead of delegating
11213 // to [`WitTarget::label`] fails at caixa-core build time.
11214 for variant in [
11215 WitTarget::Http {
11216 endpoint: "/charge",
11217 },
11218 WitTarget::PubSub {
11219 subject: "events.checkout.paid",
11220 },
11221 WitTarget::Store {
11222 slot: "checkout/$order",
11223 },
11224 WitTarget::Capability,
11225 ] {
11226 assert_eq!(
11227 variant.to_string(),
11228 variant.label(),
11229 "WitTarget::{variant:?} Display must route through \
11230 WitTarget::label (single source of truth: the lifted \
11231 payload_pair 4-arm dispatch the label helper already \
11232 threads through)"
11233 );
11234 }
11235 }
11236
11237 #[test]
11238 fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
11239 // Consumer-side pin on the three-path convergence:
11240 // [`std::fmt::Display`] agrees byte-for-byte with the
11241 // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
11242 // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
11243 // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
11244 // Pre-lift the two paths were structurally independent — the
11245 // substrate-side gate reached for `target_view.label()` while a
11246 // future downstream diagnostic / graph / audit line reaching
11247 // for `format!("{target}")` would silently land on the `Debug`
11248 // derive's structural output. Pin the two paths byte-for-byte
11249 // here so any future variant addition (M4 `Rest`/`Grpc` split
11250 // of [`WitTarget::Http`], `Queue`-shaped peer of
11251 // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
11252 // match error at [`WitTarget::payload_pair`] rather than a
11253 // silent per-consumer dispatch miss.
11254 for variant in [
11255 WitTarget::Http {
11256 endpoint: "/charge",
11257 },
11258 WitTarget::PubSub {
11259 subject: "events.checkout.paid",
11260 },
11261 WitTarget::Store {
11262 slot: "checkout/$order",
11263 },
11264 WitTarget::Capability,
11265 ] {
11266 assert_eq!(
11267 format!("{variant}"),
11268 variant.label(),
11269 "WitTarget::{variant:?} Display byte-string must match \
11270 the AplicacaoError::ContratoDuplicate `target:` carrier \
11271 the AplicacaoSpec::validate duplicate-`:contratos` gate \
11272 seeds via WitTarget::label — three-path convergence: \
11273 Display + label + payload_pair all resolve to the same \
11274 per-arm byte-string"
11275 );
11276 }
11277 }
11278
11279 #[test]
11280 fn wit_target_payload_pair_pins_per_variant() {
11281 // Pin the per-arm `(field-name, payload)` pair single-sourced
11282 // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
11283 // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
11284 // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
11285 // and [`WitTarget::field_name`] (returns the first component)
11286 // route through. Until this lift landed [`WitTarget::label`]
11287 // dispatched on the same three arms with a per-arm
11288 // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
11289 // paired [`WitTarget::HTTP_FIELD_NAME`] /
11290 // [`WitTarget::PUBSUB_FIELD_NAME`] /
11291 // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
11292 // canonical "same shape, written N times" duplication
11293 // THEORY.md §I.3.5 promotes to a build-time concern. A future
11294 // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
11295 // [`WitTarget::Http`], `Queue`-shaped peer of
11296 // [`WitTarget::Store`]) is one match-arm edit at
11297 // [`WitTarget::payload_pair`], visible here as a compile-time
11298 // exhaustiveness error on both this pin and the label-format
11299 // pin above.
11300 assert_eq!(
11301 WitTarget::Http {
11302 endpoint: "/charge"
11303 }
11304 .payload_pair(),
11305 Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
11306 );
11307 assert_eq!(
11308 WitTarget::PubSub {
11309 subject: "events.x",
11310 }
11311 .payload_pair(),
11312 Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
11313 );
11314 assert_eq!(
11315 WitTarget::Store {
11316 slot: "checkout/$order",
11317 }
11318 .payload_pair(),
11319 Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
11320 );
11321 assert_eq!(WitTarget::Capability.payload_pair(), None);
11322 }
11323
11324 #[test]
11325 fn wit_target_field_name_pins_per_variant() {
11326 // Pin the per-arm author-facing `:contratos` payload field
11327 // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
11328 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11329 // + returned by [`WitTarget::field_name`]. Every downstream
11330 // consumer (the [`WitContract::target`] gate's `expected:`
11331 // scalar, the [`WitTarget::label`] template's keyword prefix,
11332 // the `feira app graph` verb's `endpoint=…` prefix) routes
11333 // through the same three peer consts, so a rename on the
11334 // author-surface `(defcaixa … :contratos ((:de … :para …
11335 // :wit … :endpoint …)))` field lands in exactly one place.
11336 assert_eq!(
11337 WitTarget::Http {
11338 endpoint: "/charge"
11339 }
11340 .field_name(),
11341 Some(WitTarget::HTTP_FIELD_NAME),
11342 );
11343 assert_eq!(
11344 WitTarget::PubSub {
11345 subject: "events.x",
11346 }
11347 .field_name(),
11348 Some(WitTarget::PUBSUB_FIELD_NAME),
11349 );
11350 assert_eq!(
11351 WitTarget::Store {
11352 slot: "checkout/$order",
11353 }
11354 .field_name(),
11355 Some(WitTarget::STORE_FIELD_NAME),
11356 );
11357 // Capability arm carries no payload field — the diagnostic
11358 // never reports `expected: "capability"` because the gate's
11359 // Capability arm accepts no payload at all (it fires the
11360 // "expected: none" WrongTarget error instead), so the field-
11361 // name method returns None here rather than a placeholder.
11362 assert_eq!(WitTarget::Capability.field_name(), None);
11363
11364 // Peer const scalar values pinned so a rename on either side
11365 // (author-surface field name in the `(defcaixa …)` DSL, or
11366 // the diagnostic's `expected:` scalar) can't drift without
11367 // failing here first.
11368 assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
11369 assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
11370 assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
11371 }
11372
11373 #[test]
11374 fn wit_target_field_names_are_pairwise_distinct() {
11375 // Distinctness pin: if any two of the three payload-field-name
11376 // scalars ever collapse (e.g. an accidental `endpoint` copy-
11377 // paste over the `subject` const), the [`WitContract::target`]
11378 // gate's diagnostic would point authors at the wrong field —
11379 // an "expected `:endpoint`" error on a pub-sub edge would
11380 // silently misroute the fix. Same cross-axis-distinctness
11381 // discipline as the peer M3 `:placement :estrategia` variant-
11382 // discriminator scalar-value pins (cc8f749) applied to the
11383 // payload-field-name axis.
11384 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
11385 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11386 assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
11387 }
11388
11389 #[test]
11390 fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
11391 // 4-way distinctness pin extending the sibling
11392 // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
11393 // (which covers only the HTTP / PubSub / Store payload arms)
11394 // onto the fourth scalar the shared
11395 // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
11396 // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
11397 // (`"none"`), the payload-less Capability-arm rejection scalar.
11398 //
11399 // All four [`WitTarget::HTTP_FIELD_NAME`] /
11400 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
11401 // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
11402 // dispatch surface [`WitContract::target`] writes onto the
11403 // `ContratoWrongTarget::expected` field — the same `&'static
11404 // str` axis authors read as "this WIT world's shape admits
11405 // (only|not) `:<field>`". Pairwise-distinctness is the invariant
11406 // downstream consumers rely on: an `expected: "endpoint"`
11407 // diagnostic on a Capability-shaped edge tells the author to
11408 // add a `:endpoint "…"` slot to a WIT world that admits none,
11409 // silently misrouting the fix. Until this pin landed the three
11410 // payload-arm consts were distinctness-guarded by the sibling
11411 // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
11412 // scalar (d4f54f2) sat unguarded — a rebrand collision (the
11413 // author-facing vocabulary shift from `"none"` to `"endpoint"`
11414 // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
11415 // into per-shape peers) would have silently landed one
11416 // Capability-arm rejection on a payload-arm's `expected:` byte-
11417 // string and desynchronized the diagnostic from the author's
11418 // typed shape.
11419 //
11420 // Same 4-way pairwise-distinctness pin discipline as the peer
11421 // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
11422 // (cc8f749) applies on the sibling M3 closed-set typed-enum
11423 // scalar-value dispatch axis; extends the pin trajectory the
11424 // sibling `wit_target_field_names_are_pairwise_distinct`
11425 // 3-way pin opened to cover the last unguarded corner on the
11426 // `ContratoWrongTarget::expected` scalar-value axis.
11427 //
11428 // Fail-before-pass-after locally verified by mutating
11429 // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
11430 // — this pin fires as expected; restoring passes.
11431 let all = [
11432 WitTarget::HTTP_FIELD_NAME,
11433 WitTarget::PUBSUB_FIELD_NAME,
11434 WitTarget::STORE_FIELD_NAME,
11435 WitTarget::CAPABILITY_EXPECTED,
11436 ];
11437 for (i, a) in all.iter().enumerate() {
11438 for (j, b) in all.iter().enumerate() {
11439 if i != j {
11440 assert_ne!(
11441 a, b,
11442 "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
11443 STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
11444 pairwise distinct — got duplicate {a:?} at indices \
11445 {i} and {j}; all four scalars thread through the \
11446 shared `AplicacaoError::ContratoWrongTarget::expected` \
11447 &'static str axis, so a collapse silently misdirects \
11448 the diagnostic on which typed shape the WIT world admits",
11449 );
11450 }
11451 }
11452 }
11453 }
11454
11455 #[test]
11456 fn wit_target_is_variant_predicates_partition_the_arm_set() {
11457 // Fail-before-pass-after pin on the
11458 // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
11459 // each of the four variants exactly one of the generated
11460 // `is_http` / `is_pubsub` / `is_store` / `is_capability`
11461 // predicates returns `true` and the other three return
11462 // `false`. Prior to this derive the only production
11463 // arm-discriminator on [`WitTarget`] — the sync-cycle
11464 // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
11465 // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
11466 // the variant that expressed no compile-time link back to
11467 // the closed-set typed dispatch a future fifth
11468 // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
11469 // split of [`WitTarget::PubSub`] into shape-specific peers,
11470 // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
11471 // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
11472 // to thread through in lockstep or the DFS exclusion would
11473 // silently disagree with the peer diagnostic templates on
11474 // which arms carry sync-versus-async semantics. Peer of the
11475 // sibling [`crate::CaixaKind`] (f5bba80),
11476 // [`PlacementStrategy`] (766ec63),
11477 // [`crate::supervisor::RestartStrategy`],
11478 // [`crate::supervisor::RestartPolicy`], and
11479 // [`crate::upgrade::UpgradeInstruction`] (915a934)
11480 // `IsVariant` derives on the sibling closed-set typed-enum
11481 // discriminator axes — extends the same one-typed-dispatch-
11482 // per-variant discipline onto the last unlifted closed-set
11483 // typed-enum discriminator on the caixa surface (the M3
11484 // mesh-slot per-`:contratos` target-arm axis), closing the
11485 // arm-discriminator convergence trajectory across every
11486 // closed-set typed enum in caixa-core.
11487 let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
11488 (
11489 WitTarget::Http { endpoint: "/x" },
11490 [true, false, false, false],
11491 ),
11492 (
11493 WitTarget::PubSub {
11494 subject: "events.x",
11495 },
11496 [false, true, false, false],
11497 ),
11498 (
11499 WitTarget::Store { slot: "kv/x" },
11500 [false, false, true, false],
11501 ),
11502 (WitTarget::Capability, [false, false, false, true]),
11503 ];
11504 for (variant, expected) in rows {
11505 let observed = [
11506 variant.is_http(),
11507 variant.is_pubsub(),
11508 variant.is_store(),
11509 variant.is_capability(),
11510 ];
11511 assert_eq!(
11512 observed, expected,
11513 "WitTarget::{variant:?} is_* predicates must partition \
11514 the arm set (http, pubsub, store, capability); got {observed:?}"
11515 );
11516 }
11517 }
11518
11519 #[test]
11520 fn wit_target_is_variant_predicates_are_const_fn() {
11521 // The [`gen_platform::IsVariant`] derive emits `const fn`
11522 // predicates on the peer [`crate::CaixaKind`] +
11523 // [`crate::upgrade::UpgradeInstruction`] +
11524 // [`crate::supervisor::RestartStrategy`] +
11525 // [`crate::supervisor::RestartPolicy`] +
11526 // [`PlacementStrategy`] closed-set typed enums — pin the
11527 // same posture on [`WitTarget`] so a future accidental
11528 // downgrade to non-`const` (an added runtime helper reachable
11529 // only from a non-`const` context, a manual hand-rolled
11530 // `impl` that shadows the derive-generated method) trips at
11531 // caixa-core build time rather than surfacing as a downstream
11532 // `const`-context regression far from the derive declaration.
11533 //
11534 // Unlike the peer unit-variant enums (`CaixaKind` /
11535 // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
11536 // whose `const` constructors need no arguments, the three
11537 // payload-carrying [`WitTarget`] arms are const-constructed
11538 // through `&'static str` payloads — the same `'static`
11539 // lifetime the closed-set typed enum's four-arm partition
11540 // pin above already threads through.
11541 const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
11542 const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
11543 const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
11544 const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
11545 const IS_HTTP: bool = HTTP.is_http();
11546 const IS_PUBSUB: bool = PUBSUB.is_pubsub();
11547 const IS_STORE: bool = STORE.is_store();
11548 const IS_CAPABILITY: bool = CAPABILITY.is_capability();
11549 assert!(IS_HTTP);
11550 assert!(IS_PUBSUB);
11551 assert!(IS_STORE);
11552 assert!(IS_CAPABILITY);
11553 }
11554
11555 #[test]
11556 fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
11557 // Consumer-side pin on the sole production converge site:
11558 // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
11559 // edges from the synchronous-subgraph DFS via the lifted
11560 // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
11561 // predicate (rebound from the prior raw
11562 // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
11563 // variant). Byte-equivalent today (`is_pubsub` is the
11564 // derive-generated `matches!(self, Self::PubSub { .. })` by
11565 // construction, the `#[is_variant(name = "pubsub")]` override
11566 // aliasing the auto-derived `is_pub_sub` back to the sibling
11567 // [`WitContract::is_pubsub`] name); pin the behavior so a
11568 // future accidental drift (a rebind onto a peer arm
11569 // predicate, a manual hand-rolled `impl` that shadows the
11570 // derive-generated method with different semantics, a peer
11571 // arm rename that shifts which variant carries sync-versus-
11572 // async semantics) trips at caixa-core test time rather than
11573 // at some downstream operator's runtime dispatch far from the
11574 // rebind commit.
11575 //
11576 // The fixture constructs a two-Servico Aplicacao with one
11577 // pub-sub edge that would close a sync-cycle if the DFS did
11578 // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
11579 // pub-sub exclusion means the DFS sees only the `b → a` HTTP
11580 // edge, which is not a cycle. A regression in the converge
11581 // (a rebind that reads the pub-sub arm as sync) would report
11582 // `AplicacaoError::ContratoCycle`.
11583 let s = AplicacaoSpec {
11584 membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
11585 contratos: vec![
11586 // Pub-sub edge: DFS must skip via is_pubsub().
11587 WitContract {
11588 de: "a".into(),
11589 para: "b".into(),
11590 wit: "nats:pub-sub".into(),
11591 endpoint: None,
11592 subject: Some("events.x".into()),
11593 slot: None,
11594 },
11595 // HTTP edge: DFS must include.
11596 WitContract {
11597 de: "b".into(),
11598 para: "a".into(),
11599 wit: "wasi:http/proxy".into(),
11600 endpoint: Some("/x".into()),
11601 subject: None,
11602 slot: None,
11603 },
11604 ],
11605 politicas: MeshPolicy::default(),
11606 placement: Placement {
11607 estrategia: PlacementStrategy::Replicated,
11608 clusters: vec!["rio".into()],
11609 affinity: None,
11610 shard_key: None,
11611 },
11612 entrada: None,
11613 };
11614 s.validate()
11615 .expect("pub-sub edge must be excluded from sync-cycle DFS");
11616 }
11617
11618 #[test]
11619 fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
11620 // Consumer-side pin: the same three peer consts thread through
11621 // both the [`WitTarget::label`] template (leading-`:` keyword
11622 // prefix in the duplicate-`:contratos` diagnostic) and the
11623 // [`WitContract::target`] gate's [`AplicacaoError::
11624 // ContratoMissingTarget`] `expected:` scalar (the field the
11625 // author needs to add). Pin both routes at once so a future
11626 // refactor can't accidentally split them onto separate string
11627 // literals — the "one place, everywhere reaches for it"
11628 // invariant the peer const set carries.
11629 let http_label = WitTarget::Http { endpoint: "/x" }.label();
11630 assert!(
11631 http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
11632 "label must lead with :{} keyword (got {http_label:?})",
11633 WitTarget::HTTP_FIELD_NAME,
11634 );
11635
11636 let mut s = three_member_spec();
11637 s.contratos.push(WitContract {
11638 de: "cart".into(),
11639 para: "catalog".into(),
11640 wit: "kafka:topic".into(),
11641 endpoint: None,
11642 subject: None,
11643 slot: None,
11644 });
11645 match s.validate().unwrap_err() {
11646 AplicacaoError::ContratoMissingTarget { expected, .. } => {
11647 assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
11648 }
11649 other => panic!("expected ContratoMissingTarget, got {other:?}"),
11650 }
11651 }
11652
11653 #[test]
11654 fn duplicate_pubsub_diagnostic_names_offending_subject() {
11655 // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
11656 // on the pub-sub target axis: the duplicate-edge diagnostic
11657 // must name the `:subject` payload verbatim (not just the
11658 // `(de, para, wit)` triple). Prior to lifting the label onto
11659 // [`WitTarget::label`] the diagnostic derived the label from
11660 // raw [`WitContract`] `Option<String>` probes — a future
11661 // `WitTarget` variant addition (M4 per-edge WIT registry)
11662 // would silently fall through to the `Capability` "no
11663 // payload" default without a compiler warning. Pinning the
11664 // pub-sub arm's format closes the second of three
11665 // payload-carrying `WitTarget` arms this diagnostic threads
11666 // through.
11667 let mut s = three_member_spec();
11668 let pubsub = WitContract {
11669 de: "payment".into(),
11670 para: "cart".into(),
11671 wit: "nats:pub-sub".into(),
11672 endpoint: None,
11673 subject: Some("events.checkout.paid".into()),
11674 slot: None,
11675 };
11676 s.contratos.push(pubsub.clone());
11677 s.contratos.push(pubsub);
11678 let err = s.validate().unwrap_err();
11679 let msg = format!("{err}");
11680 assert!(
11681 msg.contains(":subject \"events.checkout.paid\""),
11682 "duplicate-pubsub diagnostic must name the offending \
11683 :subject payload (got: {msg:?})"
11684 );
11685 }
11686
11687 #[test]
11688 fn duplicate_store_diagnostic_names_offending_slot() {
11689 // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
11690 // key-value target axis: the diagnostic must name the `:slot`
11691 // payload verbatim. Third of three payload-carrying
11692 // `WitTarget` arms this diagnostic threads through, closing
11693 // the per-arm label pin trilogy (`Http` — 6841,
11694 // `PubSub` + `Store` — this test + peer above).
11695 let mut s = three_member_spec();
11696 let store = WitContract {
11697 de: "cart".into(),
11698 para: "payment".into(),
11699 wit: "wasi:keyvalue/store".into(),
11700 endpoint: None,
11701 subject: None,
11702 slot: Some("checkout/$orderId".into()),
11703 };
11704 s.contratos
11705 .retain(|c| !(c.de == "cart" && c.para == "payment"));
11706 s.contratos.push(store.clone());
11707 s.contratos.push(store);
11708 let err = s.validate().unwrap_err();
11709 let msg = format!("{err}");
11710 assert!(
11711 msg.contains(":slot \"checkout/$orderId\""),
11712 "duplicate-store diagnostic must name the offending :slot \
11713 payload (got: {msg:?})"
11714 );
11715 }
11716
11717 #[test]
11718 fn rejects_entrada_path_without_leading_slash() {
11719 let mut s = three_member_spec();
11720 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
11721 let err = s.validate().unwrap_err();
11722 assert!(
11723 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
11724 "got {err:?}"
11725 );
11726 }
11727
11728 #[test]
11729 fn rejects_empty_entrada_path() {
11730 let mut s = three_member_spec();
11731 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
11732 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
11733 }
11734
11735 #[test]
11736 fn rejects_duplicate_entrada_paths() {
11737 let mut s = three_member_spec();
11738 s.entrada.as_mut().unwrap().paths = vec![
11739 "/api/cart".into(),
11740 "/api/products".into(),
11741 "/api/cart".into(),
11742 ];
11743 let err = s.validate().unwrap_err();
11744 assert!(
11745 matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
11746 "got {err:?}"
11747 );
11748 }
11749
11750 #[test]
11751 fn rejects_zero_entrada_port() {
11752 let mut s = three_member_spec();
11753 s.entrada.as_mut().unwrap().port = 0;
11754 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
11755 }
11756
11757 // ── :entrada :paths value-shape gate ─────────────────────────────
11758 //
11759 // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
11760 // sibling `:paths` axis. Every authoring footgun the K8s Gateway
11761 // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
11762 // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
11763 // time now becomes a caixa-build-time `EntradaPathInvalid` with
11764 // the offending `:paths` entry named verbatim.
11765
11766 #[test]
11767 fn rejects_entrada_path_with_query() {
11768 // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
11769 // silently passed validate and the Gateway API webhook
11770 // rejected it at apply time with no source citation.
11771 let mut s = three_member_spec();
11772 s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
11773 let err = s.validate().unwrap_err();
11774 assert!(
11775 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11776 if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
11777 "got {err:?}"
11778 );
11779 }
11780
11781 #[test]
11782 fn rejects_entrada_path_with_fragment() {
11783 let mut s = three_member_spec();
11784 s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
11785 let err = s.validate().unwrap_err();
11786 assert!(
11787 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11788 if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
11789 "got {err:?}"
11790 );
11791 }
11792
11793 #[test]
11794 fn rejects_entrada_path_with_space() {
11795 let mut s = three_member_spec();
11796 s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
11797 let err = s.validate().unwrap_err();
11798 assert!(
11799 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11800 if path == "/api/my cart" && reason.contains("whitespace")),
11801 "got {err:?}"
11802 );
11803 }
11804
11805 #[test]
11806 fn rejects_entrada_path_with_tab() {
11807 let mut s = three_member_spec();
11808 s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
11809 let err = s.validate().unwrap_err();
11810 assert!(
11811 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11812 if path == "/api/\tcart" && reason.contains("whitespace")),
11813 "got {err:?}"
11814 );
11815 }
11816
11817 #[test]
11818 fn rejects_entrada_path_with_control_char() {
11819 // 0x01 (SOH) — a non-whitespace control char surfaces the
11820 // distinct "control character" reason arm, separate from
11821 // the whitespace arm. Pinned so a future refactor that
11822 // collapses the two arms can't accidentally drop the more
11823 // self-locating diagnostic.
11824 let mut s = three_member_spec();
11825 s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
11826 let err = s.validate().unwrap_err();
11827 assert!(
11828 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11829 if path == "/api/\x01cart" && reason.contains("control character")),
11830 "got {err:?}"
11831 );
11832 }
11833
11834 #[test]
11835 fn rejects_entrada_path_with_non_ascii() {
11836 // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
11837 // unreserved-set rule rejects. The Gateway API webhook
11838 // rejects literal non-ASCII bytes; percent-encoding is the
11839 // only way to author non-ASCII in a path.
11840 let mut s = three_member_spec();
11841 s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
11842 let err = s.validate().unwrap_err();
11843 assert!(
11844 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11845 if path == "/api/café" && reason.contains("non-ASCII")),
11846 "got {err:?}"
11847 );
11848 }
11849
11850 #[test]
11851 fn rejects_entrada_path_with_consecutive_slashes() {
11852 let mut s = three_member_spec();
11853 s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
11854 let err = s.validate().unwrap_err();
11855 assert!(
11856 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11857 if path == "/api//cart" && reason.contains("consecutive `/`")),
11858 "got {err:?}"
11859 );
11860 }
11861
11862 #[test]
11863 fn rejects_entrada_path_with_dot_segment() {
11864 let mut s = three_member_spec();
11865 s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
11866 let err = s.validate().unwrap_err();
11867 assert!(
11868 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11869 if path == "/api/./cart" && reason.contains("`.` segment")),
11870 "got {err:?}"
11871 );
11872 }
11873
11874 #[test]
11875 fn rejects_entrada_path_with_trailing_dot_segment() {
11876 // The bare `/.` and the trailing `/foo/.` are both rejected
11877 // by the Gateway API webhook; pinned separately so a future
11878 // narrowing that catches only the inner form surfaces here.
11879 let mut s = three_member_spec();
11880 s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
11881 let err = s.validate().unwrap_err();
11882 assert!(
11883 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11884 if path == "/api/." && reason.contains("`.` segment")),
11885 "got {err:?}"
11886 );
11887 }
11888
11889 #[test]
11890 fn rejects_entrada_path_with_parent_segment() {
11891 let mut s = three_member_spec();
11892 s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
11893 let err = s.validate().unwrap_err();
11894 assert!(
11895 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11896 if path == "/api/../etc" && reason.contains("`..` parent-segment")),
11897 "got {err:?}"
11898 );
11899 }
11900
11901 #[test]
11902 fn rejects_entrada_path_with_trailing_parent_segment() {
11903 // Trailing `/..` — symmetric arm of the parent-segment rule,
11904 // pinned separately so a future relaxation that only checks
11905 // the inner form (`/../`) surfaces here.
11906 let mut s = three_member_spec();
11907 s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
11908 let err = s.validate().unwrap_err();
11909 assert!(
11910 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11911 if path == "/api/.." && reason.contains("`..` parent-segment")),
11912 "got {err:?}"
11913 );
11914 }
11915
11916 #[test]
11917 fn rejects_entrada_path_too_long() {
11918 // 1025-byte path — one over the Gateway API HTTPPathMatch.value
11919 // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
11920 // ASCII-alphanumeric body so only the length rule fires.
11921 let mut s = three_member_spec();
11922 let big = format!("/api/{}", "a".repeat(1020));
11923 assert_eq!(big.len(), 1025);
11924 s.entrada.as_mut().unwrap().paths = vec![big.clone()];
11925 let err = s.validate().unwrap_err();
11926 assert!(
11927 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
11928 if path == &big && reason.contains("max length of 1024")),
11929 "got {err:?}"
11930 );
11931 }
11932
11933 #[test]
11934 fn entrada_path_max_length_validates() {
11935 // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
11936 // maxLength cap. Boundary pin: drift in the cap surfaces here
11937 // and at `rejects_entrada_path_too_long` simultaneously.
11938 let mut s = three_member_spec();
11939 let big = format!("/api/{}", "a".repeat(1019));
11940 assert_eq!(big.len(), 1024);
11941 s.entrada.as_mut().unwrap().paths = vec![big];
11942 s.validate().unwrap();
11943 }
11944
11945 #[test]
11946 fn entrada_accepts_canonical_paths() {
11947 // Positive-control sweep — every form the Gateway API
11948 // apiserver accepts must round-trip through validate. Covers
11949 // the root catch-all, plain paths, dot-prefixed segments
11950 // (hidden-file-style, distinct from `.` and `..` segments
11951 // which are rejected), digit-bearing segments, the canonical
11952 // route-template `:param` form (`:` is RFC 3986 reserved-set
11953 // valid in paths), trailing-slash form, percent-encoded
11954 // segments, and an interior `..` *substring* (`/foo..bar` is
11955 // not the `..` segment and is allowed).
11956 for path in [
11957 "/",
11958 "/api/cart",
11959 "/healthz",
11960 "/api/.config",
11961 "/v1/products",
11962 "/products/:id",
11963 "/api/cart/",
11964 "/api/caf%C3%A9",
11965 "/foo..bar",
11966 "/...",
11967 ] {
11968 let mut s = three_member_spec();
11969 s.entrada.as_mut().unwrap().paths = vec![path.into()];
11970 s.validate()
11971 .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
11972 }
11973 }
11974
11975 #[test]
11976 fn entrada_path_empty_takes_precedence_over_invalid() {
11977 // Ordering pin: `EntradaPathEmpty` is the more self-locating
11978 // diagnostic on `""` and must lead — `validate_entrada_path`
11979 // is only reached after the empty-check fires at the call
11980 // site. (The predicate itself defends against direct
11981 // invocation by returning the same error on `""`.)
11982 let mut s = three_member_spec();
11983 s.entrada.as_mut().unwrap().paths = vec!["".into()];
11984 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
11985 }
11986
11987 #[test]
11988 fn entrada_path_not_absolute_takes_precedence_over_invalid() {
11989 // Ordering pin: a path without a leading `/` surfaces the
11990 // narrower `EntradaPathNotAbsolute` diagnostic first; the
11991 // value-shape gate is only consulted on paths that already
11992 // satisfy the absolute-prefix invariant.
11993 let mut s = three_member_spec();
11994 // `bad path` would fire the whitespace rule under the
11995 // value-shape gate, but missing-leading-`/` is the more
11996 // self-locating diagnostic.
11997 s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
11998 let err = s.validate().unwrap_err();
11999 assert!(
12000 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
12001 "got {err:?}"
12002 );
12003 }
12004
12005 #[test]
12006 fn entrada_path_invalid_fires_before_duplicate_check() {
12007 // Ordering pin: a malformed path on the *first* entry of a
12008 // would-be duplicate pair fires the value-shape gate before
12009 // the duplicate gate, mirroring the
12010 // `placement_cluster_invalid_fires_before_duplicate_check`
12011 // (6cbb900) pattern on the peer axis.
12012 let mut s = three_member_spec();
12013 s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
12014 let err = s.validate().unwrap_err();
12015 assert!(
12016 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
12017 "got {err:?}"
12018 );
12019 }
12020
12021 #[test]
12022 fn entrada_path_diagnostic_carries_offending_path() {
12023 // Diagnostic-shape pin — the offending path + a non-empty
12024 // reason flow through verbatim so the author can grep their
12025 // caixa.lisp for `:paths` and fix it in one edit. Same shape
12026 // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
12027 let mut s = three_member_spec();
12028 s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
12029 let err = s.validate().unwrap_err();
12030 match err {
12031 AplicacaoError::EntradaPathInvalid { path, reason } => {
12032 assert_eq!(path, "/api?q=1");
12033 assert!(!reason.is_empty(), "reason field must be non-empty");
12034 }
12035 other => panic!("expected EntradaPathInvalid, got {other:?}"),
12036 }
12037 }
12038
12039 #[test]
12040 fn rejects_entrada_path_with_curly_brace_template_form() {
12041 // Per-axis pin on the shared `is_gateway_api_http_path`
12042 // reserved-byte arm: the canonical "I wrote an OpenAPI
12043 // path-template `{id}` instead of the Gateway API `:id` form"
12044 // footgun the K8s apiserver would otherwise catch at admission
12045 // time on every `HTTPRoute.spec.rules[].matches[].path.value`
12046 // landing site, far from the caixa.lisp. Surfaces as
12047 // `EntradaPathInvalid` carrying the offending path verbatim
12048 // plus the canonical `%7B`/`%7D` percent-encoding remediation
12049 // — the substrate-side `gateway_api_http_path_rejects_every_
12050 // reserved_printable_ascii_byte` predicate-level sweep pins the
12051 // full eleven-byte set; this per-axis pin confirms the
12052 // diagnostic flows through to the `EntradaPathInvalid` variant.
12053 let mut s = three_member_spec();
12054 s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
12055 let err = s.validate().unwrap_err();
12056 assert!(
12057 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
12058 if path == "/api/cart/{id}"
12059 && reason.contains("reserved character")
12060 && reason.contains("'{'")
12061 && reason.contains("%7B")),
12062 "got {err:?}"
12063 );
12064 }
12065
12066 #[test]
12067 fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
12068 // Per-axis peer of `rejects_entrada_path_with_curly_brace_
12069 // template_form` on the sibling `:contratos :endpoint` axis.
12070 // Same shared `is_gateway_api_http_path` reserved-byte arm
12071 // fires through `ContratoEndpointInvalid`, with the offending
12072 // endpoint + `:de` + `:para` + reason flowing through verbatim.
12073 // Pins that the lifted predicate's tightening lands on both
12074 // caller axes simultaneously — one source of truth for the
12075 // Gateway API HTTPPathMatch.value accepted set.
12076 let err = contrato_endpoint_err("/api/cart/{id}");
12077 assert!(
12078 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12079 if endpoint == "/api/cart/{id}"
12080 && reason.contains("reserved character")
12081 && reason.contains("'{'")
12082 && reason.contains("%7B")),
12083 "got {err:?}"
12084 );
12085 }
12086
12087 // ── :entrada :host value-shape gate ──────────────────────────────
12088 //
12089 // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
12090 // the sibling `:host` axis. Every authoring footgun the K8s
12091 // Gateway API v1 apiserver would catch at admission time becomes
12092 // a caixa-build-time `EntradaHostInvalid` with the offending
12093 // `:host` named verbatim. Same diagnostic shape as
12094 // `MembroVersaoInvalid` (9888b13).
12095
12096 #[test]
12097 fn rejects_entrada_host_with_scheme() {
12098 // Fail-before-pass-after pin — pre-gate codebases silently
12099 // accepted `https://…` and the apiserver rejected it at apply
12100 // time with no source citation.
12101 let mut s = three_member_spec();
12102 s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
12103 let err = s.validate().unwrap_err();
12104 assert!(
12105 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12106 if host == "https://checkout.quero.cloud"),
12107 "got {err:?}"
12108 );
12109 }
12110
12111 #[test]
12112 fn rejects_entrada_host_with_port() {
12113 // The `:8080` port suffix is the canonical "I forgot the port
12114 // belongs in `:entrada :port`" footgun. The top-level `:` arm
12115 // (introduced after the per-label loop-only impl silently
12116 // surfaced a deep "label \"cloud:8080\" contains invalid
12117 // character ':'" leak) names the canonical fix verbatim — the
12118 // `:entrada :port` slot.
12119 let mut s = three_member_spec();
12120 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
12121 let err = s.validate().unwrap_err();
12122 assert!(
12123 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12124 if host == "checkout.quero.cloud:8080"
12125 && reason.contains(":entrada :port")),
12126 "got {err:?}"
12127 );
12128 }
12129
12130 #[test]
12131 fn rejects_entrada_host_with_trailing_colon() {
12132 // Trailing `:` (e.g. an in-progress `:host "example.com:"`
12133 // edit) — the per-label loop would land it as a deep
12134 // "label \"com:\" must start and end with an alphanumeric"
12135 // / "contains invalid character ':'" leak. The top-level
12136 // `:` arm pre-empts with the canonical `:port` slot
12137 // diagnostic.
12138 let mut s = three_member_spec();
12139 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
12140 let err = s.validate().unwrap_err();
12141 assert!(
12142 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12143 if host == "checkout.quero.cloud:"
12144 && reason.contains(":entrada :port")),
12145 "got {err:?}"
12146 );
12147 }
12148
12149 #[test]
12150 fn rejects_entrada_host_unbracketed_ipv6_literal() {
12151 // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
12152 // literals across the board (peer with `rejects_entrada_host_
12153 // ipv4_literal` above for the four-label-all-digit IPv4 arm).
12154 // Before this top-level `:` arm landed the per-label loop
12155 // surfaced a single-label byte-class diagnostic that named the
12156 // `:` byte but not the IP-literal prohibition. The top-level
12157 // `:` arm names both the `:port` slot and the IP-literal
12158 // prohibition verbatim, so an author whose `:host "2001:..."`
12159 // value lands here gets a self-locating fix either way.
12160 let mut s = three_member_spec();
12161 s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
12162 let err = s.validate().unwrap_err();
12163 assert!(
12164 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12165 if host == "2001:db8::1"
12166 && reason.contains("IPv6")),
12167 "got {err:?}"
12168 );
12169 }
12170
12171 #[test]
12172 fn rejects_entrada_host_wildcard_with_port() {
12173 // Wildcard host with port suffix — the `*.` strip and the
12174 // per-label loop on `["foo", "quero", "cloud:8080"]` would
12175 // surface the deep byte-class leak. The top-level `:` arm sits
12176 // upstream of the `*.` strip, so it names the canonical `:port`
12177 // fix verbatim regardless of whether the host is wildcard-led.
12178 let mut s = three_member_spec();
12179 s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
12180 let err = s.validate().unwrap_err();
12181 assert!(
12182 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
12183 if host == "*.quero.cloud:8080"
12184 && reason.contains(":entrada :port")),
12185 "got {err:?}"
12186 );
12187 }
12188
12189 #[test]
12190 fn rejects_entrada_host_with_path() {
12191 let mut s = three_member_spec();
12192 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
12193 let err = s.validate().unwrap_err();
12194 assert!(
12195 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12196 if host == "checkout.quero.cloud/api"),
12197 "got {err:?}"
12198 );
12199 }
12200
12201 #[test]
12202 fn rejects_entrada_host_with_uppercase() {
12203 // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
12204 // rejected, not silently lower-cased.
12205 let mut s = three_member_spec();
12206 s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
12207 let err = s.validate().unwrap_err();
12208 assert!(
12209 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12210 if reason.contains("uppercase")),
12211 "got {err:?}"
12212 );
12213 }
12214
12215 #[test]
12216 fn rejects_entrada_host_with_underscore() {
12217 // RFC 1123 allows `[a-z0-9-]` only; underscore is the
12218 // canonical "I'm thinking of HTTP cookies / SRV records" leak.
12219 let mut s = three_member_spec();
12220 s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
12221 let err = s.validate().unwrap_err();
12222 assert!(
12223 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12224 if reason.contains('_')),
12225 "got {err:?}"
12226 );
12227 }
12228
12229 #[test]
12230 fn rejects_entrada_host_ipv4_literal() {
12231 // Gateway API v1 explicitly forbids IP literals as Hostnames.
12232 let mut s = three_member_spec();
12233 s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
12234 let err = s.validate().unwrap_err();
12235 assert!(
12236 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12237 if reason.contains("IPv4")),
12238 "got {err:?}"
12239 );
12240 }
12241
12242 #[test]
12243 fn rejects_entrada_host_with_trailing_dot() {
12244 // The Gateway API regex anchors at end-of-string with no
12245 // trailing `.` allowance — the FQDN root-dot form is rejected.
12246 let mut s = three_member_spec();
12247 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
12248 let err = s.validate().unwrap_err();
12249 assert!(
12250 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12251 if host == "checkout.quero.cloud."),
12252 "got {err:?}"
12253 );
12254 }
12255
12256 #[test]
12257 fn rejects_entrada_host_with_leading_dot() {
12258 let mut s = three_member_spec();
12259 s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
12260 let err = s.validate().unwrap_err();
12261 assert!(
12262 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12263 if reason.contains("empty label")),
12264 "got {err:?}"
12265 );
12266 }
12267
12268 #[test]
12269 fn rejects_entrada_host_with_consecutive_dots() {
12270 let mut s = three_member_spec();
12271 s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
12272 let err = s.validate().unwrap_err();
12273 assert!(
12274 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12275 if reason.contains("empty label")),
12276 "got {err:?}"
12277 );
12278 }
12279
12280 #[test]
12281 fn rejects_entrada_host_with_leading_hyphen_label() {
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("alphanumeric")),
12288 "got {err:?}"
12289 );
12290 }
12291
12292 #[test]
12293 fn rejects_entrada_host_with_trailing_hyphen_label() {
12294 let mut s = three_member_spec();
12295 s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
12296 let err = s.validate().unwrap_err();
12297 assert!(
12298 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12299 if reason.contains("alphanumeric")),
12300 "got {err:?}"
12301 );
12302 }
12303
12304 #[test]
12305 fn rejects_entrada_host_with_inner_wildcard() {
12306 // Gateway API allows `*` only as the first label (`*.foo`);
12307 // any inner or trailing `*` is rejected.
12308 let mut s = three_member_spec();
12309 s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
12310 let err = s.validate().unwrap_err();
12311 assert!(
12312 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12313 if reason.contains("wildcard")),
12314 "got {err:?}"
12315 );
12316 }
12317
12318 #[test]
12319 fn rejects_entrada_host_bare_wildcard() {
12320 // `*.` with no domain is meaningless; Gateway API rejects it.
12321 let mut s = three_member_spec();
12322 s.entrada.as_mut().unwrap().host = "*.".into();
12323 let err = s.validate().unwrap_err();
12324 assert!(
12325 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12326 if reason.contains("wildcard")),
12327 "got {err:?}"
12328 );
12329 }
12330
12331 #[test]
12332 fn rejects_entrada_host_with_whitespace() {
12333 let mut s = three_member_spec();
12334 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12335 let err = s.validate().unwrap_err();
12336 assert!(
12337 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12338 if reason.contains("whitespace")),
12339 "got {err:?}"
12340 );
12341 }
12342
12343 #[test]
12344 fn rejects_entrada_host_space_names_offending_byte() {
12345 // Embedded space in the `:entrada :host` axis surfaces the
12346 // byte-naming diagnostic through the lifted
12347 // `find_ascii_whitespace_byte` predicate. Peer with the
12348 // sibling `parse_rejects_leading_whitespace` pins on
12349 // `supervisor::duration_codec` (a7ae622) — same "the
12350 // diagnostic carries the offending byte's `0x{b:02x}` shape"
12351 // discipline extended from the shared duration codec to the
12352 // Gateway API v1 Hostname axis.
12353 let mut s = three_member_spec();
12354 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
12355 let err = s.validate().unwrap_err();
12356 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12357 panic!("expected EntradaHostInvalid, got {err:?}");
12358 };
12359 assert!(
12360 reason.contains("ASCII whitespace byte"),
12361 "expected byte-naming diagnostic, got {reason:?}"
12362 );
12363 assert!(
12364 reason.contains("0x20"),
12365 "expected offending space byte 0x20, got {reason:?}"
12366 );
12367 }
12368
12369 #[test]
12370 fn rejects_entrada_host_tab_names_offending_byte() {
12371 // Embedded tab byte in the `:entrada :host` axis — the
12372 // canonical paste-from-YAML-block-scalar / paste-from-
12373 // indented-doc footgun. Pins that the lifted predicate covers
12374 // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
12375 // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
12376 // not just the leading-space case the pre-lift `.bytes().any`
12377 // arm's opaque "must not contain whitespace" reason already
12378 // covered. Peer with `parse_rejects_tab_byte` on
12379 // `supervisor::duration_codec` (a7ae622).
12380 let mut s = three_member_spec();
12381 s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
12382 let err = s.validate().unwrap_err();
12383 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12384 panic!("expected EntradaHostInvalid, got {err:?}");
12385 };
12386 assert!(
12387 reason.contains("ASCII whitespace byte"),
12388 "expected byte-naming diagnostic, got {reason:?}"
12389 );
12390 assert!(
12391 reason.contains("0x09"),
12392 "expected offending tab byte 0x09, got {reason:?}"
12393 );
12394 }
12395
12396 #[test]
12397 fn rejects_entrada_host_lf_names_offending_byte() {
12398 // Embedded LF byte in the `:entrada :host` axis — the
12399 // canonical paste-from-shell-heredoc / paste-from-multiline-
12400 // doc footgun the caixa-mesh YAML emitter would silently
12401 // reinterpret at the Gateway API v1 HTTPRoute admission
12402 // layer (an embedded LF byte in a YAML plain scalar either
12403 // truncates the value at the emitter or crashes the parser
12404 // on the k8s-apiserver side). Pins the third representative
12405 // of the full ASCII-whitespace set through the shared
12406 // predicate.
12407 let mut s = three_member_spec();
12408 s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
12409 let err = s.validate().unwrap_err();
12410 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12411 panic!("expected EntradaHostInvalid, got {err:?}");
12412 };
12413 assert!(
12414 reason.contains("ASCII whitespace byte"),
12415 "expected byte-naming diagnostic, got {reason:?}"
12416 );
12417 assert!(
12418 reason.contains("0x0a"),
12419 "expected offending LF byte 0x0a, got {reason:?}"
12420 );
12421 }
12422
12423 #[test]
12424 fn rejects_entrada_host_nbsp_names_offending_codepoint() {
12425 // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
12426 // axis — the canonical paste-from-typography /
12427 // paste-from-word-processor footgun. Before the non-ASCII
12428 // Unicode `White_Space` scan lifted through the shared
12429 // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
12430 // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
12431 // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
12432 // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
12433 // with the far-from-source `label "…" must start and end
12434 // with an alphanumeric` diagnostic — burying the
12435 // paste-from-typography origin under a label-shape leak.
12436 // Peer with the sibling non-ASCII-whitespace pins at
12437 // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
12438 // — 1b75b38), `limits::parse_duration`,
12439 // `limits::parse_millicores`, and the shared duration codec
12440 // — same "the diagnostic carries the offending Unicode
12441 // codepoint's `U+XXXX` shape" discipline extended from every
12442 // typed-magnitude codec to the Gateway API v1 Hostname axis.
12443 let mut s = three_member_spec();
12444 s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
12445 let err = s.validate().unwrap_err();
12446 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12447 panic!("expected EntradaHostInvalid, got {err:?}");
12448 };
12449 assert!(
12450 reason.contains("non-ASCII Unicode whitespace character"),
12451 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12452 );
12453 assert!(
12454 reason.contains("U+00A0"),
12455 "expected offending NBSP codepoint U+00A0, got {reason:?}"
12456 );
12457 }
12458
12459 #[test]
12460 fn rejects_entrada_host_line_separator_names_offending_codepoint() {
12461 // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
12462 // `:entrada :host` axis — the canonical paste-from-web-doc /
12463 // paste-from-published-HTML footgun. `char::is_whitespace`
12464 // returns true for `U+2028` per the Unicode `White_Space`
12465 // property, so `str::trim` at any downstream site would
12466 // silently strip it — same drift class as NBSP but on a
12467 // different codepoint region. Pins the second representative
12468 // (non-Latin-1 `char::is_whitespace` member) through the
12469 // shared predicate. Peer with
12470 // `parse_byte_size_rejects_internal_line_separator` on
12471 // `limits::parse_byte_size` (1b75b38).
12472 let mut s = three_member_spec();
12473 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
12474 let err = s.validate().unwrap_err();
12475 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12476 panic!("expected EntradaHostInvalid, got {err:?}");
12477 };
12478 assert!(
12479 reason.contains("non-ASCII Unicode whitespace character"),
12480 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12481 );
12482 assert!(
12483 reason.contains("U+2028"),
12484 "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
12485 );
12486 }
12487
12488 #[test]
12489 fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
12490 // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
12491 // labels in the `:entrada :host` axis — the canonical
12492 // paste-from-CJK-typography footgun (CJK IMEs default to
12493 // full-width whitespace when the space bar is pressed in
12494 // Japanese / Chinese input modes). Pins the third
12495 // representative of the non-ASCII Unicode `White_Space` set
12496 // through the shared predicate: the CJK block, distinct from
12497 // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
12498 // SEPARATOR `U+2028` — covering the same axis breadth the
12499 // sibling `parse_byte_size_rejects_trailing_ideographic_space`
12500 // (1b75b38) pins on `limits::parse_byte_size`.
12501 let mut s = three_member_spec();
12502 s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
12503 let err = s.validate().unwrap_err();
12504 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
12505 panic!("expected EntradaHostInvalid, got {err:?}");
12506 };
12507 assert!(
12508 reason.contains("non-ASCII Unicode whitespace character"),
12509 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
12510 );
12511 assert!(
12512 reason.contains("U+3000"),
12513 "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
12514 );
12515 }
12516
12517 #[test]
12518 fn rejects_entrada_host_too_long() {
12519 // Total length cap = 253; build a 254-byte host out of two
12520 // 63-byte labels + one 62-byte label + dots.
12521 let mut s = three_member_spec();
12522 let big = format!(
12523 "{}.{}.{}.{}",
12524 "a".repeat(63),
12525 "b".repeat(63),
12526 "c".repeat(63),
12527 "d".repeat(254 - 63 * 3 - 3)
12528 );
12529 assert_eq!(big.len(), 254);
12530 s.entrada.as_mut().unwrap().host = big;
12531 let err = s.validate().unwrap_err();
12532 assert!(
12533 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12534 if reason.contains("max length of 253")),
12535 "got {err:?}"
12536 );
12537 }
12538
12539 #[test]
12540 fn rejects_entrada_host_label_too_long() {
12541 let mut s = three_member_spec();
12542 // 64-byte label — one over the per-label cap.
12543 s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
12544 let err = s.validate().unwrap_err();
12545 assert!(
12546 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
12547 if reason.contains("label max length of 63")),
12548 "got {err:?}"
12549 );
12550 }
12551
12552 #[test]
12553 fn entrada_host_diagnostic_carries_offending_host() {
12554 // Diagnostic-shape pin — the offending host + a non-empty
12555 // reason flow through verbatim so the author can grep their
12556 // caixa.lisp for `:host "<host>"` and fix it in one edit.
12557 let mut s = three_member_spec();
12558 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
12559 let err = s.validate().unwrap_err();
12560 match err {
12561 AplicacaoError::EntradaHostInvalid { host, reason } => {
12562 assert_eq!(host, "checkout.quero.cloud:8080");
12563 assert!(!reason.is_empty(), "reason field must be non-empty");
12564 }
12565 other => panic!("expected EntradaHostInvalid, got {other:?}"),
12566 }
12567 }
12568
12569 #[test]
12570 fn entrada_host_empty_takes_precedence_over_invalid() {
12571 // Ordering pin: `EmptyEntradaHost` is the more self-locating
12572 // diagnostic on `""` and must lead — `validate_entrada_host`
12573 // is only reached after the empty-check fires at the call
12574 // site. (The predicate itself defends against direct
12575 // invocation by returning the same error on `""`.)
12576 let mut s = three_member_spec();
12577 s.entrada.as_mut().unwrap().host = String::new();
12578 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
12579 }
12580
12581 #[test]
12582 fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
12583 // Ordering pin: a missing :para member is the more
12584 // self-locating diagnostic and fires before the host gate.
12585 let mut s = three_member_spec();
12586 let e = s.entrada.as_mut().unwrap();
12587 e.para = "ghost".into();
12588 e.host = "BAD HOST".into();
12589 let err = s.validate().unwrap_err();
12590 assert!(
12591 matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
12592 "got {err:?}"
12593 );
12594 }
12595
12596 #[test]
12597 fn entrada_host_invalid_fires_before_port_zero() {
12598 // Ordering pin: the host gate fires before the port gate so
12599 // a malformed host is named even when the port is also wrong.
12600 let mut s = three_member_spec();
12601 let e = s.entrada.as_mut().unwrap();
12602 e.host = "Checkout.quero.cloud".into();
12603 e.port = 0;
12604 let err = s.validate().unwrap_err();
12605 assert!(
12606 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
12607 if host == "Checkout.quero.cloud"),
12608 "got {err:?}"
12609 );
12610 }
12611
12612 #[test]
12613 fn entrada_accepts_canonical_hosts() {
12614 // Positive-control sweep — every form the Gateway API
12615 // apiserver accepts must round-trip through validate. Covers
12616 // a plain DNS subdomain, a leading wildcard, a single-label
12617 // host (cluster-internal), a max-length-edge label, a
12618 // hyphen-bearing label, and a Punycode IDN label.
12619 for host in [
12620 "checkout.quero.cloud",
12621 "*.quero.cloud",
12622 "checkout",
12623 // 63-byte label — exactly the per-label cap.
12624 "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
12625 "foo-bar.quero.cloud",
12626 // Punycode IDN — valid because the author pre-encoded.
12627 "xn--bcher-kva.example.com",
12628 ] {
12629 let mut s = three_member_spec();
12630 s.entrada.as_mut().unwrap().host = host.into();
12631 s.validate()
12632 .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
12633 }
12634 }
12635
12636 #[test]
12637 fn entrada_host_max_length_validates() {
12638 // 253-byte host is the cap exactly — must validate. Build a
12639 // 253-byte host out of three 63-byte labels + one 61-byte
12640 // label + 3 dots = 252 bytes, then pad one byte to 253.
12641 let mut s = three_member_spec();
12642 let host = format!(
12643 "{}.{}.{}.{}",
12644 "a".repeat(63),
12645 "b".repeat(63),
12646 "c".repeat(63),
12647 "d".repeat(253 - 63 * 3 - 3)
12648 );
12649 assert_eq!(host.len(), 253);
12650 s.entrada.as_mut().unwrap().host = host;
12651 s.validate().unwrap();
12652 }
12653
12654 #[test]
12655 fn entrada_host_total_length_cap_threads_lifted_render_const() {
12656 // Cross-crate-side pin: the aplicacao-side `:entrada :host`
12657 // total-length gate now reads the K8s Gateway API v1 Hostname
12658 // `maxLength: 253` cap from the lifted
12659 // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
12660 // of truth — the same constant every future Gateway-API-Hostname
12661 // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
12662 // materializer's per-host validator, the future per-`Certificate`
12663 // SAN emitter for cert-manager, the multi-`:entrada`
12664 // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
12665 // from. Before the lift, the aplicacao-side reader consumed a
12666 // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
12667 // 253-byte value as the peer render-side canonical bounds
12668 // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
12669 // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
12670 // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
12671 // module boundary — a future 253-byte drift on either side would
12672 // silently split into two axes' worth of admission-schema mismatch
12673 // without a build-time signal. Pin the cap through a fresh 254-
12674 // byte host that hits the total-length arm, then read the reason
12675 // for the exact byte count the shared constant carries: any future
12676 // regression on the lift (a private alias reintroduced, a hard-
12677 // coded literal at the arm, a mismatch between the aplicacao-side
12678 // and render-side canonicals) surfaces as this pin's diagnostic
12679 // failing to match, not as a per-cluster admission rejection far
12680 // from the caixa.lisp source line.
12681 let mut s = three_member_spec();
12682 let over_cap = format!(
12683 "{}.{}.{}.{}",
12684 "a".repeat(63),
12685 "b".repeat(63),
12686 "c".repeat(63),
12687 "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
12688 );
12689 assert_eq!(
12690 over_cap.len(),
12691 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
12692 );
12693 s.entrada.as_mut().unwrap().host = over_cap;
12694 let err = s.validate().unwrap_err();
12695 match err {
12696 AplicacaoError::EntradaHostInvalid { reason, .. } => {
12697 let needle = format!(
12698 "max length of {} bytes",
12699 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
12700 );
12701 assert!(
12702 reason.contains(&needle),
12703 "diagnostic must name the lifted \
12704 GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
12705 );
12706 }
12707 other => panic!("expected EntradaHostInvalid, got {other:?}"),
12708 }
12709 }
12710
12711 #[test]
12712 fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
12713 // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
12714 // on the per-label-cap axis. Before the lift, the aplicacao-side
12715 // per-label arm consumed a private const alias
12716 // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
12717 // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
12718 // split from it at the module boundary — every `.`-separated
12719 // label in a Gateway API v1 Hostname is a DNS-1123 label under
12720 // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
12721 // so the private alias's 63 and the canonical const's 63 were
12722 // pinning the same underlying rule twice. Pin the cap through a
12723 // 64-byte label that hits the per-label arm, then read the reason
12724 // for the exact byte count the shared constant carries: any
12725 // future drift on either side (a private alias reintroduced, a
12726 // hard-coded literal at the arm, a mismatch between the two
12727 // 63-byte pins) surfaces at this pin's diagnostic rather than at
12728 // a per-cluster admission rejection whose "field is invalid"
12729 // opacity misframes the root cause.
12730 let mut s = three_member_spec();
12731 let over_cap_label = format!(
12732 "{}.quero.cloud",
12733 "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
12734 );
12735 s.entrada.as_mut().unwrap().host = over_cap_label;
12736 let err = s.validate().unwrap_err();
12737 match err {
12738 AplicacaoError::EntradaHostInvalid { reason, .. } => {
12739 let needle = format!(
12740 "label max length of {} bytes",
12741 crate::render::DNS_1123_LABEL_MAX_LEN,
12742 );
12743 assert!(
12744 reason.contains(&needle),
12745 "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
12746 cap verbatim on the per-label arm, got: {reason:?}",
12747 );
12748 }
12749 other => panic!("expected EntradaHostInvalid, got {other:?}"),
12750 }
12751 }
12752
12753 #[test]
12754 fn entrada_with_empty_paths_validates() {
12755 // Empty `:paths` is the documented "match every path" form;
12756 // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
12757 let mut s = three_member_spec();
12758 s.entrada.as_mut().unwrap().paths = vec![];
12759 s.validate().unwrap();
12760 }
12761
12762 #[test]
12763 fn entrada_root_path_validates() {
12764 // The author-supplied bare-root `:entrada :paths` entry is the
12765 // same byte-shape the peer emit-side catch-all constant
12766 // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
12767 // the author's `:paths` list is empty — sweeping the test-side
12768 // probe literal onto the lifted const closes the two-axis pin
12769 // (author-side admit + emit-side canonical fallback) around
12770 // one `&'static str`, so a future rebrand of the catch-all
12771 // reaches both consumers by construction. Peer to
12772 // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
12773 // on the canonical-literal pin surface.
12774 let mut s = three_member_spec();
12775 s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
12776 s.validate().unwrap();
12777 }
12778
12779 #[test]
12780 fn placement_strategy_variants_round_trip() {
12781 for s in [
12782 PlacementStrategy::SingleNode,
12783 PlacementStrategy::Replicated,
12784 PlacementStrategy::Sharded,
12785 ] {
12786 let p = Placement {
12787 estrategia: s,
12788 clusters: vec!["rio".into()],
12789 affinity: None,
12790 shard_key: if s.is_sharded() {
12791 Some("$key".into())
12792 } else {
12793 None
12794 },
12795 };
12796 let json = serde_json::to_string(&p).unwrap();
12797 let back: Placement = serde_json::from_str(&json).unwrap();
12798 assert_eq!(back, p);
12799 }
12800 }
12801
12802 #[test]
12803 fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
12804 // The fail-before-pass-after pin: pre-lift there was no
12805 // single-source binding between the [`PlacementStrategy`]
12806 // variant name the `Serialize` derive emits and the byte-
12807 // string every downstream cluster-side dispatcher (the
12808 // `lareira-fleet-programs` aggregator's per-entry strategy
12809 // branch, the future `app-operator` reconciler, the M3
12810 // Adaptive compression pass's per-strategy weighting) probes
12811 // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
12812 // future `#[serde(rename_all = "kebab-case")]` attribute on
12813 // the enum — or a variant rename in the source — would
12814 // silently rebrand the emitted scalar under one spelling
12815 // while every downstream dispatcher still probed the other,
12816 // with the failure surfacing at the aggregator's dispatch
12817 // step or the operator's reconcile posture (workloads coming
12818 // up under the `default()` `Replicated` arm rather than the
12819 // typed slot's declared strategy) far from the source
12820 // rebrand commit and with no field naming the drift. Pinning
12821 // the two paths (the `Serialize` derive's serialized string
12822 // AND the [`PlacementStrategy::as_str`] helper) to the same
12823 // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
12824 // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
12825 // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
12826 // makes any future drift on either endpoint fail here at
12827 // caixa-core build time.
12828 for (variant, expected) in [
12829 (
12830 PlacementStrategy::SingleNode,
12831 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
12832 ),
12833 (
12834 PlacementStrategy::Replicated,
12835 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
12836 ),
12837 (
12838 PlacementStrategy::Sharded,
12839 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
12840 ),
12841 ] {
12842 let json = serde_json::to_string(&variant).unwrap();
12843 assert_eq!(
12844 json,
12845 format!("\"{expected}\""),
12846 "PlacementStrategy::{variant:?} must serialize to {expected:?}"
12847 );
12848 assert_eq!(
12849 variant.as_str(),
12850 expected,
12851 "PlacementStrategy::{variant:?}.as_str() must return the lifted \
12852 M3_PLACEMENT_ESTRATEGIA_* constant"
12853 );
12854 }
12855 }
12856
12857 #[test]
12858 fn m3_placement_estrategia_consts_are_pairwise_distinct() {
12859 // Cross-arm drift-detection pin on the M3
12860 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
12861 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
12862 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
12863 // scalar-value pentad: a future collapse of two canonical
12864 // variant byte-strings onto the same value (an accidental
12865 // copy-paste flip of
12866 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
12867 // read `"SingleNode"`, a per-arm rebrand that lands one const
12868 // without touching its paired peer) would silently reroute
12869 // every downstream operator's per-strategy dispatch onto the
12870 // sibling arm's reconcile branch and pass every
12871 // propagation-probe test that expected only the stale arm's
12872 // value — a `Replicated`-declared Aplicacao would come up
12873 // under the `SingleNode` primary-and-standby reconcile
12874 // posture, so every-cluster active-active workload would
12875 // silently collapse onto one-cluster-runs-at-a-time takeover
12876 // semantics against its declared strategy, with no field
12877 // naming the strategy-value drift root cause. Peer of the
12878 // sibling
12879 // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
12880 // (09ffb2d) /
12881 // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
12882 // (ccdf955) /
12883 // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
12884 // (d739850) distinctness pins on the sibling OTP-shape /
12885 // caixa-kind closed-set typed-enum discriminator axes — the
12886 // fourth (and structurally the M3 mesh-primitive-defining)
12887 // closed-set typed-enum axis to converge on the same
12888 // "pairwise-distinct-by-construction" discipline.
12889 //
12890 // Fail-before-pass-after locally verified by mutating
12891 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
12892 // also read `"SingleNode"` — this pin fires as expected;
12893 // restoring passes.
12894 let all = [
12895 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
12896 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
12897 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
12898 ];
12899 for (i, a) in all.iter().enumerate() {
12900 for (j, b) in all.iter().enumerate() {
12901 if i != j {
12902 assert_ne!(
12903 a, b,
12904 "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
12905 distinct — got duplicate {a:?} at indices {i} and {j}",
12906 );
12907 }
12908 }
12909 }
12910 }
12911
12912 #[test]
12913 fn placement_strategy_display_routes_through_as_str_helper() {
12914 // The fail-before-pass-after pin: pre-lift the sibling
12915 // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
12916 // / [`crate::supervisor::RestartPolicy`] both carried a stable
12917 // [`std::fmt::Display`] surface via their
12918 // `#[discriminant(also_display)]` gen-platform derive, but
12919 // [`PlacementStrategy`] did not — every consumer reaching for
12920 // a strategy byte-string past the wire format had to pick
12921 // between three paths ([`PlacementStrategy::as_str`], the
12922 // `Serialize` derive's serialized string, or `format!("{v:?}")`
12923 // on the `Debug` derive), any two of which a future variant
12924 // rename or `#[serde(rename_all = "kebab-case")]` attribute
12925 // would silently desynchronize. Wiring [`std::fmt::Display`]
12926 // through [`PlacementStrategy::as_str`] closes the third path:
12927 // every `format!("{v}")` call reaches the same lifted
12928 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
12929 // and the [`PlacementStrategy::as_str`] helper already route
12930 // through, so a future variant rename lands at exactly one
12931 // place. Pin the routing here so a future
12932 // `impl std::fmt::Display for PlacementStrategy` reimplementation
12933 // that hand-rolls the arms instead of delegating to
12934 // [`PlacementStrategy::as_str`] fails at caixa-core build time.
12935 for variant in [
12936 PlacementStrategy::SingleNode,
12937 PlacementStrategy::Replicated,
12938 PlacementStrategy::Sharded,
12939 ] {
12940 assert_eq!(
12941 variant.to_string(),
12942 variant.as_str(),
12943 "PlacementStrategy::{variant:?} Display must route through \
12944 PlacementStrategy::as_str (single source of truth: the lifted \
12945 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
12946 );
12947 }
12948 }
12949
12950 #[test]
12951 fn placement_strategy_display_matches_serialized_wire_byte_string() {
12952 // The fail-before-pass-after pin on the second half of the
12953 // three-path convergence: `Display` (user-facing text) agrees
12954 // byte-for-byte with the `Serialize` derive's wire format
12955 // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
12956 // scalar) on every variant. Pre-lift the two paths were
12957 // structurally independent — a future
12958 // `#[serde(rename_all = "kebab-case")]` attribute on the enum
12959 // would silently rebrand the emitted wire scalar
12960 // (`single-node`, `replicated`, `sharded`) while every consumer
12961 // that pretty-prints the strategy (the M3 diagnostic templates,
12962 // the future `feira app graph` per-Aplicacao strategy line,
12963 // the future M4 CR materializer's admission-webhook rejection
12964 // body) would still emit the TitleCase form the `as_str` /
12965 // `Display` route returns, with the mismatch surfacing at
12966 // consumer parse time / operator dispatch time far from the
12967 // source rebrand commit. Pin the two paths byte-for-byte here
12968 // so any future serde-attribute or variant-rename drift is a
12969 // caixa-core-build-time test failure at this call, not a
12970 // silent per-consumer dispatch miss.
12971 for variant in [
12972 PlacementStrategy::SingleNode,
12973 PlacementStrategy::Replicated,
12974 PlacementStrategy::Sharded,
12975 ] {
12976 let wire = serde_json::to_string(&variant).unwrap();
12977 // Strip the outer `"…"` the JSON string form carries — the
12978 // wire scalar the K8s / YAML apiserver consumes is the
12979 // enclosed byte-string, not the quote wrapper.
12980 let unquoted = wire
12981 .strip_prefix('"')
12982 .and_then(|s| s.strip_suffix('"'))
12983 .expect("serialized PlacementStrategy is a JSON string");
12984 assert_eq!(
12985 variant.to_string(),
12986 unquoted,
12987 "PlacementStrategy::{variant:?} Display byte-string must match the \
12988 Serialize derive's wire byte-string (three-path convergence: \
12989 Display + as_str + Serialize all resolve to the same \
12990 M3_PLACEMENT_ESTRATEGIA_* const)"
12991 );
12992 }
12993 }
12994
12995 #[test]
12996 fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
12997 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
12998 // derive on [`PlacementStrategy`]: for each of the three variants
12999 // exactly one of the generated `is_single_node` / `is_replicated`
13000 // / `is_sharded` predicates returns `true` and the other two
13001 // return `false`. Prior to this derive the three per-arm
13002 // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
13003 // (the `placement_strategy_variants_round_trip` fixture, the
13004 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
13005 // fixture, and the
13006 // `validate_placement_reads_through_lifted_estrategia_accessor`
13007 // fixture) each open-coded a per-arm PartialEq compare against
13008 // the enum variant — three sites that expressed no compile-time
13009 // link back to the closed-set typed dispatch a future fourth
13010 // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
13011 // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
13012 // would have to thread through in lockstep or one fixture would
13013 // silently disagree with the others on which arms consume the
13014 // `:shard-key` axis. Peer of the sibling
13015 // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
13016 // / [`crate::supervisor::RestartPolicy`] /
13017 // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
13018 // the sibling closed-set typed-enum discriminator axes — extends
13019 // the same one-typed-dispatch-per-variant discipline onto the
13020 // fifth (and only remaining) closed-set typed-enum discriminator
13021 // on the caixa surface, closing the axis on the M3 mesh-slot
13022 // family.
13023 let rows: [(PlacementStrategy, [bool; 3]); 3] = [
13024 (PlacementStrategy::SingleNode, [true, false, false]),
13025 (PlacementStrategy::Replicated, [false, true, false]),
13026 (PlacementStrategy::Sharded, [false, false, true]),
13027 ];
13028 for (variant, expected) in rows {
13029 let observed = [
13030 variant.is_single_node(),
13031 variant.is_replicated(),
13032 variant.is_sharded(),
13033 ];
13034 assert_eq!(
13035 observed, expected,
13036 "PlacementStrategy::{variant:?} is_* predicates must partition \
13037 the arm set (single_node, replicated, sharded); got {observed:?}"
13038 );
13039 }
13040 }
13041
13042 #[test]
13043 fn placement_strategy_is_variant_predicates_are_const_fn() {
13044 // The [`gen_platform::IsVariant`] derive emits `const fn`
13045 // predicates on the peer [`crate::CaixaKind`] +
13046 // [`crate::upgrade::UpgradeInstruction`] +
13047 // [`crate::supervisor::RestartStrategy`] +
13048 // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
13049 // pin the same posture on [`PlacementStrategy`] so a future
13050 // accidental downgrade to non-`const` (an added runtime helper
13051 // reachable only from a non-`const` context, a manual hand-rolled
13052 // `impl` that shadows the derive-generated method) trips at
13053 // caixa-core build time rather than surfacing as a downstream
13054 // `const`-context regression far from the derive declaration.
13055 const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
13056 const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
13057 const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
13058 assert!(IS_SINGLE_NODE);
13059 assert!(IS_REPLICATED);
13060 assert!(IS_SHARDED);
13061 }
13062
13063 #[test]
13064 fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
13065 // Pin the M3 diagnostic template routes through the typed
13066 // [`PlacementStrategy`] Display byte-string (rebound from the
13067 // prior `{estrategia:?}` `Debug` route). Pre-lift the two
13068 // routes emitted identical bytes (the `Debug` derive on a
13069 // unit variant emits the variant name verbatim, exactly what
13070 // `as_str` returns), but the two paths were structurally
13071 // independent — a future `#[serde(rename_all = "…")]`
13072 // attribute or variant rename would coordinate the wire /
13073 // `Display` / `as_str` triple through the lifted const but
13074 // leave the `Debug` route on the compiler-derived variant name,
13075 // silently desynchronizing the diagnostic byte-string from the
13076 // wire byte-string. Rebinding the template onto `Display`
13077 // ties the diagnostic to the same lifted
13078 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
13079 // emits — drift becomes structurally impossible. Pin the
13080 // byte-string here so a future edit that reverts the template
13081 // to `{estrategia:?}` is caught at caixa-core test time, not
13082 // at consumer dispatch time.
13083 for (variant, expected_scalar) in [
13084 (
13085 PlacementStrategy::SingleNode,
13086 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13087 ),
13088 (
13089 PlacementStrategy::Replicated,
13090 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13091 ),
13092 (
13093 PlacementStrategy::Sharded,
13094 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
13095 ),
13096 ] {
13097 let err = AplicacaoError::PlacementWithoutClusters {
13098 estrategia: variant,
13099 };
13100 let msg = err.to_string();
13101 assert!(
13102 msg.starts_with(&format!(":placement {expected_scalar} requires")),
13103 "PlacementWithoutClusters diagnostic for {variant:?} must open \
13104 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
13105 );
13106 }
13107 }
13108
13109 #[test]
13110 fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
13111 // Peer of
13112 // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
13113 // on the second M3 diagnostic that carries the typed
13114 // [`PlacementStrategy`] in its `#[error(…)]` template. Both
13115 // diagnostics now route the strategy scalar through the same
13116 // [`std::fmt::Display`] surface, tying the diagnostic
13117 // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
13118 // const set the wire format also emits. The two non-Sharded
13119 // arms are exercised here (the diagnostic exists to flag a
13120 // `:shard-key` slot the current strategy will never consume);
13121 // the peer `Sharded` arm never reaches this diagnostic (the
13122 // `Sharded` strategy consumes `:shard-key` — the
13123 // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
13124 // slot instead).
13125 for (variant, expected_scalar) in [
13126 (
13127 PlacementStrategy::SingleNode,
13128 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
13129 ),
13130 (
13131 PlacementStrategy::Replicated,
13132 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
13133 ),
13134 ] {
13135 let err = AplicacaoError::ShardKeyOnNonSharded {
13136 estrategia: variant,
13137 shard_key: "$tenantId".into(),
13138 };
13139 let msg = err.to_string();
13140 assert!(
13141 msg.starts_with(&format!(":placement {expected_scalar} carries")),
13142 "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
13143 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
13144 );
13145 }
13146 }
13147
13148 #[test]
13149 fn rejects_zero_policy_timeout() {
13150 let mut s = three_member_spec();
13151 s.politicas.timeout = Some(Duration::ZERO);
13152 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
13153 }
13154
13155 #[test]
13156 fn rejects_zero_policy_retries() {
13157 let mut s = three_member_spec();
13158 s.politicas.retries = Some(0);
13159 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
13160 }
13161
13162 #[test]
13163 fn rejects_policy_retries_above_cap() {
13164 // The fail-before-pass-after pin: `Some(11)` is structurally
13165 // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
13166 // passed validate on every pre-gate codebase because the
13167 // typed slot's only check was the zero-floor arm. The
13168 // thundering-herd amplification vector only surfaced at the
13169 // runtime substrate (Envoy / Cilium L7 retry overlay)
13170 // far from the source caixa.lisp with no field naming the
13171 // offending policy.
13172 let mut s = three_member_spec();
13173 s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
13174 assert_eq!(
13175 s.validate().unwrap_err(),
13176 AplicacaoError::PolicyRetriesExceedsCap {
13177 retries: POLICY_RETRIES_MAX + 1
13178 }
13179 );
13180 }
13181
13182 #[test]
13183 fn rejects_policy_retries_far_above_cap() {
13184 // The `u32::MAX` worst case — the four-billion-retry policy
13185 // a typo (`(:retries 4294967295)`) or struct-literal
13186 // copy-paste lands in the slot. Pin the cap arm's coverage
13187 // explicitly across the full `u32` overflow so a future
13188 // relaxation that drops the upper bound surfaces here.
13189 let mut s = three_member_spec();
13190 s.politicas.retries = Some(u32::MAX);
13191 assert_eq!(
13192 s.validate().unwrap_err(),
13193 AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
13194 );
13195 }
13196
13197 #[test]
13198 fn accepts_policy_retries_at_cap() {
13199 // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
13200 // must validate. The cap is inclusive on the top edge,
13201 // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
13202 // discipline on the sibling [`crate::LimitsSpec::memory`]
13203 // axis. Pin the boundary explicitly so a future off-by-one
13204 // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
13205 // surfaces here as a test failure rather than a silent
13206 // contract narrowing.
13207 let mut s = three_member_spec();
13208 s.politicas.retries = Some(POLICY_RETRIES_MAX);
13209 s.validate()
13210 .expect("retries == POLICY_RETRIES_MAX must validate");
13211 }
13212
13213 #[test]
13214 fn accepts_policy_retries_typical_values() {
13215 // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
13216 // every value in the validated set must pass. The
13217 // Envoy / Istio production-playbook recommendation band
13218 // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
13219 // (`maxRetries ≤ 10`) both lie within this set.
13220 for r in 1..=POLICY_RETRIES_MAX {
13221 let mut s = three_member_spec();
13222 s.politicas.retries = Some(r);
13223 s.validate()
13224 .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
13225 }
13226 }
13227
13228 #[test]
13229 fn policy_retries_zero_takes_precedence_over_cap() {
13230 // The cross-arm ordering pin: `Some(0)` is structurally
13231 // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
13232 // (cap), but the zero-floor diagnostic is the more
13233 // self-locating one (it directly names the omit-axis
13234 // remediation), so the validate gate must fire on zero
13235 // first. Pin the order so a future refactor that reorders
13236 // the arms surfaces here as a test failure rather than a
13237 // silent diagnostic regression. Same shape every other
13238 // zero-then-shape ordering on this surface uses
13239 // ([`AplicacaoError::PolicyTimeoutZero`] then
13240 // [`AplicacaoError::PolicyTimeoutNotCanonical`];
13241 // [`AplicacaoError::PolicyBreakerZeroWindow`] then
13242 // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
13243 let mut s = three_member_spec();
13244 s.politicas.retries = Some(0);
13245 assert_eq!(
13246 s.validate().unwrap_err(),
13247 AplicacaoError::PolicyRetriesZero,
13248 "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
13249 );
13250 }
13251
13252 #[test]
13253 fn policy_retries_cap_diagnostic_carries_offending_value() {
13254 // The diagnostic-shape pin: the offending `u32` is carried
13255 // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
13256 // variant so the surfaced error message names the value the
13257 // author wrote (`":politicas :retries (47) exceeds the
13258 // mesh-policy ceiling …"`), not just the cap. Same
13259 // self-locating diagnostic shape every other typed-cap arm
13260 // on this surface carries
13261 // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
13262 // offending byte count verbatim).
13263 let mut s = three_member_spec();
13264 s.politicas.retries = Some(47);
13265 let err = s.validate().unwrap_err();
13266 assert!(
13267 matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
13268 "got {err:?}"
13269 );
13270 let msg = err.to_string();
13271 assert!(
13272 msg.contains("47"),
13273 ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
13274 );
13275 }
13276
13277 #[test]
13278 fn policy_retries_cap_is_aws_app_mesh_aligned() {
13279 // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
13280 // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
13281 // schema cap — the only upstream mesh-policy schema that
13282 // documents an explicit hard cap. Pinning the literal value
13283 // here surfaces a future drift (a relaxation to 20, a
13284 // tightening to 5) as a deliberate test edit, not a silent
13285 // contract narrowing.
13286 assert_eq!(POLICY_RETRIES_MAX, 10);
13287 }
13288
13289 #[test]
13290 fn rejects_circuit_breaker_zero_max_failures() {
13291 let mut s = three_member_spec();
13292 s.politicas.circuit_breaker = Some(CircuitBreaker {
13293 max_failures: 0,
13294 window: Duration::from_secs(60),
13295 });
13296 assert_eq!(
13297 s.validate().unwrap_err(),
13298 AplicacaoError::PolicyBreakerZeroFailures
13299 );
13300 }
13301
13302 #[test]
13303 fn rejects_circuit_breaker_max_failures_above_cap() {
13304 // The fail-before-pass-after pin: `1001` is structurally one
13305 // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
13306 // silently passed validate on every pre-gate codebase
13307 // because the typed slot's only check was the zero-floor
13308 // arm. The breaker-no-op vector only surfaced at the runtime
13309 // substrate (Envoy / Cilium L7 outlier-detection overlay)
13310 // far from the source caixa.lisp with no field naming the
13311 // offending policy.
13312 let mut s = three_member_spec();
13313 s.politicas.circuit_breaker = Some(CircuitBreaker {
13314 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13315 window: Duration::from_secs(60),
13316 });
13317 assert_eq!(
13318 s.validate().unwrap_err(),
13319 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13320 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13321 }
13322 );
13323 }
13324
13325 #[test]
13326 fn rejects_circuit_breaker_max_failures_far_above_cap() {
13327 // The `u32::MAX` worst case — the four-billion-failure
13328 // threshold a typo (`(:max-failures 4294967295)`) or a
13329 // struct-literal copy-paste lands in the slot. Pin the cap
13330 // arm's coverage explicitly across the full `u32` overflow
13331 // so a future relaxation that drops the upper bound surfaces
13332 // here.
13333 let mut s = three_member_spec();
13334 s.politicas.circuit_breaker = Some(CircuitBreaker {
13335 max_failures: u32::MAX,
13336 window: Duration::from_secs(60),
13337 });
13338 assert_eq!(
13339 s.validate().unwrap_err(),
13340 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13341 max_failures: u32::MAX,
13342 }
13343 );
13344 }
13345
13346 #[test]
13347 fn accepts_circuit_breaker_max_failures_at_cap() {
13348 // The boundary value — exactly
13349 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
13350 // cap is inclusive on the top edge, matching the
13351 // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
13352 // discipline on the sibling capped axes. Pin the boundary
13353 // explicitly so a future off-by-one tightening
13354 // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
13355 // surfaces here as a test failure rather than a silent
13356 // contract narrowing.
13357 let mut s = three_member_spec();
13358 s.politicas.circuit_breaker = Some(CircuitBreaker {
13359 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
13360 window: Duration::from_secs(60),
13361 });
13362 s.validate()
13363 .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
13364 }
13365
13366 #[test]
13367 fn accepts_circuit_breaker_max_failures_typical_values() {
13368 // The documented production-playbook band positive-control
13369 // sweep — every value Hystrix / Istio / Envoy / Polly /
13370 // Resilience4j recommend (5..=50) must pass, plus a sweep
13371 // through the hyperscale band (100, 500, 1000) the cap
13372 // accepts. Pin the inclusive validated set explicitly so a
13373 // future tightening of the ceiling surfaces here.
13374 for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
13375 let mut s = three_member_spec();
13376 s.politicas.circuit_breaker = Some(CircuitBreaker {
13377 max_failures: n,
13378 window: Duration::from_secs(60),
13379 });
13380 s.validate()
13381 .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
13382 }
13383 }
13384
13385 #[test]
13386 fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
13387 // The cross-arm ordering pin: `0` is structurally outside
13388 // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
13389 // (cap), but the zero-floor diagnostic is the more
13390 // self-locating one (it directly names the omit-axis
13391 // remediation), so the validate gate must fire on zero
13392 // first. Same shape every other zero-then-shape ordering on
13393 // this surface uses
13394 // ([`AplicacaoError::PolicyRetriesZero`] then
13395 // [`AplicacaoError::PolicyRetriesExceedsCap`];
13396 // [`AplicacaoError::PolicyTimeoutZero`] then
13397 // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
13398 let mut s = three_member_spec();
13399 s.politicas.circuit_breaker = Some(CircuitBreaker {
13400 max_failures: 0,
13401 window: Duration::from_secs(60),
13402 });
13403 assert_eq!(
13404 s.validate().unwrap_err(),
13405 AplicacaoError::PolicyBreakerZeroFailures,
13406 "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
13407 );
13408 }
13409
13410 #[test]
13411 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
13412 // The cross-arm ordering pin between the cap and the
13413 // sibling `:window` gates (zero-window, canonical-window).
13414 // A breaker carrying both an over-cap `max_failures` AND a
13415 // structurally invalid window (zero, sub-ms) must surface
13416 // the cap diagnostic first — the cap arm is wired
13417 // immediately after the zero-failure arm and strictly
13418 // before the window arms, so the offending value the
13419 // diagnostic names matches the order the author would
13420 // discover the gates by reading top-to-bottom through
13421 // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
13422 // future refactor that reorders the arms surfaces here as a
13423 // test failure rather than a silent diagnostic regression.
13424 let mut s = three_member_spec();
13425 s.politicas.circuit_breaker = Some(CircuitBreaker {
13426 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13427 window: Duration::ZERO,
13428 });
13429 assert_eq!(
13430 s.validate().unwrap_err(),
13431 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13432 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
13433 },
13434 "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
13435 );
13436 }
13437
13438 #[test]
13439 fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
13440 // The diagnostic-shape pin: the offending `u32` is carried
13441 // verbatim into the
13442 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
13443 // variant so the surfaced error message names the value the
13444 // author wrote (`":politicas :circuit-breaker :max-failures
13445 // (50000) exceeds the mesh-policy ceiling …"`), not just
13446 // the cap. Same self-locating diagnostic shape every other
13447 // typed-cap arm on this surface carries
13448 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
13449 // offending retry count verbatim,
13450 // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
13451 // offending byte count verbatim).
13452 let mut s = three_member_spec();
13453 s.politicas.circuit_breaker = Some(CircuitBreaker {
13454 max_failures: 50_000,
13455 window: Duration::from_secs(60),
13456 });
13457 let err = s.validate().unwrap_err();
13458 assert!(
13459 matches!(
13460 err,
13461 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
13462 max_failures: 50_000
13463 }
13464 ),
13465 "got {err:?}"
13466 );
13467 let msg = err.to_string();
13468 assert!(
13469 msg.contains("50000"),
13470 ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
13471 );
13472 }
13473
13474 #[test]
13475 fn policy_breaker_max_failures_cap_pins_canonical_value() {
13476 // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
13477 // value at 1000 — an order of magnitude above every
13478 // documented production-playbook recommendation band
13479 // (Hystrix `requestVolumeThreshold` default 20, Istio
13480 // `outlierDetection.consecutive5xxErrors` default 5, Envoy
13481 // `outlier_detection.consecutive_5xx` default 5, Polly /
13482 // Resilience4j typical 5..=50) and below the
13483 // clearly-pathological "effectively no protection" floor
13484 // (10_000, 100_000, u32::MAX). Pinning the literal value
13485 // here surfaces a future drift (a relaxation to 10_000, a
13486 // tightening to 100) as a deliberate test edit, not a
13487 // silent contract narrowing.
13488 assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
13489 }
13490
13491 #[test]
13492 fn rejects_circuit_breaker_zero_window() {
13493 let mut s = three_member_spec();
13494 s.politicas.circuit_breaker = Some(CircuitBreaker {
13495 max_failures: 5,
13496 window: Duration::ZERO,
13497 });
13498 assert_eq!(
13499 s.validate().unwrap_err(),
13500 AplicacaoError::PolicyBreakerZeroWindow
13501 );
13502 }
13503
13504 #[test]
13505 fn rejects_zero_rate_limit() {
13506 let mut s = three_member_spec();
13507 s.politicas.rate_limit = Some(RateLimit {
13508 rate: 0,
13509 window: Duration::from_secs(1),
13510 });
13511 assert_eq!(
13512 s.validate().unwrap_err(),
13513 AplicacaoError::PolicyRateLimitZero
13514 );
13515 }
13516
13517 #[test]
13518 fn rejects_rate_limit_zero_window() {
13519 // `RateLimit { rate: 100, window: Duration::ZERO }` is
13520 // constructible programmatically (the typed `Duration` field
13521 // imposes no nonzero invariant) but renders through
13522 // `rate_limit_codec::render` as `"100/0s"` — a fragment the
13523 // codec's `parse` rejects as `unknown rate-limit window unit
13524 // "0s"`. Until this validate-time gate landed the typed slot
13525 // accepted the value silently and the round-trip break only
13526 // surfaced at deserialize time (potentially in a downstream
13527 // consumer that never re-validates). Pin the rejection at
13528 // `AplicacaoSpec::validate` so the typed slot's valid set
13529 // matches the codec's round-trippable set structurally.
13530 let mut s = three_member_spec();
13531 s.politicas.rate_limit = Some(RateLimit {
13532 rate: 100,
13533 window: Duration::ZERO,
13534 });
13535 assert_eq!(
13536 s.validate().unwrap_err(),
13537 AplicacaoError::PolicyRateLimitWindowNotCanonical {
13538 window: Duration::ZERO
13539 }
13540 );
13541 }
13542
13543 #[test]
13544 fn rejects_rate_limit_arbitrary_seconds_window() {
13545 // 45 seconds is a valid `Duration` but not one of the three
13546 // canonical rate-limit windows the codec round-trips
13547 // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
13548 // refuses on round-trip — same round-trip-break shape the
13549 // zero-window arm above pins, with a non-zero magnitude to
13550 // guard against a future "reject only zero" half-measure.
13551 let mut s = three_member_spec();
13552 let window = Duration::from_secs(45);
13553 s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
13554 assert_eq!(
13555 s.validate().unwrap_err(),
13556 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13557 );
13558 }
13559
13560 #[test]
13561 fn rejects_rate_limit_two_minute_window() {
13562 // 120 seconds = 2 minutes is a "looks-canonical" but
13563 // not-canonical window: it's a clean integer multiple of the
13564 // minute unit, but the codec only round-trips the
13565 // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
13566 // A `Duration::from_secs(120)` window renders as `"100/120s"`
13567 // which the parser rejects. Pinning this case rules out a
13568 // future "accept any clean multiple of s/m/h" relaxation
13569 // that would silently break the codec contract.
13570 let mut s = three_member_spec();
13571 let window = Duration::from_secs(120);
13572 s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
13573 assert_eq!(
13574 s.validate().unwrap_err(),
13575 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13576 );
13577 }
13578
13579 #[test]
13580 fn rejects_rate_limit_subsecond_window() {
13581 // A sub-second window (e.g. 500ms) is a valid `Duration` but
13582 // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
13583 // Pin the rejection so a future relaxation can't silently
13584 // admit fractional-second windows that the codec can't
13585 // round-trip.
13586 let mut s = three_member_spec();
13587 let window = Duration::from_millis(500);
13588 s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
13589 assert_eq!(
13590 s.validate().unwrap_err(),
13591 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
13592 );
13593 }
13594
13595 #[test]
13596 fn rejects_policy_rate_limit_above_cap() {
13597 // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
13598 // is structurally one past the cap and silently passed
13599 // validate on every pre-gate codebase because the typed slot's
13600 // only `rate` check was the zero-floor arm. The no-op-limiter
13601 // shape only surfaced at the runtime substrate (Envoy's
13602 // `local_rate_limit.token_bucket.max_tokens`, the future
13603 // Cilium L7 rate-limit overlay) far from the source caixa.lisp
13604 // with no field naming the offending policy.
13605 let mut s = three_member_spec();
13606 s.politicas.rate_limit = Some(RateLimit {
13607 rate: POLICY_RATE_LIMIT_MAX + 1,
13608 window: Duration::from_secs(1),
13609 });
13610 assert_eq!(
13611 s.validate().unwrap_err(),
13612 AplicacaoError::PolicyRateLimitExceedsCap {
13613 rate: POLICY_RATE_LIMIT_MAX + 1
13614 }
13615 );
13616 }
13617
13618 #[test]
13619 fn rejects_policy_rate_limit_far_above_cap() {
13620 // The `u32::MAX` worst case — the four-billion-token rate-limit
13621 // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
13622 // copy-paste lands in the slot. Pin the cap arm's coverage
13623 // explicitly across the full `u32` overflow so a future
13624 // relaxation that drops the upper bound surfaces here. Peer to
13625 // `rejects_policy_retries_far_above_cap` on the sibling
13626 // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
13627 // on the sibling `:max-failures` axis.
13628 let mut s = three_member_spec();
13629 s.politicas.rate_limit = Some(RateLimit {
13630 rate: u32::MAX,
13631 window: Duration::from_secs(1),
13632 });
13633 assert_eq!(
13634 s.validate().unwrap_err(),
13635 AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
13636 );
13637 }
13638
13639 #[test]
13640 fn accepts_policy_rate_limit_at_cap() {
13641 // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
13642 // must validate. The cap is inclusive on the top edge, matching
13643 // every other typed upper bound in this crate
13644 // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
13645 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
13646 // across all three canonical windows so a future off-by-one
13647 // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
13648 // window-conditional cap surfaces here as a test failure rather
13649 // than a silent contract narrowing.
13650 for secs in [1u64, 60, 3600] {
13651 let mut s = three_member_spec();
13652 s.politicas.rate_limit = Some(RateLimit {
13653 rate: POLICY_RATE_LIMIT_MAX,
13654 window: Duration::from_secs(secs),
13655 });
13656 s.validate().unwrap_or_else(|e| {
13657 panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
13658 });
13659 }
13660 }
13661
13662 #[test]
13663 fn accepts_policy_rate_limit_typical_values() {
13664 // The documented production-playbook recommendation band —
13665 // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
13666 // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
13667 // Enterprise ~1M per-hour. Every value in the validated set
13668 // must pass; pin the band explicitly so a future tightening
13669 // surfaces here.
13670 for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
13671 for secs in [1u64, 60, 3600] {
13672 let mut s = three_member_spec();
13673 s.politicas.rate_limit = Some(RateLimit {
13674 rate,
13675 window: Duration::from_secs(secs),
13676 });
13677 s.validate().unwrap_or_else(|e| {
13678 panic!("rate={rate} window={secs}s must validate; got {e:?}")
13679 });
13680 }
13681 }
13682 }
13683
13684 #[test]
13685 fn policy_rate_limit_zero_takes_precedence_over_cap() {
13686 // The cross-arm ordering pin: `rate == 0` is structurally
13687 // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
13688 // (cap), but the zero-floor diagnostic is the more
13689 // self-locating one (it directly names the omit-axis
13690 // remediation). Pin the order so a future refactor that
13691 // reorders the arms surfaces here as a test failure rather
13692 // than a silent diagnostic regression. Same shape every other
13693 // zero-then-cap ordering on this surface uses
13694 // ([`AplicacaoError::PolicyRetriesZero`] then
13695 // [`AplicacaoError::PolicyRetriesExceedsCap`];
13696 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
13697 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
13698 let mut s = three_member_spec();
13699 s.politicas.rate_limit = Some(RateLimit {
13700 rate: 0,
13701 window: Duration::from_secs(1),
13702 });
13703 assert_eq!(
13704 s.validate().unwrap_err(),
13705 AplicacaoError::PolicyRateLimitZero,
13706 "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
13707 );
13708 }
13709
13710 #[test]
13711 fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
13712 // Two-axis-bad pin: rate above cap *and* window non-canonical.
13713 // The validate gate must fire on the rate cap first — the
13714 // amplification-shape (no-op limiter) diagnostic is the more
13715 // fundamental one; the window-canonical diagnostic is the
13716 // narrower codec-round-trip shape. Pin the ordering so a future
13717 // refactor that reorders the rate-then-window check arms
13718 // surfaces here as a test failure rather than a silent
13719 // diagnostic regression.
13720 let mut s = three_member_spec();
13721 s.politicas.rate_limit = Some(RateLimit {
13722 rate: POLICY_RATE_LIMIT_MAX + 1,
13723 window: Duration::from_secs(45),
13724 });
13725 assert_eq!(
13726 s.validate().unwrap_err(),
13727 AplicacaoError::PolicyRateLimitExceedsCap {
13728 rate: POLICY_RATE_LIMIT_MAX + 1
13729 },
13730 "above-cap rate must surface the cap diagnostic, not the window diagnostic"
13731 );
13732 }
13733
13734 #[test]
13735 fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
13736 // The diagnostic-shape pin: the offending `u32` is carried
13737 // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
13738 // variant so the surfaced error message names the value the
13739 // author wrote (`":politicas :rate-limit rate (5000000) exceeds
13740 // the mesh-policy ceiling …"`), not just the cap. Same
13741 // self-locating diagnostic shape every other typed-cap arm on
13742 // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
13743 // carries the offending retries count verbatim,
13744 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
13745 // the offending failure count verbatim).
13746 let mut s = three_member_spec();
13747 s.politicas.rate_limit = Some(RateLimit {
13748 rate: 5_000_000,
13749 window: Duration::from_secs(1),
13750 });
13751 let err = s.validate().unwrap_err();
13752 assert!(
13753 matches!(
13754 err,
13755 AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
13756 ),
13757 "got {err:?}"
13758 );
13759 let msg = err.to_string();
13760 assert!(
13761 msg.contains("5000000"),
13762 ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
13763 );
13764 }
13765
13766 #[test]
13767 fn policy_rate_limit_cap_pins_canonical_value() {
13768 // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
13769 // 1_000_000 — two-to-three orders of magnitude above every
13770 // documented production-playbook recommendation band (Envoy /
13771 // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
13772 // Gateway 10_000..=100_000 per-minute) and below the
13773 // clearly-pathological "paste-from-binary blob" floor
13774 // (100_000_000, u32::MAX). Pinning the literal value here
13775 // surfaces a future drift (a relaxation to 10_000_000, a
13776 // tightening to 100_000) as a deliberate test edit, not a
13777 // silent contract narrowing.
13778 assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
13779 }
13780
13781 #[test]
13782 fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
13783 // Both axes are invalid here: rate == 0 *and* window is
13784 // non-canonical. The validate gate must fire on rate first
13785 // (matching the existing `rejects_zero_rate_limit` ordering),
13786 // so the existing diagnostic continues to lead with the
13787 // simpler "zero rate" framing. Pinning the order of checks
13788 // so a future refactor that reorders the arms surfaces here
13789 // as a test failure rather than a silent diagnostic
13790 // regression.
13791 let mut s = three_member_spec();
13792 s.politicas.rate_limit = Some(RateLimit {
13793 rate: 0,
13794 window: Duration::from_secs(45),
13795 });
13796 assert_eq!(
13797 s.validate().unwrap_err(),
13798 AplicacaoError::PolicyRateLimitZero
13799 );
13800 }
13801
13802 #[test]
13803 fn rate_limit_canonical_windows_validate() {
13804 // The three canonical windows the codec round-trips
13805 // losslessly — 1s / 60s / 3600s — must all pass `validate()`
13806 // unchanged. Pin the full canonical set as a positive case
13807 // (the existing `rate_limit_round_trip_seconds` /
13808 // `rate_limit_round_trip_minutes` tests pin the
13809 // serialize-then-deserialize property at the codec layer; this
13810 // test pins the validate-side complement so a future tightening
13811 // of the canonical set — e.g. dropping `:hour` — surfaces here
13812 // as a test failure rather than a silent contract narrowing).
13813 for secs in [1u64, 60, 3600] {
13814 let mut s = three_member_spec();
13815 s.politicas.rate_limit = Some(RateLimit {
13816 rate: 100,
13817 window: Duration::from_secs(secs),
13818 });
13819 s.validate().expect("canonical window must validate");
13820 }
13821 }
13822
13823 #[test]
13824 fn rate_limit_validated_value_round_trips_through_codec() {
13825 // The structural property the validate gate enforces:
13826 // every `RateLimit` past `AplicacaoSpec::validate` round-trips
13827 // losslessly through the `rate_limit_codec` (serialize → string
13828 // → deserialize → equal value). Pin this end-to-end so a future
13829 // change to either side (the validate gate's accepted window
13830 // set, the codec's parse/render unit set) that breaks the
13831 // alignment surfaces here. The previous-state shape (typed
13832 // slot accepts arbitrary `Duration`, codec only round-trips
13833 // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
13834 // window — the validate gate now forecloses that.
13835 for secs in [1u64, 60, 3600] {
13836 let mut s = three_member_spec();
13837 s.politicas.rate_limit = Some(RateLimit {
13838 rate: 250,
13839 window: Duration::from_secs(secs),
13840 });
13841 s.validate().unwrap();
13842 let json = serde_json::to_string(&s.politicas).unwrap();
13843 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13844 assert_eq!(
13845 back.rate_limit, s.politicas.rate_limit,
13846 "every validated :rate-limit must round-trip losslessly through the codec"
13847 );
13848 }
13849 }
13850
13851 #[test]
13852 fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
13853 // The hour-window canonical form (`"<n>/h"`) was missing from
13854 // the prior `rate_limit_round_trip_seconds` / `_minutes` test
13855 // pair. Now that the validate gate pins 3600s as part of the
13856 // canonical set, pin its serialize-side render shape too so
13857 // the third leg of the s/m/h tripod is explicitly tested.
13858 let policy = MeshPolicy {
13859 rate_limit: Some(RateLimit {
13860 rate: 10000,
13861 window: Duration::from_secs(3600),
13862 }),
13863 ..Default::default()
13864 };
13865 let json = serde_json::to_string(&policy).unwrap();
13866 assert!(
13867 json.contains("\"10000/h\""),
13868 "hour-window canonical form must render with `h` suffix (got: {json})"
13869 );
13870 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
13871 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
13872 }
13873
13874 #[test]
13875 fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
13876 // Pin the substrate-primitive [`RateLimit::canonical_unit`]
13877 // typed accessor's accepted-window set against the codec's
13878 // accepted set explicitly. A future addition to the codec
13879 // (e.g. accepting `:day`/`:week` as authoring units) must be
13880 // accompanied by a parallel addition here, and a regression
13881 // that drops one of the three canonical units from either
13882 // side surfaces as a test failure. The accessor is the
13883 // single source of truth for the canonical-window set —
13884 // [`AplicacaoSpec::validate_politicas`]'s canonical-window
13885 // gate and [`rate_limit_codec::render`]'s canonical arm both
13886 // read through it — this test enshrines that its
13887 // `Duration → Option<RateLimitUnit>` projection matches the
13888 // codec's parse / render arms' accepted-window set exactly.
13889 //
13890 // Predecessor: this pin previously read the module-private
13891 // free helper `is_canonical_rate_limit_window` — a delegate
13892 // that composed [`RateLimitUnit::from_window`] with `.is_some()`
13893 // — but the helper had no production consumers left after the
13894 // validate-gate migration onto [`RateLimit::canonical_unit`]
13895 // and was deleted; the closed-set arm-window bijection now
13896 // lives on exactly one typed dispatch on the substrate
13897 // primitive.
13898 let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
13899 RateLimit { rate: 1, window }.canonical_unit()
13900 };
13901 assert!(canonical_unit(Duration::from_secs(1)).is_some());
13902 assert!(canonical_unit(Duration::from_secs(60)).is_some());
13903 assert!(canonical_unit(Duration::from_secs(3600)).is_some());
13904 // Non-canonical windows the accessor rejects.
13905 assert!(canonical_unit(Duration::ZERO).is_none());
13906 assert!(canonical_unit(Duration::from_secs(2)).is_none());
13907 assert!(canonical_unit(Duration::from_secs(30)).is_none());
13908 assert!(canonical_unit(Duration::from_secs(120)).is_none());
13909 assert!(canonical_unit(Duration::from_secs(86400)).is_none());
13910 // Sub-second windows: even `Duration::from_millis(1000)` is
13911 // exactly 1s and accepted; `Duration::from_millis(500)` is
13912 // sub-second and rejected.
13913 assert!(canonical_unit(Duration::from_millis(1000)).is_some());
13914 assert!(canonical_unit(Duration::from_millis(500)).is_none());
13915 assert!(canonical_unit(Duration::from_millis(1500)).is_none());
13916 }
13917
13918 #[test]
13919 fn rate_limit_unit_table_projections_are_mutual_inverses() {
13920 // Bidirection pin against the closed-set typed enum
13921 // [`RateLimitUnit`] arm-table (the canonical
13922 // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
13923 // of the rate-limit unit surface reads from). The two
13924 // projection directions [`RateLimitUnit::from_suffix`] /
13925 // [`RateLimitUnit::window`] (str → Duration, exposed as one
13926 // typed dispatch through [`RateLimitUnit::window_from_suffix`])
13927 // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
13928 // (Duration → str, exposed as one typed dispatch through
13929 // [`RateLimit::canonical_unit`] composed with
13930 // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
13931 // codec's parse arm ([`rate_limit_codec::parse`] via
13932 // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
13933 // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
13934 // and the validate gate ([`AplicacaoSpec::validate_politicas`]
13935 // via [`RateLimit::canonical_unit`]) all key off. A future
13936 // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
13937 // sub-second window) is one variant + one arm per method on the
13938 // closed-set enum; the compiler-enforced exhaustiveness on
13939 // every consumer's `match self` arms picks it up by
13940 // construction. This pin enshrines that both projection
13941 // directions agree on every canonical arm row and neither
13942 // leaks a spurious entry the other doesn't recognize.
13943 //
13944 // Predecessor: this test previously read the two vestigial
13945 // module-private free helpers `rate_limit_window_unit` and
13946 // `rate_limit_window_from_unit` on the `Duration → &str` and
13947 // `&str → Duration` axes; the former was deleted after its
13948 // sole production consumer ([`rate_limit_codec::render`])
13949 // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
13950 // the latter is folded here into the substrate primitive
13951 // [`RateLimitUnit::window_from_suffix`] so both projection
13952 // directions live on the closed-set enum's arm-table.
13953 for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
13954 let window = super::RateLimitUnit::window_from_suffix(unit)
13955 .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
13956 assert_eq!(
13957 window,
13958 Duration::from_secs(secs),
13959 "unit {unit:?} must resolve to {secs}s"
13960 );
13961 let projected_suffix = RateLimit { rate: 1, window }
13962 .canonical_unit()
13963 .map(super::RateLimitUnit::as_suffix);
13964 assert_eq!(
13965 projected_suffix,
13966 Some(unit),
13967 "Duration({secs}s) must render as {unit:?} \
13968 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
13969 );
13970 }
13971 // Non-table units yield None on the `unit → Duration`
13972 // projection — a future `"d"` addition to the table would
13973 // flip this arm; today it pins the current three-row table's
13974 // rejection semantics.
13975 assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
13976 assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
13977 assert!(super::RateLimitUnit::window_from_suffix("").is_none());
13978 // Non-table Durations yield None on the `Duration → unit`
13979 // projection — pins that the two projections agree on the
13980 // "not in the table" semantic too, so a drift where the
13981 // parse-side accepts a value the render-side can't emit is
13982 // a build error at the two-arm pair, not a silent codec
13983 // round-trip break.
13984 let projected_suffix = |window: Duration| -> Option<&'static str> {
13985 RateLimit { rate: 1, window }
13986 .canonical_unit()
13987 .map(super::RateLimitUnit::as_suffix)
13988 };
13989 assert!(projected_suffix(Duration::from_secs(2)).is_none());
13990 assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
13991 assert!(projected_suffix(Duration::from_millis(1500)).is_none());
13992 }
13993
13994 #[test]
13995 fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
13996 // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
13997 // substrate-primitive `&str → Duration` associated method the
13998 // codec's parse arm ([`rate_limit_codec::parse`]) now routes
13999 // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
14000 // to the same [`Duration`] the two-step composition
14001 // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
14002 // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
14003 // `"MIN"`) must project to [`None`] on both paths. A future
14004 // implementation of `window_from_suffix` that took a shortcut
14005 // through a per-suffix `match` table (bypassing the arm-table's
14006 // `Self::from_suffix` scan and the arm-table's `Self::window`
14007 // dispatch) would silently split the accept-set — the parse
14008 // arm would accept a suffix the enum's arm-table doesn't know,
14009 // or reject a suffix the enum's arm-table does; this pin
14010 // surfaces that drift at caixa-core build time rather than at a
14011 // downstream serde round-trip audit on a live `MeshPolicy`.
14012 //
14013 // Same byte-parity discipline the sibling
14014 // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
14015 // pin carries on the peer `Duration → RateLimitUnit` axis via
14016 // [`RateLimit::canonical_unit`], and the peer
14017 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
14018 // carries on the bidirectional arm-table axis — extended here
14019 // onto the fifth (and last unlifted) projection axis on the
14020 // closed-set enum's arm-table.
14021 let composition = |suffix: &str| -> Option<Duration> {
14022 super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
14023 };
14024 for suffix in ["s", "m", "h"] {
14025 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
14026 let via_composition = composition(suffix);
14027 assert_eq!(
14028 via_method, via_composition,
14029 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
14030 from_suffix({suffix:?}).map(window) — the substrate-primitive \
14031 method must delegate to the arm-table's two typed dispatches, \
14032 not shortcut through a per-suffix match table"
14033 );
14034 assert!(
14035 via_method.is_some(),
14036 "canonical suffix {suffix:?} must resolve to Some(Duration) via \
14037 RateLimitUnit::window_from_suffix"
14038 );
14039 }
14040 for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
14041 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
14042 let via_composition = composition(suffix);
14043 assert_eq!(
14044 via_method, via_composition,
14045 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
14046 from_suffix({suffix:?}).map(window) on the non-arm rejection \
14047 axis too"
14048 );
14049 assert!(
14050 via_method.is_none(),
14051 "non-arm suffix {suffix:?} must project to None via \
14052 RateLimitUnit::window_from_suffix — a future extension that \
14053 accepted this suffix without a corresponding arm on the enum \
14054 would split the codec's parse-accepted set from the enum's \
14055 arm-table"
14056 );
14057 }
14058 // And the codec's parse arm now reads through this method: a
14059 // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
14060 // the same `Duration` the method returns for its unit, closing
14061 // the two-consumer drift surface (the codec's parse arm and the
14062 // enum's arm-table) with one typed dispatch on the substrate
14063 // primitive.
14064 for suffix in ["s", "m", "h"] {
14065 let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
14066 let mp: MeshPolicy = serde_json::from_str(&wire)
14067 .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
14068 let parsed = mp.rate_limit().expect("rate_limit payload present");
14069 let via_method = super::RateLimitUnit::window_from_suffix(suffix)
14070 .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
14071 assert_eq!(
14072 parsed.window(),
14073 via_method,
14074 "codec parse arm on {wire:?} must resolve the window through \
14075 RateLimitUnit::window_from_suffix, not a divergent path"
14076 );
14077 }
14078 }
14079
14080 #[test]
14081 fn rate_limit_unit_all_enumerates_every_arm_once() {
14082 // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
14083 // enumerate every arm of the closed-set enum exactly once, in
14084 // the canonical shortest-to-longest window order (Second before
14085 // Minute before Hour) — the same order the sibling
14086 // [`crate::supervisor::RestartStrategy`] /
14087 // [`crate::supervisor::RestartPolicy`] /
14088 // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
14089 // typed enums carry (the arm declared first is the arm listed
14090 // first). A future variant addition that extends the enum
14091 // without appending to [`RateLimitUnit::ALL`] leaves the
14092 // exhaustive iteration surface silently short one arm — the
14093 // codec's parse arm would then reject the new suffix even
14094 // though the enum knows it. This pin closes the drift.
14095 assert_eq!(
14096 super::RateLimitUnit::ALL,
14097 &[
14098 super::RateLimitUnit::Second,
14099 super::RateLimitUnit::Minute,
14100 super::RateLimitUnit::Hour,
14101 ],
14102 "RateLimitUnit::ALL must enumerate every arm exactly once, \
14103 in canonical shortest-to-longest window order"
14104 );
14105 }
14106
14107 #[test]
14108 fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
14109 // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
14110 // every arm's [`RateLimitUnit::as_suffix`] output must parse
14111 // back through [`RateLimitUnit::from_suffix`] to the same
14112 // variant. A future arm addition that lands `as_suffix` but
14113 // forgets `from_suffix` (`from_suffix` iterates
14114 // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
14115 // is the load-bearing carrier of the round-trip; the sibling
14116 // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
14117 // the `ALL` half) trips here at caixa-core build time rather
14118 // than surfacing as a codec round-trip miss (a `render` emit
14119 // that lands a suffix the paired `parse` cannot decode).
14120 for unit in super::RateLimitUnit::ALL {
14121 let suffix = unit.as_suffix();
14122 let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
14123 panic!(
14124 "RateLimitUnit::from_suffix({suffix:?}) must accept every \
14125 RateLimitUnit::as_suffix output — got None for {unit:?}"
14126 )
14127 });
14128 assert_eq!(
14129 parsed, *unit,
14130 "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
14131 must return RateLimitUnit::{unit:?}"
14132 );
14133 }
14134 }
14135
14136 #[test]
14137 fn rate_limit_unit_from_window_and_window_round_trip() {
14138 // Total round-trip pin on the `(from_window, window)` pair:
14139 // every arm's [`RateLimitUnit::window`] output must parse back
14140 // through [`RateLimitUnit::from_window`] to the same variant.
14141 // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
14142 // on the peer `Duration` axis — the two round-trip pins
14143 // together enshrine that both projections of the typed
14144 // canonical-unit bijection are total on the arm-set.
14145 for unit in super::RateLimitUnit::ALL {
14146 let window = unit.window();
14147 let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
14148 panic!(
14149 "RateLimitUnit::from_window({window:?}) must accept every \
14150 RateLimitUnit::window output — got None for {unit:?}"
14151 )
14152 });
14153 assert_eq!(
14154 parsed, *unit,
14155 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
14156 must return RateLimitUnit::{unit:?}"
14157 );
14158 }
14159 }
14160
14161 #[test]
14162 fn rate_limit_unit_projections_are_pairwise_distinct() {
14163 // Distinctness pin: [`RateLimitUnit::as_suffix`] and
14164 // [`RateLimitUnit::window`] outputs must be pairwise distinct
14165 // across every arm — an accidental copy-paste flip that
14166 // reroutes one arm's suffix or window to also match another
14167 // silently collapses two arms onto one, so
14168 // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
14169 // (both using `find` on `Self::ALL`) would return whichever
14170 // arm the linear scan lands on first — a match-arm-ordering-
14171 // dependent outcome the closed-set typed-enum shape is meant
14172 // to rule out structurally. Peer of the sibling
14173 // `caixa_kind_wire_consts_are_pairwise_distinct` /
14174 // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
14175 // other closed-set typed-enum discriminator axes.
14176 let all = super::RateLimitUnit::ALL;
14177 for (i, a) in all.iter().enumerate() {
14178 for (j, b) in all.iter().enumerate() {
14179 if i != j {
14180 assert_ne!(
14181 a.as_suffix(),
14182 b.as_suffix(),
14183 "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
14184 must be distinct — a collision silently collapses two \
14185 arms onto one under from_suffix's linear scan"
14186 );
14187 assert_ne!(
14188 a.window(),
14189 b.window(),
14190 "RateLimitUnit::{a:?}.window() and {b:?}.window() \
14191 must be distinct — a collision silently collapses two \
14192 arms onto one under from_window's linear scan"
14193 );
14194 }
14195 }
14196 }
14197 }
14198
14199 #[test]
14200 fn rate_limit_unit_display_routes_through_as_suffix() {
14201 // Route pin: [`std::fmt::Display`] must byte-equal
14202 // [`RateLimitUnit::as_suffix`] on every arm — the single
14203 // source of truth for the canonical suffix. A future
14204 // reimplementation that hand-rolls the arms instead of
14205 // delegating to [`RateLimitUnit::as_suffix`] would silently
14206 // desynchronize `format!("{u}")` from the codec's parse arm
14207 // (which uses `as_suffix` to compare suffixes). Peer of the
14208 // sibling `caixa_kind_display_routes_through_as_str_helper` /
14209 // `placement_strategy_display_routes_through_as_str_helper`
14210 // pins on the peer closed-set typed-enum Display axes.
14211 for unit in super::RateLimitUnit::ALL {
14212 assert_eq!(
14213 unit.to_string(),
14214 unit.as_suffix(),
14215 "RateLimitUnit::{unit:?} Display must route through \
14216 as_suffix (single source of truth: the canonical suffix \
14217 the codec parses and renders)"
14218 );
14219 }
14220 }
14221
14222 #[test]
14223 fn rate_limit_unit_from_window_rejects_non_canonical() {
14224 // Rejection pin on the parser's accept-set: any Duration
14225 // outside the three-arm [`RateLimitUnit::window`] output set
14226 // (sub-second residue, or a second-magnitude outside `{1, 60,
14227 // 3600}`) must return `None`. A future accidental widening of
14228 // the accept-set (rounding down sub-second residue to the
14229 // nearest arm, admitting `Duration::from_secs(30)` as a
14230 // half-minute unit) would silently drift the parser's accept-
14231 // set from the emitter's — a validated slot with a
14232 // non-canonical window would then round-trip through the
14233 // codec to a canonical form the author never wrote.
14234 assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
14235 assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
14236 assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
14237 assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
14238 assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
14239 assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
14240 assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
14241 }
14242
14243 #[test]
14244 fn rate_limit_unit_from_suffix_rejects_unknown() {
14245 // Rejection pin on the suffix parser's accept-set: any string
14246 // outside the three-arm [`RateLimitUnit::as_suffix`] output
14247 // set must return `None`. Peer of the sibling
14248 // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
14249 // the [`crate::CaixaKind`] `from_wire` accept-set.
14250 for bad in [
14251 "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
14252 " s",
14253 ] {
14254 assert!(
14255 super::RateLimitUnit::from_suffix(bad).is_none(),
14256 "RateLimitUnit::from_suffix({bad:?}) must return None — the \
14257 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
14258 outputs"
14259 );
14260 }
14261 }
14262
14263 #[test]
14264 fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
14265 // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
14266 // every canonical `:window` magnitude the validate gate
14267 // accepts must map to the paired [`RateLimitUnit`] arm through
14268 // this accessor. A future validate-gate rebrand that widened
14269 // the accepted-window set without extending [`RateLimitUnit`]
14270 // would silently split the accessor's `Some`-return set from
14271 // the validate gate's accept-set — a slot that satisfies
14272 // validate would land at the accessor with `None`, so a
14273 // consumer past validate that pattern-matches on the returned
14274 // `Some` would silently miss the newly-accepted magnitude.
14275 for (window_secs, expected) in [
14276 (1u64, super::RateLimitUnit::Second),
14277 (60, super::RateLimitUnit::Minute),
14278 (3600, super::RateLimitUnit::Hour),
14279 ] {
14280 let rl = RateLimit {
14281 rate: 100,
14282 window: Duration::from_secs(window_secs),
14283 };
14284 assert_eq!(
14285 rl.canonical_unit(),
14286 Some(expected),
14287 "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
14288 must return Some({expected:?})"
14289 );
14290 }
14291 // Non-canonical windows the validate gate rejects also return
14292 // None here — the accessor is the typed-enum projection of
14293 // the sibling `is_canonical_rate_limit_window` predicate.
14294 let bad = RateLimit {
14295 rate: 100,
14296 window: Duration::from_secs(30),
14297 };
14298 assert!(
14299 bad.canonical_unit().is_none(),
14300 "RateLimit with a non-canonical window must return None from \
14301 canonical_unit — the validate gate rejects the same set"
14302 );
14303 }
14304
14305 #[test]
14306 fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
14307 // Fail-before-pass-after byte-parity pin: for every canonical
14308 // window the [`rate_limit_codec::render`] arm's emitted string
14309 // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
14310 // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
14311 // the vestigial free helper [`rate_limit_window_unit`] (a
14312 // `find_map`-walked `Duration → &'static str` delegate) onto the
14313 // substrate primitive [`RateLimit::canonical_unit`] typed method
14314 // (a closed-set `match self.window` arm on
14315 // [`RateLimitUnit::from_window`], projected through
14316 // [`RateLimitUnit::as_suffix`] via the enum's
14317 // [`std::fmt::Display`] impl). A future re-routing of the render
14318 // arm through a differently-computed unit projection would break
14319 // this pin at build time rather than as a silent per-consumer
14320 // codec round-trip drift far from the substrate primitive edit.
14321 //
14322 // Sibling to the peer
14323 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
14324 // on the free-helper axis: that pin locks the two projections
14325 // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
14326 // on the closed-set arm table; this pin locks the codec's render
14327 // arm reads through the typed accessor rather than the free
14328 // helper. Two production consumers of the canonical-unit axis
14329 // now key off one typed dispatch on the substrate primitive.
14330 for (window_secs, unit) in [
14331 (1u64, super::RateLimitUnit::Second),
14332 (60, super::RateLimitUnit::Minute),
14333 (3600, super::RateLimitUnit::Hour),
14334 ] {
14335 let rl = RateLimit {
14336 rate: 42,
14337 window: Duration::from_secs(window_secs),
14338 };
14339 let policy = MeshPolicy {
14340 rate_limit: Some(rl),
14341 ..Default::default()
14342 };
14343 let json = serde_json::to_string(&policy).unwrap();
14344 let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
14345 assert!(
14346 json.contains(&expected),
14347 "rate_limit_codec::render must emit {expected} (via \
14348 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
14349 for a {window_secs}s window; serialized MeshPolicy was: {json}"
14350 );
14351 // And the accessor route resolves to the same typed unit
14352 // the render arm's Display formatting is asked to produce —
14353 // so a future edit that split the two paths (one through
14354 // the accessor, one through a re-introduced free helper)
14355 // trips this pin.
14356 assert_eq!(
14357 rl.canonical_unit(),
14358 Some(unit),
14359 "RateLimit::canonical_unit must return Some({unit:?}) for a \
14360 {window_secs}s window; the codec render arm reads the same \
14361 typed unit through this accessor"
14362 );
14363 }
14364 }
14365
14366 #[test]
14367 fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
14368 // Fail-before-pass-after byte-parity pin on the validate gate's
14369 // canonical-window shape probe: every non-canonical `:window`
14370 // the free-helper predicate [`is_canonical_rate_limit_window`]
14371 // rejects is also rejected by the substrate primitive
14372 // [`RateLimit::canonical_unit`] `.is_none()` route the validate
14373 // gate now reads through, and vice versa on the accepted set
14374 // (the three canonical windows). Locks the migration from the
14375 // free helper onto the substrate primitive: a future re-routing
14376 // of one of the two paths through a differently-computed unit
14377 // projection would silently split the codec's accepted set from
14378 // the validate gate's accepted set — a two-consumer drift the
14379 // codec-round-trip pin
14380 // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
14381 // above closes on the render arm and this pin closes on the
14382 // validate arm.
14383 for canonical_window_secs in [1u64, 60, 3600] {
14384 let mut s = three_member_spec();
14385 let rl = RateLimit {
14386 rate: 100,
14387 window: Duration::from_secs(canonical_window_secs),
14388 };
14389 s.politicas.rate_limit = Some(rl);
14390 assert!(
14391 s.validate().is_ok(),
14392 "canonical {canonical_window_secs}s window must pass \
14393 validate_politicas — the validate gate now reads \
14394 RateLimit::canonical_unit().is_none() and the accessor \
14395 returns Some on every canonical arm"
14396 );
14397 assert!(
14398 rl.canonical_unit().is_some(),
14399 "canonical {canonical_window_secs}s window must resolve to \
14400 Some on RateLimit::canonical_unit — the validate gate reads \
14401 this accessor directly"
14402 );
14403 }
14404 for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
14405 let mut s = three_member_spec();
14406 let rl = RateLimit {
14407 rate: 100,
14408 window: Duration::from_secs(non_canonical_window_secs),
14409 };
14410 s.politicas.rate_limit = Some(rl);
14411 assert_eq!(
14412 s.validate().unwrap_err(),
14413 AplicacaoError::PolicyRateLimitWindowNotCanonical {
14414 window: rl.window(),
14415 },
14416 "non-canonical {non_canonical_window_secs}s window must be \
14417 rejected by validate_politicas — the validate gate now \
14418 keys off RateLimit::canonical_unit().is_none()"
14419 );
14420 assert!(
14421 rl.canonical_unit().is_none(),
14422 "non-canonical {non_canonical_window_secs}s window must \
14423 resolve to None on RateLimit::canonical_unit — the two \
14424 paths (the free helper the validate gate previously read \
14425 and the substrate primitive the validate gate now reads) \
14426 must agree on the same rejected set"
14427 );
14428 }
14429 // And the substrate-primitive [`RateLimit::canonical_unit`]
14430 // accessor's accepted-window set matches the codec's parse arm's
14431 // accepted-suffix set on every canonical / non-canonical shape,
14432 // so a future silent drift between the codec's accepted set and
14433 // the validate gate's accepted set is a build error at test time
14434 // (both consumers key off the same closed-set enum's `match self`
14435 // arms). The predecessor free helper `is_canonical_rate_limit_window`
14436 // — a delegate that composed [`RateLimitUnit::from_window`] with
14437 // `.is_some()` — was deleted after this migration; the
14438 // canonical-window set now lives on exactly one typed dispatch
14439 // on the substrate primitive.
14440 for (secs, expected) in [
14441 (1u64, true),
14442 (60, true),
14443 (3600, true),
14444 (2, false),
14445 (30, false),
14446 (86_400, false),
14447 ] {
14448 let window = Duration::from_secs(secs);
14449 let rl = RateLimit { rate: 1, window };
14450 assert_eq!(
14451 rl.canonical_unit().is_some(),
14452 expected,
14453 "RateLimit::canonical_unit().is_some() must agree with the \
14454 codec-accepted canonical-window set on {secs}s"
14455 );
14456 let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
14457 1 => "s",
14458 60 => "m",
14459 3600 => "h",
14460 _ => return,
14461 })
14462 .is_some_and(|d| d == window);
14463 if expected {
14464 assert!(
14465 suffix_from_axis,
14466 "the codec's `&str → Duration` axis \
14467 ({secs}s) must round-trip to the same Duration the \
14468 substrate primitive's accessor returns Some on"
14469 );
14470 }
14471 }
14472 }
14473
14474 #[test]
14475 fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
14476 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
14477 // derive: for each of the three variants, exactly one of the
14478 // generated `is_second` / `is_minute` / `is_hour` predicates
14479 // returns `true` and the other two return `false`. Peer of
14480 // the sibling
14481 // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
14482 // sibling `IsVariant`-derived closed-set typed-enum pins.
14483 let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
14484 (super::RateLimitUnit::Second, [true, false, false]),
14485 (super::RateLimitUnit::Minute, [false, true, false]),
14486 (super::RateLimitUnit::Hour, [false, false, true]),
14487 ];
14488 for (variant, expected) in rows {
14489 let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
14490 assert_eq!(
14491 observed, expected,
14492 "RateLimitUnit::{variant:?} is_* predicates must partition \
14493 the arm set (second, minute, hour); got {observed:?}"
14494 );
14495 }
14496 }
14497
14498 #[test]
14499 fn rejects_policy_timeout_sub_millisecond() {
14500 // A purely sub-millisecond `Duration` (`from_micros(500)` =
14501 // 500_000 ns) is not the zero `Duration` — the `is_zero()`
14502 // arm passes — but `as_millis() == 0`, so the shared codec's
14503 // `render` arm returns the literal `"0s"`, which the
14504 // codec's `parse` arm then deserializes as `Duration::ZERO`
14505 // and the `PolicyTimeoutZero` zero-floor gate would reject
14506 // on re-validate. Pin the rejection at the typed slot's
14507 // canonical-floor gate so the round-trip break surfaces at
14508 // validate time, naming the offending `Duration`, rather
14509 // than at the next serialize → deserialize round-trip far
14510 // from the source `caixa.lisp`.
14511 let mut s = three_member_spec();
14512 let timeout = Duration::from_micros(500);
14513 s.politicas.timeout = Some(timeout);
14514 assert_eq!(
14515 s.validate().unwrap_err(),
14516 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
14517 );
14518 }
14519
14520 #[test]
14521 fn rejects_policy_timeout_non_integer_millisecond() {
14522 // A `Duration` with non-integer-millisecond residue
14523 // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
14524 // through the shared codec's `render` arm as `"1ms"` (the
14525 // `as_millis()` floor truncates), which the codec's `parse`
14526 // arm then deserializes as `Duration::from_millis(1)` =
14527 // 1_000_000 ns — silently *different* from the original.
14528 // Pin the rejection so this round-trip break surfaces at
14529 // validate time, where the offending `Duration` is named,
14530 // rather than as a silent value-laundered round-trip on the
14531 // next codec round-trip.
14532 let mut s = three_member_spec();
14533 let timeout = Duration::from_micros(1500);
14534 s.politicas.timeout = Some(timeout);
14535 assert_eq!(
14536 s.validate().unwrap_err(),
14537 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
14538 );
14539 }
14540
14541 #[test]
14542 fn accepts_policy_timeout_integer_millisecond_forms() {
14543 // The codec's accepted set — integer multiples of 1ms — is
14544 // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
14545 // `1h` all pass the canonical gate. Pin the canonical-forms
14546 // sweep so a future tightening of the codec's grammar (e.g.
14547 // dropping `:ms`) surfaces here as a test failure rather
14548 // than a silent contract narrowing on the typed slot.
14549 for timeout in [
14550 Duration::from_millis(1),
14551 Duration::from_millis(500),
14552 Duration::from_millis(1500),
14553 Duration::from_secs(30),
14554 Duration::from_secs(120),
14555 Duration::from_secs(3600),
14556 ] {
14557 let mut s = three_member_spec();
14558 s.politicas.timeout = Some(timeout);
14559 s.validate()
14560 .expect("integer-millisecond :timeout must validate");
14561 }
14562 }
14563
14564 #[test]
14565 fn policy_timeout_zero_takes_precedence_over_canonical() {
14566 // `Duration::ZERO` carries `subsec_nanos() == 0` and would
14567 // pass the canonical-millisecond gate; the more self-locating
14568 // `PolicyTimeoutZero` arm (which names the omit-axis
14569 // remediation directly) must fire first. Pin the ordering so
14570 // a future refactor that reorders the arms surfaces here as a
14571 // test failure rather than a silent diagnostic regression.
14572 let mut s = three_member_spec();
14573 s.politicas.timeout = Some(Duration::ZERO);
14574 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
14575 }
14576
14577 #[test]
14578 fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
14579 // The diagnostic envelope carries the offending `Duration`
14580 // verbatim so the author can grep their `caixa.lisp` for
14581 // `:timeout "<value>"` and fix it in one edit. Same
14582 // diagnostic shape every other typed-slot canonical-form
14583 // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
14584 // peer `:rate-limit :window` axis.
14585 let mut s = three_member_spec();
14586 let timeout = Duration::from_nanos(1_000_001);
14587 s.politicas.timeout = Some(timeout);
14588 match s.validate().unwrap_err() {
14589 AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
14590 assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
14591 }
14592 other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
14593 }
14594 }
14595
14596 #[test]
14597 fn rejects_policy_timeout_above_cap() {
14598 // The fail-before-pass-after pin: 3601s = 1h + 1s is
14599 // structurally one canonical-tick past the
14600 // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
14601 // integer-millisecond magnitude the canonical-form arm above
14602 // accepts cleanly, that the codec round-trips losslessly as
14603 // `"3601s"`, and that silently passed validate on every
14604 // pre-gate codebase because the typed slot's only checks were
14605 // the zero-floor and canonical-form arms. The mesh-level
14606 // deadline degenerates only at the runtime substrate (Envoy
14607 // / Cilium L7 timeout overlay) far from the source
14608 // `caixa.lisp` with no field naming the offending policy.
14609 let mut s = three_member_spec();
14610 let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
14611 s.politicas.timeout = Some(timeout);
14612 assert_eq!(
14613 s.validate().unwrap_err(),
14614 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
14615 );
14616 }
14617
14618 #[test]
14619 fn rejects_policy_timeout_one_millisecond_above_cap() {
14620 // Boundary case: exactly 1ms past the cap (the granularity
14621 // the canonical-form gate enforces). Catches a future
14622 // "strictly less than" half-measure and pins the diagnostic
14623 // to name the offending `Duration` verbatim. Peer of
14624 // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
14625 // boundary pin on the sibling `:limits :memory` top edge.
14626 let mut s = three_member_spec();
14627 let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
14628 s.politicas.timeout = Some(timeout);
14629 assert_eq!(
14630 s.validate().unwrap_err(),
14631 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
14632 );
14633 }
14634
14635 #[test]
14636 fn rejects_policy_timeout_far_above_cap() {
14637 // The "obvious authoring footgun" case: a `(:timeout "24h")`
14638 // or `(:timeout "86400s")` — values the canonical-form arm
14639 // accepts as integer-millisecond magnitudes, the codec
14640 // round-trips losslessly through serde, but the mesh-level
14641 // policy cannot honor (a 24-hour synchronous-`:contratos`
14642 // deadline is operationally indistinguishable from
14643 // omit-the-axis). Until this gate landed validate accepted
14644 // it. Pin both common above-cap values (24h, 7d) so a future
14645 // relaxation that drops the upper bound surfaces here.
14646 for timeout in [
14647 Duration::from_secs(86_400), // 24h
14648 Duration::from_secs(604_800), // 7d
14649 Duration::from_secs(1_000_000), // ~11.5 days
14650 ] {
14651 let mut s = three_member_spec();
14652 s.politicas.timeout = Some(timeout);
14653 assert_eq!(
14654 s.validate().unwrap_err(),
14655 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
14656 );
14657 }
14658 }
14659
14660 #[test]
14661 fn accepts_policy_timeout_at_cap() {
14662 // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
14663 // must validate. The cap is inclusive on the top edge,
14664 // matching the [`POLICY_RETRIES_MAX`] /
14665 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
14666 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
14667 // sibling capped axes. Pin the boundary explicitly so a
14668 // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
14669 // instead of `>`) surfaces here as a test failure rather
14670 // than a silent contract narrowing.
14671 let mut s = three_member_spec();
14672 s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
14673 s.validate()
14674 .expect("timeout == POLICY_TIMEOUT_MAX must validate");
14675 }
14676
14677 #[test]
14678 fn accepts_policy_timeout_typical_values() {
14679 // The documented production-playbook band positive-control
14680 // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
14681 // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
14682 // plus a sweep through the long-running-workflow band
14683 // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
14684 // validated set explicitly so a future tightening of the
14685 // ceiling surfaces here as a deliberate test edit, not a
14686 // silent contract narrowing.
14687 for timeout in [
14688 Duration::from_millis(1),
14689 Duration::from_millis(500),
14690 Duration::from_secs(1),
14691 Duration::from_secs(10),
14692 Duration::from_secs(15), // Envoy default
14693 Duration::from_secs(30),
14694 Duration::from_secs(60), // AWS App Mesh typical
14695 Duration::from_secs(300),
14696 Duration::from_secs(900),
14697 Duration::from_secs(1800),
14698 Duration::from_secs(3600), // exactly 1h, the cap
14699 ] {
14700 let mut s = three_member_spec();
14701 s.politicas.timeout = Some(timeout);
14702 s.validate()
14703 .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
14704 }
14705 }
14706
14707 #[test]
14708 fn policy_timeout_zero_takes_precedence_over_cap() {
14709 // The cross-arm ordering pin: `Duration::ZERO` is
14710 // structurally outside both `>= 1ms` (zero-floor) and
14711 // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
14712 // diagnostic is the more self-locating one (it directly
14713 // names the omit-axis remediation), so the validate gate
14714 // must fire on zero first. Same shape every other
14715 // zero-then-shape ordering on this surface uses
14716 // ([`AplicacaoError::PolicyRetriesZero`] then
14717 // [`AplicacaoError::PolicyRetriesExceedsCap`];
14718 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
14719 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
14720 let mut s = three_member_spec();
14721 s.politicas.timeout = Some(Duration::ZERO);
14722 assert_eq!(
14723 s.validate().unwrap_err(),
14724 AplicacaoError::PolicyTimeoutZero,
14725 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
14726 );
14727 }
14728
14729 #[test]
14730 fn policy_timeout_canonical_takes_precedence_over_cap() {
14731 // The cross-arm ordering pin: a `Duration` that is *both*
14732 // sub-millisecond (non-canonical-form) and structurally
14733 // above the cap surfaces the canonical-form diagnostic
14734 // first, because the round-trip-shape break is the more
14735 // fundamental issue (the value can't even round-trip
14736 // through the codec, so the cap diagnostic naming
14737 // `1ms..=1h` would be misleading — there's no integer-ms
14738 // form of the offending value). Pin the order so a future
14739 // refactor that reorders the arms surfaces here as a test
14740 // failure rather than a silent diagnostic regression.
14741 let mut s = three_member_spec();
14742 // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
14743 // *and* total magnitude above the 1h cap.
14744 let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
14745 s.politicas.timeout = Some(timeout);
14746 assert_eq!(
14747 s.validate().unwrap_err(),
14748 AplicacaoError::PolicyTimeoutNotCanonical { timeout },
14749 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
14750 );
14751 }
14752
14753 #[test]
14754 fn policy_timeout_cap_diagnostic_carries_offending_value() {
14755 // The diagnostic-shape pin: the offending `Duration` is
14756 // carried verbatim into the
14757 // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
14758 // surfaced error message names the value the author wrote
14759 // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
14760 // exceeds the mesh-policy ceiling …"`), not just the cap.
14761 // Same self-locating diagnostic shape every other typed-cap
14762 // arm on this surface carries
14763 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
14764 // offending retry count verbatim).
14765 let mut s = three_member_spec();
14766 let timeout = Duration::from_secs(7200); // 2h
14767 s.politicas.timeout = Some(timeout);
14768 let err = s.validate().unwrap_err();
14769 assert!(
14770 matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
14771 "got {err:?}"
14772 );
14773 let msg = err.to_string();
14774 assert!(
14775 msg.contains("7200"),
14776 ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
14777 );
14778 }
14779
14780 #[test]
14781 fn policy_timeout_cap_pins_canonical_value() {
14782 // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
14783 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
14784 // the shared duration codec emits as a clean canonical
14785 // string (`"<n>h"`). Pinning the literal value here surfaces
14786 // a future drift (a relaxation to 24h, a tightening to 5m)
14787 // as a deliberate test edit, not a silent contract
14788 // narrowing. Same shape every other typed-cap value pin on
14789 // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
14790 assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
14791 assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
14792 }
14793
14794 #[test]
14795 fn policy_timeout_cap_value_round_trips_through_codec() {
14796 // The codec round-trip property the cap arm preserves: the
14797 // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
14798 // the shared duration codec — every value at the cap renders
14799 // to a clean canonical string (`"1h"`) and parses back to
14800 // the same `Duration`. Pin this so a future drift between
14801 // the cap constant and the codec's largest emitted unit
14802 // surfaces here. Same shape every other typed boundary pin
14803 // on this surface uses
14804 // (`wasm32_memory_cap_matches_parsed_4_gib`).
14805 let policy = MeshPolicy {
14806 timeout: Some(POLICY_TIMEOUT_MAX),
14807 ..Default::default()
14808 };
14809 let json = serde_json::to_string(&policy).unwrap();
14810 // The codec emits `"1h"` for the canonical 1-hour magnitude.
14811 assert!(
14812 json.contains("\"1h\""),
14813 "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
14814 );
14815 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
14816 assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
14817 }
14818
14819 #[test]
14820 fn rejects_circuit_breaker_window_sub_millisecond() {
14821 // Peer of the `:timeout` sub-millisecond arm on the second
14822 // typed-`Duration` `:politicas` axis: a purely sub-ms
14823 // `Duration` (`from_micros(500)`) renders through the shared
14824 // codec as `"0s"`, which the codec parses back to
14825 // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
14826 // zero-floor gate then rejects on re-validate.
14827 let mut s = three_member_spec();
14828 let window = Duration::from_micros(500);
14829 s.politicas.circuit_breaker = Some(CircuitBreaker {
14830 max_failures: 5,
14831 window,
14832 });
14833 assert_eq!(
14834 s.validate().unwrap_err(),
14835 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
14836 );
14837 }
14838
14839 #[test]
14840 fn rejects_circuit_breaker_window_non_integer_millisecond() {
14841 // Peer of the `:timeout` non-integer-ms arm: a `Duration`
14842 // with non-integer-millisecond residue renders through the
14843 // shared codec as the truncated `"<n>ms"` form, parsing back
14844 // to a *different* `Duration` on the next round-trip.
14845 let mut s = three_member_spec();
14846 let window = Duration::from_micros(1500);
14847 s.politicas.circuit_breaker = Some(CircuitBreaker {
14848 max_failures: 5,
14849 window,
14850 });
14851 assert_eq!(
14852 s.validate().unwrap_err(),
14853 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
14854 );
14855 }
14856
14857 #[test]
14858 fn accepts_circuit_breaker_window_integer_millisecond_forms() {
14859 // The canonical-forms sweep on the breaker axis: every
14860 // integer-ms multiple the codec round-trips losslessly
14861 // passes the canonical gate.
14862 for window in [
14863 Duration::from_millis(1),
14864 Duration::from_millis(500),
14865 Duration::from_millis(1500),
14866 Duration::from_secs(30),
14867 Duration::from_secs(60),
14868 Duration::from_secs(3600),
14869 ] {
14870 let mut s = three_member_spec();
14871 s.politicas.circuit_breaker = Some(CircuitBreaker {
14872 max_failures: 5,
14873 window,
14874 });
14875 s.validate()
14876 .expect("integer-millisecond :circuit-breaker :window must validate");
14877 }
14878 }
14879
14880 #[test]
14881 fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
14882 // `Duration::ZERO` would pass the canonical-ms gate (the
14883 // sub-ns residue is zero) but must surface the narrower
14884 // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
14885 // remediation.
14886 let mut s = three_member_spec();
14887 s.politicas.circuit_breaker = Some(CircuitBreaker {
14888 max_failures: 5,
14889 window: Duration::ZERO,
14890 });
14891 assert_eq!(
14892 s.validate().unwrap_err(),
14893 AplicacaoError::PolicyBreakerZeroWindow
14894 );
14895 }
14896
14897 #[test]
14898 fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
14899 // Both axes invalid: max_failures == 0 *and* window is
14900 // sub-ms. The validate gate must fire on max_failures first
14901 // (matching the existing ordering pin
14902 // `rejects_circuit_breaker_zero_max_failures` enshrines), so
14903 // the existing diagnostic continues to lead with the simpler
14904 // "zero threshold" framing.
14905 let mut s = three_member_spec();
14906 s.politicas.circuit_breaker = Some(CircuitBreaker {
14907 max_failures: 0,
14908 window: Duration::from_micros(500),
14909 });
14910 assert_eq!(
14911 s.validate().unwrap_err(),
14912 AplicacaoError::PolicyBreakerZeroFailures
14913 );
14914 }
14915
14916 #[test]
14917 fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
14918 let mut s = three_member_spec();
14919 let window = Duration::from_nanos(60_000_000_001);
14920 s.politicas.circuit_breaker = Some(CircuitBreaker {
14921 max_failures: 5,
14922 window,
14923 });
14924 match s.validate().unwrap_err() {
14925 AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
14926 assert_eq!(w, window, "diagnostic must carry the offending Duration");
14927 }
14928 other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
14929 }
14930 }
14931
14932 #[test]
14933 fn rejects_circuit_breaker_window_above_cap() {
14934 // The fail-before-pass-after pin: 3601s = 1h + 1s is
14935 // structurally one canonical-tick past the
14936 // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
14937 // integer-millisecond magnitude the canonical-form arm above
14938 // accepts cleanly, that the codec round-trips losslessly as
14939 // `"3601s"`, and that silently passed validate on every
14940 // pre-gate codebase because the typed slot's only checks were
14941 // the zero-floor and canonical-form arms. The
14942 // rolling-window-to-lifetime-counter degeneration surfaces
14943 // only at the runtime substrate (Envoy's outlier_detection
14944 // interval, the future CiliumClusterwideEnvoyConfig overlay)
14945 // far from the source `caixa.lisp` with no field naming the
14946 // offending policy.
14947 let mut s = three_member_spec();
14948 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
14949 s.politicas.circuit_breaker = Some(CircuitBreaker {
14950 max_failures: 5,
14951 window,
14952 });
14953 assert_eq!(
14954 s.validate().unwrap_err(),
14955 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
14956 );
14957 }
14958
14959 #[test]
14960 fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
14961 // Boundary case: exactly 1ms past the cap (the granularity the
14962 // canonical-form gate enforces). Catches a future "strictly
14963 // less than" half-measure and pins the diagnostic to name the
14964 // offending `Duration` verbatim. Peer of
14965 // `rejects_policy_timeout_one_millisecond_above_cap` on the
14966 // sibling duration-typed `:politicas :timeout` top edge.
14967 let mut s = three_member_spec();
14968 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
14969 s.politicas.circuit_breaker = Some(CircuitBreaker {
14970 max_failures: 5,
14971 window,
14972 });
14973 assert_eq!(
14974 s.validate().unwrap_err(),
14975 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
14976 );
14977 }
14978
14979 #[test]
14980 fn rejects_circuit_breaker_window_far_above_cap() {
14981 // The "obvious authoring footgun" case: a `(:window "24h")` or
14982 // `(:window "86400s")` — values the canonical-form arm
14983 // accepts as integer-millisecond magnitudes, the codec
14984 // round-trips losslessly through serde, but the
14985 // rolling-window breaker contract cannot honor (a 24-hour
14986 // rolling failure window is operationally a lifetime counter).
14987 // Until this gate landed validate accepted it. Pin both common
14988 // above-cap values (24h, 7d) so a future relaxation that
14989 // drops the upper bound surfaces here.
14990 for window in [
14991 Duration::from_secs(86_400), // 24h
14992 Duration::from_secs(604_800), // 7d
14993 Duration::from_secs(1_000_000), // ~11.5 days
14994 ] {
14995 let mut s = three_member_spec();
14996 s.politicas.circuit_breaker = Some(CircuitBreaker {
14997 max_failures: 5,
14998 window,
14999 });
15000 assert_eq!(
15001 s.validate().unwrap_err(),
15002 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
15003 );
15004 }
15005 }
15006
15007 #[test]
15008 fn accepts_circuit_breaker_window_at_cap() {
15009 // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
15010 // (1h) — must validate. The cap is inclusive on the top edge,
15011 // matching the [`POLICY_TIMEOUT_MAX`] /
15012 // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
15013 // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
15014 // sibling capped axes. Pin the boundary explicitly so a
15015 // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
15016 // instead of `>`) surfaces here as a test failure rather than
15017 // a silent contract narrowing.
15018 let mut s = three_member_spec();
15019 s.politicas.circuit_breaker = Some(CircuitBreaker {
15020 max_failures: 5,
15021 window: POLICY_BREAKER_WINDOW_MAX,
15022 });
15023 s.validate()
15024 .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
15025 }
15026
15027 #[test]
15028 fn accepts_circuit_breaker_window_typical_values() {
15029 // The documented production-playbook band positive-control
15030 // sweep — every value Hystrix / resilience4j / Istio / Envoy
15031 // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
15032 // through the long-tail failure-detection band (15m, 30m, 1h)
15033 // the cap accepts. Pin the inclusive validated set explicitly
15034 // so a future tightening of the ceiling surfaces here as a
15035 // deliberate test edit, not a silent contract narrowing.
15036 for window in [
15037 Duration::from_millis(1),
15038 Duration::from_millis(500),
15039 Duration::from_secs(1),
15040 Duration::from_secs(10), // Hystrix / Istio / Envoy default
15041 Duration::from_secs(30),
15042 Duration::from_secs(60), // resilience4j typical
15043 Duration::from_secs(300), // AWS App Mesh typical
15044 Duration::from_secs(900),
15045 Duration::from_secs(1800),
15046 Duration::from_secs(3600), // exactly 1h, the cap
15047 ] {
15048 let mut s = three_member_spec();
15049 s.politicas.circuit_breaker = Some(CircuitBreaker {
15050 max_failures: 5,
15051 window,
15052 });
15053 s.validate()
15054 .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
15055 }
15056 }
15057
15058 #[test]
15059 fn circuit_breaker_zero_window_takes_precedence_over_cap() {
15060 // The cross-arm ordering pin: `Duration::ZERO` is structurally
15061 // outside both `>= 1ms` (zero-floor) and
15062 // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
15063 // diagnostic is the more self-locating one (it directly names
15064 // the omit-axis remediation), so the validate gate must fire
15065 // on zero first. Same shape every other zero-then-cap
15066 // ordering on this surface uses
15067 // ([`AplicacaoError::PolicyTimeoutZero`] then
15068 // [`AplicacaoError::PolicyTimeoutExceedsCap`];
15069 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
15070 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
15071 let mut s = three_member_spec();
15072 s.politicas.circuit_breaker = Some(CircuitBreaker {
15073 max_failures: 5,
15074 window: Duration::ZERO,
15075 });
15076 assert_eq!(
15077 s.validate().unwrap_err(),
15078 AplicacaoError::PolicyBreakerZeroWindow,
15079 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
15080 );
15081 }
15082
15083 #[test]
15084 fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
15085 // The cross-arm ordering pin: a `Duration` that is *both*
15086 // sub-millisecond (non-canonical-form) and structurally above
15087 // the cap surfaces the canonical-form diagnostic first,
15088 // because the round-trip-shape break is the more fundamental
15089 // issue (the value can't even round-trip through the codec, so
15090 // the cap diagnostic naming `1ms..=1h` would be misleading —
15091 // there's no integer-ms form of the offending value). Pin the
15092 // order so a future refactor that reorders the arms surfaces
15093 // here as a test failure rather than a silent diagnostic
15094 // regression. Peer of
15095 // `policy_timeout_canonical_takes_precedence_over_cap` on the
15096 // sibling duration-typed `:politicas :timeout` axis.
15097 let mut s = three_member_spec();
15098 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
15099 s.politicas.circuit_breaker = Some(CircuitBreaker {
15100 max_failures: 5,
15101 window,
15102 });
15103 assert_eq!(
15104 s.validate().unwrap_err(),
15105 AplicacaoError::PolicyBreakerWindowNotCanonical { window },
15106 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
15107 );
15108 }
15109
15110 #[test]
15111 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
15112 // The cross-arm ordering pin between the two breaker axes: a
15113 // `CircuitBreaker` whose *both* `max_failures` is above its
15114 // cap *and* `window` is above its cap surfaces the
15115 // max-failures cap diagnostic first, because the validate
15116 // gate visits the failures arm before the window arm. Pin the
15117 // order so a future refactor that reorders the breaker arms
15118 // surfaces here.
15119 let mut s = three_member_spec();
15120 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
15121 s.politicas.circuit_breaker = Some(CircuitBreaker {
15122 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15123 window,
15124 });
15125 assert_eq!(
15126 s.validate().unwrap_err(),
15127 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15128 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
15129 },
15130 "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
15131 );
15132 }
15133
15134 #[test]
15135 fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
15136 // The diagnostic-shape pin: the offending `Duration` is
15137 // carried verbatim into the
15138 // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
15139 // the surfaced error message names the value the author wrote
15140 // (`":politicas :circuit-breaker :window (Duration { secs:
15141 // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
15142 // just the cap. Same self-locating diagnostic shape every
15143 // other typed-cap arm on this surface carries
15144 // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
15145 // offending `Duration` verbatim).
15146 let mut s = three_member_spec();
15147 let window = Duration::from_secs(7200); // 2h
15148 s.politicas.circuit_breaker = Some(CircuitBreaker {
15149 max_failures: 5,
15150 window,
15151 });
15152 let err = s.validate().unwrap_err();
15153 assert!(
15154 matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
15155 "got {err:?}"
15156 );
15157 let msg = err.to_string();
15158 assert!(
15159 msg.contains("7200"),
15160 ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
15161 );
15162 }
15163
15164 #[test]
15165 fn circuit_breaker_window_cap_pins_canonical_value() {
15166 // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
15167 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
15168 // shared duration codec emits as a clean canonical string
15169 // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
15170 // the sibling duration-typed `:politicas :timeout` axis (the
15171 // two duration-typed `:politicas` axes share a uniform top
15172 // edge). Pinning the literal value here surfaces a future
15173 // drift (a relaxation to 24h, a tightening to 5m) as a
15174 // deliberate test edit, not a silent contract narrowing. Same
15175 // shape every other typed-cap value pin on this surface uses
15176 // (`policy_timeout_cap_pins_canonical_value`).
15177 assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
15178 assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
15179 assert_eq!(
15180 POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
15181 "the two duration-typed `:politicas` caps share the same top edge"
15182 );
15183 }
15184
15185 #[test]
15186 fn circuit_breaker_window_cap_value_round_trips_through_codec() {
15187 // The codec round-trip property the cap arm preserves: the
15188 // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
15189 // through the shared duration codec — every value at the cap
15190 // renders to a clean canonical string (`"1h"`) and parses back
15191 // to the same `Duration`. Pin this so a future drift between
15192 // the cap constant and the codec's largest emitted unit
15193 // surfaces here. Same shape every other typed boundary pin on
15194 // this surface uses
15195 // (`policy_timeout_cap_value_round_trips_through_codec`).
15196 let policy = MeshPolicy {
15197 circuit_breaker: Some(CircuitBreaker {
15198 max_failures: 5,
15199 window: POLICY_BREAKER_WINDOW_MAX,
15200 }),
15201 ..Default::default()
15202 };
15203 let json = serde_json::to_string(&policy).unwrap();
15204 // The codec emits `"1h"` for the canonical 1-hour magnitude.
15205 assert!(
15206 json.contains("\"1h\""),
15207 "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
15208 );
15209 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15210 assert_eq!(
15211 back.circuit_breaker.unwrap().window,
15212 POLICY_BREAKER_WINDOW_MAX
15213 );
15214 }
15215
15216 #[test]
15217 fn is_integer_millisecond_duration_predicate_tracks_codec() {
15218 // Pin the predicate's accepted set against the codec's
15219 // accepted set explicitly. The codec parses
15220 // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
15221 // accepted value is an integer-millisecond multiple — so the
15222 // predicate must accept exactly that set. Same shape every
15223 // other predicate-on-the-typed-slot helper carries
15224 // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
15225 // Read directly from the codec-owned predicate — the crate's
15226 // single source of truth every typed-`Duration` axis now routes
15227 // through via
15228 // [`crate::render::require_positive_canonical_bounded_duration`].
15229 use super::supervisor::duration_codec::is_integer_millisecond_duration;
15230 assert!(is_integer_millisecond_duration(Duration::ZERO));
15231 assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
15232 assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
15233 assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
15234 assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
15235 assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
15236 // Non-integer-millisecond residue: rejected.
15237 assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
15238 assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
15239 assert!(!is_integer_millisecond_duration(Duration::from_micros(
15240 1500
15241 )));
15242 assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
15243 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
15244 999_999
15245 )));
15246 // The 1-ns-past-1ms boundary: rejected (no longer a clean
15247 // integer-millisecond multiple).
15248 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
15249 1_000_001
15250 )));
15251 }
15252
15253 #[test]
15254 fn policy_timeout_validated_value_round_trips_through_codec() {
15255 // The structural property the canonical-ms gate enforces:
15256 // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
15257 // round-trips losslessly through the shared `duration_codec`
15258 // (serialize → string → deserialize → equal value). Pin this
15259 // end-to-end so a future change to either side (the validate
15260 // gate's accepted granularity, the codec's parse/render unit
15261 // set) that breaks the alignment surfaces here. The
15262 // previous-state shape (typed slot accepts arbitrary
15263 // `Duration`, codec only round-trips integer-ms) would fail
15264 // this test for any `Duration::from_micros(1500)` timeout —
15265 // the validate gate now forecloses that.
15266 for timeout in [
15267 Duration::from_millis(1),
15268 Duration::from_millis(1500),
15269 Duration::from_secs(30),
15270 Duration::from_secs(3600),
15271 ] {
15272 let mut s = three_member_spec();
15273 s.politicas.timeout = Some(timeout);
15274 s.validate().unwrap();
15275 let json = serde_json::to_string(&s.politicas).unwrap();
15276 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15277 assert_eq!(
15278 back.timeout, s.politicas.timeout,
15279 "every validated :timeout must round-trip losslessly through the codec"
15280 );
15281 }
15282 }
15283
15284 #[test]
15285 fn circuit_breaker_window_validated_value_round_trips_through_codec() {
15286 // Peer of the `:timeout` round-trip property on the breaker
15287 // axis.
15288 for window in [
15289 Duration::from_millis(1),
15290 Duration::from_millis(1500),
15291 Duration::from_secs(30),
15292 Duration::from_secs(3600),
15293 ] {
15294 let mut s = three_member_spec();
15295 s.politicas.circuit_breaker = Some(CircuitBreaker {
15296 max_failures: 5,
15297 window,
15298 });
15299 s.validate().unwrap();
15300 let json = serde_json::to_string(&s.politicas).unwrap();
15301 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15302 assert_eq!(
15303 back.circuit_breaker.unwrap().window,
15304 window,
15305 "every validated :circuit-breaker :window must round-trip losslessly"
15306 );
15307 }
15308 }
15309
15310 #[test]
15311 fn empty_politicas_validates() {
15312 // Omitting every policy axis is fine — defaults express "no
15313 // policy on this axis", not "policy = 0". The fixture's typical
15314 // values continue to validate; this test pins that
15315 // MeshPolicy::default() is a clean pass through validate().
15316 let mut s = three_member_spec();
15317 s.politicas = MeshPolicy::default();
15318 s.validate().unwrap();
15319 }
15320
15321 #[test]
15322 fn typical_politicas_validates_with_every_axis_set() {
15323 // The full §III.1 example block (timeout + retries + breaker +
15324 // mtls + rate-limit) — every axis nonzero — must remain a
15325 // clean pass.
15326 let mut s = three_member_spec();
15327 s.politicas = MeshPolicy {
15328 timeout: Some(Duration::from_secs(30)),
15329 retries: Some(3),
15330 circuit_breaker: Some(CircuitBreaker {
15331 max_failures: 5,
15332 window: Duration::from_secs(60),
15333 }),
15334 mtls_required: Some(true),
15335 rate_limit: Some(RateLimit {
15336 rate: 100,
15337 window: Duration::from_secs(1),
15338 }),
15339 };
15340 s.validate().unwrap();
15341 }
15342
15343 #[test]
15344 fn rejects_empty_cluster_name() {
15345 let mut s = three_member_spec();
15346 s.placement.clusters = vec!["rio".into(), "".into()];
15347 assert_eq!(
15348 s.validate().unwrap_err(),
15349 AplicacaoError::PlacementClusterEmpty
15350 );
15351 }
15352
15353 #[test]
15354 fn rejects_duplicate_cluster_names() {
15355 let mut s = three_member_spec();
15356 s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
15357 let err = s.validate().unwrap_err();
15358 assert!(
15359 matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
15360 "got {err:?}"
15361 );
15362 }
15363
15364 #[test]
15365 fn rejects_placement_cluster_with_uppercase() {
15366 // The canonical "I copied the cluster's display name verbatim"
15367 // typo — K8s context names are lowercase per DNS-1123 label
15368 // rule, but org docs often round-trip a TitleCase identifier
15369 // (`Rio`, `Mar-East`) from an ADR. Mirrors the
15370 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
15371 // on the peer name axis.
15372 let mut s = three_member_spec();
15373 s.placement.clusters = vec!["Rio".into(), "mar".into()];
15374 let err = s.validate().unwrap_err();
15375 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15376 panic!("expected PlacementClusterInvalid, got other variant");
15377 };
15378 assert_eq!(cluster, "Rio");
15379 assert!(
15380 reason.contains("uppercase"),
15381 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
15382 );
15383 assert!(
15384 reason.contains("\"rio\""),
15385 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
15386 );
15387 }
15388
15389 #[test]
15390 fn rejects_placement_cluster_with_underscore() {
15391 // The canonical "I'm thinking of an env var / hostname slug"
15392 // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
15393 // schema. K8s context filtering on `my_cluster` silently misses
15394 // the cluster the author intended; the gate moves it to caixa-
15395 // build time. Same shape as `rejects_membro_caixa_with_underscore`
15396 // (3f9d7a0).
15397 let mut s = three_member_spec();
15398 s.placement.clusters = vec!["my_cluster".into()];
15399 let err = s.validate().unwrap_err();
15400 assert!(
15401 matches!(
15402 err,
15403 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15404 if cluster == "my_cluster" && reason.contains('_')
15405 ),
15406 "got {err:?}"
15407 );
15408 }
15409
15410 #[test]
15411 fn rejects_placement_cluster_with_dot() {
15412 // A `:placement :clusters` entry is a single DNS-1123 *label*,
15413 // not a subdomain — even though K8s context names sometimes
15414 // carry a dotted form via kubeconfig conventions, the strictest
15415 // floor among the use sites (DNS-1035 cluster.x-k8s.io
15416 // `metadata.name`, Cilium identity label values) wins. The "I
15417 // want to namespace my cluster names with `.`" intent is
15418 // expressed via `-` (`mar-east`).
15419 let mut s = three_member_spec();
15420 s.placement.clusters = vec!["team.rio".into()];
15421 let err = s.validate().unwrap_err();
15422 assert!(
15423 matches!(
15424 err,
15425 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15426 if cluster == "team.rio" && reason.contains('.')
15427 ),
15428 "got {err:?}"
15429 );
15430 }
15431
15432 #[test]
15433 fn rejects_placement_cluster_with_leading_hyphen() {
15434 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
15435 // with an alphanumeric. The K8s apiserver rejects `-rio`
15436 // outright; the rendered fan-out would emit a `metadata.name:
15437 // "-rio"` that fails admission far from the source caixa.lisp.
15438 let mut s = three_member_spec();
15439 s.placement.clusters = vec!["-rio".into()];
15440 let err = s.validate().unwrap_err();
15441 assert!(
15442 matches!(
15443 err,
15444 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
15445 if cluster == "-rio" && reason.contains("start and end")
15446 ),
15447 "got {err:?}"
15448 );
15449 }
15450
15451 #[test]
15452 fn rejects_placement_cluster_with_trailing_hyphen() {
15453 // The symmetric arm of the boundary rule. Pin separately so
15454 // both ends are covered against a future relaxation that only
15455 // checks one boundary (parallel to
15456 // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
15457 let mut s = three_member_spec();
15458 s.placement.clusters = vec!["rio-".into()];
15459 let err = s.validate().unwrap_err();
15460 assert!(
15461 matches!(
15462 err,
15463 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15464 if cluster == "rio-"
15465 ),
15466 "got {err:?}"
15467 );
15468 }
15469
15470 #[test]
15471 fn rejects_placement_cluster_with_unicode() {
15472 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
15473 // before it reaches K8s. The byte-by-byte ASCII validity check
15474 // rejects multi-byte UTF-8 sequences by the first byte that
15475 // fails `[a-z0-9-]`.
15476 let mut s = three_member_spec();
15477 s.placement.clusters = vec!["rió".into()];
15478 let err = s.validate().unwrap_err();
15479 assert!(
15480 matches!(
15481 err,
15482 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15483 if cluster == "rió"
15484 ),
15485 "got {err:?}"
15486 );
15487 }
15488
15489 #[test]
15490 fn rejects_placement_cluster_with_whitespace() {
15491 // Whitespace is the canonical "I pasted from a sketch / doc"
15492 // footgun. The apiserver rejects every cluster `metadata.name`
15493 // value carrying whitespace.
15494 let mut s = three_member_spec();
15495 s.placement.clusters = vec!["rio cluster".into()];
15496 let err = s.validate().unwrap_err();
15497 assert!(
15498 matches!(
15499 err,
15500 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
15501 if cluster == "rio cluster"
15502 ),
15503 "got {err:?}"
15504 );
15505 }
15506
15507 #[test]
15508 fn rejects_placement_cluster_too_long() {
15509 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
15510 // pin. The diagnostic names both the cap (63) and the actual
15511 // length so the author can shorten in one edit. Mirrors
15512 // `rejects_membro_caixa_too_long` (3f9d7a0).
15513 let mut s = three_member_spec();
15514 let too_long = "a".repeat(64);
15515 s.placement.clusters = vec![too_long.clone()];
15516 let err = s.validate().unwrap_err();
15517 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15518 panic!("expected PlacementClusterInvalid");
15519 };
15520 assert_eq!(cluster, too_long);
15521 assert!(
15522 reason.contains("63") && reason.contains("64"),
15523 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
15524 );
15525 }
15526
15527 #[test]
15528 fn placement_cluster_max_length_validates() {
15529 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
15530 // future tightening (e.g. dropping to 62) surfaces here as a
15531 // regression, mirroring `membro_caixa_max_length_validates`
15532 // (3f9d7a0).
15533 let mut s = three_member_spec();
15534 s.placement.clusters = vec!["a".repeat(63)];
15535 s.validate().unwrap();
15536 }
15537
15538 #[test]
15539 fn accepts_canonical_placement_cluster_forms() {
15540 // The DNS-1123 label shapes a caixa author is realistically
15541 // going to write for cluster names: single-word lowercase
15542 // (`rio`), regional hyphen-joined (`mar-east`), single
15543 // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
15544 // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
15545 // Pin every leg so a future tightening that bans (e.g.) digit-
15546 // start identifiers surfaces here.
15547 for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
15548 let mut s = three_member_spec();
15549 s.placement.clusters = vec![form.into()];
15550 s.validate().unwrap_or_else(|e| {
15551 panic!("canonical cluster form {form:?} must validate, got {e:?}")
15552 });
15553 }
15554 }
15555
15556 #[test]
15557 fn placement_cluster_empty_takes_precedence_over_invalid() {
15558 // Order pin: the existing `PlacementClusterEmpty` diagnostic
15559 // (which doesn't try to parse) fires before the new
15560 // `PlacementClusterInvalid` parse-side diagnostic, so an empty
15561 // `:clusters` entry keeps its narrower error message — the new
15562 // gate would also reject `""`, but the empty-string arm is the
15563 // more self-locating diagnostic. Mirrors the
15564 // `membro_caixa_empty_takes_precedence_over_invalid` pin
15565 // (3f9d7a0).
15566 let mut s = three_member_spec();
15567 s.placement.clusters = vec!["rio".into(), "".into()];
15568 let err = s.validate().unwrap_err();
15569 assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
15570 }
15571
15572 #[test]
15573 fn placement_cluster_invalid_fires_before_duplicate_check() {
15574 // Order pin: a malformed-shape `:clusters` entry surfaces *its
15575 // own* diagnostic, even when a later entry would otherwise
15576 // collapse onto a duplicate name. The per-entry shape gate runs
15577 // inline before the duplicate-key insert, parallel to
15578 // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
15579 let mut s = three_member_spec();
15580 s.placement.clusters = vec!["Rio".into(), "rio".into()];
15581 let err = s.validate().unwrap_err();
15582 assert!(
15583 matches!(
15584 err,
15585 AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
15586 ),
15587 "got {err:?}"
15588 );
15589 }
15590
15591 #[test]
15592 fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
15593 // The diagnostic-shape pin: the error names the offending
15594 // `:clusters` value verbatim so the author can grep their
15595 // caixa.lisp without re-running the build, and carries a
15596 // non-empty `reason` naming the specific violation. Same shape
15597 // every typed-shape gate enshrines
15598 // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
15599 // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
15600 let mut s = three_member_spec();
15601 s.placement.clusters = vec!["BAD_CLUSTER".into()];
15602 let err = s.validate().unwrap_err();
15603 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
15604 panic!("expected PlacementClusterInvalid");
15605 };
15606 assert_eq!(cluster, "BAD_CLUSTER");
15607 assert!(
15608 !reason.is_empty(),
15609 "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
15610 );
15611 }
15612
15613 #[test]
15614 fn rejects_sharded_with_empty_clusters() {
15615 // §III.1: Sharded uses :clusters as the shard pool. An empty
15616 // pool means "shard across no clusters" — meaningless, same as
15617 // Replicated with no hosts.
15618 let mut s = three_member_spec();
15619 s.placement.estrategia = PlacementStrategy::Sharded;
15620 s.placement.shard_key = Some("$tenantId".into());
15621 s.placement.clusters = vec![];
15622 assert!(matches!(
15623 s.validate().unwrap_err(),
15624 AplicacaoError::PlacementWithoutClusters {
15625 estrategia: PlacementStrategy::Sharded
15626 }
15627 ));
15628 }
15629
15630 #[test]
15631 fn rejects_sharded_with_empty_shard_key() {
15632 let mut s = three_member_spec();
15633 s.placement.estrategia = PlacementStrategy::Sharded;
15634 s.placement.shard_key = Some("".into());
15635 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
15636 }
15637
15638 #[test]
15639 fn rejects_shard_key_under_replicated_strategy() {
15640 // The fail-before-pass-after pin: a `:placement (:estrategia
15641 // Replicated :shard-key "tenantId")` manifest carries the
15642 // hash-keyed-distribution slot on a strategy that never consumes
15643 // it. Before the gate the typed slot's value silently vanished
15644 // at the renderer layer (caixa-mesh emits `placement.shardKey`
15645 // verbatim regardless of strategy; the Akka-style cluster-
15646 // sharding reconciler keys off `estrategia == Sharded` and
15647 // ignores the slot otherwise), with no diagnostic. Lifting the
15648 // rejection to a build-time gate makes the
15649 // `shard_key.is_some() == matches!(estrategia, Sharded)`
15650 // partition a structural property of every validated
15651 // [`Placement`].
15652 let mut s = three_member_spec();
15653 // The fixture already uses Replicated; just add a shard-key.
15654 s.placement.shard_key = Some("$tenantId".into());
15655 let err = s.validate().unwrap_err();
15656 let AplicacaoError::ShardKeyOnNonSharded {
15657 estrategia,
15658 shard_key,
15659 } = err
15660 else {
15661 panic!("expected ShardKeyOnNonSharded, got {err:?}");
15662 };
15663 assert_eq!(estrategia, PlacementStrategy::Replicated);
15664 assert_eq!(shard_key, "$tenantId");
15665 }
15666
15667 #[test]
15668 fn rejects_shard_key_under_singlenode_strategy() {
15669 // Peer of the Replicated case above on the SingleNode arm: OTP
15670 // distributed-app takeover (one cluster runs at a time) has no
15671 // hash-keyed routing axis to consume `:shard-key` either, so
15672 // the rejection fires on both non-Sharded arms uniformly.
15673 let mut s = three_member_spec();
15674 s.placement.estrategia = PlacementStrategy::SingleNode;
15675 s.placement.shard_key = Some("$tenantId".into());
15676 let err = s.validate().unwrap_err();
15677 let AplicacaoError::ShardKeyOnNonSharded {
15678 estrategia,
15679 shard_key,
15680 } = err
15681 else {
15682 panic!("expected ShardKeyOnNonSharded, got {err:?}");
15683 };
15684 assert_eq!(estrategia, PlacementStrategy::SingleNode);
15685 assert_eq!(shard_key, "$tenantId");
15686 }
15687
15688 #[test]
15689 fn rejects_empty_shard_key_under_replicated_strategy() {
15690 // The `Some("")` case under non-Sharded is rejected by
15691 // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
15692 // fires before the empty-value gate), not
15693 // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
15694 // the `Sharded` arm). Pin the partition so a future reorder of
15695 // the validate_placement match arms doesn't silently swap which
15696 // diagnostic the author sees — both are author errors, but
15697 // ShardKeyOnNonSharded names which strategy is the actual fix
15698 // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
15699 // only says "pick a non-empty key".
15700 let mut s = three_member_spec();
15701 s.placement.shard_key = Some(String::new());
15702 let err = s.validate().unwrap_err();
15703 assert!(
15704 matches!(
15705 err,
15706 AplicacaoError::ShardKeyOnNonSharded {
15707 estrategia: PlacementStrategy::Replicated,
15708 ref shard_key,
15709 } if shard_key.is_empty()
15710 ),
15711 "got {err:?}"
15712 );
15713 }
15714
15715 #[test]
15716 fn replicated_without_shard_key_validates() {
15717 // The complement of the rejection: `:placement :estrategia
15718 // Replicated` with `:shard-key None` is the canonical happy
15719 // path on every existing fixture. Pin the no-shard-key case so
15720 // the new gate doesn't accidentally fire on `None`.
15721 let mut s = three_member_spec();
15722 assert!(matches!(
15723 s.placement.estrategia,
15724 PlacementStrategy::Replicated
15725 ));
15726 s.placement.shard_key = None;
15727 s.validate().unwrap();
15728 }
15729
15730 #[test]
15731 fn singlenode_without_shard_key_validates() {
15732 // Peer of the Replicated no-shard-key case on the SingleNode
15733 // arm — both non-Sharded strategies must validate cleanly when
15734 // the slot is omitted.
15735 let mut s = three_member_spec();
15736 s.placement.estrategia = PlacementStrategy::SingleNode;
15737 s.placement.shard_key = None;
15738 s.validate().unwrap();
15739 }
15740
15741 fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
15742 // Fixture builder for the `:placement :shard-key` shape gate
15743 // tests: a three-member Aplicacao on the `Sharded` strategy
15744 // with the supplied `:shard-key` slot. Co-locates the
15745 // arm-construction so every test below carries one line of
15746 // setup (the offending `:shard-key` value) and the assertion.
15747 let mut s = three_member_spec();
15748 s.placement.estrategia = PlacementStrategy::Sharded;
15749 s.placement.shard_key = Some(key.into());
15750 s
15751 }
15752
15753 #[test]
15754 fn rejects_shard_key_with_embedded_space() {
15755 // The canonical paste-from-aligned-doc footgun:
15756 // `:shard-key "$tenant Id"` — the Akka-style entity-id
15757 // extractor reads the slot as a single-token reference, and an
15758 // embedded space breaks the token boundary at the runtime
15759 // hash-extractor pass with no diagnostic naming the offending
15760 // entry.
15761 let s = sharded_spec_with_key("$tenant Id");
15762 let err = s.validate().unwrap_err();
15763 assert!(
15764 matches!(
15765 err,
15766 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15767 if shard_key == "$tenant Id" && reason.contains("space")
15768 ),
15769 "got {err:?}"
15770 );
15771 }
15772
15773 #[test]
15774 fn rejects_shard_key_with_leading_space() {
15775 // Leading-space arm of the embedded-whitespace footgun — the
15776 // paste-from-aligned-doc / paste-from-CSV-cell variant where
15777 // the leading column-padding leaked into the slot.
15778 let s = sharded_spec_with_key(" $tenantId");
15779 let err = s.validate().unwrap_err();
15780 assert!(
15781 matches!(
15782 err,
15783 AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
15784 if shard_key == " $tenantId"
15785 ),
15786 "got {err:?}"
15787 );
15788 }
15789
15790 #[test]
15791 fn rejects_shard_key_with_trailing_newline() {
15792 // The canonical paste-from-shell-heredoc footgun — every
15793 // `<<EOF` heredoc terminator paste leaves a trailing newline
15794 // the YAML emitter then folds away inconsistently across
15795 // emitter implementations.
15796 let s = sharded_spec_with_key("$tenantId\n");
15797 let err = s.validate().unwrap_err();
15798 assert!(
15799 matches!(
15800 err,
15801 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15802 if shard_key == "$tenantId\n" && reason.contains("0x0a")
15803 ),
15804 "got {err:?}"
15805 );
15806 }
15807
15808 #[test]
15809 fn rejects_shard_key_with_embedded_tab() {
15810 // The paste-from-aligned-doc tab-stop variant — tabs land
15811 // alongside spaces in copy-paste from formatted columns.
15812 let s = sharded_spec_with_key("$tenant\tId");
15813 let err = s.validate().unwrap_err();
15814 assert!(
15815 matches!(
15816 err,
15817 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15818 if shard_key == "$tenant\tId" && reason.contains("tab")
15819 ),
15820 "got {err:?}"
15821 );
15822 }
15823
15824 #[test]
15825 fn rejects_shard_key_with_control_character() {
15826 // The paste-from-binary / paste-from-screen-cleared-terminal
15827 // footgun — an embedded `\x01` (SOH) byte that some YAML
15828 // emitters silently strip and others escape as ``,
15829 // breaking round-trip across emitter implementations.
15830 let s = sharded_spec_with_key("$tenant\u{0001}Id");
15831 let err = s.validate().unwrap_err();
15832 assert!(
15833 matches!(
15834 err,
15835 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15836 if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
15837 ),
15838 "got {err:?}"
15839 );
15840 }
15841
15842 #[test]
15843 fn rejects_shard_key_with_non_ascii() {
15844 // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
15845 // footgun — non-ASCII bytes normalize differently between the
15846 // caixa-mesh-side YAML emitter and the in-cluster reconciler's
15847 // YAML parser, the same entity ID can silently map to two
15848 // distinct shards on a re-render.
15849 let s = sharded_spec_with_key("$tenàntId");
15850 let err = s.validate().unwrap_err();
15851 assert!(
15852 matches!(
15853 err,
15854 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
15855 if shard_key == "$tenàntId" && reason.contains("non-ASCII")
15856 ),
15857 "got {err:?}"
15858 );
15859 }
15860
15861 #[test]
15862 fn rejects_shard_key_too_long() {
15863 // Length cap pin: 64 bytes — one byte over the
15864 // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
15865 // here is a paste-from-doc multi-line blob landing in
15866 // `:shard-key` instead of a single-token extractor expression.
15867 let too_long = "a".repeat(64);
15868 let s = sharded_spec_with_key(&too_long);
15869 let err = s.validate().unwrap_err();
15870 let AplicacaoError::ShardKeyInvalid {
15871 ref shard_key,
15872 ref reason,
15873 } = err
15874 else {
15875 panic!("expected ShardKeyInvalid, got {err:?}");
15876 };
15877 assert_eq!(shard_key, &too_long);
15878 assert!(
15879 reason.contains("63") && reason.contains("64"),
15880 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
15881 );
15882 }
15883
15884 #[test]
15885 fn shard_key_max_length_validates() {
15886 // Boundary pin: 63 bytes exactly — the
15887 // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
15888 // dropping to 62) surfaces here as a regression, mirroring
15889 // `placement_cluster_max_length_validates` /
15890 // `placement_affinity_max_length_validates` on the peer
15891 // identifier-shaped slots.
15892 let s = sharded_spec_with_key(&"a".repeat(63));
15893 s.validate().unwrap();
15894 }
15895
15896 #[test]
15897 fn accepts_canonical_shard_key_forms() {
15898 // The Akka-style entity-id extractor shapes a caixa author is
15899 // realistically going to write — pin every leg so a future
15900 // tightening that bans (e.g.) the `${...}` interpolation
15901 // variant or the `metadata.<field>` JSONPath form surfaces
15902 // here as a regression. The canonical forms span:
15903 //
15904 // - bare property name (`tenantId`, `customerId`)
15905 // - Akka `ExtractEntityId` placeholder (`$tenantId`)
15906 // - JSONPath-style nested reference (`metadata.tenantId`,
15907 // `$.user.id`)
15908 // - interpolation-style template (`${tenant}`)
15909 // - snake_case property name (`customer_id`)
15910 // - kebab-case property name (`customer-id` — accepted
15911 // because the slot is a printable-ASCII single-token
15912 // reference, not a DNS-1123 label like
15913 // `:placement :affinity` / `:clusters`)
15914 // - single character (`a`, `$` — boundary)
15915 for form in [
15916 "tenantId",
15917 "customerId",
15918 "$tenantId",
15919 "metadata.tenantId",
15920 "$.user.id",
15921 "${tenant}",
15922 "customer_id",
15923 "customer-id",
15924 "a",
15925 "$",
15926 ] {
15927 let s = sharded_spec_with_key(form);
15928 s.validate().unwrap_or_else(|e| {
15929 panic!("canonical shard-key form {form:?} must validate, got {e:?}")
15930 });
15931 }
15932 }
15933
15934 #[test]
15935 fn shard_key_empty_takes_precedence_over_invalid() {
15936 // Order pin: the existing `ShardedKeyEmpty` diagnostic
15937 // (reserved for the `Sharded` `Some("")` arm) fires before the
15938 // new `ShardKeyInvalid` parse-side diagnostic, so an empty
15939 // `:shard-key` keeps its narrower error message — the new gate
15940 // would also reject `""` defensively, but the empty-string arm
15941 // is the more self-locating diagnostic. Mirrors the
15942 // `placement_cluster_empty_takes_precedence_over_invalid` pin
15943 // on the peer identifier-shaped slot.
15944 let s = sharded_spec_with_key("");
15945 let err = s.validate().unwrap_err();
15946 assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
15947 }
15948
15949 #[test]
15950 fn shard_key_invalid_diagnostic_carries_offending_value() {
15951 // The diagnostic-shape pin: the error names the offending
15952 // `:shard-key` value verbatim so the author can grep their
15953 // caixa.lisp without re-running the build, and carries a
15954 // parser-shaped `reason:` naming the specific violation —
15955 // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
15956 // on the peer identifier-shaped slot.
15957 let s = sharded_spec_with_key("$tenant Id");
15958 let err = s.validate().unwrap_err();
15959 let AplicacaoError::ShardKeyInvalid {
15960 ref shard_key,
15961 ref reason,
15962 } = err
15963 else {
15964 panic!("expected ShardKeyInvalid, got {err:?}");
15965 };
15966 assert_eq!(shard_key, "$tenant Id");
15967 assert!(
15968 !reason.is_empty(),
15969 "reason must name the specific violation, got empty string"
15970 );
15971 }
15972
15973 #[test]
15974 fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
15975 // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
15976 // `:shard-key` carried on non-Sharded strategies) fires before
15977 // the shape gate, so a malformed `:shard-key` carried on (e.g.)
15978 // a `Replicated` strategy surfaces the more self-locating
15979 // strategy-mismatch diagnostic (naming the actual fix — drop
15980 // the slot, or switch to Sharded) rather than the shape
15981 // diagnostic. The strategy-mismatch arm is the more actionable
15982 // diagnostic: a malformed shard-key on Replicated is "you
15983 // shouldn't have a :shard-key here at all", not "your
15984 // :shard-key value is malformed".
15985 let mut s = three_member_spec();
15986 // Replicated is the default fixture strategy.
15987 s.placement.shard_key = Some("$tenant Id".into());
15988 let err = s.validate().unwrap_err();
15989 assert!(
15990 matches!(
15991 err,
15992 AplicacaoError::ShardKeyOnNonSharded {
15993 estrategia: PlacementStrategy::Replicated,
15994 ..
15995 }
15996 ),
15997 "got {err:?}"
15998 );
15999 }
16000
16001 #[test]
16002 fn rejects_empty_affinity_hint() {
16003 let mut s = three_member_spec();
16004 s.placement.affinity = Some("".into());
16005 assert_eq!(
16006 s.validate().unwrap_err(),
16007 AplicacaoError::PlacementAffinityEmpty
16008 );
16009 }
16010
16011 #[test]
16012 fn placement_without_affinity_validates() {
16013 // Omitting :affinity is fine — the placement engine falls back
16014 // to the default heuristic. Pin the no-hint case so the
16015 // affinity-empty rejection doesn't accidentally fire on `None`.
16016 let mut s = three_member_spec();
16017 s.placement.affinity = None;
16018 s.validate().unwrap();
16019 }
16020
16021 #[test]
16022 fn rejects_placement_affinity_with_uppercase() {
16023 // The canonical "I copied the ADR's display name verbatim" typo
16024 // — placement hints land verbatim in K8s label-selector
16025 // territory, where the apiserver enforces the DNS-1123 label
16026 // rule (lowercase-only) on every identity-keyed admission axis.
16027 // Mirrors `rejects_placement_cluster_with_uppercase` on the
16028 // sibling slot.
16029 let mut s = three_member_spec();
16030 s.placement.affinity = Some("DataLocality".into());
16031 let err = s.validate().unwrap_err();
16032 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
16033 panic!("expected PlacementAffinityInvalid, got other variant");
16034 };
16035 assert_eq!(affinity, "DataLocality");
16036 assert!(
16037 reason.contains("uppercase"),
16038 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
16039 );
16040 assert!(
16041 reason.contains("\"datalocality\""),
16042 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
16043 );
16044 }
16045
16046 #[test]
16047 fn rejects_placement_affinity_with_underscore() {
16048 // The canonical "I'm thinking of an env var / Python identifier"
16049 // leak — `_` is forbidden by every DNS-1123 label schema. Same
16050 // shape as `rejects_placement_cluster_with_underscore` on the
16051 // sibling slot.
16052 let mut s = three_member_spec();
16053 s.placement.affinity = Some("data_locality".into());
16054 let err = s.validate().unwrap_err();
16055 assert!(
16056 matches!(
16057 err,
16058 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
16059 if affinity == "data_locality" && reason.contains('_')
16060 ),
16061 "got {err:?}"
16062 );
16063 }
16064
16065 #[test]
16066 fn rejects_placement_affinity_with_dot() {
16067 // A `:placement :affinity` value is a single DNS-1123 *label*
16068 // (it lands as a K8s label value selector key), not a subdomain.
16069 // The "I want to namespace my hint with `.`" intent is expressed
16070 // via `-` (`data-locality-east`).
16071 let mut s = three_member_spec();
16072 s.placement.affinity = Some("data.locality".into());
16073 let err = s.validate().unwrap_err();
16074 assert!(
16075 matches!(
16076 err,
16077 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
16078 if affinity == "data.locality" && reason.contains('.')
16079 ),
16080 "got {err:?}"
16081 );
16082 }
16083
16084 #[test]
16085 fn rejects_placement_affinity_with_unicode() {
16086 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
16087 // before it reaches K8s. The byte-by-byte ASCII validity check
16088 // rejects multi-byte UTF-8 sequences by the first byte that
16089 // fails `[a-z0-9-]`.
16090 let mut s = three_member_spec();
16091 s.placement.affinity = Some("data-localité".into());
16092 let err = s.validate().unwrap_err();
16093 assert!(
16094 matches!(
16095 err,
16096 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
16097 if affinity == "data-localité"
16098 ),
16099 "got {err:?}"
16100 );
16101 }
16102
16103 #[test]
16104 fn rejects_placement_affinity_with_leading_hyphen() {
16105 // DNS-1123 boundary rule: labels must start with an
16106 // alphanumeric. Pin separately from the trailing-hyphen arm so
16107 // a future relaxation that only checks one boundary surfaces
16108 // here as a regression (parallel to
16109 // `rejects_placement_cluster_with_leading_hyphen`).
16110 let mut s = three_member_spec();
16111 s.placement.affinity = Some("-data-locality".into());
16112 let err = s.validate().unwrap_err();
16113 assert!(
16114 matches!(
16115 err,
16116 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
16117 if affinity == "-data-locality" && reason.contains("start and end")
16118 ),
16119 "got {err:?}"
16120 );
16121 }
16122
16123 #[test]
16124 fn rejects_placement_affinity_with_trailing_hyphen() {
16125 // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
16126 // ends are covered against a future relaxation.
16127 let mut s = three_member_spec();
16128 s.placement.affinity = Some("data-locality-".into());
16129 let err = s.validate().unwrap_err();
16130 assert!(
16131 matches!(
16132 err,
16133 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
16134 if affinity == "data-locality-"
16135 ),
16136 "got {err:?}"
16137 );
16138 }
16139
16140 #[test]
16141 fn rejects_placement_affinity_with_whitespace() {
16142 // Whitespace is the canonical "I pasted from a sketch / doc"
16143 // footgun. The apiserver rejects every label-selector value
16144 // carrying whitespace.
16145 let mut s = three_member_spec();
16146 s.placement.affinity = Some("data locality".into());
16147 let err = s.validate().unwrap_err();
16148 assert!(
16149 matches!(
16150 err,
16151 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
16152 if affinity == "data locality"
16153 ),
16154 "got {err:?}"
16155 );
16156 }
16157
16158 #[test]
16159 fn rejects_placement_affinity_too_long() {
16160 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
16161 // pin. The diagnostic names both the cap (63) and the actual
16162 // length so the author can shorten in one edit. Mirrors
16163 // `rejects_placement_cluster_too_long`.
16164 let mut s = three_member_spec();
16165 let too_long = "a".repeat(64);
16166 s.placement.affinity = Some(too_long.clone());
16167 let err = s.validate().unwrap_err();
16168 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
16169 panic!("expected PlacementAffinityInvalid");
16170 };
16171 assert_eq!(affinity, too_long);
16172 assert!(
16173 reason.contains("63") && reason.contains("64"),
16174 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
16175 );
16176 }
16177
16178 #[test]
16179 fn placement_affinity_max_length_validates() {
16180 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
16181 // future tightening (e.g. dropping to 62) surfaces here as a
16182 // regression, mirroring `placement_cluster_max_length_validates`.
16183 let mut s = three_member_spec();
16184 s.placement.affinity = Some("a".repeat(63));
16185 s.validate().unwrap();
16186 }
16187
16188 #[test]
16189 fn accepts_canonical_placement_affinity_forms() {
16190 // The DNS-1123 label shapes a caixa author is realistically
16191 // going to write for placement hints: the M3 canonical examples
16192 // (`data-locality`, `low-latency`, `anti-affinity`), the
16193 // single-token form (`affinity`), the single-character boundary
16194 // (`a`), the digit-start (DNS-1123 allows this, unlike
16195 // DNS-1035), and a regional-suffixed form. Pin every leg so a
16196 // future tightening that bans (e.g.) digit-start identifiers
16197 // surfaces here.
16198 for form in [
16199 "data-locality",
16200 "low-latency",
16201 "anti-affinity",
16202 "affinity",
16203 "a",
16204 "3-tier",
16205 "locality-east",
16206 ] {
16207 let mut s = three_member_spec();
16208 s.placement.affinity = Some(form.into());
16209 s.validate().unwrap_or_else(|e| {
16210 panic!("canonical affinity form {form:?} must validate, got {e:?}")
16211 });
16212 }
16213 }
16214
16215 #[test]
16216 fn placement_affinity_empty_takes_precedence_over_invalid() {
16217 // Order pin: the existing `PlacementAffinityEmpty` diagnostic
16218 // (which doesn't try to parse) fires before the new
16219 // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
16220 // `:affinity` keeps its narrower error message — the new gate
16221 // would also reject `""`, but the empty-string arm is the more
16222 // self-locating diagnostic. Mirrors the
16223 // `placement_cluster_empty_takes_precedence_over_invalid` pin.
16224 let mut s = three_member_spec();
16225 s.placement.affinity = Some(String::new());
16226 let err = s.validate().unwrap_err();
16227 assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
16228 }
16229
16230 #[test]
16231 fn placement_affinity_invalid_diagnostic_carries_offending_value() {
16232 // The diagnostic shape pin: every rejection carries the offending
16233 // `affinity:` verbatim plus a parser-shaped `reason:` so the
16234 // author can grep their caixa.lisp for `:affinity "<hint>"` and
16235 // fix it in one edit. Mirrors the
16236 // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
16237 // pin on the sibling slot.
16238 let mut s = three_member_spec();
16239 s.placement.affinity = Some("Data_Locality".into());
16240 let err = s.validate().unwrap_err();
16241 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
16242 panic!("expected PlacementAffinityInvalid");
16243 };
16244 assert_eq!(affinity, "Data_Locality");
16245 assert!(
16246 !reason.is_empty(),
16247 "diagnostic reason must not be empty (got: {reason:?})"
16248 );
16249 }
16250
16251 #[test]
16252 fn singlenode_with_takeover_candidates_validates() {
16253 // OTP distributed-application convention (MESH-COMPOSITION
16254 // §II.1): SingleNode runs on one cluster at a time but the
16255 // :clusters list enumerates the takeover candidates. Multiple
16256 // entries are not a contradiction — they are the failover pool.
16257 let mut s = three_member_spec();
16258 s.placement.estrategia = PlacementStrategy::SingleNode;
16259 s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
16260 s.validate().unwrap();
16261 }
16262
16263 // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
16264
16265 #[test]
16266 fn mesh_policy_default_is_empty() {
16267 // The Default impl carries None on every axis — the typed
16268 // analog of an unset `:politicas (())` slot. Renderers that
16269 // overlay the policy onto a cluster artifact key off this
16270 // predicate to skip the slot entirely; pinning so a future
16271 // axis added to MeshPolicy can't silently break the contract
16272 // (a new field whose Default is non-None would flip is_empty
16273 // to false on every existing caixa, surfacing here).
16274 assert!(MeshPolicy::default().is_empty());
16275 }
16276
16277 #[test]
16278 fn mesh_policy_with_only_timeout_is_not_empty() {
16279 let p = MeshPolicy {
16280 timeout: Some(Duration::from_secs(30)),
16281 ..Default::default()
16282 };
16283 assert!(!p.is_empty());
16284 }
16285
16286 #[test]
16287 fn mesh_policy_with_only_retries_is_not_empty() {
16288 let p = MeshPolicy {
16289 retries: Some(3),
16290 ..Default::default()
16291 };
16292 assert!(!p.is_empty());
16293 }
16294
16295 #[test]
16296 fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
16297 let p = MeshPolicy {
16298 circuit_breaker: Some(CircuitBreaker {
16299 max_failures: 5,
16300 window: Duration::from_secs(60),
16301 }),
16302 ..Default::default()
16303 };
16304 assert!(!p.is_empty());
16305 }
16306
16307 #[test]
16308 fn mesh_policy_with_only_mtls_required_is_not_empty() {
16309 // Even `mtls_required: Some(false)` (an explicit opt-out) is
16310 // not empty — the author *named* the axis, the renderer needs
16311 // to honor that vs. fall back to the cluster default.
16312 let p = MeshPolicy {
16313 mtls_required: Some(false),
16314 ..Default::default()
16315 };
16316 assert!(!p.is_empty());
16317 }
16318
16319 #[test]
16320 fn mesh_policy_with_only_rate_limit_is_not_empty() {
16321 let p = MeshPolicy {
16322 rate_limit: Some(RateLimit {
16323 rate: 100,
16324 window: Duration::from_secs(1),
16325 }),
16326 ..Default::default()
16327 };
16328 assert!(!p.is_empty());
16329 }
16330
16331 #[test]
16332 fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
16333 // The three-member happy-path fixture sets timeout + retries +
16334 // mtls_required — every populated axis must read non-empty.
16335 // Pin the round-trip so the M3.x per-:politicas emitter (the
16336 // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
16337 // on is_empty() to decide whether to emit at all without
16338 // re-deriving the contract from inline field probes.
16339 assert!(!three_member_spec().politicas.is_empty());
16340 }
16341
16342 // ── shared duration codec: cross-slot integer-magnitude gate ──
16343 //
16344 // The integer-magnitude discipline applied to
16345 // `supervisor::duration_codec::parse` lifts onto every typed slot
16346 // that routes through the shared codec — `MeshPolicy::timeout`
16347 // (`:politicas :timeout`) and `CircuitBreaker::window`
16348 // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
16349 // These cross-slot tests pin that the gate fires at the serde
16350 // layer for both typed slots, not just for the supervisor side.
16351
16352 #[test]
16353 fn policy_timeout_serde_rejects_fractional_seconds() {
16354 // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
16355 // so the shared codec's integer-magnitude gate applies on
16356 // deserialize. `"1.5s"` previously parsed to 1500ms and round-
16357 // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
16358 // deserialize with the canonical-form diagnostic naming the
16359 // offending `"1.5"` and the remediation `"1500ms"`.
16360 let payload = r#"{"timeout":"1.5s"}"#;
16361 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16362 let msg = err.to_string();
16363 assert!(
16364 msg.contains("not a non-negative integer"),
16365 "expected integer-magnitude diagnostic in {msg:?}"
16366 );
16367 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
16368 assert!(
16369 msg.contains("\"1500ms\""),
16370 "missing canonical-form remediation in {msg:?}"
16371 );
16372 }
16373
16374 #[test]
16375 fn policy_timeout_serde_rejects_leading_plus_sign() {
16376 // Pin the leading-`+` arm cross-slot — the prior f64 parser
16377 // accepted `"+30s"` silently and round-tripped to `"30s"`.
16378 let payload = r#"{"timeout":"+30s"}"#;
16379 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16380 let msg = err.to_string();
16381 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
16382 }
16383
16384 #[test]
16385 fn circuit_breaker_window_serde_rejects_fractional_minutes() {
16386 // `CircuitBreaker::window` uses `with =
16387 // "supervisor::duration_codec_required"` (the required-Duration
16388 // variant that delegates to the same shared parser). `"0.5m"`
16389 // parsed to 30s and round-tripped to `"30s"` on next emit —
16390 // DRIFT closed.
16391 let payload = format!(
16392 r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
16393 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
16394 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
16395 );
16396 let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
16397 let msg = err.to_string();
16398 assert!(
16399 msg.contains("not a non-negative integer"),
16400 "expected integer-magnitude diagnostic in {msg:?}"
16401 );
16402 assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
16403 assert!(
16404 msg.contains("\"30s\""),
16405 "missing canonical-form remediation in {msg:?}"
16406 );
16407 }
16408
16409 #[test]
16410 fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
16411 // Pin the happy-path on the cross-slot side: every canonical
16412 // author shape `render` ever emits parses cleanly through the
16413 // shared codec on the `CircuitBreaker` slot. The
16414 // codec's accepted set (post-gate) is exactly its emitted set
16415 // for the integer-magnitude class.
16416 for window_lit in ["30s", "500ms", "2m", "1h"] {
16417 let payload = format!(
16418 r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
16419 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
16420 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
16421 );
16422 let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
16423 panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
16424 });
16425 assert_eq!(cb.max_failures, 5);
16426 }
16427 }
16428
16429 // ── rate_limit_codec: integer-magnitude gate ──
16430 //
16431 // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
16432 // / 737a676 / d53c922 trajectory landed on every typed-duration /
16433 // typed-byte-size codec in caixa-core lifts onto the fifth typed
16434 // codec — `rate_limit_codec` — through the digit-only magnitude
16435 // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
16436 // These tests pin the gate at the serde layer for `:politicas
16437 // :rate-limit` (the only typed slot the codec backs), and at the
16438 // codec-internal `parse` layer for the canonical positive cases.
16439
16440 #[test]
16441 fn rate_limit_serde_rejects_fractional_rate() {
16442 // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
16443 // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
16444 // wording, which didn't name the canonical-form remediation or
16445 // the round-trip drift the next emit would produce. Now refused
16446 // at deserialize with the canonical-form diagnostic naming the
16447 // offending `"1.5"` magnitude and the round-trip drift wording.
16448 let payload = r#"{"rateLimit":"1.5/s"}"#;
16449 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16450 let msg = err.to_string();
16451 assert!(
16452 msg.contains("not a non-negative integer"),
16453 "expected integer-magnitude diagnostic in {msg:?}"
16454 );
16455 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
16456 assert!(
16457 msg.contains("THEORY.md"),
16458 "missing render-determinism contract citation in {msg:?}"
16459 );
16460 }
16461
16462 #[test]
16463 fn rate_limit_serde_rejects_leading_plus_sign() {
16464 // `u32::from_str("+100")` returns `Ok(100)` (Rust's
16465 // permissive-`+` parse), so `"+100/s"` silently parsed to
16466 // `RateLimit { 100, 1s }` and round-tripped through `render` to
16467 // `"100/s"` — a *different* canonical string on the next emit,
16468 // breaking the THEORY.md Part V render-determinism contract
16469 // exactly the way the peer duration codecs' `"+30s"` case did.
16470 // This is the load-bearing class the digit-only gate closes
16471 // beyond what `u32::from_str`'s strictness covers on its own.
16472 let payload = r#"{"rateLimit":"+100/s"}"#;
16473 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16474 let msg = err.to_string();
16475 assert!(
16476 msg.contains("not a non-negative integer"),
16477 "expected integer-magnitude diagnostic in {msg:?}"
16478 );
16479 assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
16480 }
16481
16482 #[test]
16483 fn rate_limit_serde_rejects_leading_minus_sign() {
16484 // The signed-negative arm: `"-1/s"` lands on the
16485 // non-canonical-but-numeric branch via the `i64` fallback (the
16486 // `f64` parse also succeeds), surfacing the canonical-form
16487 // diagnostic. Replaces the prior value-laundered "not a u32"
16488 // wording with the unified diagnostic across signs.
16489 let payload = r#"{"rateLimit":"-1/s"}"#;
16490 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16491 let msg = err.to_string();
16492 assert!(
16493 msg.contains("not a non-negative integer"),
16494 "expected integer-magnitude diagnostic in {msg:?}"
16495 );
16496 assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
16497 }
16498
16499 #[test]
16500 fn rate_limit_serde_rejects_decimal_shaped_integer() {
16501 // `"100.0/s"` is integer-valued numerically but not in the
16502 // codec's accepted set — `render` emits `"100/s"`, so the
16503 // round-trip would drift. Lifted to the canonical-form
16504 // diagnostic peer with the duration codec's `"1.0s"` case
16505 // (1c55a2a).
16506 let payload = r#"{"rateLimit":"100.0/s"}"#;
16507 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16508 let msg = err.to_string();
16509 assert!(
16510 msg.contains("not a non-negative integer"),
16511 "expected integer-magnitude diagnostic in {msg:?}"
16512 );
16513 assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
16514 }
16515
16516 #[test]
16517 fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
16518 // Non-numeric, non-digit-only input lands on the existing
16519 // narrower `"not a u32"` arm (preserved for diagnostic-shape
16520 // stability on the parser-shape footgun case). Pin this so a
16521 // future relaxation of the numeric-fallback predicate doesn't
16522 // silently collapse garbage onto the canonical-form arm — same
16523 // partition the peer duration codecs draw between
16524 // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
16525 let payload = r#"{"rateLimit":"abc/s"}"#;
16526 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16527 let msg = err.to_string();
16528 assert!(
16529 msg.contains("not a u32"),
16530 "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
16531 );
16532 assert!(
16533 !msg.contains("not a non-negative integer"),
16534 "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
16535 );
16536 }
16537
16538 #[test]
16539 fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
16540 // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
16541 // u32's range. The digit-only gate passes; `u32::from_str`
16542 // fails on overflow. Surface that with the overflow-shaped
16543 // diagnostic naming the offending magnitude verbatim, peer
16544 // with `supervisor::duration_codec`'s overflow arm. Pinning
16545 // the wording so a future refactor doesn't silently collapse
16546 // overflow onto the canonical-form arm.
16547 let payload = r#"{"rateLimit":"4294967296/s"}"#;
16548 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16549 let msg = err.to_string();
16550 assert!(
16551 msg.contains("overflows u32"),
16552 "expected overflow diagnostic in {msg:?}"
16553 );
16554 assert!(
16555 msg.contains("\"4294967296\""),
16556 "missing offending magnitude in {msg:?}"
16557 );
16558 }
16559
16560 #[test]
16561 fn rate_limit_serde_rejects_leading_zero_magnitude() {
16562 // `"0100/s"` is digit-only, so the existing
16563 // non-digit-only / sign / fractional arm doesn't catch it —
16564 // `u32::from_str("0100")` returns `Ok(100)`, so before this
16565 // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
16566 // round-tripped through `render` to `"100/s"` — a *different*
16567 // canonical string on the next emit, breaking the THEORY.md
16568 // Part V render-determinism contract exactly the way the
16569 // peer `"+100/s"` case did before the leading-`+` arm landed.
16570 // This is the load-bearing class the leading-zero gate closes
16571 // beyond what the existing digit-only / sign / fractional
16572 // gates cover, and the peer arm to the leading-`+` test
16573 // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
16574 // canonical-form-drift axis.
16575 let payload = r#"{"rateLimit":"0100/s"}"#;
16576 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16577 let msg = err.to_string();
16578 assert!(
16579 msg.contains("non-canonical leading zero"),
16580 "expected leading-zero diagnostic in {msg:?}"
16581 );
16582 assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
16583 assert!(
16584 msg.contains("THEORY.md"),
16585 "missing render-determinism contract citation in {msg:?}"
16586 );
16587 }
16588
16589 #[test]
16590 fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
16591 // `"00/s"` is the degenerate leading-zero case — every byte
16592 // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
16593 // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
16594 // a *different* canonical string, same render-determinism
16595 // violation. The single-byte `"0/s"` itself is in the
16596 // accepted set (round-trips losslessly through `render`,
16597 // refused downstream by `PolicyRateLimitZero`); the
16598 // multi-byte `"00/s"` is not. Pins the boundary between the
16599 // accepted single-`0` and the rejected leading-zero class.
16600 let payload = r#"{"rateLimit":"00/s"}"#;
16601 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16602 let msg = err.to_string();
16603 assert!(
16604 msg.contains("non-canonical leading zero"),
16605 "expected leading-zero diagnostic in {msg:?}"
16606 );
16607 assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
16608 }
16609
16610 #[test]
16611 fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
16612 // Cross-window pin — the gate is window-agnostic; the
16613 // leading-zero class is a property of the magnitude, not the
16614 // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
16615 // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
16616 // single-window coverage extended across the three canonical
16617 // windows the codec accepts.
16618 let payload = r#"{"rateLimit":"007/h"}"#;
16619 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16620 let msg = err.to_string();
16621 assert!(
16622 msg.contains("non-canonical leading zero"),
16623 "expected leading-zero diagnostic in {msg:?}"
16624 );
16625 assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
16626 }
16627
16628 #[test]
16629 fn rate_limit_serde_rejects_leading_whitespace() {
16630 // `" 100/s"` — the canonical paste-from-aligned-doc /
16631 // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
16632 // the top-level `s.trim()` silently ate the leading space and
16633 // parsed the value to `RateLimit { 100, 1s }`, which then
16634 // round-tripped through `render` to `"100/s"` (a *different*
16635 // canonical string on the next emit) — the exact
16636 // canonical-form-drift class the leading-`+` / leading-zero
16637 // arms already close, extended to the whitespace byte class.
16638 let payload = r#"{"rateLimit":" 100/s"}"#;
16639 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16640 let msg = err.to_string();
16641 assert!(
16642 msg.contains("contains whitespace byte"),
16643 "expected whitespace diagnostic in {msg:?}"
16644 );
16645 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
16646 assert!(
16647 msg.contains("THEORY.md"),
16648 "missing render-determinism contract citation in {msg:?}"
16649 );
16650 }
16651
16652 #[test]
16653 fn rate_limit_serde_rejects_trailing_whitespace() {
16654 // `"100/s "` — the canonical shell-history / trailing-space
16655 // paste footgun. Before this gate the top-level `s.trim()`
16656 // silently ate the trailing space and parsed to
16657 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
16658 // next emit — same canonical-form drift as the leading-space
16659 // sibling, closed on the same whitespace-byte arm.
16660 let payload = r#"{"rateLimit":"100/s "}"#;
16661 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16662 let msg = err.to_string();
16663 assert!(
16664 msg.contains("contains whitespace byte"),
16665 "expected whitespace diagnostic in {msg:?}"
16666 );
16667 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
16668 }
16669
16670 #[test]
16671 fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
16672 // `"100 / s"` — the canonical typographically-spaced author
16673 // shape (the same idiom every prose reference to a rate limit
16674 // renders as, mistakenly retained when the value is pasted
16675 // into a codec-shaped slot). Before this gate the per-part
16676 // `rate_str.trim()` / `unit.trim()` calls silently ate both
16677 // spaces on either side of `/` and parsed to
16678 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
16679 // codec's *internal* whitespace-tolerance vector, orthogonal
16680 // to the leading / trailing surface but the same canonical-
16681 // form-drift class. Pins the arm as strictly stronger than the
16682 // pre-existing top-level `s.trim()` behavior: it fires on
16683 // whitespace anywhere in the value, not just at the string
16684 // boundary.
16685 let payload = r#"{"rateLimit":"100 / s"}"#;
16686 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16687 let msg = err.to_string();
16688 assert!(
16689 msg.contains("contains whitespace byte"),
16690 "expected whitespace diagnostic in {msg:?}"
16691 );
16692 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
16693 }
16694
16695 #[test]
16696 fn rate_limit_serde_rejects_tab_byte() {
16697 // `"\t100/s"` — the canonical paste-from-indented-doc /
16698 // paste-from-YAML-block-scalar footgun where a tab byte leads
16699 // the magnitude. Pins that the gate covers tab (`0x09`) as
16700 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
16701 // members and both would be silently swallowed by `s.trim()`
16702 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
16703 // space alone to the full ASCII-whitespace set (space `0x20`,
16704 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
16705 // the tab arm as a representative of the non-space members.
16706 let payload = r#"{"rateLimit":"\t100/s"}"#;
16707 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16708 let msg = err.to_string();
16709 assert!(
16710 msg.contains("contains whitespace byte"),
16711 "expected whitespace diagnostic in {msg:?}"
16712 );
16713 assert!(
16714 msg.contains("0x09"),
16715 "missing offending tab byte in {msg:?}"
16716 );
16717 }
16718
16719 // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
16720 //
16721 // Successor to the ASCII-whitespace arm (1ad7755) on
16722 // `rate_limit_codec` — closes the strictly-complementary class the
16723 // byte-scan cannot see, through the lifted
16724 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
16725
16726 #[test]
16727 fn rate_limit_serde_rejects_leading_nbsp() {
16728 // NBSP prefix — paste-from-typography footgun. Byte-scan
16729 // misses, `str::trim` silently strips it, value drifts to
16730 // `"100/s"` on next serialize.
16731 let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
16732 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16733 let msg = err.to_string();
16734 assert!(
16735 msg.contains("non-ASCII Unicode whitespace character"),
16736 "expected non-ASCII whitespace diagnostic in {msg:?}"
16737 );
16738 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
16739 }
16740
16741 #[test]
16742 fn rate_limit_serde_rejects_internal_em_space() {
16743 // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
16744 // paste-from-typography footgun on the `<integer>/<unit>`
16745 // shape.
16746 let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
16747 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
16748 let msg = err.to_string();
16749 assert!(
16750 msg.contains("non-ASCII Unicode whitespace character"),
16751 "expected non-ASCII whitespace diagnostic in {msg:?}"
16752 );
16753 assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
16754 }
16755
16756 #[test]
16757 fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
16758 // Positive-control pin: every ASCII-only canonical form the
16759 // renderer emits stays accepted through the new arm.
16760 for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
16761 let payload = format!(r#"{{"rateLimit":{lit}}}"#);
16762 let p: MeshPolicy = serde_json::from_str(&payload)
16763 .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
16764 assert!(p.rate_limit.is_some());
16765 }
16766 }
16767
16768 #[test]
16769 fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
16770 // The boundary case — `"0/s"` is the canonical form
16771 // `render(RateLimit { 0, 1s })` emits, so the codec accepts
16772 // it at the parse layer; the downstream
16773 // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
16774 // `rate == 0` at the typed-validate layer above. Pins the
16775 // partition: the leading-zero gate at the codec layer does
16776 // not poach the rate-zero semantic-validation arm at the
16777 // typed-validate layer above (a future stricter codec must
16778 // not reject `"0/s"` here, or it'd collapse the diagnostic
16779 // partitioning that lets `PolicyRateLimitZero` name the
16780 // offending typed slot).
16781 let payload = r#"{"rateLimit":"0/s"}"#;
16782 let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
16783 panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
16784 });
16785 let rl = policy.rate_limit.expect("rate_limit must be Some");
16786 assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
16787 assert_eq!(
16788 rl.window,
16789 Duration::from_secs(1),
16790 "single-`0` magnitude with `s` unit must parse to window=1s"
16791 );
16792 }
16793
16794 #[test]
16795 fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
16796 // The complementary boundary pin — every magnitude
16797 // `render` emits starts with `[1-9]` (or is the single byte
16798 // `"0"`), so the canonical-form predicate is `(len == 1) ||
16799 // (first byte != '0')`. Pinning the `len > 1 && first byte ==
16800 // '1'` case explicitly so a future tightening of the gate
16801 // (e.g. an over-eager "no leading digit < 5" rule, or a
16802 // mistakenly anchored start-of-magnitude byte check) lands
16803 // here before the canonical-forms-iterating test would catch
16804 // it.
16805 let payload = r#"{"rateLimit":"100/s"}"#;
16806 let policy: MeshPolicy = serde_json::from_str(payload)
16807 .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
16808 let rl = policy.rate_limit.expect("rate_limit must be Some");
16809 assert_eq!(
16810 rl.rate, 100,
16811 "canonical-100 magnitude must parse to rate=100"
16812 );
16813 }
16814
16815 #[test]
16816 fn rate_limit_serde_accepts_integer_canonical_forms() {
16817 // Pin the happy-path: every canonical author shape `render`
16818 // ever emits parses cleanly through the codec post-gate. The
16819 // codec's accepted set (post-gate) is exactly its emitted set
16820 // for the integer-magnitude class — same property
16821 // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
16822 // gates guarantee on the peer codecs. Iterating across rate
16823 // magnitudes (including `"0"`, which the codec accepts even
16824 // though `validate_politicas` rejects `rate == 0` at the typed
16825 // layer above) closes the codec contract at the parse layer
16826 // independently of the validate layer.
16827 for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
16828 for unit_lit in ["s", "m", "h"] {
16829 let lit = format!("{rate_lit}/{unit_lit}");
16830 let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
16831 let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
16832 panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
16833 });
16834 let rl = policy.rate_limit.expect("rate_limit must be Some");
16835 assert_eq!(
16836 rl.rate,
16837 rate_lit.parse::<u32>().unwrap(),
16838 "rate mismatch for {lit:?}"
16839 );
16840 }
16841 }
16842 }
16843
16844 #[test]
16845 fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
16846 // The structural property the gate enforces: serialize ∘
16847 // deserialize is the identity on every canonical author shape.
16848 // Peer of `parse_byte_size`'s and `parse_duration`'s
16849 // `_round_trips_through_render_for_every_canonical_form` tests
16850 // on the rate-limit axis. Before the gate, `"+100/s"` violated
16851 // this (`parse` → `RateLimit { 100, 1s }` → `render` →
16852 // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
16853 for rate in [1u32, 100, 5000, 1_000_000] {
16854 for (window, unit) in [
16855 (Duration::from_secs(1), "s"),
16856 (Duration::from_secs(60), "m"),
16857 (Duration::from_secs(3600), "h"),
16858 ] {
16859 let policy = MeshPolicy {
16860 rate_limit: Some(RateLimit { rate, window }),
16861 ..Default::default()
16862 };
16863 let json = serde_json::to_string(&policy).unwrap();
16864 let expected = format!("\"{rate}/{unit}\"");
16865 assert!(
16866 json.contains(&expected),
16867 "expected {expected:?} in {json:?}"
16868 );
16869 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16870 assert_eq!(
16871 back.rate_limit, policy.rate_limit,
16872 "round-trip for {json:?}"
16873 );
16874 }
16875 }
16876 }
16877
16878 // ── self-membership cross-slot gate ──────────────────────────────
16879
16880 #[test]
16881 fn validate_no_self_membership_rejects_self_named_membro() {
16882 // An Aplicacao whose `:membros` lists its own `:nome` is a
16883 // one-node lacre-closure recursion — rejected, naming the parent.
16884 let membros = vec![
16885 membro("catalog", "^0.1"),
16886 membro("checkout", "^0.1"),
16887 membro("cart", "^0.1"),
16888 ];
16889 let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
16890 assert!(
16891 matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
16892 "got {err:?}"
16893 );
16894 }
16895
16896 #[test]
16897 fn validate_no_self_membership_accepts_distinct_membros() {
16898 // Positive control: distinct member names (including a member
16899 // that is itself an Aplicacao — recursive composition is valid,
16900 // MESH-COMPOSITION §V) pass the gate.
16901 let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
16902 validate_no_self_membership(&membros, "checkout").unwrap();
16903 }
16904
16905 #[test]
16906 fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
16907 // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
16908 // `NoMembros` arm (the more-fundamental "graph must have nodes"
16909 // gate), not by this cross-slot self-edge gate. Keeping the
16910 // self-membership predicate vacuously-ok on the empty input
16911 // matches its supervisor-axis peer
16912 // (`validate_no_self_supervision_empty_children_is_ok`) and
16913 // makes the gate composable from any future call site (an M4
16914 // CR materializer's per-membros validator) without re-checking
16915 // emptiness.
16916 validate_no_self_membership(&[], "checkout").unwrap();
16917 }
16918
16919 #[test]
16920 fn validate_no_self_membership_diagnostic_names_offending_caixa() {
16921 // Pinning the Display: the self-membership diagnostic must name
16922 // the offending caixa verbatim + the "lists itself" framing the
16923 // author can grep for, so the cluster-far failure surfaces at
16924 // build time with one-line remediation. Same diagnostic shape
16925 // as the supervisor-axis `ChildSupervisesSelf` peer.
16926 let membros = vec![membro("orquestra", "^0.1")];
16927 let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
16928 let msg = err.to_string();
16929 assert!(
16930 msg.contains("orquestra"),
16931 "diagnostic must name the offending caixa nome (got: {msg:?})"
16932 );
16933 assert!(
16934 msg.contains("lists itself"),
16935 "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
16936 );
16937 }
16938
16939 #[test]
16940 fn default_servico_port_constant_pins_canonical_8080_literal() {
16941 // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
16942 // at the verbatim `8080` literal both consumers (the
16943 // `Entrada::port` serde default via [`default_port`] and the
16944 // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
16945 // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
16946 // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
16947 // discipline (a085b26) on the per-renderer canonical-K8s-axis
16948 // string-constant axis: a future refactor that drifts the
16949 // constant out from under either consumer surfaces here ahead
16950 // of every per-renderer's first emission. The literal value
16951 // matches the well-known HTTP-alt port the `pleme-computeunit`
16952 // library chart already emits as its `trigger.service.port`
16953 // default — by construction the same value the substrate
16954 // assumes about every Servico's in-cluster L4 listener.
16955 assert_eq!(
16956 DEFAULT_SERVICO_PORT, 8080,
16957 "canonical Servico port literal must remain `8080` verbatim — \
16958 this is the value both the `Entrada::port` serde default and the \
16959 caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
16960 );
16961 }
16962
16963 #[test]
16964 fn default_port_helper_returns_canonical_servico_port_constant() {
16965 // The bridge-arm — pins that the [`default_port`] helper
16966 // [`Entrada::port`]'s `#[serde(default = "default_port")]`
16967 // attribute hooks routes through the lifted
16968 // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
16969 // literal. A future refactor that re-introduces the `8080`
16970 // literal at the helper's return site (silently re-opening
16971 // the drift footgun this lift closed) surfaces here ahead of
16972 // every author-side `(:entrada (:host … :para …))` slot
16973 // without an explicit `:port`. Peer with the
16974 // `default_namespace_re_export_points_at_caixa_core_canonical`
16975 // pin on the caixa-mesh-side re-export axis.
16976 assert_eq!(
16977 default_port(),
16978 DEFAULT_SERVICO_PORT,
16979 "the serde-default helper must route through the lifted constant"
16980 );
16981 }
16982
16983 #[test]
16984 fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
16985 // The end-to-end pin — an author-surface `(:entrada (:host …
16986 // :para …))` without an explicit `:port` slot deserializes to
16987 // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
16988 // verbatim. Routes the canonical lifted constant through both
16989 // the serde-default machinery (the `#[serde(default =
16990 // "default_port")]` attribute) and the typed-value-shape
16991 // contract (the resulting [`Entrada::port`] value). A future
16992 // refactor that drifts either axis — replacing the serde
16993 // hook's helper, changing the typed slot's wire shape — would
16994 // surface here before any per-renderer's CNP / Gateway /
16995 // HTTPRoute emission consumed the drifted default.
16996 let entrada: Entrada =
16997 serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
16998 assert_eq!(
16999 entrada.port, DEFAULT_SERVICO_PORT,
17000 "the serde default must materialize as the lifted canonical Servico port"
17001 );
17002 }
17003
17004 #[test]
17005 fn servico_port_min_pins_canonical_accept_set_floor() {
17006 // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
17007 // verbatim `1` literal every typed `:entrada :port` acceptance
17008 // gate keys off. Peer with the
17009 // [`default_servico_port_constant_pins_canonical_8080_literal`]
17010 // discipline on the canonical-Servico-port-constant axis: a
17011 // future refactor that drifts the accept-set floor out from
17012 // under the sole consumer at [`AplicacaoSpec::validate`]'s
17013 // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
17014 // every per-`:entrada` `EntradaPortZero` diagnostic. The
17015 // literal value matches the IANA-registered TCP/UDP port
17016 // space floor (`1..=65535` — port `0` is the "any ephemeral"
17017 // sentinel, not a well-defined destination the substrate's
17018 // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
17019 // axis can honor).
17020 assert_eq!(
17021 SERVICO_PORT_MIN, 1,
17022 "canonical Servico port accept-set floor must remain `1` verbatim — \
17023 this is the value the `AplicacaoSpec::validate` gate at \
17024 `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
17025 );
17026 }
17027
17028 #[test]
17029 fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
17030 // The cross-const invariant pin — the substrate's canonical
17031 // default port must satisfy its own accept-set floor by
17032 // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
17033 // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
17034 // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
17035 // override the operator pins through a future
17036 // `:placement :default-port` slot that lands out-of-range, a
17037 // per-edition Servico-port migration that lifted the floor
17038 // above the previous default without coordinating the pair —
17039 // would silently invalidate the serde-default emission at
17040 // every author-side `(:entrada (:host … :para …))` slot
17041 // without an explicit `:port`: the default port would fall
17042 // below the accept-set floor, the `AplicacaoSpec::validate`
17043 // gate would reject every default-carrying Aplicacao as
17044 // `EntradaPortZero`, and the substrate's typed
17045 // `(defcaixa … :kind Aplicacao)` surface would fail validate
17046 // on every Aplicacao whose author omitted `:entrada :port`
17047 // for the substrate's chosen default — a class of authoring-
17048 // surface footguns the compile-time pin structurally closes.
17049 // Peer with the
17050 // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
17051 // (27f9b34) cross-const invariant pin discipline on the peer
17052 // canonical-Helm-per-values-block child-chart-enablement-toggle
17053 // axis pair.
17054 assert!(
17055 SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
17056 "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
17057 satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
17058 every default-carrying `(:entrada (:host … :para …))` slot without an \
17059 explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
17060 hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
17061 );
17062 }
17063
17064 #[test]
17065 fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
17066 // The gate-site pin — asserts the `AplicacaoSpec::validate`
17067 // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
17068 // `EntradaPortZero` diagnostic on the below-floor input
17069 // `port: 0` (the only below-floor value the `u16` field can
17070 // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
17071 // is the singleton `{0}`). A future refactor that drifts the
17072 // gate off the lifted const (silently re-introducing an
17073 // inline `if e.port == 0` byte-check) surfaces here — the
17074 // pin cannot distinguish `< 1` from `== 0` on the current
17075 // floor, but it *does* pin that the diagnostic fires on `0`
17076 // through whichever gate is wired, so any future accept-set
17077 // floor migration (a hypothetical unprivileged-only
17078 // migration lifting `SERVICO_PORT_MIN` to `1024`) must
17079 // update this test alongside the const declaration —
17080 // structurally guaranteeing the gate + accept-set + pin
17081 // trio move together. Peer with the
17082 // [`rejects_zero_entrada_port`] behavioral pin on the same
17083 // per-`:entrada :port` axis — that pin asserts the pre-lift
17084 // behavioral contract (`port: 0` → `EntradaPortZero`); this
17085 // pin adds the structural link to the lifted floor const.
17086 assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
17087 let mut s = three_member_spec();
17088 s.entrada.as_mut().unwrap().port = 0;
17089 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
17090 }
17091
17092 // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
17093
17094 #[test]
17095 fn membro_serde_keys_match_lifted_membro_key_consts() {
17096 // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
17097 // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
17098 // name the exact camelCase JSON keys the
17099 // `#[serde(rename_all = "camelCase")]` attribute on
17100 // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
17101 // that each canonical byte-sequence appears verbatim in the
17102 // JSON — a future accidental `rename_all = "snake_case"` /
17103 // `"kebab-case"` / verbatim-field-name flip at the derive
17104 // attribute (any of which would silently break every downstream
17105 // JSON consumer that reaches for one of the two consts via
17106 // `Value::get(...)`) surfaces here as a build-time test failure
17107 // at `aplicacao.rs`, not as an apply-time
17108 // `.get(<stale-canonical-const>)` returning `None` far from the
17109 // derive-attr drift's commit. Peer with the sibling
17110 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
17111 // (40cc4e5) pin on the M2 supervision-tree top-level axis —
17112 // same discipline the SupervisorSpec top-level lift established,
17113 // extended here to the M3 [`Membro`] per-`:membros` axis.
17114 let m = Membro {
17115 caixa: "catalog".into(),
17116 versao: "^0.1".into(),
17117 };
17118 let json = serde_json::to_string(&m).unwrap();
17119 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
17120 let quoted = format!("\"{key}\"");
17121 assert!(
17122 json.contains("ed),
17123 "serialized Membro must carry the lifted MEMBRO_KEY_* \
17124 byte-sequence {quoted} verbatim in the JSON emission \
17125 (got: {json})",
17126 );
17127 }
17128 }
17129
17130 #[test]
17131 fn membro_key_consts_are_pairwise_distinct() {
17132 // Cross-axis drift-detection pin: a future collapse of the two
17133 // canonical [`Membro`] per-entry byte-strings onto the same
17134 // value (e.g. an accidental copy-paste flip of
17135 // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
17136 // silently reroute every downstream probe on one axis onto the
17137 // sibling axis's overlay entry and pass every propagation-probe
17138 // test that expected only the stale axis's value. Peer of the
17139 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
17140 // (40cc4e5).
17141 let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
17142 for (i, a) in all.iter().enumerate() {
17143 for b in all.iter().skip(i + 1) {
17144 assert_ne!(
17145 a, b,
17146 "MEMBRO_KEY_* consts must be pairwise-distinct \
17147 canonical byte-sequences — got `{a}` == `{b}`",
17148 );
17149 }
17150 }
17151 }
17152
17153 // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
17154 // URL-path fallback resolver every HTTPRoute-aware renderer
17155 // reaching for a per-rule path-list resolution routes through.
17156 // The four pin tests below fix the four-way accept-set the
17157 // resolver must always honor: (:paths-non-empty-verbatim,
17158 // :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
17159 // :paths-preserves-order-across-multiple-entries) — drift on any
17160 // arm surfaces at caixa-core build time rather than at cluster-
17161 // apply time. Peer discipline with `MeshPolicy::is_empty` on the
17162 // sibling `:politicas` typed-primitive dispatch axis.
17163
17164 fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
17165 Entrada {
17166 host: "example.com".into(),
17167 para: "cart".into(),
17168 paths: paths.into_iter().map(String::from).collect(),
17169 port: DEFAULT_SERVICO_PORT,
17170 }
17171 }
17172
17173 #[test]
17174 fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
17175 // The typed `:entrada :paths` slot carries an author-declared
17176 // list — the resolver returns each entry verbatim, no
17177 // catch-all substitution. The canonical "author declared
17178 // paths, honor them verbatim" arm of the path-list dispatch.
17179 let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
17180 assert_eq!(
17181 e.resolved_paths(),
17182 vec!["/api/cart", "/api/products"],
17183 "resolved_paths must return each `:entrada :paths` entry \
17184 verbatim when the typed slot is non-empty (got {:?})",
17185 e.resolved_paths(),
17186 );
17187 }
17188
17189 #[test]
17190 fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
17191 // Empty `:entrada :paths` slot — the resolver substitutes the
17192 // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
17193 // catch-all fallback verbatim. Pins the empty-arm of the
17194 // resolver's four-way accept-set against a future silent
17195 // detour that returned an empty Vec (which would emit an
17196 // HTTPRoute with zero rules — silently dropping every
17197 // external `:entrada` flow at admission time), routed to a
17198 // different fallback shape, or dropped the catch-all
17199 // altogether.
17200 let e = entrada_with_paths(vec![]);
17201 assert_eq!(
17202 e.resolved_paths(),
17203 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
17204 "resolved_paths on empty `:entrada :paths` must fall back \
17205 to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
17206 all — got {:?}",
17207 e.resolved_paths(),
17208 );
17209 }
17210
17211 #[test]
17212 fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
17213 // Single-entry `:entrada :paths` — the resolver returns the
17214 // single declared path verbatim, NOT the catch-all fallback
17215 // (author declared a path, honor it — the empty-arm and the
17216 // len-1 arm are semantically distinct axes of the resolver's
17217 // accept-set). Pins that the resolver treats "author declared
17218 // one path" as authored input, not as the empty case.
17219 let e = entrada_with_paths(vec!["/api/only"]);
17220 assert_eq!(
17221 e.resolved_paths(),
17222 vec!["/api/only"],
17223 "resolved_paths on single-entry `:entrada :paths` must \
17224 return the declared path verbatim, NOT the catch-all \
17225 fallback (got {:?})",
17226 e.resolved_paths(),
17227 );
17228 }
17229
17230 #[test]
17231 fn resolved_paths_preserves_author_declared_order() {
17232 // The `:entrada :paths` list is author-ordered — the resolver
17233 // preserves the author's declaration order verbatim, since
17234 // per-rule dispatch order at the K8s Gateway API HTTPRoute
17235 // consumer is significant (first-match-wins under the
17236 // path-prefix matcher). Pins against a future silent
17237 // re-sort / dedup / normalize detour that reordered author
17238 // input.
17239 let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
17240 assert_eq!(
17241 e.resolved_paths(),
17242 vec!["/z/last", "/a/first", "/m/mid"],
17243 "resolved_paths must preserve author-declared `:entrada \
17244 :paths` order verbatim — got {:?}",
17245 e.resolved_paths(),
17246 );
17247 }
17248
17249 // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
17250 // slot `&[String]` slice accessor every per-`:entrada` consumer
17251 // that must see the author's declaration verbatim (not the
17252 // fallback-applied projection the sibling `resolved_paths`
17253 // returns) routes through. The three pin tests below fix the
17254 // accept-set the accessor must honor: (:non-empty-byte-equal,
17255 // :empty-projects-empty-slice, :preserves-author-declared-order)
17256 // — drift on any arm surfaces at caixa-core build time rather
17257 // than at cluster-apply time. Peer discipline with the sibling
17258 // [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
17259 // peer M3 mesh-slot `Vec<String>`-carry axis.
17260
17261 #[test]
17262 fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
17263 // Byte-equal pin: [`Entrada::paths`] must project the raw
17264 // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
17265 // slice borrowed from the typed slot's own [`Vec<String>`]
17266 // storage — no re-ordering, no dedup, no per-entry normalization,
17267 // no fallback substitution (the fallback-applying projection is
17268 // the sibling [`Entrada::resolved_paths`] resolver). Pins against
17269 // a future silent detour that re-normalized the list, dropped
17270 // duplicates the [`AplicacaoSpec::validate`]
17271 // `EntradaPathDuplicate` refusal already rejects at build time,
17272 // or (most severe) accidentally routed through the fallback-
17273 // applying sibling and returned the substrate catch-all when
17274 // the author declared an empty list — collapsing the raw-slot
17275 // and fallback-applied axes into one and breaking the
17276 // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
17277 //
17278 // Peer of the sibling
17279 // [`Placement::clusters`]-shape byte-equal pin
17280 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
17281 // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
17282 let fixtures: Vec<Vec<String>> = vec![
17283 Vec::new(),
17284 vec!["/api/cart".into()],
17285 vec!["/api/cart".into(), "/api/products".into()],
17286 vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
17287 ];
17288 for paths in fixtures {
17289 let e = Entrada {
17290 host: "example.com".into(),
17291 para: "cart".into(),
17292 paths: paths.clone(),
17293 port: DEFAULT_SERVICO_PORT,
17294 };
17295 assert_eq!(
17296 e.paths(),
17297 paths.as_slice(),
17298 "Entrada::paths must return :entrada :paths verbatim \
17299 (got {:?}, expected {:?})",
17300 e.paths(),
17301 paths.as_slice(),
17302 );
17303 assert_eq!(
17304 e.paths(),
17305 e.paths.as_slice(),
17306 "Entrada::paths accessor and .paths.as_slice() field \
17307 access must byte-equal — the accessor is the substrate-\
17308 primitive typed dispatch every downstream per-`:entrada` \
17309 raw-slot path-list consumer must route through",
17310 );
17311 assert_eq!(
17312 e.paths().len(),
17313 e.paths.len(),
17314 "Entrada::paths().len() must byte-equal self.paths.len() \
17315 — a length drift would silently split the paired \
17316 pre-flight cascade-head `.is_empty()` probe input in \
17317 the sibling [`Entrada::resolved_paths`] resolver from \
17318 the per-entry validate loop's traversal input in \
17319 [`AplicacaoSpec::validate`]",
17320 );
17321 }
17322 }
17323
17324 #[test]
17325 fn resolved_paths_reads_through_lifted_paths_accessor() {
17326 // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
17327 // pre-flight `.paths().is_empty()` cascade-head probe (which
17328 // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
17329 // catch-all fallback arm when the accessor projects the empty
17330 // slice) and the per-entry `.paths().iter().map(String::as_str)`
17331 // projection (which must reach every entry in the same order
17332 // the accessor projects, so the sibling
17333 // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
17334 // per-entry projection stay in lockstep by construction) must
17335 // both key off the lifted accessor. Pins the two-site coherence
17336 // by exercising each production consumer end-to-end: (1) the
17337 // catch-all-fallback arm under the empty slice, (2) the
17338 // author-declared-verbatim arm under a two-entry cohort whose
17339 // per-entry projection must byte-equal the input's per-entry
17340 // author-declared paths in the author's declared order.
17341 //
17342 // Peer of the sibling M3
17343 // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
17344 // `validate_placement_reads_through_lifted_clusters_accessor`
17345 // on the sibling `Placement::clusters` reader-site convergence.
17346 let empty = entrada_with_paths(vec![]);
17347 assert_eq!(
17348 empty.resolved_paths(),
17349 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
17350 "resolved_paths on empty :entrada :paths must trip the \
17351 lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
17352 catch-all fallback — routing through the lifted paths() \
17353 accessor must not silently drop the fallback arm",
17354 );
17355
17356 let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
17357 assert_eq!(
17358 declared.resolved_paths(),
17359 vec!["/api/cart", "/api/products"],
17360 "resolved_paths on non-empty :entrada :paths must return each \
17361 entry verbatim in the author's declared order — routing \
17362 through the lifted paths() accessor must not silently \
17363 reorder or drop entries",
17364 );
17365 // Byte-equal pin against the raw-slot accessor to keep the
17366 // fallback-applying resolver's per-entry projection input in
17367 // lockstep with the raw-slot accessor's projection.
17368 let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
17369 assert_eq!(
17370 declared.resolved_paths(),
17371 raw_projected,
17372 "resolved_paths non-empty projection must byte-equal the \
17373 lifted paths() accessor's per-entry String::as_str projection \
17374 — the two projections share the same input slice by \
17375 construction, so any drift here would surface a silent \
17376 re-ordering / dedup / normalization detour in the resolver",
17377 );
17378 }
17379
17380 #[test]
17381 fn validate_reads_through_lifted_entrada_paths_accessor() {
17382 // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
17383 // per-entry value-shape gate's `for p in e.paths()` traversal
17384 // (which must reach every entry in the same order the accessor
17385 // projects, so both the per-entry `EntradaPathEmpty` /
17386 // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
17387 // the duplicate-detection HashSet insert that trips
17388 // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
17389 // projection) must route through the lifted accessor. Pins the
17390 // coherence by exercising each production consumer end-to-end:
17391 // (1) the `EntradaPathEmpty` refusal fires on the second entry
17392 // of a two-entry cohort whose head is valid but tail is empty
17393 // (which requires the loop to reach the second entry through
17394 // the accessor), and (2) the `EntradaPathDuplicate` refusal
17395 // fires on the second entry of a two-entry cohort that shares
17396 // a path (which requires the loop to reach both entries — a
17397 // first-entry-only projection would silently pass since the
17398 // dedup HashSet has room for the first insert).
17399 //
17400 // Peer of the sibling
17401 // `validate_placement_reads_through_lifted_clusters_accessor`
17402 // on the sibling `Placement::clusters` reader-site convergence.
17403 let base = crate::AplicacaoSpec {
17404 membros: vec![crate::Membro {
17405 caixa: "cart".into(),
17406 versao: "^0.1".into(),
17407 }],
17408 contratos: Vec::new(),
17409 politicas: crate::MeshPolicy::default(),
17410 placement: crate::Placement {
17411 estrategia: crate::PlacementStrategy::SingleNode,
17412 clusters: vec!["rio".into()],
17413 shard_key: None,
17414 affinity: None,
17415 },
17416 entrada: Some(Entrada {
17417 host: "example.com".into(),
17418 para: "cart".into(),
17419 paths: vec!["/api/cart".into(), String::new()],
17420 port: DEFAULT_SERVICO_PORT,
17421 }),
17422 };
17423 assert_eq!(
17424 base.validate(),
17425 Err(crate::AplicacaoError::EntradaPathEmpty),
17426 "validate must trip EntradaPathEmpty on the second entry of \
17427 a two-entry cohort — routing through the lifted paths() \
17428 accessor must not silently short-circuit the loop at the \
17429 valid head entry",
17430 );
17431
17432 let mut dup = base;
17433 dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
17434 assert_eq!(
17435 dup.validate(),
17436 Err(crate::AplicacaoError::EntradaPathDuplicate {
17437 path: "/api/cart".into(),
17438 }),
17439 "validate must trip EntradaPathDuplicate on the second entry \
17440 of a two-entry cohort that shares a path — routing through \
17441 the lifted paths() accessor must not silently short-circuit \
17442 the dedup HashSet insert at the first entry",
17443 );
17444 }
17445
17446 // ── Entrada::hostname / Entrada::hostnames — the substrate-
17447 // canonical per-`:entrada` DNS-hostname resolver pair every
17448 // Gateway-API-aware renderer reaching for a per-listener
17449 // singular `hostname:` filter (Gateway) or a per-route plural
17450 // `spec.hostnames[]` filter list (HTTPRoute) routes through.
17451 // The three pin tests below fix the two-way accept-set the pair
17452 // must always honor: (:singular-byte-equal-to-host,
17453 // :plural-is-singleton-of-singular, :plural-len-is-one) — drift
17454 // on any arm surfaces at caixa-core build time rather than at
17455 // cluster-apply time when the API server refuses the HTTPRoute
17456 // for non-intersecting hostname filters. Peer discipline with
17457 // the sibling `resolved_paths` accept-set pin block above on the
17458 // per-`:entrada` path-list resolver axis.
17459
17460 fn entrada_with_host(host: &str) -> Entrada {
17461 Entrada {
17462 host: host.into(),
17463 para: "cart".into(),
17464 paths: Vec::new(),
17465 port: DEFAULT_SERVICO_PORT,
17466 }
17467 }
17468
17469 #[test]
17470 fn hostname_returns_entrada_host_byte_equal() {
17471 // The canonical singular-axis pin: [`Entrada::hostname`] must
17472 // return the `:entrada :host` field byte-for-byte, borrowed
17473 // from the typed slot's own [`String`] storage. Pins against a
17474 // future silent detour that re-normalized the host (an
17475 // accidental `.to_lowercase()` — validate_entrada_host already
17476 // enforces lowercase, so any re-normalization is redundant + a
17477 // drift surface between the validator and the accessor), a
17478 // trailing-`.` fully-qualified DNS shape substitution, or a
17479 // Punycode round-trip that lowered a Unicode host through IDNA.
17480 let e = entrada_with_host("checkout.quero.cloud");
17481 assert_eq!(
17482 e.hostname(),
17483 "checkout.quero.cloud",
17484 "Entrada::hostname must return :entrada :host verbatim \
17485 (got {:?})",
17486 e.hostname(),
17487 );
17488 assert_eq!(
17489 e.hostname(),
17490 e.host.as_str(),
17491 "Entrada::hostname must byte-equal the .host field access",
17492 );
17493 }
17494
17495 #[test]
17496 fn hostnames_returns_singleton_of_hostname_accessor() {
17497 // The pair-invariant pin: [`Entrada::hostnames`] must always
17498 // return exactly `vec![hostname()]` — the singleton list whose
17499 // sole entry is the substrate's canonical per-`:entrada`
17500 // singular hostname. Pins the two-consumer coherence axis: the
17501 // Gateway listener's singular `hostname:` filter and the
17502 // HTTPRoute's plural `spec.hostnames[]` filter list must
17503 // agree, else the Gateway API v1.x conformance layer rejects
17504 // the HTTPRoute at attach time with
17505 // `Accepted:False/NoMatchingParent` (the parent Gateway's
17506 // listener hostname doesn't intersect the route's hostname
17507 // filter list) — a divergence whose apply-time symptom is far
17508 // from any single-site commit and never surfaces in the
17509 // emitted YAML. Pinning the pair-invariant here makes any
17510 // future accidental split (an accidental `.to_string() + "."`
17511 // trailing-`.` on the plural side that didn't land on the
17512 // singular side, an accidental prefix stripping on one axis,
17513 // an accidental wildcard prepend the SNI fan-out overlay
17514 // authors on the plural side without a paired singular
17515 // migration) trip at caixa-core build time.
17516 let e = entrada_with_host("checkout.quero.cloud");
17517 assert_eq!(
17518 e.hostnames(),
17519 vec![e.hostname()],
17520 "Entrada::hostnames must return `vec![hostname()]` under \
17521 the pair-invariant — got {:?} vs. singleton {:?}",
17522 e.hostnames(),
17523 vec![e.hostname()],
17524 );
17525 }
17526
17527 #[test]
17528 fn hostnames_is_singleton_under_single_host_author_surface() {
17529 // The singleton-shape pin: under today's single-hostname-per-
17530 // `:entrada` author surface (the `:host` slot is a single
17531 // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
17532 // must always return a list of length exactly one. Pins
17533 // against a future silent detour that returned an empty list
17534 // (which would emit an HTTPRoute with `spec.hostnames: []` —
17535 // matching every incoming Host header regardless of the
17536 // Aplicacao's declared ingress apex, silently over-matching
17537 // every foreign VirtualHost the parent Gateway also fronts) or
17538 // a duplicated entry (which the Gateway API v1.x parser
17539 // accepts as a `[]-length-2 list of equal hostnames]` but
17540 // whose semantics differ from the intended singleton). The
17541 // author-surface extension point ("a future `:entrada
17542 // :alt-hosts` list overlay" the docstring names) is the sole
17543 // future axis that flips this pin — that migration will re-
17544 // author this test to pin the new plural cardinality.
17545 let e = entrada_with_host("checkout.quero.cloud");
17546 assert_eq!(
17547 e.hostnames().len(),
17548 1,
17549 "Entrada::hostnames must be a singleton under today's \
17550 single-hostname-per-`:entrada` author surface — got \
17551 length {}: {:?}",
17552 e.hostnames().len(),
17553 e.hostnames(),
17554 );
17555 }
17556
17557 // ── Entrada::destination — the substrate-canonical per-`:entrada`
17558 // destination-Servico scalar accessor every Gateway-API
17559 // HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
17560 // discriminator arg (HTTPRoute name composer) or a per-rule
17561 // `backendRefs[0].name` axis routes through. The two pin tests
17562 // below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
17563 // either arm surfaces at caixa-core build time rather than at
17564 // cluster-apply time when an HTTPRoute's `metadata.name` and
17565 // `backendRefs[]` silently disagree on which destination Servico
17566 // the ingress fronts. Peer discipline with the sibling
17567 // `resolved_paths` + `hostname` + `hostnames` accept-set pin
17568 // blocks above on the per-`:entrada` path-list / DNS-hostname
17569 // resolver axes.
17570
17571 #[test]
17572 fn destination_returns_entrada_para_byte_equal() {
17573 // The canonical destination-scalar pin: [`Entrada::destination`]
17574 // must return the `:entrada :para` field byte-for-byte, borrowed
17575 // from the typed slot's own [`String`] storage. Pins against a
17576 // future silent detour that re-normalized the destination (an
17577 // accidental `.to_lowercase()` — the destination Servico is
17578 // already validated as a DNS-1123 label upstream, so any
17579 // re-normalization is redundant + a drift surface between the
17580 // validator and the accessor), a namespace-prefix rewrite (an
17581 // accidental `format!("{namespace}/{para}")` per-CR fully-
17582 // qualified rewrite that didn't land on the peer axis), or a
17583 // per-cluster suffix stamp the operator authors on one
17584 // consumer without the other.
17585 for para in ["cart", "checkout", "catalog", "orders-v2"] {
17586 let e = Entrada {
17587 host: "checkout.quero.cloud".into(),
17588 para: para.into(),
17589 paths: Vec::new(),
17590 port: DEFAULT_SERVICO_PORT,
17591 };
17592 assert_eq!(
17593 e.destination(),
17594 para,
17595 "Entrada::destination must return :entrada :para verbatim \
17596 (got {:?}, expected {para:?})",
17597 e.destination(),
17598 );
17599 assert_eq!(
17600 e.destination(),
17601 e.para.as_str(),
17602 "Entrada::destination must byte-equal the .para field access",
17603 );
17604 }
17605 }
17606
17607 #[test]
17608 fn destination_borrows_from_entrada_para_storage() {
17609 // The borrow-not-copy pin: [`Entrada::destination`] must
17610 // return a `&str` slice that borrows from the typed slot's
17611 // own [`String`] storage — same-address invariant with
17612 // `entrada.para.as_str()`. Pins against a future silent detour
17613 // that allocated a fresh `String` (`self.para.clone()` in the
17614 // body would type-check but silently drop the borrow, and
17615 // every downstream consumer that assumed the returned slice
17616 // outlives `&self` would break on a stale-reference use-after-
17617 // free). Peer with the sibling `hostname_returns_entrada_
17618 // host_byte_equal` on the singular-DNS-hostname axis.
17619 let e = entrada_with_host("checkout.quero.cloud");
17620 let dest = e.destination();
17621 let para_slice = e.para.as_str();
17622 assert_eq!(
17623 dest.as_ptr(),
17624 para_slice.as_ptr(),
17625 "Entrada::destination must borrow from the .para String's \
17626 backing storage — a fresh allocation here means the \
17627 accessor no longer names the substrate-primitive typed \
17628 dispatch and every downstream consumer would silently \
17629 carry a detached copy",
17630 );
17631 assert_eq!(
17632 dest.len(),
17633 para_slice.len(),
17634 "Entrada::destination and .para.as_str() must byte-equal in \
17635 length as well as in address",
17636 );
17637 }
17638
17639 #[test]
17640 fn port_returns_entrada_port_verbatim_across_permutations() {
17641 // The canonical L4-port-scalar pin: [`Entrada::port`] must
17642 // return the `:entrada :port` field verbatim as a `u16` across
17643 // every author-declared value in the validated accept-set
17644 // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
17645 // silent detour that clamped the port (an accidental
17646 // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
17647 // land on the peer [`AplicacaoSpec::port_for_destination`]
17648 // resolver), rewrote it through a per-cluster port-remap table
17649 // the operator authors on one consumer without the other, or
17650 // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
17651 // serde-default value (which would silently collapse the
17652 // distinction between "author explicitly declared `:port 8080`"
17653 // and "author omitted the slot and inherited the default" the
17654 // future per-cluster override slot depends on). Peer with the
17655 // sibling `destination_returns_entrada_para_byte_equal` +
17656 // `hostname_returns_entrada_host_byte_equal` pins on the
17657 // per-`:entrada` `&str` scalar axes.
17658 for port in [
17659 SERVICO_PORT_MIN,
17660 DEFAULT_SERVICO_PORT,
17661 8443u16,
17662 9090u16,
17663 u16::MAX,
17664 ] {
17665 let e = Entrada {
17666 host: "checkout.quero.cloud".into(),
17667 para: "cart".into(),
17668 paths: Vec::new(),
17669 port,
17670 };
17671 assert_eq!(
17672 e.port(),
17673 port,
17674 "Entrada::port must return :entrada :port verbatim \
17675 (got {}, expected {port})",
17676 e.port(),
17677 );
17678 assert_eq!(
17679 e.port(),
17680 e.port,
17681 "Entrada::port accessor and .port field access must \
17682 byte-equal — the accessor is the substrate-primitive \
17683 typed dispatch every downstream L4-port consumer must \
17684 route through",
17685 );
17686 }
17687 }
17688
17689 #[test]
17690 fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
17691 // Two-consumer coherence pin: the
17692 // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
17693 // (which reads through [`Entrada::port`] to compare against
17694 // [`SERVICO_PORT_MIN`]) and the
17695 // [`AplicacaoSpec::port_for_destination`] resolver (which reads
17696 // through [`Entrada::port`] to emit the per-destination
17697 // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
17698 // lifted accessor, so any future rebrand on the typed slot's
17699 // reader shape lands at exactly one place. Pins the two-site
17700 // coherence by exercising a below-floor port through validate
17701 // (which must reject) and a validated in-accept-set port through
17702 // port_for_destination (which must emit the same value the
17703 // accessor returns).
17704 let mut spec = three_member_spec();
17705 if let Some(e) = spec.entrada.as_mut() {
17706 e.port = 0;
17707 }
17708 assert_eq!(
17709 spec.validate().unwrap_err(),
17710 AplicacaoError::EntradaPortZero,
17711 "validate must reject `:entrada :port 0` through the lifted \
17712 Entrada::port accessor — port zero lies below \
17713 SERVICO_PORT_MIN and the validator routes through port() \
17714 to name the floor",
17715 );
17716
17717 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
17718 let mut spec = three_member_spec();
17719 if let Some(e) = spec.entrada.as_mut() {
17720 e.port = port;
17721 }
17722 spec.validate().expect(
17723 "entrada with in-accept-set :port must validate — the \
17724 structural-floor gate reads through Entrada::port",
17725 );
17726 let entrada_ref = spec.entrada.as_ref().expect(":entrada present");
17727 assert_eq!(
17728 spec.port_for_destination(entrada_ref.destination()),
17729 entrada_ref.port(),
17730 "port_for_destination(entrada.destination()) must equal \
17731 entrada.port() — the two consumers of the per-:entrada \
17732 L4-port axis (validator, per-destination resolver) both \
17733 route through Entrada::port",
17734 );
17735 }
17736 }
17737
17738 #[test]
17739 fn wit_contract_source_returns_de_byte_equal_across_permutations() {
17740 // The canonical caller-Servico-scalar pin: [`WitContract::source`]
17741 // must return the `:contratos :de` field byte-for-byte, borrowed
17742 // from the typed slot's own [`String`] storage. Peer of the
17743 // sibling `destination_returns_entrada_para_byte_equal` pin on
17744 // the per-`:entrada` axis — same "the substrate-primitive
17745 // accessor must byte-equal the raw field access verbatim across
17746 // every author-declared value" discipline extended to the
17747 // per-`:contratos` caller arm. Pins against a future silent
17748 // detour that re-normalized the caller (an accidental
17749 // `.to_lowercase()` — every `:contratos :de` is validated as a
17750 // DNS-1123 label upstream via `validate_contrato_caixa`, so any
17751 // re-normalization is redundant + a drift surface between the
17752 // validator and the accessor), a namespace-prefix rewrite (an
17753 // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
17754 // rewrite that didn't land on the peer axis), or a per-cluster
17755 // suffix stamp the operator authors on one consumer without the
17756 // other.
17757 for de in ["cart", "checkout", "catalog", "orders-v2"] {
17758 let c = WitContract {
17759 de: de.into(),
17760 para: "downstream".into(),
17761 wit: "wasi:http/proxy".into(),
17762 endpoint: Some("/lookup".into()),
17763 subject: None,
17764 slot: None,
17765 };
17766 assert_eq!(
17767 c.source(),
17768 de,
17769 "WitContract::source must return :contratos :de verbatim \
17770 (got {:?}, expected {de:?})",
17771 c.source(),
17772 );
17773 assert_eq!(
17774 c.source(),
17775 c.de.as_str(),
17776 "WitContract::source must byte-equal the .de field access",
17777 );
17778 }
17779 }
17780
17781 #[test]
17782 fn wit_contract_source_borrows_from_de_storage() {
17783 // The borrow-not-copy pin: [`WitContract::source`] must return a
17784 // `&str` slice that borrows from the typed slot's own [`String`]
17785 // storage — same-address invariant with `c.de.as_str()`. Pins
17786 // against a future silent detour that allocated a fresh `String`
17787 // (`self.de.clone()` in the body would type-check but silently
17788 // drop the borrow, and every downstream consumer that assumed
17789 // the returned slice outlives `&self` would break on a stale-
17790 // reference use-after-free). Peer of the sibling
17791 // `destination_borrows_from_entrada_para_storage` on the
17792 // per-`:entrada` axis.
17793 let c = WitContract {
17794 de: "cart".into(),
17795 para: "catalog".into(),
17796 wit: "wasi:http/proxy".into(),
17797 endpoint: Some("/lookup".into()),
17798 subject: None,
17799 slot: None,
17800 };
17801 let src = c.source();
17802 let de_slice = c.de.as_str();
17803 assert_eq!(
17804 src.as_ptr(),
17805 de_slice.as_ptr(),
17806 "WitContract::source must borrow from the .de String's \
17807 backing storage — a fresh allocation here means the \
17808 accessor no longer names the substrate-primitive typed \
17809 dispatch and every downstream consumer would silently \
17810 carry a detached copy",
17811 );
17812 assert_eq!(
17813 src.len(),
17814 de_slice.len(),
17815 "WitContract::source and .de.as_str() must byte-equal in \
17816 length as well as in address",
17817 );
17818 }
17819
17820 #[test]
17821 fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
17822 // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
17823 // must return the `:contratos :para` field byte-for-byte,
17824 // borrowed from the typed slot's own [`String`] storage. Peer of
17825 // the sibling `destination_returns_entrada_para_byte_equal` on
17826 // the per-`:entrada` axis — both accessors name "the destination-
17827 // Servico byte-string" concept on their respective mesh-slot
17828 // atoms (per-ingress apex vs. per-typed-edge callee) and both
17829 // must project the underlying `.para` field verbatim so every
17830 // downstream renderer that composes them with peer accessors
17831 // (e.g. `spec.port_for_destination(c.destination())` at the CNP
17832 // per-edge L4 port emit site) reads the same byte-string the
17833 // author declared.
17834 for para in ["catalog", "payment", "orders", "inventory-v3"] {
17835 let c = WitContract {
17836 de: "cart".into(),
17837 para: para.into(),
17838 wit: "wasi:http/proxy".into(),
17839 endpoint: Some("/lookup".into()),
17840 subject: None,
17841 slot: None,
17842 };
17843 assert_eq!(
17844 c.destination(),
17845 para,
17846 "WitContract::destination must return :contratos :para \
17847 verbatim (got {:?}, expected {para:?})",
17848 c.destination(),
17849 );
17850 assert_eq!(
17851 c.destination(),
17852 c.para.as_str(),
17853 "WitContract::destination must byte-equal the .para \
17854 field access",
17855 );
17856 }
17857 }
17858
17859 #[test]
17860 fn wit_contract_destination_borrows_from_para_storage() {
17861 // The borrow-not-copy pin: [`WitContract::destination`] must
17862 // return a `&str` slice that borrows from the typed slot's own
17863 // [`String`] storage — same-address invariant with
17864 // `c.para.as_str()`. Peer of the sibling
17865 // `destination_borrows_from_entrada_para_storage` on the
17866 // per-`:entrada` axis.
17867 let c = WitContract {
17868 de: "cart".into(),
17869 para: "catalog".into(),
17870 wit: "wasi:http/proxy".into(),
17871 endpoint: Some("/lookup".into()),
17872 subject: None,
17873 slot: None,
17874 };
17875 let dest = c.destination();
17876 let para_slice = c.para.as_str();
17877 assert_eq!(
17878 dest.as_ptr(),
17879 para_slice.as_ptr(),
17880 "WitContract::destination must borrow from the .para \
17881 String's backing storage — a fresh allocation here means \
17882 the accessor no longer names the substrate-primitive typed \
17883 dispatch and every downstream consumer would silently \
17884 carry a detached copy",
17885 );
17886 assert_eq!(
17887 dest.len(),
17888 para_slice.len(),
17889 "WitContract::destination and .para.as_str() must byte-equal \
17890 in length as well as in address",
17891 );
17892 }
17893
17894 #[test]
17895 fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
17896 // The canonical per-`:contratos` WIT-world-reference scalar pin:
17897 // [`WitContract::world_ref`] must return the `:contratos :wit`
17898 // field byte-for-byte, borrowed from the typed slot's own
17899 // [`String`] storage. Sibling of the peer per-`:contratos`
17900 // [`WitContract::source`] / [`WitContract::destination`]
17901 // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
17902 // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
17903 // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
17904 // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
17905 // "the substrate-primitive accessor must byte-equal the raw
17906 // field access verbatim across every author-declared value"
17907 // discipline extended to the per-`:contratos` WIT-world arm.
17908 // Pins against a future silent detour that re-canonicalized the
17909 // WIT world reference (an accidental `.to_lowercase()` pass that
17910 // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
17911 // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
17912 // gate is already lowercase-prefixed so any re-normalization is
17913 // redundant + a drift surface between the validator and the
17914 // accessor), an M4-promotion-shape rewrite that formatted a
17915 // typed WIT-world enum through [`Display`] and silently drifted
17916 // the printer output from the source `caixa.lisp`, or a per-
17917 // cluster WIT-alias rewrite that didn't land on the peer field-
17918 // access sites. Five values sweep the shape-dispatch accept-set
17919 // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
17920 // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
17921 // `wasi:keyvalue/`).
17922 for (wit, endpoint, subject, slot) in [
17923 ("wasi:http/proxy", Some("/lookup"), None, None),
17924 ("http:proxy", Some("/health"), None, None),
17925 ("nats:pub-sub", None, Some("orders.paid"), None),
17926 ("kafka:events", None, Some("checkout-events"), None),
17927 ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
17928 ] {
17929 let c = WitContract {
17930 de: "cart".into(),
17931 para: "downstream".into(),
17932 wit: wit.into(),
17933 endpoint: endpoint.map(str::to_string),
17934 subject: subject.map(str::to_string),
17935 slot: slot.map(str::to_string),
17936 };
17937 assert_eq!(
17938 c.world_ref(),
17939 wit,
17940 "WitContract::world_ref must return :contratos :wit \
17941 verbatim (got {:?}, expected {wit:?})",
17942 c.world_ref(),
17943 );
17944 assert_eq!(
17945 c.world_ref(),
17946 c.wit.as_str(),
17947 "WitContract::world_ref must byte-equal the .wit field \
17948 access",
17949 );
17950 }
17951 }
17952
17953 #[test]
17954 fn wit_contract_world_ref_borrows_from_wit_storage() {
17955 // The borrow-not-copy pin: [`WitContract::world_ref`] must
17956 // return a `&str` slice that borrows from the typed slot's own
17957 // [`String`] storage — same-address invariant with
17958 // `c.wit.as_str()`. Pins against a future silent detour that
17959 // allocated a fresh `String` (`self.wit.clone()` in the body
17960 // would type-check but silently drop the borrow, and every
17961 // downstream consumer that assumed the returned slice outlives
17962 // `&self` would break on a stale-reference use-after-free — the
17963 // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
17964 // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
17965 // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
17966 // / [`is_pubsub`][WitContract::is_pubsub] /
17967 // [`is_store`][WitContract::is_store] methods route through —
17968 // each borrow from the WitContract's own storage and each would
17969 // silently misbehave if this accessor produced a detached copy).
17970 // Peer of the sibling per-`:contratos` [`WitContract::source`] /
17971 // [`WitContract::destination`] and per-`:entrada`
17972 // [`Entrada::destination`] / [`Entrada::hostname`] and
17973 // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
17974 // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
17975 let c = WitContract {
17976 de: "cart".into(),
17977 para: "catalog".into(),
17978 wit: "wasi:http/proxy".into(),
17979 endpoint: Some("/lookup".into()),
17980 subject: None,
17981 slot: None,
17982 };
17983 let world = c.world_ref();
17984 let wit_slice = c.wit.as_str();
17985 assert_eq!(
17986 world.as_ptr(),
17987 wit_slice.as_ptr(),
17988 "WitContract::world_ref must borrow from the .wit String's \
17989 backing storage — a fresh allocation here means the \
17990 accessor no longer names the substrate-primitive typed \
17991 dispatch and every downstream consumer would silently carry \
17992 a detached copy",
17993 );
17994 assert_eq!(
17995 world.len(),
17996 wit_slice.len(),
17997 "WitContract::world_ref and .wit.as_str() must byte-equal in \
17998 length as well as in address",
17999 );
18000 }
18001
18002 #[test]
18003 fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
18004 // Sibling-triple invariant pin composing all three per-`:contratos`
18005 // substrate-primitive typed dispatches — [`WitContract::source`]
18006 // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
18007 // [`WitContract::world_ref`] — at the joint
18008 // `(source(), destination(), world_ref())` call shape every
18009 // renderer that fans on per-edge caller-callee-shape identity
18010 // keys off. The invariant, evaluated per-contract:
18011 //
18012 // (c.source(), c.destination(), c.world_ref())
18013 // == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
18014 //
18015 // Closes the last unlifted per-`:contratos` scalar axis — every
18016 // downstream consumer that reads the triple now routes through
18017 // exactly three typed dispatches on the substrate primitive,
18018 // not two typed + one open-coded field access. A future refactor
18019 // that silently split any one accessor's projection (an
18020 // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
18021 // canonicalization that didn't reach the peer `source`/
18022 // `destination` arms, an accidental `source()` per-cluster
18023 // caller-alias rewrite that didn't land on the `world_ref` peer)
18024 // surfaces at caixa-core build time. Peer of the sibling per-
18025 // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
18026 // per-`:entrada` `(hostname(), destination())` (6db982c /
18027 // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
18028 // axes, extended to the per-`:contratos` triple.
18029 for (de, para, wit, endpoint, subject, slot) in [
18030 (
18031 "cart",
18032 "catalog",
18033 "wasi:http/proxy",
18034 Some("/lookup"),
18035 None,
18036 None,
18037 ),
18038 (
18039 "checkout",
18040 "orders",
18041 "nats:pub-sub",
18042 None,
18043 Some("orders.paid"),
18044 None,
18045 ),
18046 (
18047 "cart",
18048 "kv",
18049 "wasi:keyvalue/store",
18050 None,
18051 None,
18052 Some("carts/{cart_id}"),
18053 ),
18054 (
18055 "orders-v2",
18056 "inventory-v3",
18057 "http:proxy",
18058 Some("/reserve"),
18059 None,
18060 None,
18061 ),
18062 ] {
18063 let c = WitContract {
18064 de: de.into(),
18065 para: para.into(),
18066 wit: wit.into(),
18067 endpoint: endpoint.map(str::to_string),
18068 subject: subject.map(str::to_string),
18069 slot: slot.map(str::to_string),
18070 };
18071 assert_eq!(
18072 (c.source(), c.destination(), c.world_ref()),
18073 (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
18074 "(WitContract::source, ::destination, ::world_ref) must \
18075 project (.de, .para, .wit) verbatim across every author-\
18076 declared triple (got ({:?}, {:?}, {:?}), expected \
18077 ({de:?}, {para:?}, {wit:?}))",
18078 c.source(),
18079 c.destination(),
18080 c.world_ref(),
18081 );
18082 }
18083 }
18084
18085 #[test]
18086 fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
18087 // The canonical per-`:contratos` owned-form caller-callee-pair
18088 // pin: [`WitContract::edge_pair`] must return the
18089 // `(source(), destination())` tuple in owned form byte-for-byte,
18090 // projected through the lifted [`WitContract::source`] /
18091 // [`WitContract::destination`] scalar accessors. Pins the
18092 // composite-projection invariant on the per-`:contratos`
18093 // mesh-slot atom — every author-declared `(de, para)` pair must
18094 // round-trip verbatim through the substrate primitive's typed
18095 // dispatch, so the nine [`AplicacaoError`] diagnostic-
18096 // construction sites the accessor now feeds
18097 // ([`AplicacaoError::EmptyWit`],
18098 // [`AplicacaoError::ContratoEndpointEmpty`],
18099 // [`AplicacaoError::ContratoEndpointNotAbsolute`],
18100 // [`AplicacaoError::ContratoEndpointInvalid`],
18101 // [`AplicacaoError::ContratoSubjectEmpty`],
18102 // [`AplicacaoError::ContratoSubjectInvalid`],
18103 // [`AplicacaoError::ContratoSlotEmpty`],
18104 // [`AplicacaoError::ContratoSlotInvalid`],
18105 // [`AplicacaoError::ContratoDuplicate`]) all read the same
18106 // `(de, para)` label pair every author sees at the source
18107 // `caixa.lisp`. Pins against a future silent detour that swapped
18108 // the `.0` / `.1` arms (an accidental `(destination(),
18109 // source())` re-order in the body would silently invert every
18110 // downstream diagnostic's `de:` / `para:` label pair, silently
18111 // reversing the direction of every operator-facing typed error
18112 // arrow), a fresh-allocation shape drift (an accidental
18113 // `.to_string()` on one arm but not the other would leave the
18114 // owned/borrowed pair mismatched vs. the sibling `source()` /
18115 // `destination()` returns), or an M4 per-cluster caller/callee-
18116 // alias rewrite that landed on `source()` without reaching
18117 // `destination()` (or vice versa). Peer of the sibling per-
18118 // `:contratos` `(source, destination, world_ref)` triple
18119 // pin above on the mesh-slot-atom scalar-value axes, extended
18120 // to the owned-form pair-projection axis.
18121 for (de, para, wit, endpoint, subject, slot) in [
18122 (
18123 "cart",
18124 "catalog",
18125 "wasi:http/proxy",
18126 Some("/lookup"),
18127 None,
18128 None,
18129 ),
18130 (
18131 "checkout",
18132 "orders",
18133 "nats:pub-sub",
18134 None,
18135 Some("orders.paid"),
18136 None,
18137 ),
18138 (
18139 "cart",
18140 "kv",
18141 "wasi:keyvalue/store",
18142 None,
18143 None,
18144 Some("carts/{cart_id}"),
18145 ),
18146 (
18147 "orders-v2",
18148 "inventory-v3",
18149 "http:proxy",
18150 Some("/reserve"),
18151 None,
18152 None,
18153 ),
18154 ] {
18155 let c = WitContract {
18156 de: de.into(),
18157 para: para.into(),
18158 wit: wit.into(),
18159 endpoint: endpoint.map(str::to_string),
18160 subject: subject.map(str::to_string),
18161 slot: slot.map(str::to_string),
18162 };
18163 assert_eq!(
18164 c.edge_pair(),
18165 (de.to_string(), para.to_string()),
18166 "WitContract::edge_pair must return (:contratos :de, \
18167 :contratos :para) as an owned tuple verbatim (got {:?}, \
18168 expected ({de:?}, {para:?}))",
18169 c.edge_pair(),
18170 );
18171 }
18172 }
18173
18174 #[test]
18175 fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
18176 // The composition pin: [`WitContract::edge_pair`] must return
18177 // exactly `(source().to_string(), destination().to_string())` —
18178 // the owned form of the sibling accessor pair — so any future
18179 // refactor that silently re-authored the caller-arm / callee-arm
18180 // projection to bypass the lifted scalar accessors (an accidental
18181 // `(self.de.clone(), self.para.clone())` regression back to the
18182 // raw field-access shape, an M4-typed-caller-enum `Display`
18183 // re-canonicalization on `source()` that didn't reach
18184 // `edge_pair()`, a per-cluster alias rewrite the operator lands
18185 // on `destination()` without reaching this composite projection)
18186 // trips at caixa-core build time. Pins the "typed dispatch
18187 // composes with typed dispatch, not with raw field access"
18188 // discipline every downstream diagnostic-construction site now
18189 // routes through — a `de:` / `para:` label pair whose
18190 // projection silently drifted off the substrate primitive's
18191 // scalar accessors would silently split the diagnostic's self-
18192 // locating signal from the source `caixa.lisp` author's view.
18193 // Peer of the sibling per-`:politicas` `is_empty` /
18194 // `validate_politicas` accessor-routing-pin family on the M3
18195 // mesh-slot family (18575, 18739, 18918, 19140, 19371).
18196 let c = WitContract {
18197 de: "cart".into(),
18198 para: "catalog".into(),
18199 wit: "wasi:http/proxy".into(),
18200 endpoint: Some("/lookup".into()),
18201 subject: None,
18202 slot: None,
18203 };
18204 assert_eq!(
18205 c.edge_pair(),
18206 (c.source().to_string(), c.destination().to_string()),
18207 "WitContract::edge_pair must compose exactly \
18208 (source().to_string(), destination().to_string()) — a \
18209 bypass of either sibling accessor here would silently \
18210 decouple the composite-projection axis from the \
18211 substrate-primitive scalar accessors every downstream \
18212 consumer routes through",
18213 );
18214 }
18215
18216 #[test]
18217 fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
18218 {
18219 // The canonical per-`:contratos` owned-form
18220 // caller-callee-world-ref-triple pin:
18221 // [`WitContract::edge_triple`] must return the
18222 // `(source(), destination(), world_ref())` tuple in owned form
18223 // byte-for-byte, projected through the lifted
18224 // [`WitContract::source`] / [`WitContract::destination`] /
18225 // [`WitContract::world_ref`] scalar accessors. Pins the
18226 // composite-projection invariant on the per-`:contratos`
18227 // mesh-slot atom — every author-declared `(de, para, wit)`
18228 // triple must round-trip verbatim through the substrate
18229 // primitive's typed dispatch, so the nine
18230 // [`AplicacaoError`] diagnostic-construction sites the
18231 // accessor now feeds (the [`WitTarget`]-dispatch's eight
18232 // wrong-target / missing-target / invalid-wit / capability-
18233 // with-payload arms in [`WitContract::target`], plus the
18234 // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
18235 // diagnostic constructor in [`AplicacaoSpec::validate`]) all
18236 // read the same `(de, para, wit)` triple every author sees at
18237 // the source `caixa.lisp`. Pins against a future silent
18238 // detour that swapped any two arms (an accidental `(destination(),
18239 // source(), world_ref())` re-order in the body would silently
18240 // invert every downstream diagnostic's `de:` / `para:` label
18241 // pair, silently reversing the direction of every operator-
18242 // facing typed error arrow), a fresh-allocation shape drift
18243 // (an accidental `.to_string()` skipped on one arm would leave
18244 // the owned/borrowed triple mismatched vs. the sibling
18245 // `source()` / `destination()` / `world_ref()` returns), or an
18246 // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
18247 // canonicalization pass that landed on one accessor without
18248 // reaching the peers. Peer of the sibling per-`:contratos`
18249 // caller-callee-pair
18250 // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
18251 // pin on the mesh-slot-atom composite-projection axis,
18252 // extended to the triple-projection axis.
18253 for (de, para, wit, endpoint, subject, slot) in [
18254 (
18255 "cart",
18256 "catalog",
18257 "wasi:http/proxy",
18258 Some("/lookup"),
18259 None,
18260 None,
18261 ),
18262 (
18263 "checkout",
18264 "orders",
18265 "nats:pub-sub",
18266 None,
18267 Some("orders.paid"),
18268 None,
18269 ),
18270 (
18271 "cart",
18272 "kv",
18273 "wasi:keyvalue/store",
18274 None,
18275 None,
18276 Some("carts/{cart_id}"),
18277 ),
18278 (
18279 "orders-v2",
18280 "inventory-v3",
18281 "http:proxy",
18282 Some("/reserve"),
18283 None,
18284 None,
18285 ),
18286 ] {
18287 let c = WitContract {
18288 de: de.into(),
18289 para: para.into(),
18290 wit: wit.into(),
18291 endpoint: endpoint.map(str::to_string),
18292 subject: subject.map(str::to_string),
18293 slot: slot.map(str::to_string),
18294 };
18295 assert_eq!(
18296 c.edge_triple(),
18297 (de.to_string(), para.to_string(), wit.to_string()),
18298 "WitContract::edge_triple must return (:contratos :de, \
18299 :contratos :para, :contratos :wit) as an owned triple \
18300 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
18301 c.edge_triple(),
18302 );
18303 }
18304 }
18305
18306 #[test]
18307 fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
18308 // The composition pin: [`WitContract::edge_triple`] must return
18309 // exactly `(source().to_string(), destination().to_string(),
18310 // world_ref().to_string())` — the owned form of the sibling
18311 // scalar-accessor triple — so any future refactor that silently
18312 // re-authored one arm's projection to bypass the lifted scalar
18313 // accessors (an accidental `(self.de.clone(), self.para.clone(),
18314 // self.wit.clone())` regression back to the raw field-access
18315 // shape the internal `edge` closure and the ContratoDuplicate
18316 // diagnostic both carried before this lift landed, an
18317 // M4-typed-caller-enum `Display` re-canonicalization on
18318 // `source()` that didn't reach `edge_triple()`, a per-cluster
18319 // alias rewrite the operator lands on `destination()` /
18320 // `world_ref()` without reaching this composite projection)
18321 // trips at caixa-core build time. Pins the "typed dispatch
18322 // composes with typed dispatch, not with raw field access"
18323 // discipline every downstream diagnostic-construction site now
18324 // routes through — a `de:` / `para:` / `wit:` triple whose
18325 // projection silently drifted off the substrate primitive's
18326 // scalar accessors would silently split the diagnostic's self-
18327 // locating signal from the source `caixa.lisp` author's view.
18328 // Peer of the sibling per-`:contratos` edge_pair composition-
18329 // pin above on the mesh-slot-atom composite-projection axis.
18330 let c = WitContract {
18331 de: "cart".into(),
18332 para: "catalog".into(),
18333 wit: "wasi:http/proxy".into(),
18334 endpoint: Some("/lookup".into()),
18335 subject: None,
18336 slot: None,
18337 };
18338 assert_eq!(
18339 c.edge_triple(),
18340 (
18341 c.source().to_string(),
18342 c.destination().to_string(),
18343 c.world_ref().to_string(),
18344 ),
18345 "WitContract::edge_triple must compose exactly \
18346 (source().to_string(), destination().to_string(), \
18347 world_ref().to_string()) — a bypass of any sibling accessor \
18348 here would silently decouple the composite-projection axis \
18349 from the substrate-primitive scalar accessors every \
18350 downstream consumer routes through",
18351 );
18352 }
18353
18354 #[test]
18355 fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
18356 // The canonical semantics-pin: [`WitContract::edge_triple`] must
18357 // project the full `(de, para, wit)` identity of a `:contratos`
18358 // edge — the sub-triple every triple-carrying
18359 // [`AplicacaoError::Contrato*`] diagnostic weaves into its
18360 // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
18361 // missing-target, capability-with-payload, invalid-wit, and the
18362 // duplicate-gate). Rejects a drift in shape (an accidental
18363 // silent detour that returned a `(de, para)` pair or added an
18364 // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
18365 // would trip here because the return type would no longer
18366 // pattern-match the eight `let (de, para, wit) = edge();`
18367 // destructures the [`WitContract::target`] dispatch feeds off
18368 // + the paired duplicate-gate `let (de, para, wit) =
18369 // c.edge_triple();` destructure in
18370 // [`AplicacaoSpec::validate`]). Peer of the sibling per-
18371 // `:contratos` caller-callee-pair pin above extended to the
18372 // triple projection surface: closes the "one composite
18373 // accessor per typed diagnostic-construction sub-tuple"
18374 // discipline on the per-`:contratos` mesh-slot-atom axis.
18375 let c = WitContract {
18376 de: "checkout".into(),
18377 para: "orders".into(),
18378 wit: "nats:pub-sub".into(),
18379 endpoint: None,
18380 subject: Some("orders.paid".into()),
18381 slot: None,
18382 };
18383 let (de, para, wit) = c.edge_triple();
18384 assert_eq!(de, "checkout");
18385 assert_eq!(para, "orders");
18386 assert_eq!(wit, "nats:pub-sub");
18387 }
18388
18389 #[test]
18390 fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
18391 {
18392 // The composition pin: [`WitContract::identity`] must return
18393 // exactly `(source(), destination(), world_ref(), endpoint(),
18394 // subject(), slot())` — the borrowed form of the six-scalar-
18395 // accessor identity axis. Any future refactor that silently
18396 // re-authored one arm's projection to bypass a scalar accessor
18397 // (a `self.de.as_str()` regression back to raw field access on
18398 // any of the three required arms, a `self.endpoint.as_deref()`
18399 // regression on any of the three optional arms, an M4 per-
18400 // cluster caller/callee-alias rewrite the operator lands on
18401 // `source()` / `destination()` without reaching this composite
18402 // projection) trips at caixa-core build time. Sweeps four
18403 // permutations of the WIT-shape × payload lattice — HTTP with
18404 // endpoint, pub-sub with subject, store with slot, payload-less
18405 // capability — so every payload arm is exercised. Peer of the
18406 // sibling per-`:contratos`
18407 // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
18408 // composition pin on the mesh-slot-atom composite-projection
18409 // axis; extends the discipline from the (de, para, wit) prefix
18410 // onto the full-identity axis carrying the three payload arms.
18411 for (de, para, wit, endpoint, subject, slot) in [
18412 (
18413 "cart",
18414 "catalog",
18415 "wasi:http/proxy",
18416 Some("/lookup"),
18417 None,
18418 None,
18419 ),
18420 (
18421 "checkout",
18422 "orders",
18423 "nats:pub-sub",
18424 None,
18425 Some("orders.paid"),
18426 None,
18427 ),
18428 (
18429 "cart",
18430 "kv",
18431 "wasi:keyvalue/store",
18432 None,
18433 None,
18434 Some("carts/{cart_id}"),
18435 ),
18436 ("audit", "sink", "wasi:logging", None, None, None),
18437 ] {
18438 let c = WitContract {
18439 de: de.into(),
18440 para: para.into(),
18441 wit: wit.into(),
18442 endpoint: endpoint.map(str::to_owned),
18443 subject: subject.map(str::to_owned),
18444 slot: slot.map(str::to_owned),
18445 };
18446 assert_eq!(
18447 c.identity(),
18448 (
18449 c.source(),
18450 c.destination(),
18451 c.world_ref(),
18452 c.endpoint(),
18453 c.subject(),
18454 c.slot(),
18455 ),
18456 "WitContract::identity must compose exactly \
18457 (source(), destination(), world_ref(), endpoint(), \
18458 subject(), slot()) — a bypass of any sibling accessor \
18459 here would silently decouple the identity-projection \
18460 axis from the substrate-primitive scalar accessors \
18461 every dedup-key consumer routes through",
18462 );
18463 }
18464 }
18465
18466 #[test]
18467 fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
18468 // The canonical semantics-pin: [`WitContract::identity`] must
18469 // project the six-axis (de, para, wit, endpoint, subject, slot)
18470 // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
18471 // gate keys off — two `WitContract`s that agree on all six axes
18472 // are the same typed edge declared twice, the graph-edge
18473 // analogue of duplicate `:membros` / `:placement :clusters` /
18474 // `:entrada :paths` entries. Rejects a shape drift (an
18475 // accidental silent detour that returned a prefix tuple or
18476 // added an extra field) by pattern-matching the six-arm shape.
18477 // Peer of the sibling per-`:contratos`
18478 // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
18479 // pin extended from the (de, para, wit) prefix onto the full
18480 // six-axis identity that the dedup key rides.
18481 let c = WitContract {
18482 de: "cart".into(),
18483 para: "catalog".into(),
18484 wit: "wasi:http/proxy".into(),
18485 endpoint: Some("/products/:id".into()),
18486 subject: None,
18487 slot: None,
18488 };
18489 let (de, para, wit, endpoint, subject, slot) = c.identity();
18490 assert_eq!(de, "cart");
18491 assert_eq!(para, "catalog");
18492 assert_eq!(wit, "wasi:http/proxy");
18493 assert_eq!(endpoint, Some("/products/:id"));
18494 assert_eq!(subject, None);
18495 assert_eq!(slot, None);
18496
18497 // Two byte-identical contracts must produce equal identities —
18498 // the dedup key's foundational invariant.
18499 let c2 = c.clone();
18500 assert_eq!(c.identity(), c2.identity());
18501
18502 // Any change on any of the six axes must break the identity —
18503 // sweeps by mutating one axis at a time.
18504 let mut mutated = c.clone();
18505 mutated.de = "search".into();
18506 assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
18507 let mut mutated = c.clone();
18508 mutated.para = "warehouse".into();
18509 assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
18510 let mut mutated = c.clone();
18511 mutated.wit = "http:legacy".into();
18512 assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
18513 let mut mutated = c.clone();
18514 mutated.endpoint = Some("/search".into());
18515 assert_ne!(
18516 c.identity(),
18517 mutated.identity(),
18518 "endpoint axis must partition"
18519 );
18520 let mut mutated = c.clone();
18521 mutated.subject = Some("orders.paid".into());
18522 assert_ne!(
18523 c.identity(),
18524 mutated.identity(),
18525 "subject axis must partition"
18526 );
18527 let mut mutated = c;
18528 mutated.slot = Some("carts/{id}".into());
18529 assert_ne!(mutated.identity().5, None, "slot axis must partition");
18530 }
18531
18532 #[test]
18533 fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
18534 // The canonical per-`:contratos` structural-self-edge pin:
18535 // [`WitContract::is_self_loop`] must return `true` when the
18536 // `:de` and `:para` fields agree byte-for-byte, across every
18537 // WIT-shape variant the per-edge shape family carries. Pins
18538 // the shape-agnostic identity-space partition the
18539 // [`AplicacaoSpec::validate`] self-edge gate at
18540 // caixa-core/src/aplicacao.rs:5559 fires against — all four
18541 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
18542 // under the same one predicate. Four permutations sweep the
18543 // accept-set: HTTP with endpoint, pub-sub with subject, KV
18544 // store with slot, and payload-less capability.
18545 for (nome, wit, endpoint, subject, slot) in [
18546 ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
18547 ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
18548 (
18549 "kv",
18550 "wasi:keyvalue/store",
18551 None,
18552 None,
18553 Some("carts/{cart_id}"),
18554 ),
18555 ("audit", "wasi:logging", None, None, None),
18556 ] {
18557 let c = WitContract {
18558 de: nome.into(),
18559 para: nome.into(),
18560 wit: wit.into(),
18561 endpoint: endpoint.map(str::to_string),
18562 subject: subject.map(str::to_string),
18563 slot: slot.map(str::to_string),
18564 };
18565 assert!(
18566 c.is_self_loop(),
18567 "WitContract::is_self_loop must return true when \
18568 :contratos :de == :contratos :para (got false on \
18569 {nome:?} under {wit:?})",
18570 );
18571 }
18572 }
18573
18574 #[test]
18575 fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
18576 // The complement pin: [`WitContract::is_self_loop`] must return
18577 // `false` on every well-shaped inter-Servico contract (the
18578 // author-intended `:contratos` shape MESH-COMPOSITION §III.1
18579 // names — "Servico A calls Servico B" between two distinct
18580 // graph nodes). Pins against a future silent detour that
18581 // inverted the predicate (an accidental `!= ` swap for `==`
18582 // would silently reject every legitimate inter-Servico edge
18583 // and admit every self-edge — the exact inversion of the
18584 // author-intended shape). Four permutations sweep the same
18585 // WIT-shape accept-set the sibling positive-arm test carries.
18586 for (de, para, wit, endpoint, subject, slot) in [
18587 (
18588 "cart",
18589 "catalog",
18590 "wasi:http/proxy",
18591 Some("/lookup"),
18592 None,
18593 None,
18594 ),
18595 (
18596 "checkout",
18597 "orders",
18598 "nats:pub-sub",
18599 None,
18600 Some("orders.paid"),
18601 None,
18602 ),
18603 (
18604 "cart",
18605 "kv",
18606 "wasi:keyvalue/store",
18607 None,
18608 None,
18609 Some("carts/{cart_id}"),
18610 ),
18611 ("audit", "sink", "wasi:logging", None, None, None),
18612 ] {
18613 let c = WitContract {
18614 de: de.into(),
18615 para: para.into(),
18616 wit: wit.into(),
18617 endpoint: endpoint.map(str::to_string),
18618 subject: subject.map(str::to_string),
18619 slot: slot.map(str::to_string),
18620 };
18621 assert!(
18622 !c.is_self_loop(),
18623 "WitContract::is_self_loop must return false when \
18624 :contratos :de differs from :contratos :para (got true \
18625 on {de:?} → {para:?} under {wit:?})",
18626 );
18627 }
18628 }
18629
18630 #[test]
18631 fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
18632 // The composition pin: [`WitContract::is_self_loop`] must
18633 // resolve to exactly `self.source() == self.destination()` —
18634 // the equality probe of the sibling scalar-accessor pair — so
18635 // any future refactor that silently re-authored the predicate
18636 // to bypass the lifted scalar accessors (an accidental
18637 // `self.de == self.para` regression back to the raw field-
18638 // access shape, an M4-typed-caller-enum identity-comparison
18639 // rule that landed on `source()` without reaching
18640 // `destination()`, a per-cluster alias rewrite the operator
18641 // pins on `destination()` without reaching this predicate)
18642 // trips at caixa-core build time. Pins the "typed dispatch
18643 // composes with typed dispatch, not with raw field access"
18644 // discipline the sibling [`WitContract::edge_pair`] /
18645 // [`WitContract::edge_triple`] composite-projection accessors
18646 // already carry, extended onto the per-edge endpoint-equality
18647 // predicate axis. Positive and complement arms both fire.
18648 let self_edge = WitContract {
18649 de: "cart".into(),
18650 para: "cart".into(),
18651 wit: "wasi:http/proxy".into(),
18652 endpoint: Some("/lookup".into()),
18653 subject: None,
18654 slot: None,
18655 };
18656 assert_eq!(
18657 self_edge.is_self_loop(),
18658 self_edge.source() == self_edge.destination(),
18659 "WitContract::is_self_loop must compose exactly \
18660 `source() == destination()` — a bypass of either sibling \
18661 accessor here would silently decouple the endpoint-\
18662 equality predicate from the substrate-primitive scalar \
18663 accessors every downstream consumer routes through",
18664 );
18665 let inter_edge = WitContract {
18666 de: "cart".into(),
18667 para: "catalog".into(),
18668 wit: "wasi:http/proxy".into(),
18669 endpoint: Some("/lookup".into()),
18670 subject: None,
18671 slot: None,
18672 };
18673 assert_eq!(
18674 inter_edge.is_self_loop(),
18675 inter_edge.source() == inter_edge.destination(),
18676 "WitContract::is_self_loop must compose exactly \
18677 `source() == destination()` on the complement arm too",
18678 );
18679 }
18680
18681 #[test]
18682 fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
18683 // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
18684 // pin: [`WitContract::endpoint`] must return the `:contratos
18685 // :endpoint` field byte-for-byte, borrowed from the typed slot's
18686 // own `Option<String>` storage. Peer of the sibling
18687 // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
18688 // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
18689 // mesh-slot `Option<String>` optional-scalar axes — same "the
18690 // substrate-primitive accessor must byte-equal the raw field
18691 // access verbatim across every author-declared value" discipline
18692 // extended to the per-`:contratos` HTTP-payload-carrier arm.
18693 // Pins against a future silent detour that re-canonicalized the
18694 // endpoint (an accidental percent-encoding pass that didn't
18695 // reach the peer field-access site at the dedup key, a per-CR
18696 // fully-qualified prefix rewrite the operator authors on one
18697 // consumer without the other, or an M4 typed-path-template
18698 // `Display` re-canonicalization that silently drifted the
18699 // printer output from the source `caixa.lisp`). Four values
18700 // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
18701 // gate upstream admits (short root-path, dashed, param-shaped,
18702 // deep-hierarchy).
18703 for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
18704 let c = WitContract {
18705 de: "cart".into(),
18706 para: "catalog".into(),
18707 wit: "wasi:http/proxy".into(),
18708 endpoint: Some(endpoint.into()),
18709 subject: None,
18710 slot: None,
18711 };
18712 assert_eq!(
18713 c.endpoint(),
18714 Some(endpoint),
18715 "WitContract::endpoint must return :contratos :endpoint \
18716 verbatim (got {:?}, expected Some({endpoint:?}))",
18717 c.endpoint(),
18718 );
18719 assert_eq!(
18720 c.endpoint(),
18721 c.endpoint.as_deref(),
18722 "WitContract::endpoint must byte-equal the .endpoint \
18723 field's `.as_deref()` projection",
18724 );
18725 }
18726 }
18727
18728 #[test]
18729 fn wit_contract_endpoint_none_when_field_is_none() {
18730 // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
18731 // payload-carrier accessor pin: when the typed slot is absent —
18732 // the canonical shape under a non-HTTP `:wit` world per the
18733 // [`WitContract::target`]-enforced shape ↔ target partition
18734 // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
18735 // carries `:slot`, [`WitTarget::Capability`] carries none) —
18736 // [`WitContract::endpoint`] must return `None`. Pins against a
18737 // future silent detour that projected the absent slot to a
18738 // `Some("")` empty-string default (the canonical `Option<String>`
18739 // → `String` collapse footgun the sibling M2
18740 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
18741 // emptiness predicates already guard on the peer M2 typed-slot
18742 // surfaces), a `Some("None")` stringified-None round-trip, or a
18743 // `Some` arm whose contents were derived from a sibling slot (an
18744 // accidental fallback to the `:subject` / `:slot` payload that
18745 // read the pub-sub / store payload into the endpoint axis).
18746 // Three contracts sweep the accept-set every non-HTTP `:wit`
18747 // world lands on — pub-sub NATS, key/value, and payload-less
18748 // capability.
18749 for (wit, subject, slot) in [
18750 ("nats:pub-sub", Some("orders.paid"), None),
18751 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
18752 ("wasi:cli/environment", None, None),
18753 ] {
18754 let c = WitContract {
18755 de: "cart".into(),
18756 para: "downstream".into(),
18757 wit: wit.into(),
18758 endpoint: None,
18759 subject: subject.map(str::to_string),
18760 slot: slot.map(str::to_string),
18761 };
18762 assert!(
18763 c.endpoint().is_none(),
18764 "WitContract::endpoint must return None when the typed \
18765 slot is absent under :wit {wit:?} (got {:?})",
18766 c.endpoint(),
18767 );
18768 assert_eq!(
18769 c.endpoint(),
18770 c.endpoint.as_deref(),
18771 "WitContract::endpoint must byte-equal the .endpoint \
18772 field's `.as_deref()` projection in the absent arm",
18773 );
18774 }
18775 }
18776
18777 #[test]
18778 fn wit_contract_endpoint_borrows_from_endpoint_storage() {
18779 // The borrow-not-copy pin: [`WitContract::endpoint`] must return
18780 // an `Option<&str>` whose `Some` arm borrows from the typed
18781 // slot's own [`String`] storage — same-address invariant with
18782 // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
18783 // detour that allocated a fresh `String`
18784 // (`self.endpoint.clone().map(...)` in the body would type-check
18785 // but silently drop the borrow, and every downstream consumer
18786 // that assumed the returned slice outlives `&self` would break
18787 // on a stale-reference use-after-free — the [`WitContract::target`]
18788 // Http-arm payload extraction rebinds the returned `Option<&str>`
18789 // through `.ok_or_else(...)` and threads the `&str` payload into
18790 // [`WitTarget::Http { endpoint: &'a str }`], the
18791 // [`AplicacaoSpec::validate`] duplicate-`:contratos`
18792 // [`ContratoIdentity`] dedup key threads the returned
18793 // `Option<&str>` into the six-tuple's HTTP arm — each borrow
18794 // from the WitContract's own storage and each would silently
18795 // misbehave if this accessor produced a detached copy). Peer of
18796 // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
18797 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
18798 // shaped optional-scalar axes — first extension of the
18799 // `Option<&str>` borrow-not-copy discipline onto the
18800 // per-`:contratos` HTTP-shaped payload-carrier axis.
18801 let c = WitContract {
18802 de: "cart".into(),
18803 para: "catalog".into(),
18804 wit: "wasi:http/proxy".into(),
18805 endpoint: Some("/lookup".into()),
18806 subject: None,
18807 slot: None,
18808 };
18809 let ep = c.endpoint().expect("Some arm");
18810 let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
18811 assert_eq!(
18812 ep.as_ptr(),
18813 storage_slice.as_ptr(),
18814 "WitContract::endpoint must borrow from the .endpoint \
18815 String's backing storage — a fresh allocation here means \
18816 the accessor no longer names the substrate-primitive typed \
18817 dispatch and every downstream consumer would silently \
18818 carry a detached copy",
18819 );
18820 assert_eq!(
18821 ep.len(),
18822 storage_slice.len(),
18823 "WitContract::endpoint and .endpoint.as_deref() must byte-\
18824 equal in length as well as in address",
18825 );
18826 }
18827
18828 #[test]
18829 fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
18830 // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
18831 // pin: [`WitContract::subject`] must return the `:contratos
18832 // :subject` field byte-for-byte, borrowed from the typed slot's
18833 // own `Option<String>` storage. Peer of the sibling per-`:contratos`
18834 // [`WitContract::endpoint`] (7020470) accessor pin on the M3
18835 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
18836 // optional-scalar axis — same "the substrate-primitive accessor
18837 // must byte-equal the raw field access verbatim across every
18838 // author-declared value" discipline extended to the pub-sub arm.
18839 // Pins against a future silent detour that re-canonicalized the
18840 // subject (an accidental `.to_lowercase()` normalization that
18841 // didn't reach the peer field-access site at the dedup key, a
18842 // per-CR fully-qualified prefix rewrite the operator authors on
18843 // one consumer without the other, or an M4 typed-subject-template
18844 // `Display` re-canonicalization that silently drifted the printer
18845 // output from the source `caixa.lisp`). Four values sweep the
18846 // NATS accept-set every pub-sub author-declared subject lands on
18847 // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
18848 for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
18849 let c = WitContract {
18850 de: "cart".into(),
18851 para: "notifier".into(),
18852 wit: "nats:pub-sub".into(),
18853 endpoint: None,
18854 subject: Some(subject.into()),
18855 slot: None,
18856 };
18857 assert_eq!(
18858 c.subject(),
18859 Some(subject),
18860 "WitContract::subject must return :contratos :subject \
18861 verbatim (got {:?}, expected Some({subject:?}))",
18862 c.subject(),
18863 );
18864 assert_eq!(
18865 c.subject(),
18866 c.subject.as_deref(),
18867 "WitContract::subject must byte-equal the .subject \
18868 field's `.as_deref()` projection",
18869 );
18870 }
18871 }
18872
18873 #[test]
18874 fn wit_contract_subject_none_when_field_is_none() {
18875 // The absent-`:subject` arm of the per-`:contratos` pub-sub-
18876 // shaped payload-carrier accessor pin: when the typed slot is
18877 // absent — the canonical shape under a non-pub-sub `:wit` world
18878 // per the [`WitContract::target`]-enforced shape ↔ target
18879 // partition ([`WitTarget::Http`] carries `:endpoint`,
18880 // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
18881 // carries none) — [`WitContract::subject`] must return `None`.
18882 // Pins against a future silent detour that projected the absent
18883 // slot to a `Some("")` empty-string default (the canonical
18884 // `Option<String>` → `String` collapse footgun the sibling M2
18885 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
18886 // emptiness predicates already guard on the peer M2 typed-slot
18887 // surfaces), a `Some("None")` stringified-None round-trip, or a
18888 // `Some` arm whose contents were derived from a sibling slot (an
18889 // accidental fallback to the `:endpoint` / `:slot` payload that
18890 // read the HTTP / store payload into the subject axis). Three
18891 // contracts sweep the accept-set every non-pub-sub `:wit` world
18892 // lands on — HTTP proxy, key/value store, and payload-less
18893 // capability.
18894 for (wit, endpoint, slot) in [
18895 ("wasi:http/proxy", Some("/lookup"), None),
18896 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
18897 ("wasi:cli/environment", None, None),
18898 ] {
18899 let c = WitContract {
18900 de: "cart".into(),
18901 para: "downstream".into(),
18902 wit: wit.into(),
18903 endpoint: endpoint.map(str::to_string),
18904 subject: None,
18905 slot: slot.map(str::to_string),
18906 };
18907 assert!(
18908 c.subject().is_none(),
18909 "WitContract::subject must return None when the typed \
18910 slot is absent under :wit {wit:?} (got {:?})",
18911 c.subject(),
18912 );
18913 assert_eq!(
18914 c.subject(),
18915 c.subject.as_deref(),
18916 "WitContract::subject must byte-equal the .subject \
18917 field's `.as_deref()` projection in the absent arm",
18918 );
18919 }
18920 }
18921
18922 #[test]
18923 fn wit_contract_subject_borrows_from_subject_storage() {
18924 // The borrow-not-copy pin: [`WitContract::subject`] must return
18925 // an `Option<&str>` whose `Some` arm borrows from the typed
18926 // slot's own [`String`] storage — same-address invariant with
18927 // `c.subject.as_deref().unwrap()`. Pins against a future silent
18928 // detour that allocated a fresh `String`
18929 // (`self.subject.clone().map(...)` in the body would type-check
18930 // but silently drop the borrow, and every downstream consumer
18931 // that assumed the returned slice outlives `&self` would break
18932 // on a stale-reference use-after-free — the [`WitContract::target`]
18933 // PubSub-arm payload extraction rebinds the returned
18934 // `Option<&str>` through `.ok_or_else(...)` and threads the
18935 // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
18936 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
18937 // [`ContratoIdentity`] dedup key threads the returned
18938 // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
18939 // from the WitContract's own storage and each would silently
18940 // misbehave if this accessor produced a detached copy). Peer of
18941 // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
18942 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
18943 // shaped optional-scalar axis — second extension of the
18944 // `Option<&str>` borrow-not-copy discipline onto the
18945 // per-`:contratos` payload-carrier family, this time on the
18946 // pub-sub arm.
18947 let c = WitContract {
18948 de: "cart".into(),
18949 para: "notifier".into(),
18950 wit: "nats:pub-sub".into(),
18951 endpoint: None,
18952 subject: Some("orders.paid".into()),
18953 slot: None,
18954 };
18955 let sub = c.subject().expect("Some arm");
18956 let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
18957 assert_eq!(
18958 sub.as_ptr(),
18959 storage_slice.as_ptr(),
18960 "WitContract::subject must borrow from the .subject \
18961 String's backing storage — a fresh allocation here means \
18962 the accessor no longer names the substrate-primitive typed \
18963 dispatch and every downstream consumer would silently \
18964 carry a detached copy",
18965 );
18966 assert_eq!(
18967 sub.len(),
18968 storage_slice.len(),
18969 "WitContract::subject and .subject.as_deref() must byte-\
18970 equal in length as well as in address",
18971 );
18972 }
18973
18974 #[test]
18975 fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
18976 // The canonical per-`:contratos` key/value-store-shaped
18977 // `:slot`-scalar pin: [`WitContract::slot`] must return the
18978 // `:contratos :slot` field byte-for-byte, borrowed from the
18979 // typed slot's own `Option<String>` storage. Peer of the
18980 // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
18981 // [`WitContract::subject`] (90de675) accessor pins on the M3
18982 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
18983 // optional-scalar axis — same "the substrate-primitive
18984 // accessor must byte-equal the raw field access verbatim
18985 // across every author-declared value" discipline extended to
18986 // the store arm. Pins against a future silent detour that
18987 // re-canonicalized the slot template (an accidental
18988 // `.to_lowercase()` bucket-prefix normalization that didn't
18989 // reach the peer field-access site at the dedup key, a per-CR
18990 // fully-qualified prefix rewrite the operator authors on one
18991 // consumer without the other, or an M4 typed-key-template
18992 // `Display` re-canonicalization that silently drifted the
18993 // printer output from the source `caixa.lisp`). Four values
18994 // sweep the wasi:keyvalue accept-set every store-shaped
18995 // author-declared slot lands on (flat bucket, single-param
18996 // template, multi-param template, nested-hierarchy template).
18997 for slot in [
18998 "sessions",
18999 "carts/{cart_id}",
19000 "orders/{tenant}/{order_id}",
19001 "cache/tenant-a/orders/{id}",
19002 ] {
19003 let c = WitContract {
19004 de: "cart".into(),
19005 para: "kv".into(),
19006 wit: "wasi:keyvalue/store".into(),
19007 endpoint: None,
19008 subject: None,
19009 slot: Some(slot.into()),
19010 };
19011 assert_eq!(
19012 c.slot(),
19013 Some(slot),
19014 "WitContract::slot must return :contratos :slot \
19015 verbatim (got {:?}, expected Some({slot:?}))",
19016 c.slot(),
19017 );
19018 assert_eq!(
19019 c.slot(),
19020 c.slot.as_deref(),
19021 "WitContract::slot must byte-equal the .slot field's \
19022 `.as_deref()` projection",
19023 );
19024 }
19025 }
19026
19027 #[test]
19028 fn wit_contract_slot_none_when_field_is_none() {
19029 // The absent-`:slot` arm of the per-`:contratos` store-shaped
19030 // payload-carrier accessor pin: when the typed slot is absent —
19031 // the canonical shape under a non-store `:wit` world per the
19032 // [`WitContract::target`]-enforced shape ↔ target partition
19033 // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
19034 // carries `:subject`, [`WitTarget::Capability`] carries none) —
19035 // [`WitContract::slot`] must return `None`. Pins against a
19036 // future silent detour that projected the absent slot to a
19037 // `Some("")` empty-string default (the canonical
19038 // `Option<String>` → `String` collapse footgun the sibling M2
19039 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
19040 // emptiness predicates already guard on the peer M2 typed-slot
19041 // surfaces), a `Some("None")` stringified-None round-trip, or
19042 // a `Some` arm whose contents were derived from a sibling
19043 // slot (an accidental fallback to the `:endpoint` / `:subject`
19044 // payload that read the HTTP / pub-sub payload into the store
19045 // axis). Three contracts sweep the accept-set every non-store
19046 // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
19047 // payload-less capability.
19048 for (wit, endpoint, subject) in [
19049 ("wasi:http/proxy", Some("/lookup"), None),
19050 ("nats:pub-sub", None, Some("orders.paid")),
19051 ("wasi:cli/environment", None, None),
19052 ] {
19053 let c = WitContract {
19054 de: "cart".into(),
19055 para: "downstream".into(),
19056 wit: wit.into(),
19057 endpoint: endpoint.map(str::to_string),
19058 subject: subject.map(str::to_string),
19059 slot: None,
19060 };
19061 assert!(
19062 c.slot().is_none(),
19063 "WitContract::slot must return None when the typed \
19064 slot is absent under :wit {wit:?} (got {:?})",
19065 c.slot(),
19066 );
19067 assert_eq!(
19068 c.slot(),
19069 c.slot.as_deref(),
19070 "WitContract::slot must byte-equal the .slot field's \
19071 `.as_deref()` projection in the absent arm",
19072 );
19073 }
19074 }
19075
19076 #[test]
19077 fn wit_contract_slot_borrows_from_slot_storage() {
19078 // The borrow-not-copy pin: [`WitContract::slot`] must return
19079 // an `Option<&str>` whose `Some` arm borrows from the typed
19080 // slot's own [`String`] storage — same-address invariant with
19081 // `c.slot.as_deref().unwrap()`. Pins against a future silent
19082 // detour that allocated a fresh `String`
19083 // (`self.slot.clone().map(...)` in the body would type-check
19084 // but silently drop the borrow, and every downstream consumer
19085 // that assumed the returned slice outlives `&self` would
19086 // break on a stale-reference use-after-free — the
19087 // [`WitContract::target`] Store-arm payload extraction rebinds
19088 // the returned `Option<&str>` through `.ok_or_else(...)` and
19089 // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
19090 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
19091 // [`ContratoIdentity`] dedup key threads the returned
19092 // `Option<&str>` into the six-tuple's store arm — each borrow
19093 // from the WitContract's own storage and each would silently
19094 // misbehave if this accessor produced a detached copy). Peer
19095 // of the sibling per-`:contratos` [`WitContract::endpoint`]
19096 // (7020470) / [`WitContract::subject`] (90de675)
19097 // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
19098 // shaped optional-scalar axis — third and final extension of
19099 // the `Option<&str>` borrow-not-copy discipline onto the
19100 // per-`:contratos` payload-carrier family, this time on the
19101 // store arm.
19102 let c = WitContract {
19103 de: "cart".into(),
19104 para: "kv".into(),
19105 wit: "wasi:keyvalue/store".into(),
19106 endpoint: None,
19107 subject: None,
19108 slot: Some("carts/{cart_id}".into()),
19109 };
19110 let slot = c.slot().expect("Some arm");
19111 let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
19112 assert_eq!(
19113 slot.as_ptr(),
19114 storage_slice.as_ptr(),
19115 "WitContract::slot must borrow from the .slot String's \
19116 backing storage — a fresh allocation here means the \
19117 accessor no longer names the substrate-primitive typed \
19118 dispatch and every downstream consumer would silently \
19119 carry a detached copy",
19120 );
19121 assert_eq!(
19122 slot.len(),
19123 storage_slice.len(),
19124 "WitContract::slot and .slot.as_deref() must byte-equal \
19125 in length as well as in address",
19126 );
19127 }
19128
19129 #[test]
19130 fn membro_nome_returns_caixa_byte_equal_across_permutations() {
19131 // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
19132 // [`Membro::nome`] must return the `:membros :caixa` field
19133 // byte-for-byte, borrowed from the typed slot's own [`String`]
19134 // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
19135 // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19136 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
19137 // slot-atom scalar-value axes — same "the substrate-primitive
19138 // accessor must byte-equal the raw field access verbatim across
19139 // every author-declared value" discipline extended to the
19140 // per-`:membros` member-identity arm. Pins against a future
19141 // silent detour that re-normalized the member identity (an
19142 // accidental `.to_lowercase()` — every `:membros :caixa` is
19143 // validated as a DNS-1123 label upstream via
19144 // [`validate_membro_caixa`], so any re-normalization is
19145 // redundant + a drift surface between the validator and the
19146 // accessor), a namespace-prefix rewrite (an accidental
19147 // `format!("{namespace}/{caixa}")` per-CR fully-qualified
19148 // rewrite that didn't land on the peer axes), or a per-cluster
19149 // alias stamp the operator authors on one consumer without the
19150 // other. Four values sweep the accept-set the DNS-1123 gate
19151 // upstream admits (short single-word / dashed / v-suffixed
19152 // member names).
19153 for name in ["cart", "checkout", "catalog", "orders-v2"] {
19154 let m = Membro {
19155 caixa: name.into(),
19156 versao: "^0.1".into(),
19157 };
19158 assert_eq!(
19159 m.nome(),
19160 name,
19161 "Membro::nome must return :membros :caixa verbatim \
19162 (got {:?}, expected {name:?})",
19163 m.nome(),
19164 );
19165 assert_eq!(
19166 m.nome(),
19167 m.caixa.as_str(),
19168 "Membro::nome must byte-equal the .caixa field access",
19169 );
19170 }
19171 }
19172
19173 #[test]
19174 fn membro_nome_borrows_from_caixa_storage() {
19175 // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
19176 // slice that borrows from the typed slot's own [`String`]
19177 // storage — same-address invariant with `m.caixa.as_str()`. Pins
19178 // against a future silent detour that allocated a fresh `String`
19179 // (`self.caixa.clone()` in the body would type-check but
19180 // silently drop the borrow, and every downstream consumer that
19181 // assumed the returned slice outlives `&self` would break on a
19182 // stale-reference use-after-free — the `HashSet<&str>` collector
19183 // at [`AplicacaoSpec::validate`]'s `names` seed, the
19184 // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
19185 // [`AplicacaoSpec::detect_sync_cycles`], the
19186 // [`crate::render::insert_first_seen`] dedup key at
19187 // [`AplicacaoSpec::validate_membros`] — each borrow from the
19188 // Membro's own storage and each would silently misbehave if
19189 // this accessor produced a detached copy). Peer of the sibling
19190 // per-`:contratos` [`WitContract::source`] /
19191 // [`WitContract::destination`] and per-`:entrada`
19192 // [`Entrada::destination`] borrow-invariant pins on the mesh-
19193 // slot-atom scalar-value axes.
19194 let m = Membro {
19195 caixa: "checkout".into(),
19196 versao: "^0.1".into(),
19197 };
19198 let name = m.nome();
19199 let caixa_slice = m.caixa.as_str();
19200 assert_eq!(
19201 name.as_ptr(),
19202 caixa_slice.as_ptr(),
19203 "Membro::nome must borrow from the .caixa String's backing \
19204 storage — a fresh allocation here means the accessor no \
19205 longer names the substrate-primitive typed dispatch and \
19206 every downstream consumer would silently carry a detached \
19207 copy",
19208 );
19209 assert_eq!(
19210 name.len(),
19211 caixa_slice.len(),
19212 "Membro::nome and .caixa.as_str() must byte-equal in length \
19213 as well as in address",
19214 );
19215 }
19216
19217 #[test]
19218 fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
19219 // The canonical per-`:membros` member-`:versao`-scalar pin:
19220 // [`Membro::versao_requirement`] must return the
19221 // `:membros :versao` field byte-for-byte, borrowed from the typed
19222 // slot's own [`String`] storage. Sibling of the peer
19223 // `membro_nome_returns_caixa_byte_equal_across_permutations`
19224 // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
19225 // — same "the substrate-primitive accessor must byte-equal the
19226 // raw field access verbatim across every author-declared value"
19227 // discipline extended to the per-`:membros` member-`:versao`
19228 // requirement-string arm. Pins against a future silent detour
19229 // that re-canonicalized the requirement (an accidental
19230 // `.to_string()` via [`parse_requirement`] → [`Display`] round-
19231 // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
19232 // drifted the printer output away from the source `caixa.lisp`,
19233 // an accidental whitespace trim on `"^ 0.1"` that no consumer
19234 // ever produced from the field-access side, an accidental
19235 // per-cluster lacre-projected concrete-version rewrite that
19236 // didn't land on the peer field-access sites). Five values sweep
19237 // the accept-set the shared
19238 // [`crate::render::require_valid_versao_requirement`] gate
19239 // admits (caret / tilde / exact / wildcard / bare-major).
19240 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
19241 let m = Membro {
19242 caixa: "cart".into(),
19243 versao: req.into(),
19244 };
19245 assert_eq!(
19246 m.versao_requirement(),
19247 req,
19248 "Membro::versao_requirement must return :membros :versao \
19249 verbatim (got {:?}, expected {req:?})",
19250 m.versao_requirement(),
19251 );
19252 assert_eq!(
19253 m.versao_requirement(),
19254 m.versao.as_str(),
19255 "Membro::versao_requirement must byte-equal the .versao \
19256 field access",
19257 );
19258 }
19259 }
19260
19261 #[test]
19262 fn membro_versao_requirement_borrows_from_versao_storage() {
19263 // The borrow-not-copy pin: [`Membro::versao_requirement`] must
19264 // return a `&str` slice that borrows from the typed slot's own
19265 // [`String`] storage — same-address invariant with
19266 // `m.versao.as_str()`. Pins against a future silent detour that
19267 // allocated a fresh `String` (`self.versao.clone()` in the body
19268 // would type-check but silently drop the borrow, and every
19269 // downstream consumer that assumed the returned slice outlives
19270 // `&self` would break on a stale-reference use-after-free). Peer
19271 // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
19272 // per-`:contratos` [`WitContract::source`] /
19273 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19274 // [`Entrada::destination`] (6db982c) borrow-invariant pins on
19275 // the mesh-slot-atom scalar-value axes.
19276 let m = Membro {
19277 caixa: "checkout".into(),
19278 versao: "^0.1".into(),
19279 };
19280 let req = m.versao_requirement();
19281 let versao_slice = m.versao.as_str();
19282 assert_eq!(
19283 req.as_ptr(),
19284 versao_slice.as_ptr(),
19285 "Membro::versao_requirement must borrow from the .versao \
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 carry \
19289 a detached copy",
19290 );
19291 assert_eq!(
19292 req.len(),
19293 versao_slice.len(),
19294 "Membro::versao_requirement and .versao.as_str() must byte-\
19295 equal in length as well as in address",
19296 );
19297 }
19298
19299 #[test]
19300 fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
19301 // Sibling-pair invariant pin composing both per-`:membros`
19302 // substrate-primitive typed dispatches — [`Membro::nome`]
19303 // (4a32abf) and [`Membro::versao_requirement`] — at the joint
19304 // `(nome(), versao_requirement())` call shape every renderer
19305 // that fans on per-member identity + version pin keys off. The
19306 // invariant, evaluated per-member:
19307 //
19308 // (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
19309 //
19310 // Closes the last unlifted per-`:membros` scalar axis — every
19311 // downstream consumer that reads the pair now routes through
19312 // exactly two typed dispatches on the substrate primitive, not
19313 // one typed + one open-coded field access. A future refactor
19314 // that silently split either accessor's projection (an
19315 // accidental `nome()` namespace-prefix rewrite that didn't
19316 // reach the peer, an accidental `versao_requirement()` lacre-
19317 // projected concrete-version rewrite that didn't land on the
19318 // `nome()` peer) surfaces at caixa-core build time. Peer of the
19319 // sibling per-`:entrada` `(hostname(), destination())` and
19320 // per-`:contratos` `(source(), destination())` pair invariants
19321 // on the mesh-slot-atom scalar-value axes.
19322 for (caixa, versao) in [
19323 ("cart", "^0.1"),
19324 ("checkout", "~0.1.2"),
19325 ("catalog", "0.1.0"),
19326 ("orders-v2", "*"),
19327 ] {
19328 let m = Membro {
19329 caixa: caixa.into(),
19330 versao: versao.into(),
19331 };
19332 assert_eq!(
19333 (m.nome(), m.versao_requirement()),
19334 (m.caixa.as_str(), m.versao.as_str()),
19335 "(Membro::nome, Membro::versao_requirement) must project \
19336 (.caixa, .versao) verbatim across every author-declared \
19337 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
19338 m.nome(),
19339 m.versao_requirement(),
19340 );
19341 }
19342 }
19343
19344 #[test]
19345 fn validate_membros_empty_gate_routes_through_nome_accessor() {
19346 // Composition pin: [`AplicacaoSpec::validate_membros`]'s
19347 // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
19348 // not the raw `.caixa` field access. Structurally: setting
19349 // ONLY the `.caixa` field to `""` on an otherwise-well-formed
19350 // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
19351 // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
19352 // (i.e. the empty string) — so the emptiness predicate the
19353 // refusal arm reaches under is the accessor-projected value,
19354 // not a peer field that would silently drift under a future
19355 // accessor-side rewrite.
19356 //
19357 // Pins against a future silent detour that (a) re-derived the
19358 // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
19359 // instead of `self.nome().is_empty()`, silently disagreeing with
19360 // every peer consumer (the `validate_membro_caixa(m.nome())`
19361 // call one line below, the dedup-key `insert_first_seen(&mut
19362 // seen, m.nome(), …)` two lines below, the emit-side per-
19363 // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
19364 // (b) accessor-side introduced a per-tenant alias arm the
19365 // caller was unaware of, silently rewriting an author-declared
19366 // `:caixa "checkout"` to `""` — the raw-field-access gate
19367 // would fail-open while the accessor-routed peer consumers
19368 // would fail-closed, splitting the diagnostic from the actual
19369 // failure surface.
19370 //
19371 // Peer of the sibling
19372 // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
19373 // (c0110f1) composition pin — same "the shape-gate predicate
19374 // must route through the substrate-primitive typed dispatch"
19375 // discipline extended onto the per-`:membros` empty-`:caixa`
19376 // refusal-arm axis. Closes the last unlifted `.caixa` production-
19377 // code read site on `Membro` — after this converge every
19378 // caixa-core `.caixa` field access outside the accessor's own
19379 // body is either a test-side field-setter (in-module tests
19380 // constructing invalid-shape inputs) or a doc-comment reference.
19381 let mut s = three_member_spec();
19382 s.membros[1].caixa = String::new();
19383 assert!(
19384 s.membros[1].nome().is_empty(),
19385 "Membro::nome must byte-equal the .caixa field access — an \
19386 accessor-side detour that no longer projects the raw field \
19387 would silently split this drift-detection test from the \
19388 validate() refusal arm",
19389 );
19390 assert_eq!(
19391 s.membros[1].nome(),
19392 s.membros[1].caixa.as_str(),
19393 "Membro::nome and .caixa.as_str() must byte-equal on an \
19394 empty-`:caixa` entry — the emptiness gate keys off the \
19395 accessor by construction",
19396 );
19397 assert_eq!(
19398 s.validate().unwrap_err(),
19399 AplicacaoError::MembroCaixaEmpty,
19400 "validate_membros' emptiness gate must fire MembroCaixaEmpty \
19401 on an entry whose accessor-projected `nome()` is empty",
19402 );
19403 }
19404
19405 #[test]
19406 fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
19407 // The canonical per-`:placement` Akka-cluster-sharding
19408 // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
19409 // the `:placement :shard-key` field byte-for-byte, borrowed
19410 // from the typed slot's own `Option<String>` storage. Peer of
19411 // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
19412 // per-`:contratos` [`WitContract::source`] /
19413 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
19414 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
19415 // slot-atom scalar-value axes — same "the substrate-primitive
19416 // accessor must byte-equal the raw field access verbatim across
19417 // every author-declared value" discipline extended to the
19418 // per-`:placement` Akka-cluster-sharding key extractor arm.
19419 // Pins against a future silent detour that re-normalized the
19420 // key (an accidental `.to_lowercase()` — every non-empty
19421 // `:shard-key` is validated as a printable-ASCII single-token
19422 // reference upstream via [`validate_placement_shard_key`], so
19423 // any re-normalization is redundant + a drift surface between
19424 // the validator and the accessor), a per-cluster alias rewrite
19425 // the operator authors on one consumer without the other, or an
19426 // accidental variable-prefix strip (`$tenantId` → `tenantId`)
19427 // that didn't land on the peer field-access sites. Four values
19428 // sweep the accept-set the shape gate admits — bare identifier,
19429 // `$`-prefixed variable, dotted path, `${}`-quoted variable —
19430 // the four canonical Akka-style entity-id extractor shapes the
19431 // future M4 cluster-sharding reconciler hashes.
19432 for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
19433 let p = Placement {
19434 estrategia: PlacementStrategy::Sharded,
19435 clusters: vec!["rio".into()],
19436 affinity: None,
19437 shard_key: Some(key.into()),
19438 };
19439 assert_eq!(
19440 p.shard_key(),
19441 Some(key),
19442 "Placement::shard_key must return :placement :shard-key \
19443 verbatim (got {:?}, expected Some({key:?}))",
19444 p.shard_key(),
19445 );
19446 assert_eq!(
19447 p.shard_key(),
19448 p.shard_key.as_deref(),
19449 "Placement::shard_key must byte-equal the .shard_key \
19450 field's `.as_deref()` projection",
19451 );
19452 }
19453 }
19454
19455 #[test]
19456 fn placement_shard_key_none_when_field_is_none() {
19457 // The absent-`:shard-key` arm of the per-`:placement`
19458 // Akka-cluster-sharding accessor pin: when the typed slot is
19459 // absent — the canonical shape under `:estrategia Replicated` /
19460 // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
19461 // enforced `shard_key.is_some() == matches!(estrategia,
19462 // Sharded)` partition — [`Placement::shard_key`] must return
19463 // `None`. Pins against a future silent detour that projected
19464 // the absent slot to a `Some("")` empty-string default (the
19465 // canonical `Option<String>` → `String` collapse footgun the
19466 // sibling M2 [`crate::LimitsSpec::is_empty`] /
19467 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
19468 // already guard on the peer M2 typed-slot surfaces), a
19469 // `Some("None")` stringified-None round-trip, or a `Some` arm
19470 // whose contents were derived from a sibling slot (an
19471 // accidental fallback to `estrategia.as_str()` that read the
19472 // strategy discriminator into the key axis). Two placements
19473 // sweep the accept-set every `validate`-passing non-`Sharded`
19474 // shape lands on — `Replicated` (Erlang/OTP distributed-app
19475 // takeover) and `SingleNode` (single-node hosting).
19476 for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
19477 let p = Placement {
19478 estrategia,
19479 clusters: vec!["rio".into()],
19480 affinity: None,
19481 shard_key: None,
19482 };
19483 assert!(
19484 p.shard_key().is_none(),
19485 "Placement::shard_key must return None when the typed \
19486 slot is absent under :estrategia {estrategia:?} (got {:?})",
19487 p.shard_key(),
19488 );
19489 assert_eq!(
19490 p.shard_key(),
19491 p.shard_key.as_deref(),
19492 "Placement::shard_key must byte-equal the .shard_key \
19493 field's `.as_deref()` projection in the absent arm",
19494 );
19495 }
19496 }
19497
19498 #[test]
19499 fn placement_shard_key_borrows_from_shard_key_storage() {
19500 // The borrow-not-copy pin: [`Placement::shard_key`] must return
19501 // an `Option<&str>` whose `Some` arm borrows from the typed
19502 // slot's own [`String`] storage — same-address invariant with
19503 // `p.shard_key.as_deref().unwrap()`. Pins against a future
19504 // silent detour that allocated a fresh `String`
19505 // (`self.shard_key.clone().map(...)` in the body would type-
19506 // check but silently drop the borrow, and every downstream
19507 // consumer that assumed the returned slice outlives `&self`
19508 // would break on a stale-reference use-after-free — the
19509 // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
19510 // gate's `Some(k)`-bound match arm reads `k: &str` under the
19511 // accessor's return type and would silently misbehave if this
19512 // accessor produced a detached copy). Peer of the sibling
19513 // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
19514 // [`WitContract::source`] / [`WitContract::destination`]
19515 // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
19516 // (6db982c) borrow-invariant pins on the mesh-slot-atom
19517 // scalar-value axes — first extension of the discipline onto
19518 // an `Option<String>`-shaped optional-scalar axis.
19519 let p = Placement {
19520 estrategia: PlacementStrategy::Sharded,
19521 clusters: vec!["rio".into()],
19522 affinity: None,
19523 shard_key: Some("tenantId".into()),
19524 };
19525 let key = p.shard_key().expect("Some arm");
19526 let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
19527 assert_eq!(
19528 key.as_ptr(),
19529 storage_slice.as_ptr(),
19530 "Placement::shard_key must borrow from the .shard_key \
19531 String's backing storage — a fresh allocation here means \
19532 the accessor no longer names the substrate-primitive typed \
19533 dispatch and every downstream consumer would silently \
19534 carry a detached copy",
19535 );
19536 assert_eq!(
19537 key.len(),
19538 storage_slice.len(),
19539 "Placement::shard_key and .shard_key.as_deref() must byte-\
19540 equal in length as well as in address",
19541 );
19542 }
19543
19544 #[test]
19545 fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
19546 // The canonical per-`:placement` M3-Adaptive-compression-hint
19547 // scalar pin: [`Placement::affinity`] must return the
19548 // `:placement :affinity` field byte-for-byte, borrowed from the
19549 // typed slot's own `Option<String>` storage. Peer of the sibling
19550 // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
19551 // pin on the sibling `Option<&str>` optional-scalar axis — same
19552 // "the substrate-primitive accessor must byte-equal the raw
19553 // field access verbatim across every author-declared value"
19554 // discipline extended to the peer per-`:placement` M3-Adaptive-
19555 // compression-hint arm. Pins against a future silent detour
19556 // that re-normalized the hint (an accidental `.to_lowercase()`
19557 // — every `:affinity` is already validated as a DNS-1123 label
19558 // upstream via [`validate_placement_affinity`], so any re-
19559 // normalization is redundant + a drift surface between the
19560 // validator and the accessor), a per-cluster alias rewrite the
19561 // operator authors on one consumer without the other, or an
19562 // accidental hint-family collapse (`low-latency` → `latency`
19563 // that dropped the qualifier prefix). Four values sweep the
19564 // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
19565 // canonical adaptive-compression-weight biases the future M4
19566 // placement engine reads.
19567 for hint in [
19568 "data-locality",
19569 "low-latency",
19570 "high-throughput",
19571 "cost-optimized",
19572 ] {
19573 let p = Placement {
19574 estrategia: PlacementStrategy::Replicated,
19575 clusters: vec!["rio".into()],
19576 affinity: Some(hint.into()),
19577 shard_key: None,
19578 };
19579 assert_eq!(
19580 p.affinity(),
19581 Some(hint),
19582 "Placement::affinity must return :placement :affinity \
19583 verbatim (got {:?}, expected Some({hint:?}))",
19584 p.affinity(),
19585 );
19586 assert_eq!(
19587 p.affinity(),
19588 p.affinity.as_deref(),
19589 "Placement::affinity must byte-equal the .affinity \
19590 field's `.as_deref()` projection",
19591 );
19592 }
19593 }
19594
19595 #[test]
19596 fn placement_affinity_none_when_field_is_none() {
19597 // The absent-`:affinity` arm of the per-`:placement`
19598 // M3-Adaptive-compression-hint accessor pin: when the typed
19599 // slot is absent — the canonical shape of an Aplicacao that
19600 // leaves the compression weighting up to the placement engine's
19601 // cluster-default arm — [`Placement::affinity`] must return
19602 // `None`. Pins against a future silent detour that projected
19603 // the absent slot to a `Some("")` empty-string default (the
19604 // canonical `Option<String>` → `String` collapse footgun the
19605 // sibling M2 [`crate::LimitsSpec::is_empty`] /
19606 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
19607 // already guard on the peer M2 typed-slot surfaces), a
19608 // `Some("None")` stringified-None round-trip, a `Some` arm
19609 // whose contents were derived from a sibling slot (an
19610 // accidental fallback to `estrategia.as_str()` that read the
19611 // strategy discriminator into the hint axis), or a
19612 // `Some("default")` implicit-default that would silently biases
19613 // the routing without the author having written one. Three
19614 // placements sweep the accept-set every `validate`-passing
19615 // `:affinity None` shape lands on — one per PlacementStrategy
19616 // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
19617 // with a shard-key), since `:affinity` is orthogonal to
19618 // `:estrategia` in the typed grammar.
19619 for (estrategia, shard_key) in [
19620 (PlacementStrategy::SingleNode, None),
19621 (PlacementStrategy::Replicated, None),
19622 (PlacementStrategy::Sharded, Some("tenantId".to_string())),
19623 ] {
19624 let p = Placement {
19625 estrategia,
19626 clusters: vec!["rio".into()],
19627 affinity: None,
19628 shard_key,
19629 };
19630 assert!(
19631 p.affinity().is_none(),
19632 "Placement::affinity must return None when the typed \
19633 slot is absent under :estrategia {estrategia:?} (got {:?})",
19634 p.affinity(),
19635 );
19636 assert_eq!(
19637 p.affinity(),
19638 p.affinity.as_deref(),
19639 "Placement::affinity must byte-equal the .affinity \
19640 field's `.as_deref()` projection in the absent arm",
19641 );
19642 }
19643 }
19644
19645 #[test]
19646 fn placement_affinity_borrows_from_affinity_storage() {
19647 // The borrow-not-copy pin: [`Placement::affinity`] must return
19648 // an `Option<&str>` whose `Some` arm borrows from the typed
19649 // slot's own [`String`] storage — same-address invariant with
19650 // `p.affinity.as_deref().unwrap()`. Pins against a future
19651 // silent detour that allocated a fresh `String`
19652 // (`self.affinity.clone().map(...)` in the body would type-
19653 // check but silently drop the borrow, and every downstream
19654 // consumer that assumed the returned slice outlives `&self`
19655 // would break on a stale-reference use-after-free — the
19656 // [`AplicacaoSpec::validate_placement`] per-hint value-shape
19657 // gate reads the accessor's `&str` return through the
19658 // [`validate_placement_affinity`] `&str` parameter and would
19659 // silently misbehave if this accessor produced a detached
19660 // copy). Peer of the sibling per-`:placement`
19661 // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
19662 // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
19663 // extends the discipline onto the sibling per-`:placement`
19664 // M3-Adaptive-compression-hint arm.
19665 let p = Placement {
19666 estrategia: PlacementStrategy::Replicated,
19667 clusters: vec!["rio".into()],
19668 affinity: Some("data-locality".into()),
19669 shard_key: None,
19670 };
19671 let hint = p.affinity().expect("Some arm");
19672 let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
19673 assert_eq!(
19674 hint.as_ptr(),
19675 storage_slice.as_ptr(),
19676 "Placement::affinity must borrow from the .affinity \
19677 String's backing storage — a fresh allocation here means \
19678 the accessor no longer names the substrate-primitive typed \
19679 dispatch and every downstream consumer would silently \
19680 carry a detached copy",
19681 );
19682 assert_eq!(
19683 hint.len(),
19684 storage_slice.len(),
19685 "Placement::affinity and .affinity.as_deref() must byte-\
19686 equal in length as well as in address",
19687 );
19688 }
19689
19690 #[test]
19691 fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
19692 // The canonical per-`:placement` distribution-strategy-scalar
19693 // pin: [`Placement::estrategia`] must return the `:placement
19694 // :estrategia` field verbatim as a [`PlacementStrategy`],
19695 // `Copy`-projected from the typed slot's own `PlacementStrategy`
19696 // storage across every variant in the closed accept-set
19697 // (`SingleNode` — Erlang/OTP distributed-app takeover;
19698 // `Replicated` — active-active across every named cluster;
19699 // `Sharded` — Akka-style hash-keyed entity distribution). Pins
19700 // against a future silent detour that re-derived the strategy
19701 // from a peer axis (an accidental fallback to
19702 // `if shard_key.is_some() { Sharded } else { Replicated }`
19703 // collapse that read the shard-key axis into the strategy
19704 // discriminator), a variant remap the operator authors on one
19705 // consumer without the other, or a stale-derive detour that
19706 // substituted [`PlacementStrategy::default`] when the field
19707 // held any explicit variant (which would silently collapse the
19708 // distinction between "author explicitly declared `:estrategia
19709 // Replicated`" and "author omitted the slot and inherited the
19710 // default" the future per-cluster override slot depends on).
19711 // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
19712 // pin on the `Copy`-return `u16` scalar axis — same "the
19713 // substrate-primitive accessor must byte-equal the raw field
19714 // access verbatim across every author-declared value" discipline
19715 // extended onto the per-`:placement` distribution-strategy
19716 // `Copy`-composite-enum scalar axis.
19717 for estrategia in [
19718 PlacementStrategy::SingleNode,
19719 PlacementStrategy::Replicated,
19720 PlacementStrategy::Sharded,
19721 ] {
19722 let shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
19723 let p = Placement {
19724 estrategia,
19725 clusters: vec!["rio".into()],
19726 affinity: None,
19727 shard_key,
19728 };
19729 assert_eq!(
19730 p.estrategia(),
19731 estrategia,
19732 "Placement::estrategia must return :placement :estrategia \
19733 verbatim (got {:?}, expected {estrategia:?})",
19734 p.estrategia(),
19735 );
19736 assert_eq!(
19737 p.estrategia(),
19738 p.estrategia,
19739 "Placement::estrategia accessor and .estrategia field \
19740 access must byte-equal — the accessor is the substrate-\
19741 primitive typed dispatch every downstream distribution-\
19742 strategy consumer must route through",
19743 );
19744 }
19745 }
19746
19747 #[test]
19748 fn validate_placement_reads_through_lifted_estrategia_accessor() {
19749 // Three-consumer coherence pin: the
19750 // [`AplicacaoSpec::validate_placement`]
19751 // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
19752 // `estrategia:` field (which reads through
19753 // [`Placement::estrategia`] to name the strategy the empty
19754 // `:clusters` list was declared against), the same method's
19755 // `Sharded ↔ non-Sharded` `match` partition dispatch (which
19756 // reads through [`Placement::estrategia`] to fan across the
19757 // shape-gate cascades), and the non-`Sharded`-arm
19758 // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
19759 // `estrategia:` field (which reads through
19760 // [`Placement::estrategia`] to name the strategy the declared-
19761 // but-inert `:shard-key` was authored under) must all key off
19762 // the lifted accessor, so any future rebrand on the typed
19763 // slot's reader shape lands at exactly one place. Pins the
19764 // three-site coherence by exercising each error surface end-
19765 // to-end and asserting the surfaced `estrategia:` field byte-
19766 // equals the accessor's return. Peer of the sibling per-
19767 // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
19768 // pin on the M3 mesh-slot `Copy`-return scalar axis.
19769
19770 // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
19771 // whose `estrategia:` field must byte-equal the accessor's return
19772 // for every variant in the closed accept-set.
19773 for estrategia in [
19774 PlacementStrategy::SingleNode,
19775 PlacementStrategy::Replicated,
19776 PlacementStrategy::Sharded,
19777 ] {
19778 let mut spec = three_member_spec();
19779 spec.placement.estrategia = estrategia;
19780 spec.placement.clusters = Vec::new();
19781 spec.placement.shard_key = estrategia.is_sharded().then(|| "tenantId".to_string());
19782 let err = spec.validate().unwrap_err();
19783 match err {
19784 AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
19785 assert_eq!(
19786 e,
19787 spec.placement.estrategia(),
19788 "PlacementWithoutClusters.estrategia must byte-equal \
19789 Placement::estrategia() — the error carrier reads \
19790 through the lifted accessor",
19791 );
19792 }
19793 other => panic!(
19794 "expected PlacementWithoutClusters, got {other:?} for \
19795 estrategia={estrategia:?}"
19796 ),
19797 }
19798 }
19799
19800 // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
19801 // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
19802 // must byte-equal the accessor's return for both non-`Sharded`
19803 // strategies.
19804 for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
19805 let mut spec = three_member_spec();
19806 spec.placement.estrategia = estrategia;
19807 spec.placement.shard_key = Some("tenantId".into());
19808 let err = spec.validate().unwrap_err();
19809 match err {
19810 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
19811 assert_eq!(
19812 e,
19813 spec.placement.estrategia(),
19814 "ShardKeyOnNonSharded.estrategia must byte-equal \
19815 Placement::estrategia() — the non-Sharded-arm \
19816 refusal reads through the lifted accessor",
19817 );
19818 }
19819 other => panic!(
19820 "expected ShardKeyOnNonSharded, got {other:?} for \
19821 estrategia={estrategia:?}"
19822 ),
19823 }
19824 }
19825 }
19826
19827 // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
19828 //
19829 // The [`Placement::clusters`] accessor lift is the second slice-return
19830 // (`&[T]`) accessor on any typed slot — sibling to the seed M2
19831 // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
19832 // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
19833 // below cover (1) the accessor's byte-equal projection against the raw
19834 // field access across the empty / singleton / cohort fixtures the
19835 // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
19836 // and the per-cluster validate loop fan between, and (2) the two-
19837 // consumer coherence of the paired pre-flight refusal probe and the
19838 // per-cluster validate loop routing through the accessor on both arms.
19839
19840 #[test]
19841 fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
19842 // The canonical per-`:placement` cluster-pool-scalar-shape pin:
19843 // [`Placement::clusters`] must return the `:placement :clusters`
19844 // typed `Vec<String>` verbatim as a `&[String]` slice-view over
19845 // the same backing buffer the raw `self.clusters.as_slice()`
19846 // field access borrows from, byte-equal across every
19847 // representative fixture in the accept-set — the empty slice
19848 // (the pre-validation sentinel every
19849 // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
19850 // the singleton slice (the minimal `SingleNode`-shape cohort),
19851 // and multi-entry cohorts (the peer `Replicated` / `Sharded`
19852 // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
19853 //
19854 // Pins against a future silent detour that returned
19855 // `&Vec<String>` (which would type-check but leak the storage-
19856 // side `Vec`'s grow/push/reserve surface no consumer of the
19857 // typed view reaches for), a fresh-allocated `Vec<String>` copy
19858 // (which would type-check via a coercion but silently break
19859 // every downstream caller that relied on the slice sharing the
19860 // backing buffer's identity), or an out-of-order or length-
19861 // drifted projection (which would silently split the paired
19862 // pre-flight `.is_empty()` refusal probe's input from the per-
19863 // cluster validate loop's traversal input).
19864 //
19865 // Peer of the sibling M2
19866 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
19867 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
19868 // `:supervisor` static-child-list axis, extended onto the M3
19869 // per-`:placement` distribution-target-list `Vec`-carry axis.
19870 let fixtures: Vec<Vec<String>> = vec![
19871 Vec::new(),
19872 vec!["rio".into()],
19873 vec!["rio".into(), "mar".into()],
19874 vec!["rio".into(), "mar".into(), "plo".into()],
19875 ];
19876 for clusters in fixtures {
19877 let p = Placement {
19878 clusters: clusters.clone(),
19879 ..Placement::default()
19880 };
19881 assert_eq!(
19882 p.clusters(),
19883 clusters.as_slice(),
19884 "Placement::clusters must return :placement :clusters \
19885 verbatim (got {:?}, expected {:?})",
19886 p.clusters(),
19887 clusters.as_slice(),
19888 );
19889 assert_eq!(
19890 p.clusters(),
19891 p.clusters.as_slice(),
19892 "Placement::clusters accessor and .clusters.as_slice() \
19893 field access must byte-equal — the accessor is the \
19894 substrate-primitive typed dispatch every downstream \
19895 cluster-pool consumer must route through",
19896 );
19897 assert_eq!(
19898 p.clusters().len(),
19899 p.clusters.len(),
19900 "Placement::clusters().len() must byte-equal \
19901 self.clusters.len() — a length-drift would silently \
19902 split the paired pre-flight `.is_empty()` refusal \
19903 probe input from the per-cluster validate loop's \
19904 traversal input",
19905 );
19906 }
19907 }
19908
19909 #[test]
19910 fn validate_placement_reads_through_lifted_clusters_accessor() {
19911 // Two-consumer coherence pin: the
19912 // [`AplicacaoSpec::validate_placement`] pre-flight
19913 // `self.placement.clusters().is_empty()` refusal probe (which
19914 // must trip [`AplicacaoError::PlacementWithoutClusters`] when
19915 // the accessor projects the empty slice) and the per-cluster
19916 // validate loop's `for c in self.placement.clusters()`
19917 // traversal (which must reach every entry in the same order
19918 // the accessor projects, so both the per-entry value-shape
19919 // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
19920 // and the duplicate-detection HashSet insert that trips
19921 // [`AplicacaoError::PlacementClusterDuplicate`] key off the
19922 // accessor's projection) must both key off the lifted
19923 // accessor, so any future rebrand on the typed slot's reader
19924 // shape lands at exactly one place. Pins the two-site
19925 // coherence by exercising each production consumer end-to-end:
19926 // (1) the `PlacementWithoutClusters` refusal under the empty
19927 // slice, (2) the `PlacementClusterInvalid` refusal fires on
19928 // the second entry of a two-cluster cohort whose head is
19929 // valid but tail is not (which requires the loop to reach the
19930 // second entry through the accessor), and (3) the
19931 // `PlacementClusterDuplicate` refusal fires on the second
19932 // entry of a two-cluster cohort that shares a name (which
19933 // requires the loop to reach both entries — a first-entry-only
19934 // projection would silently pass since the dedup HashSet has
19935 // room for the first insert).
19936 //
19937 // Peer of the sibling M2
19938 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
19939 // (bc92bce) coherence pin on the per-`:supervisor` static-
19940 // child-list axis, extended onto the M3 per-`:placement`
19941 // distribution-target-list `Vec`-carry axis.
19942
19943 // (1) Pre-flight `.is_empty()` probe: the empty slice must
19944 // trip `PlacementWithoutClusters`.
19945 let mut spec = three_member_spec();
19946 spec.placement.clusters = Vec::new();
19947 match spec.validate().unwrap_err() {
19948 AplicacaoError::PlacementWithoutClusters { .. } => {}
19949 other => panic!("expected PlacementWithoutClusters, got {other:?}"),
19950 }
19951 assert!(
19952 spec.placement.clusters().is_empty(),
19953 "the pre-flight refusal input must be the empty slice per \
19954 the accessor's projection",
19955 );
19956
19957 // (2) Per-cluster validate loop: a two-cluster cohort with an
19958 // invalid tail entry must trip `PlacementClusterInvalid` on
19959 // the tail — the loop must reach the second entry through
19960 // the accessor.
19961 let mut spec = three_member_spec();
19962 spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
19963 match spec.validate().unwrap_err() {
19964 AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
19965 assert_eq!(
19966 cluster, "BAD_CLUSTER",
19967 "PlacementClusterInvalid.cluster must carry the \
19968 tail entry the loop reached through the accessor",
19969 );
19970 }
19971 other => panic!("expected PlacementClusterInvalid, got {other:?}"),
19972 }
19973 assert_eq!(
19974 spec.placement.clusters().len(),
19975 2,
19976 "the per-cluster validate loop's traversal input must be \
19977 a two-element slice per the accessor's projection",
19978 );
19979
19980 // (3) Per-cluster validate loop: a two-cluster cohort that
19981 // shares a name must trip `PlacementClusterDuplicate` on the
19982 // second entry — the loop must reach both entries through the
19983 // accessor for the dedup HashSet's second insert to collide.
19984 let mut spec = three_member_spec();
19985 spec.placement.clusters = vec!["rio".into(), "rio".into()];
19986 match spec.validate().unwrap_err() {
19987 AplicacaoError::PlacementClusterDuplicate { cluster } => {
19988 assert_eq!(
19989 cluster, "rio",
19990 "PlacementClusterDuplicate.cluster must carry the \
19991 shared cluster name verbatim",
19992 );
19993 }
19994 other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
19995 }
19996 assert_eq!(
19997 spec.placement.clusters().len(),
19998 2,
19999 "the per-cluster validate loop's traversal input must be \
20000 a two-element slice per the accessor's projection",
20001 );
20002 }
20003
20004 #[test]
20005 fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
20006 // The canonical per-`:membros` member-list-slice-shape pin:
20007 // [`AplicacaoSpec::membros`] must return the `:membros` typed
20008 // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
20009 // same backing buffer the raw `self.membros.as_slice()` field
20010 // access borrows from, byte-equal across every representative
20011 // fixture in the accept-set — the empty slice (the pre-
20012 // validation sentinel every [`AplicacaoError::NoMembros`]
20013 // refusal keys off), the singleton slice (the minimal one-
20014 // Servico Aplicacao shape), and multi-entry cohorts (the peer
20015 // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
20016 // load-bearing identity of the application graph).
20017 //
20018 // Pins against a future silent detour that returned
20019 // `&Vec<Membro>` (which would type-check but leak the storage-
20020 // side `Vec`'s grow/push/reserve surface no consumer of the
20021 // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
20022 // (which would type-check via a coercion but silently break
20023 // every downstream caller that relied on the slice sharing the
20024 // backing buffer's identity), or an out-of-order or length-
20025 // drifted projection (which would silently split the paired
20026 // `HashSet<&str>` name-set seed's collect input from the
20027 // pre-flight `.is_empty()` refusal probe's input from the per-
20028 // member validate loop's traversal input from the
20029 // programs.yaml emitter's per-entry fan-out loop's input from
20030 // the `feira app graph` per-member print traversal's input).
20031 //
20032 // Peer of the sibling M2
20033 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
20034 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
20035 // `:supervisor` static-child-list axis and the sibling M3
20036 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20037 // (a6e18d7) `&[String]` byte-equal pin on the per-
20038 // `:placement` distribution-target-list axis — extends the
20039 // slice-return-accessor byte-equal-projection discipline onto
20040 // the outermost M3 mesh-slot type's per-Aplicacao member-list
20041 // `Vec`-carry axis.
20042 let fixtures: Vec<Vec<Membro>> = vec![
20043 Vec::new(),
20044 vec![membro("catalog", "^0.1")],
20045 vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20046 vec![
20047 membro("catalog", "^0.1"),
20048 membro("cart", "^0.1"),
20049 membro("payment", "^0.2"),
20050 ],
20051 ];
20052 for membros in fixtures {
20053 let s = AplicacaoSpec {
20054 membros: membros.clone(),
20055 contratos: Vec::new(),
20056 politicas: MeshPolicy::default(),
20057 placement: Placement::default(),
20058 entrada: None,
20059 };
20060 assert_eq!(
20061 s.membros(),
20062 membros.as_slice(),
20063 "AplicacaoSpec::membros must return :membros verbatim \
20064 (got {:?}, expected {:?})",
20065 s.membros(),
20066 membros.as_slice(),
20067 );
20068 assert_eq!(
20069 s.membros(),
20070 s.membros.as_slice(),
20071 "AplicacaoSpec::membros accessor and .membros.as_slice() \
20072 field access must byte-equal — the accessor is the \
20073 substrate-primitive typed dispatch every downstream \
20074 member-list consumer must route through",
20075 );
20076 assert_eq!(
20077 s.membros().len(),
20078 s.membros.len(),
20079 "AplicacaoSpec::membros().len() must byte-equal \
20080 self.membros.len() — a length-drift would silently \
20081 split the paired `HashSet<&str>` name-set seed's \
20082 collect input from the pre-flight `.is_empty()` \
20083 refusal probe input from the per-member validate \
20084 loop's traversal input",
20085 );
20086 }
20087 }
20088
20089 #[test]
20090 fn validate_reads_through_lifted_membros_accessor() {
20091 // Three-consumer coherence pin: the
20092 // [`AplicacaoSpec::validate_membros`] pre-flight
20093 // `self.membros().is_empty()` refusal probe (which must trip
20094 // [`AplicacaoError::NoMembros`] when the accessor projects the
20095 // empty slice), the same method's per-member validate loop's
20096 // `for m in self.membros()` traversal (which must reach every
20097 // entry in the same order the accessor projects, so both the
20098 // per-entry empty-`:caixa` gate that trips
20099 // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
20100 // detection `insert_first_seen` that trips
20101 // [`AplicacaoError::MembroDuplicate`] key off the accessor's
20102 // projection), and the peer [`AplicacaoSpec::validate`]'s
20103 // `HashSet<&str>` name-set seed's
20104 // `self.membros().iter().map(Membro::nome).collect()` collect
20105 // input (which every `:contratos` `:de` / `:para` membership
20106 // lookup rejects an unknown name against) must all three key
20107 // off the lifted accessor, so any future rebrand on the typed
20108 // slot's reader shape lands at exactly one place. Pins the
20109 // three-site coherence by exercising each production consumer
20110 // end-to-end: (1) the `NoMembros` refusal under the empty
20111 // slice, (2) the `MembroCaixaEmpty` refusal fires on the
20112 // second entry of a two-member cohort whose head is valid but
20113 // tail has an empty `:caixa` (which requires the loop to
20114 // reach the second entry through the accessor), and (3) the
20115 // `MembroDuplicate` refusal fires on the second entry of a
20116 // two-member cohort that shares a `:caixa` name (which
20117 // requires the loop to reach both entries through the
20118 // accessor for the dedup HashSet's second insert to collide).
20119 //
20120 // Peer of the sibling M2
20121 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
20122 // (bc92bce) coherence pin on the per-`:supervisor` static-
20123 // child-list axis and the sibling M3
20124 // `validate_placement_reads_through_lifted_clusters_accessor`
20125 // (a6e18d7) coherence pin on the per-`:placement` distribution-
20126 // target-list axis — extends the slice-return-accessor
20127 // multi-consumer coherence discipline onto the outermost M3
20128 // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
20129
20130 // (1) Pre-flight `.is_empty()` probe: the empty slice must
20131 // trip `NoMembros`.
20132 let mut spec = three_member_spec();
20133 spec.membros = Vec::new();
20134 assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
20135 assert!(
20136 spec.membros().is_empty(),
20137 "the pre-flight refusal input must be the empty slice per \
20138 the accessor's projection",
20139 );
20140
20141 // (2) Per-member validate loop: a two-member cohort with an
20142 // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
20143 // the tail — the loop must reach the second entry through
20144 // the accessor.
20145 let mut spec = three_member_spec();
20146 spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
20147 assert_eq!(
20148 spec.validate().unwrap_err(),
20149 AplicacaoError::MembroCaixaEmpty,
20150 );
20151 assert_eq!(
20152 spec.membros().len(),
20153 2,
20154 "the per-member validate loop's traversal input must be \
20155 a two-element slice per the accessor's projection",
20156 );
20157
20158 // (3) Per-member validate loop: a two-member cohort that
20159 // shares a `:caixa` name must trip `MembroDuplicate` on the
20160 // second entry — the loop must reach both entries through the
20161 // accessor for the dedup HashSet's second insert to collide.
20162 let mut spec = three_member_spec();
20163 spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
20164 match spec.validate().unwrap_err() {
20165 AplicacaoError::MembroDuplicate { caixa } => {
20166 assert_eq!(
20167 caixa, "catalog",
20168 "MembroDuplicate.caixa must carry the shared \
20169 member name verbatim",
20170 );
20171 }
20172 other => panic!("expected MembroDuplicate, got {other:?}"),
20173 }
20174 assert_eq!(
20175 spec.membros().len(),
20176 2,
20177 "the per-member validate loop's traversal input must be \
20178 a two-element slice per the accessor's projection",
20179 );
20180 }
20181
20182 #[test]
20183 fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
20184 // The canonical per-`:contratos` contract-list-slice-shape pin:
20185 // [`AplicacaoSpec::contratos`] must return the `:contratos`
20186 // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
20187 // slice-view over the same backing buffer the raw
20188 // `self.contratos.as_slice()` field access borrows from, byte-
20189 // equal across every representative fixture in the accept-set —
20190 // the empty slice (the pre-validation "internal-only mesh" shape
20191 // an Aplicacao whose members exchange no typed edges renders
20192 // through), the singleton slice (the minimal one-edge Aplicacao
20193 // shape), and multi-entry cohorts (the peer multi-edge shapes
20194 // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
20195 // of the application graph).
20196 //
20197 // Pins against a future silent detour that returned
20198 // `&Vec<WitContract>` (which would type-check but leak the
20199 // storage-side `Vec`'s grow/push/reserve surface no consumer of
20200 // the typed view reaches for), a fresh-allocated
20201 // `Vec<WitContract>` copy (which would type-check via a coercion
20202 // but silently break every downstream caller that relied on the
20203 // slice sharing the backing buffer's identity), or an out-of-
20204 // order or length-drifted projection (which would silently split
20205 // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
20206 // seed's traversal input from the `detect_sync_cycles` per-edge
20207 // adjacency-list seed's traversal input from the
20208 // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
20209 // BTreeMap grouping loop's traversal input from the
20210 // `feira app graph` per-contract print traversal's input).
20211 //
20212 // Peer of the immediately-adjacent sibling M3
20213 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
20214 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
20215 // node-list axis, the sibling M3
20216 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20217 // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
20218 // distribution-target-list axis, and the sibling M2
20219 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
20220 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
20221 // `:supervisor` static-child-list axis — extends the slice-
20222 // return-accessor byte-equal-projection discipline onto the
20223 // outermost M3 mesh-slot type's per-Aplicacao contract-list
20224 // `Vec`-carry axis, closing the last unlifted per-
20225 // `AplicacaoSpec` `Vec`-carry axis.
20226 let fixtures: Vec<Vec<WitContract>> = vec![
20227 Vec::new(),
20228 vec![contract_http("cart", "catalog", "/products/:id")],
20229 vec![
20230 contract_http("cart", "catalog", "/products/:id"),
20231 contract_http("cart", "payment", "/charge"),
20232 ],
20233 vec![
20234 contract_http("cart", "catalog", "/products/:id"),
20235 contract_http("cart", "payment", "/charge"),
20236 contract_http("payment", "catalog", "/audit"),
20237 ],
20238 ];
20239 for contratos in fixtures {
20240 let s = AplicacaoSpec {
20241 membros: vec![
20242 membro("catalog", "^0.1"),
20243 membro("cart", "^0.1"),
20244 membro("payment", "^0.2"),
20245 ],
20246 contratos: contratos.clone(),
20247 politicas: MeshPolicy::default(),
20248 placement: Placement::default(),
20249 entrada: None,
20250 };
20251 assert_eq!(
20252 s.contratos(),
20253 contratos.as_slice(),
20254 "AplicacaoSpec::contratos must return :contratos verbatim \
20255 (got {:?}, expected {:?})",
20256 s.contratos(),
20257 contratos.as_slice(),
20258 );
20259 assert_eq!(
20260 s.contratos(),
20261 s.contratos.as_slice(),
20262 "AplicacaoSpec::contratos accessor and \
20263 .contratos.as_slice() field access must byte-equal — \
20264 the accessor is the substrate-primitive typed dispatch \
20265 every downstream contract-list consumer must route \
20266 through",
20267 );
20268 assert_eq!(
20269 s.contratos().len(),
20270 s.contratos.len(),
20271 "AplicacaoSpec::contratos().len() must byte-equal \
20272 self.contratos.len() — a length-drift would silently \
20273 split the paired per-edge validate-loop's traversal \
20274 input from the sync-cycle adjacency-list seed's \
20275 traversal input from the cilium_network_policies \
20276 per-`(:de, :para)` BTreeMap grouping loop's traversal \
20277 input from the `feira app graph` per-contract print \
20278 traversal's input",
20279 );
20280 }
20281 }
20282
20283 #[test]
20284 fn validate_reads_through_lifted_contratos_accessor() {
20285 // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
20286 // per-`:contratos` validate-loop's `for c in self.contratos()`
20287 // traversal (which must reach every entry in the same order the
20288 // accessor projects, so both the per-entry
20289 // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
20290 // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
20291 // dedup `HashSet` insert key off the accessor's projection),
20292 // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
20293 // `for c in self.contratos()` adjacency-list seed (which drives
20294 // the sync-subgraph deadlock-detection gate via
20295 // [`AplicacaoError::SyncCycle`]), and the peer
20296 // [`caixa_mesh::cilium_network_policies`]'s
20297 // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
20298 // grouping loop (which drives the per-CNP fan-out) must all
20299 // three key off the lifted accessor, so any future rebrand on
20300 // the typed slot's reader shape lands at exactly one place. Pins
20301 // the three-site coherence by exercising the two caixa-core
20302 // production consumers end-to-end: (1) the empty-`:contratos`
20303 // slice must validate without a per-edge diagnostic (the
20304 // per-edge loop is a no-op under the empty projection), (2) the
20305 // `ContratoMemberMissing` refusal fires on the second entry of a
20306 // two-edge cohort whose head references a valid member but tail
20307 // references a phantom name (which requires the loop to reach
20308 // the second entry through the accessor), and (3) the
20309 // `SyncCycle` refusal fires on a self-referential two-edge
20310 // cohort through the sync-cycle detector's peer projection
20311 // (which requires the detector to iterate the accessor's
20312 // projection to add the back-edge to its adjacency list).
20313 //
20314 // Peer of the sibling M3
20315 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
20316 // three-consumer coherence pin on the per-`:membros` node-list
20317 // axis and the sibling M3
20318 // `validate_placement_reads_through_lifted_clusters_accessor`
20319 // (a6e18d7) coherence pin on the per-`:placement` distribution-
20320 // target-list axis — extends the slice-return-accessor multi-
20321 // consumer coherence discipline onto the outermost M3 mesh-slot
20322 // type's per-Aplicacao contract-list `Vec`-carry axis.
20323
20324 // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
20325 // and no per-edge diagnostic surfaces. Validate succeeds on
20326 // the well-formed `:membros` head.
20327 let mut spec = three_member_spec();
20328 spec.contratos = Vec::new();
20329 assert!(
20330 spec.validate().is_ok(),
20331 "empty :contratos must validate — the per-edge loop is a \
20332 no-op under the accessor's empty projection",
20333 );
20334 assert!(
20335 spec.contratos().is_empty(),
20336 "the per-edge validate loop's traversal input must be the \
20337 empty slice per the accessor's projection",
20338 );
20339
20340 // (2) Per-edge validate loop: a two-edge cohort whose tail
20341 // references a phantom `:para` member must trip
20342 // `ContratoMemberMissing` on the tail — the loop must reach
20343 // the second entry through the accessor for the membership
20344 // lookup to fail on the phantom name.
20345 let mut spec = three_member_spec();
20346 spec.contratos = vec![
20347 contract_http("cart", "catalog", "/products/:id"),
20348 contract_http("cart", "phantom", "/x"),
20349 ];
20350 let err = spec.validate().unwrap_err();
20351 assert!(
20352 matches!(
20353 err,
20354 AplicacaoError::ContratoMemberMissing { ref caixa }
20355 if caixa == "phantom"
20356 ),
20357 "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
20358 );
20359 assert_eq!(
20360 spec.contratos().len(),
20361 2,
20362 "the per-edge validate loop's traversal input must be \
20363 a two-element slice per the accessor's projection",
20364 );
20365
20366 // (3) Sync-cycle detector: a two-edge synchronous cohort
20367 // whose second edge closes the sync-subgraph back onto the
20368 // first must trip [`AplicacaoError::ContratoCycle`] — the
20369 // detector must iterate the accessor's projection to add
20370 // both edges to its adjacency list, so a length-drift on
20371 // the accessor's projection would silently disagree with
20372 // the sync-cycle detector on which edge closes the loop.
20373 // Peer projection to the `validate` per-edge loop above:
20374 // the sync-cycle detector routes through the same lifted
20375 // accessor, so a rebrand of the reader shape lands at one
20376 // place. Uses a two-edge cohort (cart → catalog → cart)
20377 // because the per-edge `ContratoSelfLoop` gate fires before
20378 // the sync-cycle detector on a single self-referential edge
20379 // (`cart → cart`) — the cycle-detector's input must be a
20380 // multi-edge cohort for its per-edge traversal input to be
20381 // observably wider than the per-edge validate loop's input.
20382 let mut spec = three_member_spec();
20383 spec.contratos = vec![
20384 contract_http("cart", "catalog", "/products/:id"),
20385 contract_http("catalog", "cart", "/callback"),
20386 ];
20387 let err = spec.validate().unwrap_err();
20388 assert!(
20389 matches!(err, AplicacaoError::ContratoCycle { .. }),
20390 "expected ContratoCycle from the sync-cycle detector on a \
20391 two-edge back-edge cohort, got {err:?}",
20392 );
20393 assert_eq!(
20394 spec.contratos().len(),
20395 2,
20396 "the sync-cycle detector's traversal input must be a \
20397 two-element slice per the accessor's projection",
20398 );
20399 }
20400
20401 #[test]
20402 fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
20403 // The canonical per-`:politicas` outer-composite-reference-shape
20404 // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
20405 // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
20406 // the same backing storage the raw `&self.politicas` field
20407 // access borrows from, byte-equal across every representative
20408 // fixture in the accept-set — the default `MeshPolicy` (the
20409 // author-empty "no policy on any axis" shape whose
20410 // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
20411 // shapes carrying one axis at a time
20412 // (`{mtls_required, timeout, retries, circuit_breaker,
20413 // rate_limit}` — the minimal five-axis fan-out over the
20414 // per-axis lifted accessor family every downstream mesh-artifact
20415 // emitter dispatches on), and the multi-axis composite (the
20416 // canonical `three_member_spec` fixture's `{timeout, retries,
20417 // mtls_required}` triple — the load-bearing shape every
20418 // Aplicacao-scoped fixture in this suite constructs).
20419 //
20420 // Pins against a future silent detour that returned a fresh-
20421 // cloned `MeshPolicy` copy (which would type-check via a `Clone`
20422 // impl but silently break every downstream caller that relied
20423 // on the reference sharing the composite's backing identity), a
20424 // reference to an operator-resolved overlay (the future
20425 // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
20426 // acknowledges — its resolution must land at exactly this
20427 // accessor body, not silently divert the raw slot away from a
20428 // second consumer), or an axis-shuffled projection (a future
20429 // detour that swapped `timeout` and `retries` through the
20430 // accessor would silently split the paired `validate_politicas`
20431 // per-axis bracket-dispatch's traversal input from the peer
20432 // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
20433 // emitter's fan-out input from the peer
20434 // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
20435 // overlay emitter's fan-out input).
20436 //
20437 // Peer of the sibling M3
20438 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
20439 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
20440 // node-list `Vec`-carry axis and the sibling M3
20441 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
20442 // (0dcc926) `&[WitContract]` byte-equal pin on the per-
20443 // `:contratos` edge-list `Vec`-carry axis — extends the outer-
20444 // accessor byte-equal-projection discipline onto the outermost
20445 // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
20446 // reference axis, the first `&Composite`-return accessor on the
20447 // outer [`AplicacaoSpec`] type.
20448 let fixtures: Vec<MeshPolicy> = vec![
20449 MeshPolicy::default(),
20450 MeshPolicy {
20451 mtls_required: Some(true),
20452 ..MeshPolicy::default()
20453 },
20454 MeshPolicy {
20455 mtls_required: Some(false),
20456 ..MeshPolicy::default()
20457 },
20458 MeshPolicy {
20459 timeout: Some(Duration::from_secs(30)),
20460 ..MeshPolicy::default()
20461 },
20462 MeshPolicy {
20463 retries: Some(3),
20464 ..MeshPolicy::default()
20465 },
20466 MeshPolicy {
20467 circuit_breaker: Some(CircuitBreaker {
20468 max_failures: 5,
20469 window: Duration::from_secs(30),
20470 }),
20471 ..MeshPolicy::default()
20472 },
20473 MeshPolicy {
20474 rate_limit: Some(RateLimit {
20475 rate: 100,
20476 window: Duration::from_secs(1),
20477 }),
20478 ..MeshPolicy::default()
20479 },
20480 MeshPolicy {
20481 timeout: Some(Duration::from_secs(30)),
20482 retries: Some(3),
20483 mtls_required: Some(true),
20484 ..MeshPolicy::default()
20485 },
20486 ];
20487 for politicas in fixtures {
20488 let s = AplicacaoSpec {
20489 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20490 contratos: Vec::new(),
20491 politicas: politicas.clone(),
20492 placement: Placement::default(),
20493 entrada: None,
20494 };
20495 assert_eq!(
20496 *s.politicas(),
20497 politicas,
20498 "AplicacaoSpec::politicas must return :politicas verbatim \
20499 (got {:?}, expected {:?})",
20500 s.politicas(),
20501 politicas,
20502 );
20503 assert!(
20504 std::ptr::eq(s.politicas(), &s.politicas),
20505 "AplicacaoSpec::politicas accessor and &self.politicas \
20506 field access must borrow the same backing storage — \
20507 the accessor is the substrate-primitive typed dispatch \
20508 every downstream mesh-policy composite consumer must \
20509 route through, and a reference-identity split would \
20510 silently break every consumer that relied on the \
20511 borrow sharing the composite's storage",
20512 );
20513 assert_eq!(
20514 s.politicas().is_empty(),
20515 s.politicas.is_empty(),
20516 "AplicacaoSpec::politicas().is_empty() must byte-equal \
20517 self.politicas.is_empty() — an emptiness-drift would \
20518 silently split the paired `validate_politicas` \
20519 per-axis bracket-dispatch's seed from the peer \
20520 caixa-mesh CNP mTLS-overlay emitter's key from the \
20521 peer caixa-mesh HTTPRoute timeout+retry overlay \
20522 emitter's key",
20523 );
20524 }
20525 }
20526
20527 #[test]
20528 fn validate_politicas_reads_through_lifted_politicas_accessor() {
20529 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
20530 // per-axis bracket-dispatch seed (`let p = self.politicas();`,
20531 // followed by the per-axis fan-out `p.timeout()` /
20532 // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
20533 // the lifted axis-level accessor family) must key off the
20534 // lifted outer accessor, so any future rebrand on the typed
20535 // slot's outer-composite reader shape lands at exactly one
20536 // place. Pins the multi-axis coherence by exercising each
20537 // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
20538 // a `Some(Duration::ZERO)` timeout under the outer accessor's
20539 // reference projection, (2) `PolicyRetriesZero` fires on a
20540 // `Some(0)` retries under the same projection, and (3) an
20541 // empty [`MeshPolicy::default`] passes `validate_politicas` —
20542 // the outer accessor's reference-projection reaches every
20543 // per-axis branch without silently short-circuiting any.
20544 //
20545 // Peer of the sibling M3
20546 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
20547 // three-consumer coherence pin on the per-`:membros` node-list
20548 // axis and the sibling M3
20549 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
20550 // three-consumer coherence pin on the per-`:contratos`
20551 // edge-list axis — extends the multi-consumer coherence
20552 // discipline onto the outermost M3 mesh-slot type's per-
20553 // Aplicacao mesh-policy composite-reference axis, the first
20554 // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
20555 // type.
20556
20557 // (1) `PolicyTimeoutZero` refusal under the outer accessor's
20558 // reference projection: a `Some(Duration::ZERO)` timeout must
20559 // trip the zero-floor gate. The bracket-dispatch's first arm
20560 // reads `p.timeout()` on the reference returned by the outer
20561 // accessor.
20562 let mut spec = three_member_spec();
20563 spec.politicas.timeout = Some(Duration::ZERO);
20564 spec.politicas.retries = None;
20565 spec.politicas.circuit_breaker = None;
20566 spec.politicas.rate_limit = None;
20567 assert_eq!(
20568 spec.validate().unwrap_err(),
20569 AplicacaoError::PolicyTimeoutZero,
20570 );
20571 assert!(
20572 std::ptr::eq(spec.politicas(), &spec.politicas),
20573 "the `validate_politicas` per-axis bracket-dispatch's \
20574 traversal input must be the same backing composite the \
20575 accessor's reference projection borrows from",
20576 );
20577
20578 // (2) `PolicyRetriesZero` refusal under the outer accessor's
20579 // reference projection: a `Some(0)` retries must trip the
20580 // zero-floor gate. The bracket-dispatch's second arm reads
20581 // `p.retries()` on the reference returned by the outer accessor.
20582 let mut spec = three_member_spec();
20583 spec.politicas.timeout = None;
20584 spec.politicas.retries = Some(0);
20585 spec.politicas.circuit_breaker = None;
20586 spec.politicas.rate_limit = None;
20587 assert_eq!(
20588 spec.validate().unwrap_err(),
20589 AplicacaoError::PolicyRetriesZero,
20590 );
20591
20592 // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
20593 // — every per-axis arm short-circuits on `None`, so the outer
20594 // accessor's reference projection reaches the fall-through
20595 // `Ok(())` without any per-axis refusal firing.
20596 let mut spec = three_member_spec();
20597 spec.politicas = MeshPolicy::default();
20598 assert!(
20599 spec.validate().is_ok(),
20600 "an empty `MeshPolicy` must pass `validate_politicas` — \
20601 every per-axis arm short-circuits on `None` under the \
20602 outer accessor's reference projection",
20603 );
20604 assert!(
20605 spec.politicas().is_empty(),
20606 "the outer accessor's reference projection must be the \
20607 empty composite per the `MeshPolicy::default()` fixture",
20608 );
20609 }
20610
20611 #[test]
20612 #[allow(clippy::too_many_lines)]
20613 fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
20614 // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
20615 // per-axis bracket-dispatch's `:timeout` and `:retries` arms
20616 // must both key off the lifted axis-level accessors
20617 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
20618 // the peer `:circuit-breaker` / `:rate-limit` arms already
20619 // routing through [`MeshPolicy::circuit_breaker`] /
20620 // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
20621 // per axis on the substrate primitive" shape at the fan-out
20622 // (four axes, four accessors, no raw-field-access site
20623 // anywhere on the bracket-dispatch). Pins the per-axis
20624 // coherence at the accept-set boundaries the bracket carves:
20625 // 1. accessor byte-equal to raw field on every representative
20626 // accept-set value (`None`, sub-cap, at-cap, past-cap
20627 // sentinel) — a future accessor drift that no longer
20628 // shipped the raw slot verbatim would surface here,
20629 // 2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
20630 // routed through the accessor's projection, proving the
20631 // first arm reads through the accessor rather than a
20632 // silent-detour peer-axis field access,
20633 // 3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
20634 // through the accessor's projection, proving the second
20635 // arm reads through the accessor,
20636 // 4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
20637 // passes validate under the accessor projection (paired
20638 // with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
20639 // sibling axis), pinning the upper-boundary accept-arm
20640 // also routes through the accessor.
20641 //
20642 // Peer of the sibling M3
20643 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
20644 // outer-composite-reference coherence pin (which asserts the
20645 // `let p = self.politicas()` seed); extends the discipline onto
20646 // the per-axis fan-out layer that consumes the seed's
20647 // reference. Same shape as
20648 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
20649 // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
20650 // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
20651 // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
20652
20653 // (1) Accessor byte-equal to raw field on the `:timeout` axis
20654 // across the accept-set boundaries the bracket dispatch's
20655 // three-arm gate carves out
20656 // ([`crate::render::require_positive_canonical_bounded_duration`]
20657 // — zero-floor + canonical-form + upper-cap).
20658 for timeout in [
20659 None,
20660 Some(Duration::ZERO),
20661 Some(Duration::from_millis(1)),
20662 Some(POLICY_TIMEOUT_MAX),
20663 ] {
20664 let p = MeshPolicy {
20665 timeout,
20666 ..MeshPolicy::default()
20667 };
20668 assert_eq!(
20669 p.timeout(),
20670 p.timeout,
20671 "MeshPolicy::timeout accessor must byte-equal the raw \
20672 .timeout field across every accept-set boundary the \
20673 validate_politicas :timeout arm carves out — a drift \
20674 here would silently split the validate bracket's arm \
20675 from the peer caixa-mesh HTTPRoute timeout-overlay \
20676 emitter's read",
20677 );
20678 }
20679
20680 // (2) Accessor byte-equal to raw field on the `:retries` axis
20681 // across the accept-set boundaries the bracket dispatch's
20682 // two-arm gate carves out
20683 // ([`crate::render::require_positive_bounded_u32`] — zero-floor
20684 // + upper-cap).
20685 for retries in [
20686 None,
20687 Some(0u32),
20688 Some(1u32),
20689 Some(POLICY_RETRIES_MAX),
20690 Some(POLICY_RETRIES_MAX + 1),
20691 Some(u32::MAX),
20692 ] {
20693 let p = MeshPolicy {
20694 retries,
20695 ..MeshPolicy::default()
20696 };
20697 assert_eq!(
20698 p.retries(),
20699 p.retries,
20700 "MeshPolicy::retries accessor must byte-equal the raw \
20701 .retries field across every accept-set boundary the \
20702 validate_politicas :retries arm carves out — a drift \
20703 here would silently split the validate bracket's arm \
20704 from the peer caixa-mesh HTTPRoute retry-overlay \
20705 emitter's read",
20706 );
20707 }
20708
20709 // (3) `PolicyTimeoutZero` fires on the accessor-projected
20710 // zero-floor boundary. A silent detour that no longer read
20711 // through `p.timeout()` (a peer-axis field read, an accidental
20712 // Option::and-then chain that collapsed the None arm to Some,
20713 // an accessor rebrand that clamped the return through the
20714 // upper cap) would fail to refuse here.
20715 let mut spec = three_member_spec();
20716 spec.politicas.timeout = Some(Duration::ZERO);
20717 spec.politicas.retries = None;
20718 spec.politicas.circuit_breaker = None;
20719 spec.politicas.rate_limit = None;
20720 assert_eq!(
20721 spec.politicas().timeout(),
20722 Some(Duration::ZERO),
20723 "the accessor projection must reflect the fixture's \
20724 `Some(Duration::ZERO)` :timeout verbatim",
20725 );
20726 assert_eq!(
20727 spec.validate().unwrap_err(),
20728 AplicacaoError::PolicyTimeoutZero,
20729 "the validate_politicas :timeout zero-floor arm must fire \
20730 through the lifted accessor's projection — a silent \
20731 detour to a peer-axis field would fail to refuse",
20732 );
20733
20734 // (4) `PolicyRetriesZero` fires on the accessor-projected
20735 // zero-floor boundary on the sibling `:retries` axis.
20736 let mut spec = three_member_spec();
20737 spec.politicas.timeout = None;
20738 spec.politicas.retries = Some(0);
20739 spec.politicas.circuit_breaker = None;
20740 spec.politicas.rate_limit = None;
20741 assert_eq!(
20742 spec.politicas().retries(),
20743 Some(0),
20744 "the accessor projection must reflect the fixture's \
20745 `Some(0)` :retries verbatim",
20746 );
20747 assert_eq!(
20748 spec.validate().unwrap_err(),
20749 AplicacaoError::PolicyRetriesZero,
20750 "the validate_politicas :retries zero-floor arm must fire \
20751 through the lifted accessor's projection — a silent \
20752 detour to a peer-axis field would fail to refuse",
20753 );
20754
20755 // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
20756 // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
20757 // must pass validate under the accessor projection — pins the
20758 // upper-boundary accept-arm also routes through the lifted
20759 // accessor (a drift that clamped or short-circuited at the
20760 // upper boundary would fail the whole-spec validate here).
20761 let mut spec = three_member_spec();
20762 spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
20763 spec.politicas.retries = Some(POLICY_RETRIES_MAX);
20764 spec.politicas.circuit_breaker = None;
20765 spec.politicas.rate_limit = None;
20766 assert_eq!(
20767 spec.politicas().timeout(),
20768 Some(POLICY_TIMEOUT_MAX),
20769 "the accessor projection must reflect the fixture's \
20770 at-cap :timeout verbatim",
20771 );
20772 assert_eq!(
20773 spec.politicas().retries(),
20774 Some(POLICY_RETRIES_MAX),
20775 "the accessor projection must reflect the fixture's \
20776 at-cap :retries verbatim",
20777 );
20778 assert!(
20779 spec.validate().is_ok(),
20780 "at-cap :timeout + :retries must pass validate under the \
20781 accessor projection — the upper-boundary accept-arm on \
20782 both axes routes through the lifted accessor",
20783 );
20784 }
20785
20786 #[test]
20787 fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
20788 // The canonical per-`:placement` outer-composite-reference-shape
20789 // pin: [`AplicacaoSpec::placement`] must return the `:placement`
20790 // typed `Placement` verbatim as a `&Placement` reference over the
20791 // same backing storage the raw `&self.placement` field access
20792 // borrows from, byte-equal across every representative fixture in
20793 // the accept-set — the default `Placement` (the substrate seed
20794 // shape whose [`PlacementStrategy::default`] evaluates to
20795 // `SingleNode` with an empty `:clusters` pool and both
20796 // optional-scalar axes `None`), and every canonical strategy /
20797 // cluster-pool / optional-scalar combination the
20798 // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
20799 // three [`PlacementStrategy`] variants — `SingleNode`,
20800 // `Replicated`, `Sharded` — cross-projected with a non-empty
20801 // `:clusters` pool and, on the `Sharded` arm, a non-empty
20802 // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
20803 // canonical `three_member_spec` `Replicated` fixture's
20804 // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
20805 //
20806 // Pins against a future silent detour that returned a fresh-
20807 // cloned `Placement` copy (which would type-check via a `Clone`
20808 // impl but silently break every downstream caller that relied on
20809 // the reference sharing the composite's backing identity), a
20810 // reference to an operator-resolved overlay (the future per-
20811 // cluster `:placement-overrides` slot MESH-COMPOSITION §V
20812 // acknowledges — its resolution must land at exactly this
20813 // accessor body, not silently divert the raw slot away from a
20814 // second consumer), or an axis-shuffled projection (a future
20815 // detour that swapped `clusters` and `affinity` through the
20816 // accessor would silently split the paired `validate_placement`
20817 // per-axis bracket-dispatch's traversal input from the peer
20818 // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
20819 // programs.yaml distribution-annotation emitter's fan-out input
20820 // from the peer `feira app graph` per-Aplicacao print line's
20821 // input).
20822 //
20823 // Peer of the sibling M3
20824 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
20825 // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
20826 // outer mesh-policy composite-reference axis, and of the sibling
20827 // slice-return `aplicacao_spec_membros_returns_membros_slice_
20828 // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
20829 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
20830 // across_permutations` (0dcc926) `&[WitContract]` pins — extends
20831 // the outer-accessor byte-equal-projection discipline onto the
20832 // outermost M3 mesh-slot type's per-Aplicacao distribution
20833 // composite-reference axis, the second `&Composite`-return
20834 // accessor on the outer [`AplicacaoSpec`] type.
20835 let fixtures: Vec<Placement> = vec![
20836 Placement::default(),
20837 Placement {
20838 estrategia: PlacementStrategy::SingleNode,
20839 clusters: vec!["rio".into()],
20840 affinity: None,
20841 shard_key: None,
20842 },
20843 Placement {
20844 estrategia: PlacementStrategy::Replicated,
20845 clusters: vec!["rio".into(), "mar".into()],
20846 affinity: None,
20847 shard_key: None,
20848 },
20849 Placement {
20850 estrategia: PlacementStrategy::Replicated,
20851 clusters: vec!["rio".into(), "mar".into()],
20852 affinity: Some("data-locality".into()),
20853 shard_key: None,
20854 },
20855 Placement {
20856 estrategia: PlacementStrategy::Sharded,
20857 clusters: vec!["rio".into(), "mar".into()],
20858 affinity: None,
20859 shard_key: Some("tenantId".into()),
20860 },
20861 Placement {
20862 estrategia: PlacementStrategy::Sharded,
20863 clusters: vec!["rio".into(), "mar".into(), "sol".into()],
20864 affinity: Some("low-latency".into()),
20865 shard_key: Some("metadata.tenantId".into()),
20866 },
20867 ];
20868 for placement in fixtures {
20869 let s = AplicacaoSpec {
20870 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
20871 contratos: Vec::new(),
20872 politicas: MeshPolicy::default(),
20873 placement: placement.clone(),
20874 entrada: None,
20875 };
20876 assert_eq!(
20877 *s.placement(),
20878 placement,
20879 "AplicacaoSpec::placement must return :placement verbatim \
20880 (got {:?}, expected {:?})",
20881 s.placement(),
20882 placement,
20883 );
20884 assert!(
20885 std::ptr::eq(s.placement(), &s.placement),
20886 "AplicacaoSpec::placement accessor and &self.placement \
20887 field access must borrow the same backing storage — the \
20888 accessor is the substrate-primitive typed dispatch every \
20889 downstream distribution-composite consumer must route \
20890 through, and a reference-identity split would silently \
20891 break every consumer that relied on the borrow sharing \
20892 the composite's storage",
20893 );
20894 assert_eq!(
20895 s.placement().estrategia(),
20896 s.placement.estrategia,
20897 "AplicacaoSpec::placement().estrategia() must byte-equal \
20898 self.placement.estrategia — a strategy-drift would \
20899 silently split the paired `validate_placement` \
20900 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
20901 peer caixa-mesh programs.yaml `placement.estrategia` \
20902 emitter's key from the peer `feira app graph` printer's \
20903 strategy label",
20904 );
20905 assert_eq!(
20906 s.placement().clusters(),
20907 s.placement.clusters.as_slice(),
20908 "AplicacaoSpec::placement().clusters() must byte-equal \
20909 self.placement.clusters — a cluster-pool drift would \
20910 silently split the paired `validate_placement` \
20911 pre-flight `.is_empty()` refusal probe's traversal from \
20912 the peer caixa-mesh programs.yaml `placement.clusters` \
20913 emitter's fan-out from the peer `feira app graph` \
20914 printer's cluster list",
20915 );
20916 }
20917 }
20918
20919 #[test]
20920 fn validate_placement_reads_through_lifted_placement_accessor() {
20921 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
20922 // per-axis bracket-dispatch seed (`let p = self.placement();`,
20923 // followed by the per-axis fan-out `p.clusters()` /
20924 // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
20925 // lifted axis-level accessor family) must key off the lifted
20926 // outer accessor, so any future rebrand on the typed slot's
20927 // outer-composite reader shape lands at exactly one place. Pins
20928 // the multi-axis coherence by exercising each per-axis refusal
20929 // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
20930 // `:clusters` pool under the outer accessor's reference
20931 // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
20932 // strategy with a `None` `:shard-key` under the same projection,
20933 // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
20934 // with a `Some` `:shard-key` under the same projection, and
20935 // (4) the canonical `three_member_spec` `Replicated` fixture
20936 // passes `validate_placement` under the outer accessor's
20937 // reference projection — the accessor's reference-projection
20938 // reaches every per-axis branch (cluster-pool refusal, `Sharded`
20939 // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
20940 // without silently short-circuiting any.
20941 //
20942 // Peer of the sibling M3
20943 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
20944 // (534dc21) multi-axis coherence pin on the per-`:politicas`
20945 // outer mesh-policy composite-reference axis — extends the
20946 // multi-consumer coherence discipline onto the outermost M3
20947 // mesh-slot type's per-Aplicacao distribution composite-
20948 // reference axis, the second `&Composite`-return accessor on
20949 // the outer [`AplicacaoSpec`] type.
20950
20951 // (1) `PlacementWithoutClusters` refusal under the outer
20952 // accessor's reference projection: an empty `:clusters` pool
20953 // must trip the pre-flight refusal probe. The bracket-dispatch's
20954 // first arm reads `p.clusters()` on the reference returned by
20955 // the outer accessor.
20956 let mut spec = three_member_spec();
20957 spec.placement.clusters = Vec::new();
20958 assert_eq!(
20959 spec.validate().unwrap_err(),
20960 AplicacaoError::PlacementWithoutClusters {
20961 estrategia: PlacementStrategy::Replicated,
20962 },
20963 );
20964 assert!(
20965 std::ptr::eq(spec.placement(), &spec.placement),
20966 "the `validate_placement` per-axis bracket-dispatch's \
20967 traversal input must be the same backing composite the \
20968 accessor's reference projection borrows from",
20969 );
20970
20971 // (2) `ShardedWithoutKey` refusal under the outer accessor's
20972 // reference projection: a `Sharded` strategy with a `None`
20973 // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
20974 // The bracket-dispatch's third arm reads `p.estrategia()` for
20975 // the match scrutinee then `p.shard_key()` for the cascade
20976 // scrutinee, both on the reference returned by the outer
20977 // accessor.
20978 let mut spec = three_member_spec();
20979 spec.placement.estrategia = PlacementStrategy::Sharded;
20980 spec.placement.shard_key = None;
20981 assert_eq!(
20982 spec.validate().unwrap_err(),
20983 AplicacaoError::ShardedWithoutKey,
20984 );
20985
20986 // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
20987 // reference projection: a non-`Sharded` strategy with a `Some`
20988 // `:shard-key` must trip the declared-but-inert refusal. The
20989 // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
20990 // + `p.estrategia()` for the diagnostic on the reference
20991 // returned by the outer accessor.
20992 let mut spec = three_member_spec();
20993 spec.placement.estrategia = PlacementStrategy::Replicated;
20994 spec.placement.shard_key = Some("tenantId".into());
20995 assert_eq!(
20996 spec.validate().unwrap_err(),
20997 AplicacaoError::ShardKeyOnNonSharded {
20998 estrategia: PlacementStrategy::Replicated,
20999 shard_key: "tenantId".into(),
21000 },
21001 );
21002
21003 // (4) Canonical `three_member_spec` `Replicated` fixture passes
21004 // `validate_placement` — every per-axis arm reaches the fall-
21005 // through `Ok(())` without any per-axis refusal firing under the
21006 // outer accessor's reference projection.
21007 let spec = three_member_spec();
21008 assert!(
21009 spec.validate().is_ok(),
21010 "the canonical Replicated placement fixture must pass \
21011 `validate_placement` — every per-axis arm short-circuits on \
21012 valid input under the outer accessor's reference projection",
21013 );
21014 assert_eq!(
21015 spec.placement().estrategia(),
21016 PlacementStrategy::Replicated,
21017 "the outer accessor's reference projection must be the \
21018 canonical Replicated fixture's strategy",
21019 );
21020 assert_eq!(
21021 spec.placement().clusters(),
21022 &["rio", "mar"],
21023 "the outer accessor's reference projection must be the \
21024 canonical Replicated fixture's cluster pool",
21025 );
21026 }
21027
21028 #[test]
21029 fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
21030 // The canonical per-`:entrada` outer-composite-optional-
21031 // reference-shape pin: [`AplicacaoSpec::entrada`] must return
21032 // the `:entrada` typed `Option<Entrada>` verbatim as an
21033 // `Option<&Entrada>` reference over the same backing storage
21034 // the raw `self.entrada.as_ref()` field access borrows from,
21035 // byte-equal across every representative fixture in the
21036 // accept-set — the author-omitted `None` shape (the
21037 // "internal-only mesh" partition every downstream external-
21038 // gateway emitter treats as "emit nothing"), the minimal
21039 // singleton `:entrada` composite (host + destination + empty
21040 // paths + default port), the paths-carrying composite (the
21041 // canonical `three_member_spec` fixture's ["/api" "/health"]
21042 // path-list shape every HTTPRoute per-rule fan-out emitter
21043 // reads), and the non-default port composite (the canonical
21044 // custom-port shape the port-fallback resolver reads).
21045 //
21046 // Pins against a future silent detour that returned a fresh-
21047 // cloned `Entrada` copy (which would type-check via a `Clone`
21048 // impl but silently break every downstream caller that
21049 // relied on the reference sharing the composite's backing
21050 // identity), a reference to an operator-resolved overlay
21051 // (the future per-cluster `:entrada-overrides` slot the
21052 // MESH-COMPOSITION §V federation roadmap acknowledges — its
21053 // resolution must land at exactly this accessor body, not
21054 // silently divert the raw slot away from a second consumer),
21055 // a `None` → `Some(Entrada::default)` cluster-default
21056 // projection (which would collapse the load-bearing
21057 // "author-omitted `:entrada` ⇒ internal-only mesh" partition
21058 // the peer `gateway_routes` early-return + `feira app graph`
21059 // internal-only-mesh partition both read), or an axis-
21060 // shuffled projection (a future detour that swapped
21061 // `host` and `para` through the accessor would silently
21062 // split the paired `validate` per-`:entrada` shape-and-
21063 // membership gate's traversal input from the peer
21064 // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
21065 // fan-out input from the peer `feira app graph` external-
21066 // gateway summary line).
21067 //
21068 // Peer of the sibling M3
21069 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
21070 // (534dc21) `&MeshPolicy` byte-equal pin on the per-
21071 // `:politicas` outer mesh-policy composite-reference axis
21072 // and of the sibling M3
21073 // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
21074 // (9abb8f0) `&Placement` byte-equal pin on the per-
21075 // `:placement` outer distribution-composite composite-
21076 // reference axis — extends the outer-accessor byte-equal-
21077 // projection discipline onto the last unlifted outermost M3
21078 // mesh-slot type's per-Aplicacao external-gateway composite-
21079 // reference axis, the third and final `&Composite`-return
21080 // accessor on the outer [`AplicacaoSpec`] type.
21081 let fixtures: Vec<Option<Entrada>> = vec![
21082 None,
21083 Some(Entrada {
21084 host: "checkout.quero.cloud".into(),
21085 para: "cart".into(),
21086 paths: Vec::new(),
21087 port: DEFAULT_SERVICO_PORT,
21088 }),
21089 Some(Entrada {
21090 host: "checkout.quero.cloud".into(),
21091 para: "cart".into(),
21092 paths: vec!["/api".into(), "/health".into()],
21093 port: DEFAULT_SERVICO_PORT,
21094 }),
21095 Some(Entrada {
21096 host: "checkout.quero.cloud".into(),
21097 para: "cart".into(),
21098 paths: vec!["/api".into()],
21099 port: 9443,
21100 }),
21101 ];
21102 for entrada in fixtures {
21103 let s = AplicacaoSpec {
21104 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
21105 contratos: Vec::new(),
21106 politicas: MeshPolicy::default(),
21107 placement: Placement::default(),
21108 entrada: entrada.clone(),
21109 };
21110 assert_eq!(
21111 s.entrada(),
21112 entrada.as_ref(),
21113 "AplicacaoSpec::entrada must return :entrada verbatim \
21114 (got {:?}, expected {:?})",
21115 s.entrada(),
21116 entrada.as_ref(),
21117 );
21118 match (s.entrada(), s.entrada.as_ref()) {
21119 (Some(a), Some(b)) => assert!(
21120 std::ptr::eq(a, b),
21121 "AplicacaoSpec::entrada accessor and \
21122 self.entrada.as_ref() field access must borrow \
21123 the same backing storage — the accessor is the \
21124 substrate-primitive typed dispatch every \
21125 downstream external-gateway composite consumer \
21126 must route through, and a reference-identity \
21127 split would silently break every consumer that \
21128 relied on the borrow sharing the composite's \
21129 storage",
21130 ),
21131 (None, None) => {}
21132 _ => panic!(
21133 "AplicacaoSpec::entrada presence bit must byte-\
21134 equal self.entrada.is_some() — a presence-bit \
21135 drift would silently split the paired `validate` \
21136 per-`:entrada` shape-and-membership gate's \
21137 traversal head from the peer \
21138 caixa-mesh gateway_routes early-return partition \
21139 from the peer `feira app graph` internal-only-\
21140 mesh partition",
21141 ),
21142 }
21143 assert_eq!(
21144 s.entrada().is_some(),
21145 s.entrada.is_some(),
21146 "AplicacaoSpec::entrada().is_some() must byte-equal \
21147 self.entrada.is_some() — a presence-bit drift would \
21148 silently split every downstream `Option<&Entrada>` \
21149 consumer's partition on the internal-only-mesh arm",
21150 );
21151 }
21152 }
21153
21154 #[test]
21155 fn validate_reads_through_lifted_entrada_accessor() {
21156 // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
21157 // per-`:entrada` shape-and-membership gate (`if let Some(e) =
21158 // self.entrada() { … }`, followed by the per-axis fan-out
21159 // `validate_entrada_para(&e.para)` /
21160 // `EntradaMemberMissing` membership lookup /
21161 // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
21162 // per-`e.paths` `validate_entrada_path` traversal) must key
21163 // off the lifted outer accessor, so any future rebrand on
21164 // the typed slot's outer-composite reader shape lands at
21165 // exactly one place. Pins the multi-axis coherence by
21166 // exercising each per-axis refusal end-to-end: (1) the
21167 // author-omitted `None` shape short-circuits past every
21168 // per-`:entrada` refusal (the internal-only mesh partition
21169 // the accessor's `None` arm names), (2) `EntradaMemberMissing`
21170 // fires on a well-shaped but phantom `:para` under the outer
21171 // accessor's reference projection, and (3) the canonical
21172 // `three_member_spec` `:entrada` fixture passes `validate`
21173 // under the outer accessor's reference projection.
21174 //
21175 // Peer of the sibling M3
21176 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
21177 // (534dc21) multi-axis coherence pin on the per-`:politicas`
21178 // outer mesh-policy composite-reference axis and the sibling
21179 // M3
21180 // [`validate_placement_reads_through_lifted_placement_accessor`]
21181 // (9abb8f0) multi-axis coherence pin on the per-`:placement`
21182 // outer distribution-composite composite-reference axis —
21183 // extends the multi-consumer coherence discipline onto the
21184 // last unlifted outermost M3 mesh-slot type's per-Aplicacao
21185 // external-gateway composite-reference axis, the third and
21186 // final `&Composite`-return accessor on the outer
21187 // [`AplicacaoSpec`] type.
21188
21189 // (1) `None` :entrada — the internal-only-mesh partition
21190 // short-circuits past every per-`:entrada` refusal. The outer
21191 // accessor's reference projection reaches the fall-through
21192 // `Ok(())` on the `None` arm without any per-axis refusal
21193 // firing.
21194 let mut spec = three_member_spec();
21195 spec.entrada = None;
21196 assert!(
21197 spec.validate().is_ok(),
21198 "an author-omitted `:entrada` must pass `validate` — the \
21199 internal-only-mesh partition short-circuits past every \
21200 per-`:entrada` refusal under the outer accessor's \
21201 reference projection",
21202 );
21203 assert!(
21204 spec.entrada().is_none(),
21205 "the outer accessor's reference projection must name the \
21206 internal-only-mesh partition per the `None` fixture",
21207 );
21208
21209 // (2) `EntradaMemberMissing` refusal under the outer accessor's
21210 // reference projection: a well-shaped but phantom `:para` must
21211 // trip the membership-lookup refusal. The gate's second arm
21212 // reads `e.para` on the reference returned by the outer
21213 // accessor.
21214 let mut spec = three_member_spec();
21215 if let Some(e) = spec.entrada.as_mut() {
21216 e.para = "phantom".into();
21217 }
21218 assert_eq!(
21219 spec.validate().unwrap_err(),
21220 AplicacaoError::EntradaMemberMissing {
21221 para: "phantom".into(),
21222 },
21223 );
21224 match (spec.entrada(), spec.entrada.as_ref()) {
21225 (Some(a), Some(b)) => assert!(
21226 std::ptr::eq(a, b),
21227 "the `validate` per-`:entrada` gate's traversal head \
21228 must be the same backing composite the accessor's \
21229 reference projection borrows from",
21230 ),
21231 _ => panic!("fixture must carry Some(:entrada)"),
21232 }
21233
21234 // (3) Canonical `three_member_spec` `:entrada` fixture passes
21235 // `validate` — every per-axis arm reaches the fall-through
21236 // `Ok(())` without any per-axis refusal firing under the
21237 // outer accessor's reference projection.
21238 let spec = three_member_spec();
21239 assert!(
21240 spec.validate().is_ok(),
21241 "the canonical `:entrada` fixture must pass `validate` — \
21242 every per-axis arm short-circuits on valid input under \
21243 the outer accessor's reference projection",
21244 );
21245 assert!(
21246 spec.entrada().is_some(),
21247 "the outer accessor's reference projection must be the \
21248 canonical `:entrada` fixture's composite",
21249 );
21250 }
21251
21252 #[test]
21253 fn port_for_destination_reads_through_lifted_entrada_accessor() {
21254 // Peer coherence pin: the
21255 // [`AplicacaoSpec::port_for_destination`] per-destination
21256 // L4-port fallback resolver's composite-projection seed
21257 // (`self.entrada().filter(…).map_or(…)`) must key off the
21258 // lifted outer accessor. Pins the coherence by exercising
21259 // the resolver end-to-end: (1) the `None` `:entrada` shape
21260 // falls through to `DEFAULT_SERVICO_PORT` under the outer
21261 // accessor's reference projection, (2) a non-matching
21262 // destination falls through to `DEFAULT_SERVICO_PORT` under
21263 // the outer accessor's reference projection, and (3) the
21264 // matching destination resolves to the `:entrada :port`
21265 // value under the outer accessor's reference projection.
21266 //
21267 // Peer of the sibling
21268 // [`validate_reads_through_lifted_entrada_accessor`] multi-
21269 // consumer coherence pin on the same per-`:entrada` outer-
21270 // composite axis — extends the multi-consumer coherence
21271 // discipline onto the second per-`:entrada` production
21272 // consumer, the L4-port fallback resolver.
21273
21274 // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
21275 // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
21276 // arm under the outer accessor's reference projection.
21277 let mut spec = three_member_spec();
21278 spec.entrada = None;
21279 assert_eq!(
21280 spec.port_for_destination("cart"),
21281 DEFAULT_SERVICO_PORT,
21282 "the port-fallback resolver must fall through to \
21283 DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
21284 under the outer accessor's reference projection",
21285 );
21286
21287 // (2) Non-matching destination — the resolver's `filter(…)`
21288 // arm rejects a mismatched destination and falls through
21289 // to `DEFAULT_SERVICO_PORT` under the outer accessor's
21290 // reference projection.
21291 let mut spec = three_member_spec();
21292 if let Some(e) = spec.entrada.as_mut() {
21293 e.para = "cart".into();
21294 e.port = 9443;
21295 }
21296 assert_eq!(
21297 spec.port_for_destination("catalog"),
21298 DEFAULT_SERVICO_PORT,
21299 "the port-fallback resolver must fall through to \
21300 DEFAULT_SERVICO_PORT on a non-matching destination \
21301 under the outer accessor's reference projection",
21302 );
21303
21304 // (3) Matching destination — the resolver's `map_or(…)` arm
21305 // returns the `:entrada :port` value under the outer
21306 // accessor's reference projection.
21307 let mut spec = three_member_spec();
21308 if let Some(e) = spec.entrada.as_mut() {
21309 e.para = "cart".into();
21310 e.port = 9443;
21311 }
21312 assert_eq!(
21313 spec.port_for_destination("cart"),
21314 9443,
21315 "the port-fallback resolver must return the \
21316 `:entrada :port` value on a matching destination \
21317 under the outer accessor's reference projection",
21318 );
21319 }
21320
21321 #[test]
21322 fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
21323 // The canonical per-`:politicas` `:mtls-required` mTLS-
21324 // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
21325 // must return the `:politicas :mtls-required` typed bool
21326 // verbatim as an `Option<bool>`, byte-equal to the raw field
21327 // access across every value in the three-way accept-set —
21328 // `None` (cluster default applies), `Some(true)` (mTLS
21329 // handshake enforced — the sandboxing-by-default arm the
21330 // MeshPolicy's docstring names), `Some(false)` (handshake
21331 // skipped — the explicit debug-edge opt-out).
21332 //
21333 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
21334 // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
21335 // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
21336 // shape — first `Option<Copy-T>`-return accessor on the M3
21337 // mesh-slot family. Pins against a future silent detour that
21338 // re-derived the toggle from a peer axis (an accidental
21339 // `.circuit_breaker.is_some()` collapse that assumed mTLS on
21340 // whenever a breaker is set), a `None` → `Some(false)` cluster-
21341 // default projection (the canonical `Option<bool>` → `bool`
21342 // collapse footgun the surrounding `is_empty()` predicate
21343 // guards on the peer emptiness axis), or a `Some(true)` /
21344 // `Some(false)` variant swap that landed on one consumer
21345 // without the other.
21346 for required in [None, Some(true), Some(false)] {
21347 let p = MeshPolicy {
21348 mtls_required: required,
21349 ..MeshPolicy::default()
21350 };
21351 assert_eq!(
21352 p.mtls_required(),
21353 required,
21354 "MeshPolicy::mtls_required must return :politicas \
21355 :mtls-required verbatim (got {:?}, expected {required:?})",
21356 p.mtls_required(),
21357 );
21358 assert_eq!(
21359 p.mtls_required(),
21360 p.mtls_required,
21361 "MeshPolicy::mtls_required must byte-equal the raw \
21362 .mtls_required field access across every value in the \
21363 three-way accept-set",
21364 );
21365 }
21366 }
21367
21368 #[test]
21369 fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
21370 // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
21371 // arm must key off [`MeshPolicy::mtls_required`], not the raw
21372 // `.mtls_required` field access. Structurally: toggling ONLY
21373 // the `mtls_required` slot on an otherwise-default MeshPolicy
21374 // must flip `is_empty()` from `true` (all-`None`) to `false`
21375 // (one axis carries a value); the flip must be observed for
21376 // both `Some(true)` and `Some(false)` since the emptiness
21377 // semantic reads "any axis carries a value" — not "any axis
21378 // carries a truthy value" — the same non-collapsing shape the
21379 // sibling M2 [`crate::LimitsSpec::is_empty`] /
21380 // [`crate::BehaviorSpec::is_empty`] predicates carry on their
21381 // peer `Option<T>`-typed slot surfaces.
21382 //
21383 // Pins against a future silent detour that re-derived the
21384 // emptiness predicate off a peer axis (an accidental
21385 // `.rate_limit.is_none()`-only chain that dropped the
21386 // `mtls_required` arm entirely), a `mtls_required == Some(_)`
21387 // collapse to a truthy-only check (which would silently
21388 // classify `Some(false)` as empty), or an accessor-side
21389 // detour that no longer names the substrate-primitive typed
21390 // dispatch (an accidental `self.mtls_required.unwrap_or(false)
21391 // == false` fallback in the accessor that would silently
21392 // classify both `None` and `Some(false)` as the same value).
21393 //
21394 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
21395 // (7cd2a28) accessor-composition pin on the sibling optional-
21396 // scalar axis — same "the emptiness / shape-gate predicate
21397 // must route through the substrate-primitive typed dispatch"
21398 // discipline extended onto the peer per-`:politicas` emptiness
21399 // predicate.
21400 let empty = MeshPolicy::default();
21401 assert!(
21402 empty.is_empty(),
21403 "MeshPolicy::default() must be is_empty() — every axis \
21404 defaults to None",
21405 );
21406 for required in [Some(true), Some(false)] {
21407 let p = MeshPolicy {
21408 mtls_required: required,
21409 ..MeshPolicy::default()
21410 };
21411 assert!(
21412 !p.is_empty(),
21413 "MeshPolicy::is_empty must return false when \
21414 :mtls-required is {required:?} — the emptiness \
21415 predicate reads \"any axis carries a value\", not \
21416 \"any axis carries a truthy value\"",
21417 );
21418 assert_eq!(
21419 p.mtls_required().is_none(),
21420 p.is_empty(),
21421 "when :mtls-required is the only set axis, \
21422 is_empty() must equal mtls_required().is_none() — \
21423 the accessor and the emptiness predicate must \
21424 route through the same substrate-primitive typed \
21425 dispatch on the :mtls-required arm",
21426 );
21427 }
21428 }
21429
21430 #[test]
21431 fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
21432 // The by-copy pin: [`MeshPolicy::mtls_required`] returns
21433 // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
21434 // accessor must return by value, not by reference. Peer of the
21435 // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
21436 // borrow-invariant pin on the sibling `Option<String>` slot,
21437 // but extended onto the peer `Option<bool>` copy-invariant
21438 // shape — the accessor's returned `Option<bool>` must outlive
21439 // `&self` (multiple calls must return equal values from a
21440 // dropped-`&self` copy, since the returned Option carries no
21441 // borrow), and calling the accessor twice on the same
21442 // MeshPolicy must yield the same `Option<bool>` verbatim
21443 // (idempotent, no side effects on `&self`).
21444 //
21445 // Pins against a future silent detour that returned
21446 // `Option<&bool>` (which would type-check but silently break
21447 // every downstream caller — [`single_field_overlay`]'s first
21448 // parameter is `Option<T: Clone>`, and `&bool` would fold to a
21449 // detached copy at the call site), an accidental
21450 // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
21451 // would also type-check but return `Option<&bool>`), or a
21452 // one-arm-only accessor that reads `Some(*b)` in the Some arm
21453 // but reads a fresh Default::default() in the None arm.
21454 for required in [None, Some(true), Some(false)] {
21455 let p = MeshPolicy {
21456 mtls_required: required,
21457 ..MeshPolicy::default()
21458 };
21459 let first = p.mtls_required();
21460 let second = p.mtls_required();
21461 assert_eq!(
21462 first, second,
21463 "MeshPolicy::mtls_required must be idempotent — two \
21464 successive calls on the same &self must return the \
21465 same Option<bool>",
21466 );
21467 assert_eq!(
21468 first, required,
21469 "MeshPolicy::mtls_required must return :politicas \
21470 :mtls-required verbatim by copy — got {first:?}, \
21471 expected {required:?}",
21472 );
21473 }
21474 }
21475
21476 #[test]
21477 fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
21478 // The canonical per-`:politicas` `:retries` transient-failure-
21479 // retry-budget scalar pin: [`MeshPolicy::retries`] must return
21480 // the `:politicas :retries` typed `u32` verbatim as an
21481 // `Option<u32>`, byte-equal to the raw field access across every
21482 // representative value in the accept-set — `None` (cluster
21483 // default applies — typically "no retries beyond a single
21484 // dispatch attempt" the caixa-mesh `retry_overlay` builder
21485 // documents), `Some(1)` (the lower boundary of the
21486 // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
21487 // `AplicacaoSpec::validate_politicas` gate carves out on the
21488 // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
21489 // (the upper boundary the same gate carves out on the sibling
21490 // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
21491 // past-the-guard sentinel that pins the accessor doesn't perform
21492 // a silent bounds-collapse at the return path).
21493 //
21494 // Sibling of the peer per-`:politicas`
21495 // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
21496 // sibling `Option<Copy-T>` optional-scalar axis, extended to the
21497 // peer per-`:politicas` `Option<u32>` shape — second
21498 // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
21499 // Pins against a future silent detour that re-derived the retry
21500 // cap from a peer axis (an accidental `.circuit_breaker
21501 // .as_ref().map(|b| b.max_failures)` collapse that read the
21502 // breaker's max-failure count as a retry budget), a
21503 // `None → Some(0)` cluster-default projection (which would
21504 // silently re-introduce the `PolicyRetriesZero` refusal case at
21505 // the emit boundary), or a bounds-collapsing accessor that
21506 // clamped the return through `POLICY_RETRIES_MAX` (the
21507 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
21508 // must ship the raw slot verbatim so a validate-time gate
21509 // regression surfaces at the emit boundary rather than being
21510 // silently absorbed).
21511 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
21512 let p = MeshPolicy {
21513 retries,
21514 ..MeshPolicy::default()
21515 };
21516 assert_eq!(
21517 p.retries(),
21518 retries,
21519 "MeshPolicy::retries must return :politicas :retries \
21520 verbatim (got {:?}, expected {retries:?})",
21521 p.retries(),
21522 );
21523 assert_eq!(
21524 p.retries(),
21525 p.retries,
21526 "MeshPolicy::retries must byte-equal the raw .retries \
21527 field access across every value in the accept-set",
21528 );
21529 }
21530 }
21531
21532 #[test]
21533 fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
21534 // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
21535 // must key off [`MeshPolicy::retries`], not the raw `.retries`
21536 // field access. Structurally: toggling ONLY the `retries` slot
21537 // on an otherwise-default MeshPolicy must flip `is_empty()`
21538 // from `true` (all-`None`) to `false` (one axis carries a
21539 // value); the flip must be observed for every value in the
21540 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
21541 // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
21542 // the emptiness semantic reads "any axis carries a value" —
21543 // not "any axis carries a value the validate gate accepts" —
21544 // the same non-collapsing shape the peer M2
21545 // [`crate::LimitsSpec::is_empty`] /
21546 // [`crate::BehaviorSpec::is_empty`] predicates carry.
21547 //
21548 // Pins against a future silent detour that re-derived the
21549 // emptiness predicate off a peer axis (an accidental
21550 // `.rate_limit.is_none()`-only chain that dropped the
21551 // `retries` arm entirely), a `retries == Some(_)` collapse
21552 // that key-off a validate-gate-clamped bounds check (which
21553 // would silently classify a past-the-guard `Some(u32::MAX)`
21554 // as empty because it fails the `1..=POLICY_RETRIES_MAX`
21555 // check), or an accessor-side detour that no longer names the
21556 // substrate-primitive typed dispatch.
21557 //
21558 // Sibling of the peer per-`:politicas`
21559 // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
21560 // pin on the sibling `Option<Copy-T>` optional-scalar axis —
21561 // same "the emptiness predicate must route through the
21562 // substrate-primitive typed dispatch" discipline extended onto
21563 // the peer per-`:politicas` `Option<u32>` axis.
21564 let empty = MeshPolicy::default();
21565 assert!(
21566 empty.is_empty(),
21567 "MeshPolicy::default() must be is_empty() — every axis \
21568 defaults to None",
21569 );
21570 for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
21571 let p = MeshPolicy {
21572 retries,
21573 ..MeshPolicy::default()
21574 };
21575 assert!(
21576 !p.is_empty(),
21577 "MeshPolicy::is_empty must return false when \
21578 :retries is {retries:?} — the emptiness \
21579 predicate reads \"any axis carries a value\", not \
21580 \"any axis carries a value the validate gate \
21581 accepts\"",
21582 );
21583 assert_eq!(
21584 p.retries().is_none(),
21585 p.is_empty(),
21586 "when :retries is the only set axis, is_empty() \
21587 must equal retries().is_none() — the accessor and \
21588 the emptiness predicate must route through the same \
21589 substrate-primitive typed dispatch on the :retries \
21590 arm",
21591 );
21592 }
21593 }
21594
21595 #[test]
21596 fn mesh_policy_retries_projects_option_u32_by_copy() {
21597 // The by-copy pin: [`MeshPolicy::retries`] returns
21598 // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
21599 // accessor must return by value, not by reference. Sibling of
21600 // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
21601 // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
21602 // extended onto the sibling `Option<u32>` copy-invariant
21603 // shape — the accessor's returned `Option<u32>` must outlive
21604 // `&self` (multiple calls must return equal values from a
21605 // dropped-`&self` copy, since the returned Option carries no
21606 // borrow), and calling the accessor twice on the same
21607 // MeshPolicy must yield the same `Option<u32>` verbatim
21608 // (idempotent, no side effects on `&self`).
21609 //
21610 // Pins against a future silent detour that returned
21611 // `Option<&u32>` (which would type-check but silently break
21612 // every downstream caller — [`crate::render::single_field_overlay`]'s
21613 // first parameter is `Option<T: Clone>`, and `&u32` would
21614 // fold to a detached copy at the call site), an accidental
21615 // `Option::as_ref()` projection (`self.retries.as_ref()` would
21616 // also type-check but return `Option<&u32>`), or a one-arm-
21617 // only accessor that reads `Some(*n)` in the Some arm but
21618 // reads a fresh `Default::default()` (`0_u32`) in the None
21619 // arm.
21620 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
21621 let p = MeshPolicy {
21622 retries,
21623 ..MeshPolicy::default()
21624 };
21625 let first = p.retries();
21626 let second = p.retries();
21627 assert_eq!(
21628 first, second,
21629 "MeshPolicy::retries must be idempotent — two \
21630 successive calls on the same &self must return the \
21631 same Option<u32>",
21632 );
21633 assert_eq!(
21634 first, retries,
21635 "MeshPolicy::retries must return :politicas :retries \
21636 verbatim by copy — got {first:?}, expected {retries:?}",
21637 );
21638 }
21639 }
21640
21641 #[test]
21642 fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
21643 // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
21644 // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
21645 // return the `:politicas :timeout` typed [`Duration`] verbatim
21646 // as an `Option<Duration>`, byte-equal to the raw field access
21647 // across every representative value in the accept-set — `None`
21648 // (cluster default applies — typically the gateway class's
21649 // implementation-side per-request wall-clock cap the caixa-mesh
21650 // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
21651 // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
21652 // set the surrounding `AplicacaoSpec::validate_politicas` gate
21653 // carves out on the sibling `PolicyTimeoutZero` /
21654 // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
21655 // (the upper boundary the same gate carves out on the sibling
21656 // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
21657 // (a past-the-guard sentinel that pins the accessor doesn't
21658 // perform a silent bounds-collapse into `None` on the zero-
21659 // Duration arm — validate rejects zero but the accessor must
21660 // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
21661 // past-the-guard sentinel that pins the accessor doesn't
21662 // perform a silent bounds-collapse at the return path).
21663 //
21664 // Sibling of the peer per-`:politicas`
21665 // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
21666 // `Option<u32>` optional-scalar axis and the peer per-
21667 // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
21668 // pin on the sibling `Option<bool>` optional-scalar axis,
21669 // extended onto the peer per-`:politicas` `Option<Duration>`
21670 // shape — third `Option<Copy-T>`-return accessor on the M3
21671 // mesh-slot family. Pins against a future silent detour that
21672 // re-derived the per-call cap from a peer axis (an accidental
21673 // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
21674 // read the breaker's rolling-window duration as a per-call
21675 // deadline), a `None → Some(Duration::MAX)` cluster-default
21676 // projection (which would silently re-introduce the
21677 // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
21678 // blocking" arm at the emit boundary), or a bounds-collapsing
21679 // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
21680 // (the `AplicacaoSpec::validate` gate owns the bounds; the
21681 // accessor must ship the raw slot verbatim so a validate-time
21682 // gate regression surfaces at the emit boundary rather than
21683 // being silently absorbed).
21684 for timeout in [
21685 None,
21686 Some(Duration::from_millis(1)),
21687 Some(POLICY_TIMEOUT_MAX),
21688 Some(Duration::ZERO),
21689 Some(Duration::MAX),
21690 ] {
21691 let p = MeshPolicy {
21692 timeout,
21693 ..MeshPolicy::default()
21694 };
21695 assert_eq!(
21696 p.timeout(),
21697 timeout,
21698 "MeshPolicy::timeout must return :politicas :timeout \
21699 verbatim (got {:?}, expected {timeout:?})",
21700 p.timeout(),
21701 );
21702 assert_eq!(
21703 p.timeout(),
21704 p.timeout,
21705 "MeshPolicy::timeout must byte-equal the raw .timeout \
21706 field access across every value in the accept-set",
21707 );
21708 }
21709 }
21710
21711 #[test]
21712 fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
21713 // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
21714 // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
21715 // field access. Structurally: toggling ONLY the `timeout` slot
21716 // on an otherwise-default MeshPolicy must flip `is_empty()`
21717 // from `true` (all-`None`) to `false` (one axis carries a
21718 // value); the flip must be observed for every value in the
21719 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
21720 // gate accepts (`Some(Duration::from_millis(1))`,
21721 // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
21722 // reads "any axis carries a value" — not "any axis carries a
21723 // value the validate gate accepts" — the same non-collapsing
21724 // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
21725 // [`crate::BehaviorSpec::is_empty`] predicates carry.
21726 //
21727 // Pins against a future silent detour that re-derived the
21728 // emptiness predicate off a peer axis (an accidental
21729 // `.rate_limit.is_none()`-only chain that dropped the
21730 // `timeout` arm entirely), a `timeout == Some(_)` collapse
21731 // that key-off a validate-gate-clamped bounds check (which
21732 // would silently classify a past-the-guard `Some(Duration::MAX)`
21733 // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
21734 // check), or an accessor-side detour that no longer names the
21735 // substrate-primitive typed dispatch.
21736 //
21737 // Sibling of the peer per-`:politicas`
21738 // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
21739 // the sibling `Option<u32>` optional-scalar axis and the peer
21740 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
21741 // accessor-composition pin on the sibling `Option<bool>`
21742 // optional-scalar axis — same "the emptiness predicate must
21743 // route through the substrate-primitive typed dispatch"
21744 // discipline extended onto the peer per-`:politicas`
21745 // `Option<Duration>` axis.
21746 let empty = MeshPolicy::default();
21747 assert!(
21748 empty.is_empty(),
21749 "MeshPolicy::default() must be is_empty() — every axis \
21750 defaults to None",
21751 );
21752 for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
21753 let p = MeshPolicy {
21754 timeout,
21755 ..MeshPolicy::default()
21756 };
21757 assert!(
21758 !p.is_empty(),
21759 "MeshPolicy::is_empty must return false when \
21760 :timeout is {timeout:?} — the emptiness \
21761 predicate reads \"any axis carries a value\", not \
21762 \"any axis carries a value the validate gate \
21763 accepts\"",
21764 );
21765 assert_eq!(
21766 p.timeout().is_none(),
21767 p.is_empty(),
21768 "when :timeout is the only set axis, is_empty() \
21769 must equal timeout().is_none() — the accessor and \
21770 the emptiness predicate must route through the same \
21771 substrate-primitive typed dispatch on the :timeout \
21772 arm",
21773 );
21774 }
21775 }
21776
21777 #[test]
21778 fn mesh_policy_timeout_projects_option_duration_by_copy() {
21779 // The by-copy pin: [`MeshPolicy::timeout`] returns
21780 // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
21781 // and the accessor must return by value, not by reference.
21782 // Sibling of the peer per-`:politicas`
21783 // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
21784 // sibling `Option<u32>` optional-scalar axis and the peer
21785 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
21786 // by-copy pin on the sibling `Option<bool>` optional-scalar
21787 // axis, extended onto the peer per-`:politicas`
21788 // `Option<Duration>` copy-invariant shape — the accessor's
21789 // returned `Option<Duration>` must outlive `&self` (multiple
21790 // calls must return equal values from a dropped-`&self`
21791 // copy, since the returned Option carries no borrow), and
21792 // calling the accessor twice on the same MeshPolicy must
21793 // yield the same `Option<Duration>` verbatim (idempotent, no
21794 // side effects on `&self`).
21795 //
21796 // Pins against a future silent detour that returned
21797 // `Option<&Duration>` (which would type-check but silently
21798 // break every downstream caller — [`crate::render::single_field_overlay`]'s
21799 // first parameter is `Option<T: Clone>`, and `&Duration`
21800 // would fold to a detached copy at the call site), an
21801 // accidental `Option::as_ref()` projection
21802 // (`self.timeout.as_ref()` would also type-check but return
21803 // `Option<&Duration>`), or a one-arm-only accessor that
21804 // reads `Some(*d)` in the Some arm but reads a fresh
21805 // `Default::default()` (`Duration::ZERO`) in the None arm
21806 // (which would silently re-classify every unset `:timeout`
21807 // as the `PolicyTimeoutZero`-refused zero-Duration value at
21808 // the accessor boundary).
21809 for timeout in [
21810 None,
21811 Some(Duration::from_millis(1)),
21812 Some(POLICY_TIMEOUT_MAX),
21813 Some(Duration::ZERO),
21814 Some(Duration::MAX),
21815 ] {
21816 let p = MeshPolicy {
21817 timeout,
21818 ..MeshPolicy::default()
21819 };
21820 let first = p.timeout();
21821 let second = p.timeout();
21822 assert_eq!(
21823 first, second,
21824 "MeshPolicy::timeout must be idempotent — two \
21825 successive calls on the same &self must return the \
21826 same Option<Duration>",
21827 );
21828 assert_eq!(
21829 first, timeout,
21830 "MeshPolicy::timeout must return :politicas :timeout \
21831 verbatim by copy — got {first:?}, expected {timeout:?}",
21832 );
21833 }
21834 }
21835
21836 #[test]
21837 fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
21838 // The canonical per-`:politicas` `:rate-limit` Envoy-
21839 // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
21840 // [`MeshPolicy::rate_limit`] must return the `:politicas
21841 // :rate-limit` typed [`RateLimit`] verbatim as an
21842 // `Option<RateLimit>`, byte-equal to the raw field access
21843 // across every representative value in the accept-set — `None`
21844 // (cluster default applies — no per-Aplicacao rate declaration,
21845 // the gateway-class per-listener default arm the future caixa-
21846 // mesh `local_rate_limit_overlay` emitter documents),
21847 // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
21848 // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
21849 // accept-set the surrounding
21850 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
21851 // sibling `PolicyRateLimitZero` refusal, paired with the
21852 // canonical-window "1 second" arm of the three-unit
21853 // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
21854 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
21855 // (the upper boundary the same gate carves out on the sibling
21856 // `PolicyRateLimitExceedsCap` refusal, paired with the
21857 // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
21858 // (a past-the-guard sentinel that pins the accessor doesn't
21859 // perform a silent bounds-collapse into `None` on the
21860 // zero-rate/zero-window arm — validate rejects zero but the
21861 // accessor must ship the raw slot verbatim so a validate-time
21862 // gate regression surfaces at the emit boundary rather than
21863 // being silently absorbed), and
21864 // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
21865 // (a past-the-guard sentinel that pins the accessor doesn't
21866 // perform a silent bounds-collapse at the return path).
21867 //
21868 // First `Option<Copy-composite-T>`-return accessor pin on the
21869 // M3 mesh-slot family (peer of the sibling per-`:politicas`
21870 // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
21871 // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
21872 // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
21873 // Copy accessor pins, extended onto the peer per-`:politicas`
21874 // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
21875 // and the accessor returns by value). Pins against a future
21876 // silent detour that re-derived the rate declaration from a
21877 // peer axis (an accidental
21878 // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
21879 // collapse that read the breaker's trip threshold + rolling
21880 // window as a rate declaration), a `None → Some(default())`
21881 // cluster-default projection (which would silently re-
21882 // introduce a "cluster default is 0/s" arm the emit boundary
21883 // would take as "declared but inert" — the canonical
21884 // declared-but-inert footgun the sibling
21885 // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
21886 // amplification-shape axis), a bounds-collapsing accessor
21887 // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
21888 // clamped `rl.window` through [`is_canonical_rate_limit_window`]
21889 // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
21890 // accessor must ship the raw slot verbatim), or a
21891 // by-reference detour (`Option<&RateLimit>`) that broke every
21892 // downstream consumer keying off `Option<RateLimit>` by-copy.
21893 for rl in [
21894 None,
21895 Some(RateLimit {
21896 rate: 1,
21897 window: Duration::from_secs(1),
21898 }),
21899 Some(RateLimit {
21900 rate: POLICY_RATE_LIMIT_MAX,
21901 window: Duration::from_secs(3600),
21902 }),
21903 Some(RateLimit {
21904 rate: 0,
21905 window: Duration::ZERO,
21906 }),
21907 Some(RateLimit {
21908 rate: u32::MAX,
21909 window: Duration::MAX,
21910 }),
21911 ] {
21912 let p = MeshPolicy {
21913 rate_limit: rl,
21914 ..MeshPolicy::default()
21915 };
21916 assert_eq!(
21917 p.rate_limit(),
21918 rl,
21919 "MeshPolicy::rate_limit must return :politicas :rate-limit \
21920 verbatim (got {:?}, expected {rl:?})",
21921 p.rate_limit(),
21922 );
21923 assert_eq!(
21924 p.rate_limit(),
21925 p.rate_limit,
21926 "MeshPolicy::rate_limit must byte-equal the raw \
21927 .rate_limit field access across every value in the \
21928 accept-set",
21929 );
21930 }
21931 }
21932
21933 #[test]
21934 fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
21935 // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
21936 // must key off [`MeshPolicy::rate_limit`], not the raw
21937 // `.rate_limit` field access. Structurally: toggling ONLY the
21938 // `rate_limit` slot on an otherwise-default MeshPolicy must
21939 // flip `is_empty()` from `true` (all-`None`) to `false` (one
21940 // axis carries a value); the flip must be observed for every
21941 // representative value in the accept-set the surrounding
21942 // [`AplicacaoSpec::validate_politicas`] gate accepts
21943 // (`Some(RateLimit { rate: 1, window: 1s })`,
21944 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
21945 // since the emptiness semantic reads "any axis carries a
21946 // value" — not "any axis carries a value the validate gate
21947 // accepts" — the same non-collapsing shape the peer M2
21948 // [`crate::LimitsSpec::is_empty`] /
21949 // [`crate::BehaviorSpec::is_empty`] predicates carry.
21950 //
21951 // Pins against a future silent detour that re-derived the
21952 // emptiness predicate off a peer axis (an accidental
21953 // `.timeout.is_none()`-only chain that dropped the
21954 // `rate_limit` arm entirely — the last unlifted inline field
21955 // access on `is_empty` before this lift), a `rate_limit ==
21956 // Some(_)` collapse that key-off a validate-gate-clamped
21957 // bounds check (which would silently classify a past-the-
21958 // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
21959 // because it fails the value-shape gate), or an accessor-
21960 // side detour that no longer names the substrate-primitive
21961 // typed dispatch.
21962 //
21963 // Fourth "the emptiness predicate must route through the
21964 // substrate-primitive typed dispatch" composition pin on the
21965 // M3 mesh-slot family — closes the last unlifted composition
21966 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
21967 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
21968 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
21969 // 7073d0f is_empty-composition pins on the sibling primitive-
21970 // Copy axes, extended onto the peer per-`:politicas`
21971 // composite-Copy `Option<RateLimit>` axis).
21972 let empty = MeshPolicy::default();
21973 assert!(
21974 empty.is_empty(),
21975 "MeshPolicy::default() must be is_empty() — every axis \
21976 defaults to None",
21977 );
21978 for rl in [
21979 RateLimit {
21980 rate: 1,
21981 window: Duration::from_secs(1),
21982 },
21983 RateLimit {
21984 rate: POLICY_RATE_LIMIT_MAX,
21985 window: Duration::from_secs(3600),
21986 },
21987 ] {
21988 let p = MeshPolicy {
21989 rate_limit: Some(rl),
21990 ..MeshPolicy::default()
21991 };
21992 assert!(
21993 !p.is_empty(),
21994 "MeshPolicy::is_empty must return false when \
21995 :rate-limit is {rl:?} — the emptiness predicate \
21996 reads \"any axis carries a value\", not \"any axis \
21997 carries a value the validate gate accepts\"",
21998 );
21999 assert_eq!(
22000 p.rate_limit().is_none(),
22001 p.is_empty(),
22002 "when :rate-limit is the only set axis, is_empty() \
22003 must equal rate_limit().is_none() — the accessor \
22004 and the emptiness predicate must route through the \
22005 same substrate-primitive typed dispatch on the \
22006 :rate-limit arm",
22007 );
22008 }
22009 }
22010
22011 #[test]
22012 fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
22013 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22014 // `:rate-limit` value-shape gate must key off
22015 // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
22016 // field bind. Structurally: a `MeshPolicy` whose only set
22017 // axis is a `Some(RateLimit { rate: 0, .. })` must surface
22018 // the `PolicyRateLimitZero` refusal exactly, and the same
22019 // MeshPolicy with the rate at the canonical lower boundary
22020 // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
22021 // The pair jointly pins the accessor + validate-gate
22022 // composition: any future silent detour that had the accessor
22023 // omit the `Some(RateLimit { rate: 0, .. })` arm (a
22024 // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
22025 // silently absorb the `PolicyRateLimitZero` refusal at the
22026 // accessor boundary — the composition pin catches that at
22027 // caixa-core build time.
22028 //
22029 // Sibling of the peer [`validate_politicas`]
22030 // `:mtls-required` / `:retries` / `:timeout` composition pins
22031 // on the sibling primitive-Copy optional-scalar axes — same
22032 // "the validate / shape-gate predicate must route through the
22033 // substrate-primitive typed dispatch" discipline extended
22034 // onto the peer per-`:politicas` composite-Copy
22035 // `Option<RateLimit>` axis. Second composition-with-accessor
22036 // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
22037 // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
22038 let mut spec = three_member_spec();
22039 spec.politicas = MeshPolicy {
22040 rate_limit: Some(RateLimit {
22041 rate: 0,
22042 window: Duration::from_secs(1),
22043 }),
22044 ..MeshPolicy::default()
22045 };
22046 assert!(
22047 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
22048 "validate_politicas must reject rate == 0 with \
22049 PolicyRateLimitZero — the accessor and the validate gate \
22050 must route through the same substrate-primitive typed \
22051 dispatch on the :rate-limit zero-floor arm",
22052 );
22053 spec.politicas = MeshPolicy {
22054 rate_limit: Some(RateLimit {
22055 rate: 1,
22056 window: Duration::from_secs(1),
22057 }),
22058 ..MeshPolicy::default()
22059 };
22060 assert!(
22061 spec.validate().is_ok(),
22062 "validate_politicas must accept rate == 1 (the canonical \
22063 lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
22064 set) with a canonical 1s window",
22065 );
22066 }
22067
22068 #[test]
22069 fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
22070 // The canonical per-`:politicas` `:circuit-breaker` Envoy-
22071 // `outlier_detection`-mesh consecutive-failure-ejection scalar
22072 // pin: [`MeshPolicy::circuit_breaker`] must return the
22073 // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
22074 // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
22075 // raw field access across every representative value in the
22076 // accept-set — `None` (cluster default applies — no
22077 // per-Aplicacao breaker declaration, the gateway-class per-
22078 // listener default arm the future caixa-mesh
22079 // `outlier_detection_overlay` emitter documents),
22080 // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
22081 // (the lower boundary of the accept-set the surrounding
22082 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
22083 // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
22084 // refusals),
22085 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
22086 // (the upper boundary the same gate carves out on the sibling
22087 // `PolicyBreakerMaxFailuresExceedsCap` /
22088 // `PolicyBreakerWindowExceedsCap` refusals),
22089 // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
22090 // (a past-the-guard sentinel that pins the accessor doesn't
22091 // perform a silent bounds-collapse into `None` on the
22092 // zero-failures/zero-window arm — validate rejects zero but
22093 // the accessor must ship the raw slot verbatim so a validate-
22094 // time gate regression surfaces at the emit boundary rather
22095 // than being silently absorbed), and
22096 // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
22097 // (a past-the-guard sentinel that pins the accessor doesn't
22098 // perform a silent bounds-collapse at the return path).
22099 //
22100 // Second `Option<Copy-composite-T>`-return accessor pin on the
22101 // M3 mesh-slot family (peer of the sibling per-`:politicas`
22102 // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
22103 // composite-Copy accessor pin, and of the sibling per-
22104 // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
22105 // [`MeshPolicy::retries`] bdfb399 /
22106 // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
22107 // accessor pins). Pins against a future silent detour that
22108 // re-derived the breaker declaration from a peer axis (an
22109 // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
22110 // collapse that read the rate-limit's bucket capacity + refill
22111 // period as a breaker declaration), a `None → Some(default())`
22112 // cluster-default projection (which would silently re-
22113 // introduce the `PolicyBreakerZeroFailures` /
22114 // `PolicyBreakerZeroWindow` refusal cases at the emit
22115 // boundary), a bounds-collapsing accessor that clamped
22116 // `cb.max_failures` through
22117 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
22118 // through [`POLICY_BREAKER_WINDOW_MAX`] (the
22119 // [`AplicacaoSpec::validate`] gate owns the bounds; the
22120 // accessor must ship the raw slot verbatim), or a
22121 // by-reference detour (`Option<&CircuitBreaker>`) that broke
22122 // every downstream consumer keying off `Option<CircuitBreaker>`
22123 // by-copy.
22124 for cb in [
22125 None,
22126 Some(CircuitBreaker {
22127 max_failures: 1,
22128 window: Duration::from_millis(1),
22129 }),
22130 Some(CircuitBreaker {
22131 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
22132 window: POLICY_BREAKER_WINDOW_MAX,
22133 }),
22134 Some(CircuitBreaker {
22135 max_failures: 0,
22136 window: Duration::ZERO,
22137 }),
22138 Some(CircuitBreaker {
22139 max_failures: u32::MAX,
22140 window: Duration::MAX,
22141 }),
22142 ] {
22143 let p = MeshPolicy {
22144 circuit_breaker: cb,
22145 ..MeshPolicy::default()
22146 };
22147 assert_eq!(
22148 p.circuit_breaker(),
22149 cb,
22150 "MeshPolicy::circuit_breaker must return :politicas \
22151 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
22152 p.circuit_breaker(),
22153 );
22154 assert_eq!(
22155 p.circuit_breaker(),
22156 p.circuit_breaker,
22157 "MeshPolicy::circuit_breaker must byte-equal the raw \
22158 .circuit_breaker field access across every value in \
22159 the accept-set",
22160 );
22161 }
22162 }
22163
22164 #[test]
22165 fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
22166 // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
22167 // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
22168 // `.circuit_breaker` field access. Structurally: toggling ONLY
22169 // the `circuit_breaker` slot on an otherwise-default MeshPolicy
22170 // must flip `is_empty()` from `true` (all-`None`) to `false`
22171 // (one axis carries a value); the flip must be observed for
22172 // every representative value in the accept-set the surrounding
22173 // [`AplicacaoSpec::validate_politicas`] gate accepts
22174 // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
22175 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
22176 // since the emptiness semantic reads "any axis carries a
22177 // value" — not "any axis carries a value the validate gate
22178 // accepts" — the same non-collapsing shape the peer M2
22179 // [`crate::LimitsSpec::is_empty`] /
22180 // [`crate::BehaviorSpec::is_empty`] predicates carry.
22181 //
22182 // Pins against a future silent detour that re-derived the
22183 // emptiness predicate off a peer axis (an accidental
22184 // `.rate_limit.is_none()`-only chain that dropped the
22185 // `circuit_breaker` arm entirely — the last unlifted inline
22186 // field access on `is_empty` before this lift), a
22187 // `circuit_breaker == Some(_)` collapse that key-off a
22188 // validate-gate-clamped bounds check (which would silently
22189 // classify a past-the-guard `Some(CircuitBreaker { max_failures:
22190 // 0, window: 0s })` as empty because it fails the value-shape
22191 // gate), or an accessor-side detour that no longer names the
22192 // substrate-primitive typed dispatch.
22193 //
22194 // Fifth "the emptiness predicate must route through the
22195 // substrate-primitive typed dispatch" composition pin on the
22196 // M3 mesh-slot family — closes the last unlifted composition
22197 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
22198 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
22199 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
22200 // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
22201 // composition pins on the sibling primitive-Copy + composite-
22202 // Copy axes, extended onto the peer per-`:politicas`
22203 // composite-Copy `Option<CircuitBreaker>` axis).
22204 let empty = MeshPolicy::default();
22205 assert!(
22206 empty.is_empty(),
22207 "MeshPolicy::default() must be is_empty() — every axis \
22208 defaults to None",
22209 );
22210 for cb in [
22211 CircuitBreaker {
22212 max_failures: 1,
22213 window: Duration::from_millis(1),
22214 },
22215 CircuitBreaker {
22216 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
22217 window: POLICY_BREAKER_WINDOW_MAX,
22218 },
22219 ] {
22220 let p = MeshPolicy {
22221 circuit_breaker: Some(cb),
22222 ..MeshPolicy::default()
22223 };
22224 assert!(
22225 !p.is_empty(),
22226 "MeshPolicy::is_empty must return false when \
22227 :circuit-breaker is {cb:?} — the emptiness predicate \
22228 reads \"any axis carries a value\", not \"any axis \
22229 carries a value the validate gate accepts\"",
22230 );
22231 assert_eq!(
22232 p.circuit_breaker().is_none(),
22233 p.is_empty(),
22234 "when :circuit-breaker is the only set axis, \
22235 is_empty() must equal circuit_breaker().is_none() — \
22236 the accessor and the emptiness predicate must route \
22237 through the same substrate-primitive typed dispatch \
22238 on the :circuit-breaker arm",
22239 );
22240 }
22241 }
22242
22243 #[test]
22244 fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
22245 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22246 // `:circuit-breaker` value-shape gate must key off
22247 // [`MeshPolicy::circuit_breaker`], not the raw
22248 // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
22249 // whose only set axis is a `Some(CircuitBreaker { max_failures:
22250 // 0, .. })` must surface the `PolicyBreakerZeroFailures`
22251 // refusal exactly, and the same MeshPolicy with the breaker at
22252 // the canonical lower boundary
22253 // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
22254 // pass validate. The pair jointly pins the accessor +
22255 // validate-gate composition: any future silent detour that had
22256 // the accessor omit the `Some(CircuitBreaker { max_failures:
22257 // 0, .. })` arm (a
22258 // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
22259 // collapse) would silently absorb the
22260 // `PolicyBreakerZeroFailures` refusal at the accessor
22261 // boundary — the composition pin catches that at caixa-core
22262 // build time.
22263 //
22264 // Sibling of the peer [`validate_politicas`]
22265 // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
22266 // composition pins on the sibling primitive-Copy + composite-
22267 // Copy optional-scalar axes — same "the validate / shape-gate
22268 // predicate must route through the substrate-primitive typed
22269 // dispatch" discipline extended onto the peer per-`:politicas`
22270 // composite-Copy `Option<CircuitBreaker>` axis. Second
22271 // composition-with-accessor pin on the M3 mesh-slot
22272 // `Option<CircuitBreaker>` arm alongside the
22273 // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
22274 let mut spec = three_member_spec();
22275 spec.politicas = MeshPolicy {
22276 circuit_breaker: Some(CircuitBreaker {
22277 max_failures: 0,
22278 window: Duration::from_millis(1),
22279 }),
22280 ..MeshPolicy::default()
22281 };
22282 assert!(
22283 matches!(
22284 spec.validate(),
22285 Err(AplicacaoError::PolicyBreakerZeroFailures)
22286 ),
22287 "validate_politicas must reject max_failures == 0 with \
22288 PolicyBreakerZeroFailures — the accessor and the validate \
22289 gate must route through the same substrate-primitive \
22290 typed dispatch on the :circuit-breaker zero-floor arm",
22291 );
22292 spec.politicas = MeshPolicy {
22293 circuit_breaker: Some(CircuitBreaker {
22294 max_failures: 1,
22295 window: Duration::from_millis(1),
22296 }),
22297 ..MeshPolicy::default()
22298 };
22299 assert!(
22300 spec.validate().is_ok(),
22301 "validate_politicas must accept a CircuitBreaker at the \
22302 canonical lower boundary (max_failures = 1, window = \
22303 1ms) — the accessor and the validate gate must route \
22304 through the same substrate-primitive typed dispatch on \
22305 the :circuit-breaker arm",
22306 );
22307 }
22308
22309 #[test]
22310 fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
22311 // The canonical per-`:politicas :circuit-breaker` `:max-failures`
22312 // Envoy-outlier-detection trip-threshold scalar pin:
22313 // [`CircuitBreaker::max_failures`] must return the
22314 // `:politicas :circuit-breaker :max-failures` typed `u32`
22315 // verbatim, byte-equal to the raw field access across every
22316 // representative value in the accept-set — `1` (the lower
22317 // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
22318 // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
22319 // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
22320 // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
22321 // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
22322 // refusal), `0` (a past-the-guard sentinel that pins the accessor
22323 // doesn't perform a silent bounds-collapse into `1` on the zero
22324 // arm — validate rejects zero but the accessor must ship the
22325 // raw slot verbatim so a validate-time gate regression surfaces
22326 // at the emit boundary rather than being silently absorbed),
22327 // `u32::MAX` (a past-the-guard sentinel that pins the accessor
22328 // doesn't perform a silent bounds-collapse through
22329 // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
22330 //
22331 // First sub-struct required-scalar accessor pin on the M3
22332 // mesh-slot family — sibling in shape to the peer per-`:membros`
22333 // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
22334 // (a40b0e3) required-`String`-carry accessor pins and the peer
22335 // per-`:contratos` [`WitContract::source`] /
22336 // [`WitContract::destination`] (7f0fd43) required-`String`-carry
22337 // accessor pins, extended onto the peer per-`CircuitBreaker`
22338 // required-`u32` scalar-value axis. Pins against a future silent
22339 // detour that re-derived the trip threshold from a peer axis (an
22340 // accidental `self.window.as_secs() as u32` collapse that read
22341 // the breaker's rolling-window duration as a failure count), a
22342 // `0 → 1` cluster-default projection (which would silently absorb
22343 // the `PolicyBreakerZeroFailures` refusal case at the accessor
22344 // boundary), or a bounds-collapsing accessor that clamped the
22345 // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
22346 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
22347 // must ship the raw slot verbatim).
22348 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
22349 let cb = CircuitBreaker {
22350 max_failures,
22351 window: Duration::from_secs(60),
22352 };
22353 assert_eq!(
22354 cb.max_failures(),
22355 max_failures,
22356 "CircuitBreaker::max_failures must return :politicas \
22357 :circuit-breaker :max-failures verbatim (got {}, \
22358 expected {max_failures})",
22359 cb.max_failures(),
22360 );
22361 assert_eq!(
22362 cb.max_failures(),
22363 cb.max_failures,
22364 "CircuitBreaker::max_failures must byte-equal the raw \
22365 .max_failures field access across every value in the \
22366 u32 accept-set",
22367 );
22368 }
22369 }
22370
22371 #[test]
22372 fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
22373 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22374 // `:circuit-breaker :max-failures` zero-floor arm must key off
22375 // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
22376 // field access. Structurally: a `CircuitBreaker { max_failures:
22377 // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
22378 // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
22379 // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
22380 // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
22381 // pass validate. The pair jointly pins the accessor +
22382 // validate-gate composition: any future silent detour that had
22383 // the accessor return a fresh `1` on the zero arm (a
22384 // `.max_failures().max(1)` collapse) would silently absorb the
22385 // `PolicyBreakerZeroFailures` refusal at the accessor boundary
22386 // and the validate gate would accept a struct-literal
22387 // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
22388 // catches that at caixa-core build time.
22389 //
22390 // Peer of the sibling per-`:politicas`
22391 // [`MeshPolicy::mtls_required`] (c0110f1) /
22392 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
22393 // (7073d0f) accessor-composition pins on the sibling optional-
22394 // scalar axes — same "the validate / shape-gate predicate must
22395 // route through the substrate-primitive typed dispatch"
22396 // discipline extended onto the peer per-`CircuitBreaker`
22397 // required-scalar composition axis.
22398 let mut spec = three_member_spec();
22399 spec.politicas = MeshPolicy {
22400 circuit_breaker: Some(CircuitBreaker {
22401 max_failures: 0,
22402 window: Duration::from_secs(60),
22403 }),
22404 ..MeshPolicy::default()
22405 };
22406 assert!(
22407 matches!(
22408 spec.validate(),
22409 Err(AplicacaoError::PolicyBreakerZeroFailures)
22410 ),
22411 "validate_politicas must reject max_failures == 0 with \
22412 PolicyBreakerZeroFailures — the accessor and the validate \
22413 gate must route through the same substrate-primitive typed \
22414 dispatch on the :max-failures zero-floor arm",
22415 );
22416 spec.politicas = MeshPolicy {
22417 circuit_breaker: Some(CircuitBreaker {
22418 max_failures: 1,
22419 window: Duration::from_secs(60),
22420 }),
22421 ..MeshPolicy::default()
22422 };
22423 assert!(
22424 spec.validate().is_ok(),
22425 "validate_politicas must accept max_failures == 1 (the \
22426 lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
22427 accept-set)",
22428 );
22429 }
22430
22431 #[test]
22432 fn circuit_breaker_max_failures_projects_u32_by_copy() {
22433 // The by-copy pin: [`CircuitBreaker::max_failures`] returns
22434 // `u32` by copy — `u32` is `Copy` and the accessor must return
22435 // by value, not by reference. Peer of the sibling
22436 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
22437 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
22438 // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
22439 // optional-scalar axes, extended onto the peer
22440 // per-`CircuitBreaker` required-`u32` copy-invariant shape —
22441 // the accessor's returned `u32` must outlive `&self` (multiple
22442 // calls must return equal values from a dropped-`&self` copy,
22443 // since the returned scalar carries no borrow), and calling
22444 // the accessor twice on the same CircuitBreaker must yield the
22445 // same `u32` verbatim (idempotent, no side effects on `&self`).
22446 //
22447 // Pins against a future silent detour that returned `&u32`
22448 // (which would type-check but silently break every downstream
22449 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
22450 // first parameter is `u32`, and `&u32` would fold to a detached
22451 // copy at the call site with a `*` deref the sibling accessors
22452 // don't need), an accidental `.max_failures.wrapping_add(0)`
22453 // detour that returned a fresh copy through an arithmetic
22454 // no-op (breaking a future `const fn` regression), or a
22455 // one-arm-only accessor that returned a saturating value on
22456 // some sentinel input (breaking the pass-through invariant the
22457 // sibling required-scalar accessors carry).
22458 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
22459 let cb = CircuitBreaker {
22460 max_failures,
22461 window: Duration::from_secs(60),
22462 };
22463 let first = cb.max_failures();
22464 let second = cb.max_failures();
22465 assert_eq!(
22466 first, second,
22467 "CircuitBreaker::max_failures must be idempotent — two \
22468 successive calls on the same &self must return the \
22469 same u32",
22470 );
22471 assert_eq!(
22472 first, max_failures,
22473 "CircuitBreaker::max_failures must return :politicas \
22474 :circuit-breaker :max-failures verbatim by copy — \
22475 got {first}, expected {max_failures}",
22476 );
22477 }
22478 }
22479
22480 #[test]
22481 fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
22482 // The canonical per-`:politicas :circuit-breaker` `:window`
22483 // Envoy-outlier-detection rolling-observation-interval scalar
22484 // pin: [`CircuitBreaker::window`] must return the
22485 // `:politicas :circuit-breaker :window` typed `Duration`
22486 // verbatim, byte-equal to the raw field access across every
22487 // representative value in the accept-set — `Duration::from_millis(1)`
22488 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
22489 // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
22490 // gate carves out on the sibling `PolicyBreakerZeroWindow`
22491 // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
22492 // same gate carves out on the sibling
22493 // `PolicyBreakerWindowExceedsCap` refusal),
22494 // `Duration::ZERO` (a past-the-guard sentinel that pins the
22495 // accessor doesn't perform a silent bounds-collapse into
22496 // `Duration::from_millis(1)` on the zero arm — validate rejects
22497 // zero but the accessor must ship the raw slot verbatim so a
22498 // validate-time gate regression surfaces at the emit boundary
22499 // rather than being silently absorbed),
22500 // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
22501 // far above the 1h cap — that pins the accessor doesn't perform
22502 // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
22503 // at the return path).
22504 //
22505 // Second sub-struct required-scalar accessor pin on the M3
22506 // mesh-slot family — sibling in shape to the just-landed
22507 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
22508 // (3a74062) required-`u32` accessor pin on the peer
22509 // per-`CircuitBreaker` required-axis, extended onto the
22510 // per-sub-struct required-`Duration` axis. Pins against a
22511 // future silent detour that re-derived the observation window
22512 // from a peer axis (an accidental
22513 // `Duration::from_secs(self.max_failures as u64)` collapse that
22514 // read the breaker's trip count as an observation-interval
22515 // duration), a `Duration::ZERO → Duration::from_millis(1)`
22516 // cluster-default projection (which would silently absorb the
22517 // `PolicyBreakerZeroWindow` refusal case at the accessor
22518 // boundary), or a bounds-collapsing accessor that clamped the
22519 // return through `POLICY_BREAKER_WINDOW_MAX` (the
22520 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
22521 // must ship the raw slot verbatim).
22522 for window in [
22523 Duration::from_millis(1),
22524 POLICY_BREAKER_WINDOW_MAX,
22525 Duration::ZERO,
22526 Duration::from_secs(86_400),
22527 ] {
22528 let cb = CircuitBreaker {
22529 max_failures: 5,
22530 window,
22531 };
22532 assert_eq!(
22533 cb.window(),
22534 window,
22535 "CircuitBreaker::window must return :politicas \
22536 :circuit-breaker :window verbatim (got {:?}, \
22537 expected {window:?})",
22538 cb.window(),
22539 );
22540 assert_eq!(
22541 cb.window(),
22542 cb.window,
22543 "CircuitBreaker::window must byte-equal the raw \
22544 .window field access across every value in the \
22545 Duration accept-set",
22546 );
22547 }
22548 }
22549
22550 #[test]
22551 fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
22552 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
22553 // `:circuit-breaker :window` zero-floor arm must key off
22554 // [`CircuitBreaker::window`], not the raw `.window` field
22555 // access. Structurally: a `CircuitBreaker { window:
22556 // Duration::ZERO, .. }` embedded in a
22557 // `:politicas :circuit-breaker` slot must surface the
22558 // `PolicyBreakerZeroWindow` refusal exactly, and a
22559 // `CircuitBreaker { window: Duration::from_millis(1), .. }`
22560 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
22561 // accept-set) must pass validate. The pair jointly pins the
22562 // accessor + validate-gate composition: any future silent
22563 // detour that had the accessor return a fresh
22564 // `Duration::from_millis(1)` on the zero arm (a
22565 // `.window().max(Duration::from_millis(1))` collapse) would
22566 // silently absorb the `PolicyBreakerZeroWindow` refusal at the
22567 // accessor boundary and the validate gate would accept a
22568 // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
22569 // — the composition pin catches that at caixa-core build time.
22570 //
22571 // Peer of the sibling per-`CircuitBreaker`
22572 // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
22573 // pin on the peer required-scalar `:max-failures` axis — same
22574 // "the validate / shape-gate predicate must route through the
22575 // substrate-primitive typed dispatch" discipline extended onto
22576 // the peer per-`CircuitBreaker` required-`Duration` composition
22577 // axis.
22578 let mut spec = three_member_spec();
22579 spec.politicas = MeshPolicy {
22580 circuit_breaker: Some(CircuitBreaker {
22581 max_failures: 5,
22582 window: Duration::ZERO,
22583 }),
22584 ..MeshPolicy::default()
22585 };
22586 assert!(
22587 matches!(
22588 spec.validate(),
22589 Err(AplicacaoError::PolicyBreakerZeroWindow)
22590 ),
22591 "validate_politicas must reject window == Duration::ZERO \
22592 with PolicyBreakerZeroWindow — the accessor and the \
22593 validate gate must route through the same substrate-\
22594 primitive typed dispatch on the :window zero-floor arm",
22595 );
22596 spec.politicas = MeshPolicy {
22597 circuit_breaker: Some(CircuitBreaker {
22598 max_failures: 5,
22599 window: Duration::from_millis(1),
22600 }),
22601 ..MeshPolicy::default()
22602 };
22603 assert!(
22604 spec.validate().is_ok(),
22605 "validate_politicas must accept window == \
22606 Duration::from_millis(1) (the lower boundary of the \
22607 1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
22608 );
22609 }
22610
22611 #[test]
22612 fn circuit_breaker_window_projects_duration_by_copy() {
22613 // The by-copy pin: [`CircuitBreaker::window`] returns
22614 // `Duration` by copy — `Duration` is `Copy` and the accessor
22615 // must return by value, not by reference. Peer of the sibling
22616 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
22617 // (3a74062) by-copy pin on the peer required-scalar
22618 // `:max-failures` axis, extended onto the peer
22619 // per-`CircuitBreaker` required-`Duration` copy-invariant shape
22620 // — the accessor's returned `Duration` must outlive `&self`
22621 // (multiple calls must return equal values from a
22622 // dropped-`&self` copy, since the returned scalar carries no
22623 // borrow), and calling the accessor twice on the same
22624 // CircuitBreaker must yield the same `Duration` verbatim
22625 // (idempotent, no side effects on `&self`).
22626 //
22627 // Pins against a future silent detour that returned
22628 // `&Duration` (which would type-check but silently break every
22629 // downstream `Duration`-by-value consumer —
22630 // [`crate::render::require_positive_canonical_bounded_duration`]'s
22631 // first parameter is `Duration`, and `&Duration` would fold to
22632 // a detached copy at the call site with a `*` deref the sibling
22633 // accessors don't need), an accidental `.window + Duration::ZERO`
22634 // detour that returned a fresh copy through an arithmetic
22635 // no-op (breaking a future `const fn` regression), or a
22636 // one-arm-only accessor that returned a saturating value on
22637 // some sentinel input (breaking the pass-through invariant the
22638 // sibling required-scalar accessors carry).
22639 for window in [
22640 Duration::from_millis(1),
22641 POLICY_BREAKER_WINDOW_MAX,
22642 Duration::ZERO,
22643 Duration::from_secs(86_400),
22644 ] {
22645 let cb = CircuitBreaker {
22646 max_failures: 5,
22647 window,
22648 };
22649 let first = cb.window();
22650 let second = cb.window();
22651 assert_eq!(
22652 first, second,
22653 "CircuitBreaker::window must be idempotent — two \
22654 successive calls on the same &self must return the \
22655 same Duration",
22656 );
22657 assert_eq!(
22658 first, window,
22659 "CircuitBreaker::window must return :politicas \
22660 :circuit-breaker :window verbatim by copy — \
22661 got {first:?}, expected {window:?}",
22662 );
22663 }
22664 }
22665
22666 #[test]
22667 fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
22668 // Apex-identity pair-invariant pin composing both substrate-
22669 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
22670 // and [`WitContract::destination`] — at the emit-side call shape
22671 // every per-`(:de, :para)` CNP L4 port reader now takes. The
22672 // invariant, evaluated per-edge:
22673 //
22674 // spec.port_for_destination(c.destination()) == expected_port
22675 //
22676 // where `expected_port` is `entrada.port` when
22677 // `c.destination() == entrada.destination()` and
22678 // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
22679 // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
22680 // pin on the per-`:entrada` axis — that pin encodes the apex
22681 // ingress L4 identity via `entrada.destination()`; this pin
22682 // encodes the per-edge L4 identity via `c.destination()`, and
22683 // both compose on the same substrate-primitive resolver so a
22684 // future refactor that silently split either accessor's apex
22685 // behavior surfaces at caixa-core build time.
22686 let mut spec = three_member_spec();
22687 if let Some(e) = spec.entrada.as_mut() {
22688 e.para = "cart".into();
22689 e.port = 8443;
22690 }
22691 let apex_contract = WitContract {
22692 de: "checkout".into(),
22693 para: "cart".into(),
22694 wit: "wasi:http/proxy".into(),
22695 endpoint: Some("/hello".into()),
22696 subject: None,
22697 slot: None,
22698 };
22699 assert_eq!(
22700 spec.port_for_destination(apex_contract.destination()),
22701 8443,
22702 "`spec.port_for_destination(c.destination())` must equal \
22703 `entrada.port` when the contract callee names the ingress \
22704 apex — the CNP per-edge L4 port and the HTTPRoute apex \
22705 backendRef port share this substrate-primitive resolver.",
22706 );
22707 let non_apex_contract = WitContract {
22708 de: "cart".into(),
22709 para: "payment".into(),
22710 wit: "wasi:http/proxy".into(),
22711 endpoint: Some("/charge".into()),
22712 subject: None,
22713 slot: None,
22714 };
22715 assert_eq!(
22716 spec.port_for_destination(non_apex_contract.destination()),
22717 DEFAULT_SERVICO_PORT,
22718 "`spec.port_for_destination(c.destination())` must fall back \
22719 to the substrate-canonical port floor when the contract \
22720 callee is not the ingress apex — the resolver's non-apex \
22721 arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
22722 );
22723 }
22724
22725 #[test]
22726 fn membro_key_consts_are_lower_camel_case_shape() {
22727 // Shape-pin: every `MEMBRO_KEY_*` const must be a
22728 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
22729 // `kebab-case` hyphens, no leading colon, no `PascalCase`
22730 // leading capital, no whitespace / dots) — the canonical shape
22731 // the `#[serde(rename_all = "camelCase")]` derive produces on
22732 // [`Membro`]. A future flip to a non-camelCase attribute at
22733 // the derive surfaces both here (this test fails on the
22734 // stale-constant shape) and at
22735 // `membro_serde_keys_match_lifted_membro_key_consts` (that test
22736 // fails on the mismatch between const and derive). Peer with
22737 // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
22738 // on the sibling `SupervisorSpec` top-level axis.
22739 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
22740 assert!(
22741 !key.is_empty(),
22742 "MEMBRO_KEY_* must be non-empty (got {key:?})"
22743 );
22744 let first = key.chars().next().unwrap();
22745 assert!(
22746 first.is_ascii_lowercase(),
22747 "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
22748 (got {key:?}, leads with {first:?})",
22749 );
22750 assert!(
22751 key.chars().all(|c| c.is_ascii_alphanumeric()),
22752 "MEMBRO_KEY_* must be ASCII-alphanumeric only \
22753 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
22754 );
22755 }
22756 }
22757
22758 // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
22759
22760 #[test]
22761 fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
22762 // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
22763 // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
22764 // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
22765 // keys the `#[serde(rename_all = "camelCase")]` attribute on
22766 // [`WitContract`] emits for the required-triad. The three
22767 // sibling payload-arm keys already pin under
22768 // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
22769 // `STORE_FIELD_NAME` — pin all six alongside so a future
22770 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
22771 // verbatim-field-name flip at the derive attribute (any of which
22772 // would silently break every downstream JSON consumer that
22773 // reaches for one of the six via `Value::get(...)`) surfaces
22774 // here as a build-time test failure at `aplicacao.rs`, not as an
22775 // apply-time `.get(<stale-canonical-const>)` returning `None`
22776 // far from the derive-attr drift's commit. Peer with the sibling
22777 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
22778 // pin on the M3 `:membros` per-entry axis — same discipline the
22779 // `Membro` per-entry lift established, extended here to the
22780 // sibling M3 `WitContract` per-`:contratos` entry axis, the last
22781 // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
22782 // axis on the Aplicacao surface without a lifted serde-key peer.
22783 let c = WitContract {
22784 de: "cart".into(),
22785 para: "catalog".into(),
22786 wit: "wasi:http/proxy".into(),
22787 endpoint: Some("/lookup".into()),
22788 subject: None,
22789 slot: None,
22790 };
22791 let json = serde_json::to_string(&c).unwrap();
22792 for key in [
22793 crate::CONTRATO_KEY_DE,
22794 crate::CONTRATO_KEY_PARA,
22795 crate::CONTRATO_KEY_WIT,
22796 WitTarget::HTTP_FIELD_NAME,
22797 ] {
22798 let quoted = format!("\"{key}\"");
22799 assert!(
22800 json.contains("ed),
22801 "serialized WitContract must carry the lifted \
22802 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
22803 {quoted} verbatim in the JSON emission (got: {json})",
22804 );
22805 }
22806
22807 // Pin the two remaining payload-arm keys by round-tripping a
22808 // `WitContract` under each payload-shape (pub-sub, store) — the
22809 // required-triad appears on every emission but the payload arms
22810 // only surface when their `Option<String>` field is `Some`.
22811 let pubsub = WitContract {
22812 de: "cart".into(),
22813 para: "events".into(),
22814 wit: "nats:pub-sub".into(),
22815 endpoint: None,
22816 subject: Some("orders.placed".into()),
22817 slot: None,
22818 };
22819 let pubsub_json = serde_json::to_string(&pubsub).unwrap();
22820 let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
22821 assert!(
22822 pubsub_json.contains(&pubsub_quoted),
22823 "serialized pub-sub WitContract must carry the lifted \
22824 WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
22825 verbatim in the JSON emission (got: {pubsub_json})",
22826 );
22827 let store = WitContract {
22828 de: "cart".into(),
22829 para: "sessions".into(),
22830 wit: "wasi:keyvalue/store".into(),
22831 endpoint: None,
22832 subject: None,
22833 slot: Some("cart/$id".into()),
22834 };
22835 let store_json = serde_json::to_string(&store).unwrap();
22836 let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
22837 assert!(
22838 store_json.contains(&store_quoted),
22839 "serialized store WitContract must carry the lifted \
22840 WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
22841 verbatim in the JSON emission (got: {store_json})",
22842 );
22843 }
22844
22845 #[test]
22846 fn contrato_key_consts_are_pairwise_distinct() {
22847 // Cross-axis drift-detection pin: a future collapse of the six
22848 // canonical [`WitContract`] per-entry byte-strings onto the same
22849 // value (e.g. an accidental copy-paste flip of
22850 // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
22851 // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
22852 // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
22853 // every downstream probe on one axis onto the sibling axis's
22854 // overlay entry and pass every propagation-probe test that
22855 // expected only the stale axis's value. Peer of the sibling
22856 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
22857 // widened here to the six-way axis the `WitContract`
22858 // required-triad + `WitTarget` payload-triad jointly cover.
22859 let all = [
22860 crate::CONTRATO_KEY_DE,
22861 crate::CONTRATO_KEY_PARA,
22862 crate::CONTRATO_KEY_WIT,
22863 WitTarget::HTTP_FIELD_NAME,
22864 WitTarget::PUBSUB_FIELD_NAME,
22865 WitTarget::STORE_FIELD_NAME,
22866 ];
22867 for (i, a) in all.iter().enumerate() {
22868 for b in all.iter().skip(i + 1) {
22869 assert_ne!(
22870 a, b,
22871 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
22872 must be pairwise-distinct canonical byte-sequences \
22873 — got `{a}` == `{b}`",
22874 );
22875 }
22876 }
22877 }
22878
22879 #[test]
22880 fn contrato_key_consts_are_lower_camel_case_shape() {
22881 // Shape-pin: every `CONTRATO_KEY_*` (and every peer
22882 // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
22883 // byte-sequence (no `snake_case` underscores, no `kebab-case`
22884 // hyphens, no leading colon, no `PascalCase` leading capital, no
22885 // whitespace / dots) — the canonical shape the
22886 // `#[serde(rename_all = "camelCase")]` derive produces on
22887 // [`WitContract`]. A future flip to a non-camelCase attribute at
22888 // the derive surfaces both here (this test fails on the
22889 // stale-constant shape) and at
22890 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
22891 // (that test fails on the mismatch between const and derive).
22892 // Peer with `membro_key_consts_are_lower_camel_case_shape`
22893 // (ce80ca0) on the sibling `Membro` per-entry axis.
22894 for key in [
22895 crate::CONTRATO_KEY_DE,
22896 crate::CONTRATO_KEY_PARA,
22897 crate::CONTRATO_KEY_WIT,
22898 WitTarget::HTTP_FIELD_NAME,
22899 WitTarget::PUBSUB_FIELD_NAME,
22900 WitTarget::STORE_FIELD_NAME,
22901 ] {
22902 assert!(
22903 !key.is_empty(),
22904 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
22905 non-empty (got {key:?})"
22906 );
22907 let first = key.chars().next().unwrap();
22908 assert!(
22909 first.is_ascii_lowercase(),
22910 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
22911 with an ASCII-lowercase byte (got {key:?}, leads with \
22912 {first:?})",
22913 );
22914 assert!(
22915 key.chars().all(|c| c.is_ascii_alphanumeric()),
22916 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
22917 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
22918 whitespace (got {key:?})",
22919 );
22920 }
22921 }
22922
22923 // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
22924
22925 #[test]
22926 fn entrada_serde_keys_match_lifted_entrada_key_consts() {
22927 // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
22928 // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
22929 // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
22930 // name the exact camelCase JSON keys the
22931 // `#[serde(rename_all = "camelCase")]` attribute on
22932 // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
22933 // pin that each canonical byte-sequence appears verbatim in the
22934 // JSON — a future accidental `rename_all = "snake_case"` /
22935 // `"kebab-case"` / verbatim-field-name flip at the derive
22936 // attribute (any of which would silently break every downstream
22937 // JSON consumer that reaches for one of the four consts via
22938 // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
22939 // emitter's per-Aplicacao hostname/paths/port projection, the
22940 // future `app-operator` reconciler's per-Aplicacao ingress
22941 // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
22942 // materializer's admission-time cross-check) surfaces here as
22943 // a build-time test failure at `aplicacao.rs`, not as an
22944 // apply-time `.get(<stale-canonical-const>)` returning `None`
22945 // far from the derive-attr drift's commit. Peer with the
22946 // sibling
22947 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
22948 // (ca463a4) and
22949 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
22950 // pins on the M3 collection-slot atom axes — same discipline
22951 // both collection-slot lifts established, extended here to the
22952 // singleton `:entrada` mesh-slot atom axis, the last M3
22953 // typed-struct top-level `#[serde(rename_all = "camelCase")]`
22954 // axis on the Aplicacao surface without a lifted serde-key
22955 // peer.
22956 let e = Entrada {
22957 host: "checkout.quero.cloud".into(),
22958 para: "cart".into(),
22959 paths: vec!["/cart".into()],
22960 port: 8080,
22961 };
22962 let json = serde_json::to_string(&e).unwrap();
22963 for key in [
22964 crate::ENTRADA_KEY_HOST,
22965 crate::ENTRADA_KEY_PARA,
22966 crate::ENTRADA_KEY_PATHS,
22967 crate::ENTRADA_KEY_PORT,
22968 ] {
22969 let quoted = format!("\"{key}\"");
22970 assert!(
22971 json.contains("ed),
22972 "serialized Entrada must carry the lifted ENTRADA_KEY_* \
22973 byte-sequence {quoted} verbatim in the JSON emission \
22974 (got: {json})",
22975 );
22976 }
22977 }
22978
22979 #[test]
22980 fn entrada_key_consts_are_pairwise_distinct() {
22981 // Cross-axis drift-detection pin: a future collapse of the four
22982 // canonical [`Entrada`] singleton byte-strings onto the same
22983 // value (e.g. an accidental copy-paste flip of
22984 // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
22985 // silently reroute every downstream probe on one axis onto the
22986 // sibling axis's overlay entry and pass every propagation-probe
22987 // test that expected only the stale axis's value — the
22988 // Gateway/HTTPRoute emitter would read the hostname string
22989 // where the destination-Servico name was expected (or vice
22990 // versa), the admission-webhook cross-check would compare the
22991 // wrong pair of values, and the resulting Gateway resource
22992 // would either be admitted with garbage or rejected at the
22993 // controller far from the rebrand commit's source. Peer of the
22994 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
22995 // tetrad (40cc4e5), the two-way distinct pin on the
22996 // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
22997 // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
22998 // triad (ca463a4).
22999 let all = [
23000 crate::ENTRADA_KEY_HOST,
23001 crate::ENTRADA_KEY_PARA,
23002 crate::ENTRADA_KEY_PATHS,
23003 crate::ENTRADA_KEY_PORT,
23004 ];
23005 for (i, a) in all.iter().enumerate() {
23006 for b in all.iter().skip(i + 1) {
23007 assert_ne!(
23008 a, b,
23009 "ENTRADA_KEY_* consts must be pairwise-distinct \
23010 canonical byte-sequences — got `{a}` == `{b}`",
23011 );
23012 }
23013 }
23014 }
23015
23016 #[test]
23017 fn entrada_key_consts_are_lower_camel_case_shape() {
23018 // Shape-pin: every `ENTRADA_KEY_*` const must be a
23019 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23020 // `kebab-case` hyphens, no leading colon, no `PascalCase`
23021 // leading capital, no whitespace / dots) — the canonical shape
23022 // the `#[serde(rename_all = "camelCase")]` derive produces on
23023 // [`Entrada`]. A future flip to a non-camelCase attribute at
23024 // the derive surfaces both here (this test fails on the
23025 // stale-constant shape) and at
23026 // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
23027 // test fails on the mismatch between const and derive). Peer
23028 // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
23029 // and `contrato_key_consts_are_lower_camel_case_shape`
23030 // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
23031 // entry axes.
23032 for key in [
23033 crate::ENTRADA_KEY_HOST,
23034 crate::ENTRADA_KEY_PARA,
23035 crate::ENTRADA_KEY_PATHS,
23036 crate::ENTRADA_KEY_PORT,
23037 ] {
23038 assert!(
23039 !key.is_empty(),
23040 "ENTRADA_KEY_* must be non-empty (got {key:?})"
23041 );
23042 let first = key.chars().next().unwrap();
23043 assert!(
23044 first.is_ascii_lowercase(),
23045 "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
23046 (got {key:?}, leads with {first:?})",
23047 );
23048 assert!(
23049 key.chars().all(|c| c.is_ascii_alphanumeric()),
23050 "ENTRADA_KEY_* must be ASCII-alphanumeric only \
23051 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23052 );
23053 }
23054 }
23055
23056 // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
23057
23058 #[test]
23059 fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
23060 // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
23061 // ([`crate::POLITICAS_KEY_TIMEOUT`] /
23062 // [`crate::POLITICAS_KEY_RETRIES`] /
23063 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
23064 // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
23065 // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
23066 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
23067 // on [`MeshPolicy`] emits. Three of the five axes
23068 // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
23069 // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
23070 // camelCase transforms — the derive-attribute is load-bearing
23071 // on those, unlike the sibling `Entrada` / `Membro` /
23072 // `WitContract` structs whose fields are all lowercase-single-
23073 // word and where the derive is a no-op on every axis.
23074 // Serialize a fully-populated [`MeshPolicy`] (every axis
23075 // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
23076 // on none of the five slots) and pin that each canonical
23077 // byte-sequence appears verbatim in the JSON — a future
23078 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
23079 // verbatim-field-name flip at the derive attribute (any of
23080 // which would silently break every downstream JSON consumer
23081 // that reaches for one of the five consts via
23082 // `Value::get(...)` — the future M4 per-edge `:politicas`
23083 // overlay projection onto Cilium `L7Rules` and Gateway API
23084 // `HTTPRoute` backend timeouts, the future
23085 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23086 // admission-time mesh-policy cross-check, the future
23087 // `feira lint` per-`:politicas` bound-check gate) surfaces here
23088 // as a build-time test failure at `aplicacao.rs`, not as an
23089 // apply-time `.get(<stale-canonical-const>)` returning `None`
23090 // far from the derive-attr drift's commit. Peer with the
23091 // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
23092 // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23093 // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
23094 // (ce80ca0) pins on the M3 collection-slot / singleton-slot
23095 // atom axes — same discipline every M3 sibling lift
23096 // established, extended here to the singleton `:politicas`
23097 // mesh-slot atom axis, closing the last M3 typed-struct
23098 // top-level `#[serde(rename_all = "camelCase")]` axis on the
23099 // Aplicacao surface without a lifted serde-key peer.
23100 let p = MeshPolicy {
23101 timeout: Some(Duration::from_secs(30)),
23102 retries: Some(3),
23103 circuit_breaker: Some(CircuitBreaker {
23104 max_failures: 5,
23105 window: Duration::from_secs(60),
23106 }),
23107 mtls_required: Some(true),
23108 rate_limit: Some(RateLimit {
23109 rate: 100,
23110 window: Duration::from_secs(1),
23111 }),
23112 };
23113 let json = serde_json::to_string(&p).unwrap();
23114 for key in [
23115 crate::POLITICAS_KEY_TIMEOUT,
23116 crate::POLITICAS_KEY_RETRIES,
23117 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
23118 crate::POLITICAS_KEY_MTLS_REQUIRED,
23119 crate::POLITICAS_KEY_RATE_LIMIT,
23120 ] {
23121 let quoted = format!("\"{key}\"");
23122 assert!(
23123 json.contains("ed),
23124 "serialized MeshPolicy must carry the lifted \
23125 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
23126 JSON emission (got: {json})",
23127 );
23128 }
23129 }
23130
23131 #[test]
23132 fn politicas_key_consts_are_pairwise_distinct() {
23133 // Cross-axis drift-detection pin: a future collapse of the five
23134 // canonical [`MeshPolicy`] singleton byte-strings onto the same
23135 // value (e.g. an accidental copy-paste flip of
23136 // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
23137 // would silently reroute every downstream probe on one axis
23138 // onto the sibling axis's overlay entry and pass every
23139 // propagation-probe test that expected only the stale axis's
23140 // value — the M4 per-edge `:politicas` overlay projection would
23141 // read the retry-count string where the timeout duration was
23142 // expected (or vice versa), the CR materializer's admission
23143 // cross-check would compare the wrong pair of values, and the
23144 // resulting mesh reconciler would either bind the wrong axis
23145 // or reject the resource at reconcile far from the rebrand
23146 // commit's source. Peer of the sibling four-way distinct pin
23147 // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
23148 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
23149 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
23150 // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
23151 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23152 let all = [
23153 crate::POLITICAS_KEY_TIMEOUT,
23154 crate::POLITICAS_KEY_RETRIES,
23155 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
23156 crate::POLITICAS_KEY_MTLS_REQUIRED,
23157 crate::POLITICAS_KEY_RATE_LIMIT,
23158 ];
23159 for (i, a) in all.iter().enumerate() {
23160 for b in all.iter().skip(i + 1) {
23161 assert_ne!(
23162 a, b,
23163 "POLITICAS_KEY_* consts must be pairwise-distinct \
23164 canonical byte-sequences — got `{a}` == `{b}`",
23165 );
23166 }
23167 }
23168 }
23169
23170 #[test]
23171 fn politicas_key_consts_are_lower_camel_case_shape() {
23172 // Shape-pin: every `POLITICAS_KEY_*` const must be a
23173 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23174 // `kebab-case` hyphens, no leading colon, no `PascalCase`
23175 // leading capital, no whitespace / dots) — the canonical shape
23176 // the `#[serde(rename_all = "camelCase")]` derive produces on
23177 // [`MeshPolicy`]. A future flip to a non-camelCase attribute
23178 // at the derive surfaces both here (this test fails on the
23179 // stale-constant shape) and at
23180 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23181 // (that test fails on the mismatch between const and derive).
23182 // Peer with `entrada_key_consts_are_lower_camel_case_shape`
23183 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23184 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23185 // (ca463a4) on the sibling M3 typed-struct axes.
23186 for key in [
23187 crate::POLITICAS_KEY_TIMEOUT,
23188 crate::POLITICAS_KEY_RETRIES,
23189 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
23190 crate::POLITICAS_KEY_MTLS_REQUIRED,
23191 crate::POLITICAS_KEY_RATE_LIMIT,
23192 ] {
23193 assert!(
23194 !key.is_empty(),
23195 "POLITICAS_KEY_* must be non-empty (got {key:?})"
23196 );
23197 let first = key.chars().next().unwrap();
23198 assert!(
23199 first.is_ascii_lowercase(),
23200 "POLITICAS_KEY_* must lead with an ASCII-lowercase \
23201 byte (got {key:?}, leads with {first:?})",
23202 );
23203 assert!(
23204 key.chars().all(|c| c.is_ascii_alphanumeric()),
23205 "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
23206 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23207 );
23208 }
23209 }
23210
23211 // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
23212
23213 #[test]
23214 fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
23215 // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
23216 // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
23217 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
23218 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
23219 // [`CircuitBreaker`] emits inside the
23220 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
23221 // two axes (`max_failures` → `maxFailures`) is a non-trivial
23222 // camelCase transform — the derive-attribute is load-bearing on
23223 // that axis, unlike the sibling `window` field where the derive
23224 // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
23225 // pin that each canonical byte-sequence appears verbatim in the
23226 // JSON — a future accidental `rename_all = "snake_case"` /
23227 // `"kebab-case"` / verbatim-field-name flip at the derive
23228 // attribute (any of which would silently break every downstream
23229 // JSON consumer that reaches for one of the two consts via
23230 // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
23231 // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
23232 // per-edge `:politicas` overlay projection onto the mesh's
23233 // per-backend consecutive-failure-counter tripping threshold, the
23234 // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23235 // admission-time breaker cross-check, the future `feira lint`
23236 // per-`:politicas :circuit-breaker` bound-check gate) surfaces
23237 // here as a build-time test failure at `aplicacao.rs`, not as an
23238 // apply-time `.get(<stale-canonical-const>)` returning `None`
23239 // far from the derive-attr drift's commit. Peer with the sibling
23240 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23241 // (b55cca7) parent-axis pin — that test pins the outer
23242 // sub-block key the derive on [`MeshPolicy`] emits, this test
23243 // pins the inner keys the derive on the payload type emits, so
23244 // the two together lock the whole [`MeshPolicy`] breaker-tuning
23245 // shape end-to-end at build time.
23246 let cb = CircuitBreaker {
23247 max_failures: 5,
23248 window: Duration::from_secs(60),
23249 };
23250 let json = serde_json::to_string(&cb).unwrap();
23251 for key in [
23252 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23253 crate::CIRCUIT_BREAKER_KEY_WINDOW,
23254 ] {
23255 let quoted = format!("\"{key}\"");
23256 assert!(
23257 json.contains("ed),
23258 "serialized CircuitBreaker must carry the lifted \
23259 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
23260 in the JSON emission (got: {json})",
23261 );
23262 }
23263 }
23264
23265 #[test]
23266 fn circuit_breaker_key_consts_are_pairwise_distinct() {
23267 // Cross-axis drift-detection pin: a future collapse of the two
23268 // canonical [`CircuitBreaker`] sub-block byte-strings onto the
23269 // same value (e.g. an accidental copy-paste flip of
23270 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
23271 // `"maxFailures"`) would silently reroute every downstream
23272 // probe on one axis onto the sibling axis's overlay entry and
23273 // pass every propagation-probe test that expected only the
23274 // stale axis's value — the M4 per-edge `:politicas` overlay
23275 // projection would read the failure-count where the window
23276 // duration was expected (or vice versa), the CR materializer's
23277 // admission cross-check would compare the wrong pair of values,
23278 // and the resulting mesh reconciler would either bind the wrong
23279 // axis or reject the resource at reconcile far from the rebrand
23280 // commit's source. Peer of the sibling five-way distinct pin on
23281 // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
23282 // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
23283 // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
23284 // six-way distinct pin on the `CONTRATO_KEY_*` triad +
23285 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23286 let all = [
23287 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23288 crate::CIRCUIT_BREAKER_KEY_WINDOW,
23289 ];
23290 for (i, a) in all.iter().enumerate() {
23291 for b in all.iter().skip(i + 1) {
23292 assert_ne!(
23293 a, b,
23294 "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
23295 canonical byte-sequences — got `{a}` == `{b}`",
23296 );
23297 }
23298 }
23299 }
23300
23301 #[test]
23302 fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
23303 // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
23304 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23305 // `kebab-case` hyphens, no leading colon, no `PascalCase`
23306 // leading capital, no whitespace / dots) — the canonical shape
23307 // the `#[serde(rename_all = "camelCase")]` derive produces on
23308 // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
23309 // at the derive surfaces both here (this test fails on the
23310 // stale-constant shape) and at
23311 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
23312 // (that test fails on the mismatch between const and derive).
23313 // Peer with `politicas_key_consts_are_lower_camel_case_shape`
23314 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
23315 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23316 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23317 // (ca463a4) on the sibling M3 typed-struct axes.
23318 for key in [
23319 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23320 crate::CIRCUIT_BREAKER_KEY_WINDOW,
23321 ] {
23322 assert!(
23323 !key.is_empty(),
23324 "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
23325 );
23326 let first = key.chars().next().unwrap();
23327 assert!(
23328 first.is_ascii_lowercase(),
23329 "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
23330 byte (got {key:?}, leads with {first:?})",
23331 );
23332 assert!(
23333 key.chars().all(|c| c.is_ascii_alphanumeric()),
23334 "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
23335 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23336 );
23337 }
23338 }
23339
23340 // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
23341
23342 #[test]
23343 fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
23344 // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
23345 // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
23346 // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
23347 // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
23348 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
23349 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
23350 // [`Placement`] emits. One of the four axes (`shard_key` →
23351 // `shardKey`) is a non-trivial camelCase transform — the
23352 // derive-attribute is load-bearing on that axis, unlike the
23353 // sibling `estrategia` / `clusters` / `affinity` axes whose
23354 // source-side field names carry no `_` and where the derive is a
23355 // no-op. Serialize a fully-populated [`Placement`] (both
23356 // `Option`-carrying axes `Some(_)` so
23357 // `skip_serializing_if = "Option::is_none"` fires on neither of
23358 // the two optional slots) and pin that each canonical
23359 // byte-sequence appears verbatim in the JSON — a future
23360 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
23361 // verbatim-field-name flip at the derive attribute (any of which
23362 // would silently break every downstream consumer that reaches
23363 // for one of the four consts via
23364 // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
23365 // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
23366 // aggregator's per-cluster fanout filter keying off
23367 // `placement.clusters`, the M3 shard-pool dispatch materializer
23368 // keying off `placement.shardKey`, the M3 Adaptive compression
23369 // pass weighting off `placement.affinity`, every downstream
23370 // dispatcher branching on `placement.estrategia`, the future
23371 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
23372 // admission-time placement cross-check, the future `feira lint`
23373 // per-`:placement` bound-check gate) surfaces here as a
23374 // build-time test failure at `aplicacao.rs`, not as an
23375 // apply-time `.get(<stale-canonical-const>)` returning `None`
23376 // far from the derive-attr drift's commit. Peer with the sibling
23377 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
23378 // (b55cca7),
23379 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
23380 // (468e959),
23381 // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
23382 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
23383 // (ca463a4), and
23384 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
23385 // pins on the M3 collection-slot / singleton-slot atom axes —
23386 // closes the last M3 typed-struct top-level
23387 // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
23388 // surface without a drift-detection pin.
23389 let p = Placement {
23390 estrategia: PlacementStrategy::Sharded,
23391 clusters: vec!["rio".into(), "mar".into()],
23392 affinity: Some("data-locality".into()),
23393 shard_key: Some("$tenantId".into()),
23394 };
23395 let json = serde_json::to_string(&p).unwrap();
23396 for key in [
23397 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23398 crate::M3_PLACEMENT_KEY_CLUSTERS,
23399 crate::M3_PLACEMENT_KEY_AFFINITY,
23400 crate::M3_PLACEMENT_KEY_SHARD_KEY,
23401 ] {
23402 let quoted = format!("\"{key}\"");
23403 assert!(
23404 json.contains("ed),
23405 "serialized Placement must carry the lifted \
23406 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
23407 the JSON emission (got: {json})",
23408 );
23409 }
23410 }
23411
23412 #[test]
23413 fn m3_placement_key_consts_are_pairwise_distinct() {
23414 // Cross-axis drift-detection pin: a future collapse of the four
23415 // canonical [`Placement`] sub-block byte-strings onto the same
23416 // value (e.g. an accidental copy-paste flip of
23417 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
23418 // `"affinity"`) would silently reroute every downstream probe on
23419 // one axis onto the sibling axis's overlay entry and pass every
23420 // propagation-probe test that expected only the stale axis's
23421 // value — the M3 shard-pool dispatch materializer would read the
23422 // affinity placement-hint where the shard-selection template was
23423 // expected (or vice versa), the M3 Adaptive compression pass's
23424 // cross-check would compare the wrong pair of values, and the
23425 // resulting placement engine would either bind the wrong axis or
23426 // reject the resource at reconcile far from the rebrand commit's
23427 // source. Peer of the sibling two-way distinct pin on the
23428 // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
23429 // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
23430 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
23431 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
23432 // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
23433 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
23434 let all = [
23435 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23436 crate::M3_PLACEMENT_KEY_CLUSTERS,
23437 crate::M3_PLACEMENT_KEY_AFFINITY,
23438 crate::M3_PLACEMENT_KEY_SHARD_KEY,
23439 ];
23440 for (i, a) in all.iter().enumerate() {
23441 for b in all.iter().skip(i + 1) {
23442 assert_ne!(
23443 a, b,
23444 "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
23445 canonical byte-sequences — got `{a}` == `{b}`",
23446 );
23447 }
23448 }
23449 }
23450
23451 #[test]
23452 fn m3_placement_key_consts_are_lower_camel_case_shape() {
23453 // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
23454 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
23455 // `kebab-case` hyphens, no leading colon, no `PascalCase`
23456 // leading capital, no whitespace / dots) — the canonical shape
23457 // the `#[serde(rename_all = "camelCase")]` derive produces on
23458 // [`Placement`]. A future flip to a non-camelCase attribute at
23459 // the derive surfaces both here (this test fails on the stale-
23460 // constant shape) and at
23461 // `placement_serde_keys_match_lifted_m3_placement_key_consts`
23462 // (that test fails on the mismatch between const and derive).
23463 // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
23464 // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
23465 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
23466 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
23467 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
23468 // (ca463a4) on the sibling M3 typed-struct axes.
23469 for key in [
23470 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
23471 crate::M3_PLACEMENT_KEY_CLUSTERS,
23472 crate::M3_PLACEMENT_KEY_AFFINITY,
23473 crate::M3_PLACEMENT_KEY_SHARD_KEY,
23474 ] {
23475 assert!(
23476 !key.is_empty(),
23477 "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
23478 );
23479 let first = key.chars().next().unwrap();
23480 assert!(
23481 first.is_ascii_lowercase(),
23482 "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
23483 byte (got {key:?}, leads with {first:?})",
23484 );
23485 assert!(
23486 key.chars().all(|c| c.is_ascii_alphanumeric()),
23487 "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
23488 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
23489 );
23490 }
23491 }
23492
23493 // ── AplicacaoSpec::port_for_destination — the substrate-canonical
23494 // destination-facing L4 port resolver every per-Aplicacao renderer
23495 // reaching for a per-destination Servico TCP port axis routes
23496 // through. The four pin tests below fix the four-way accept-set
23497 // the resolver must always honor: (:entrada-para-matches,
23498 // :entrada-para-mismatches, :entrada-none-so-fallback,
23499 // :entrada-port-non-default-honored) — drift on any arm surfaces
23500 // at caixa-core build time rather than at cluster-apply time.
23501
23502 #[test]
23503 fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
23504 // The typed `:entrada` block's `:para "cart"` matches the
23505 // queried destination, so the resolver returns the author-
23506 // declared `:port` scalar verbatim — the canonical "the
23507 // destination Servico IS the ingress apex, honor the typed
23508 // listener port" arm of the port-resolution dispatch.
23509 let mut spec = three_member_spec();
23510 if let Some(e) = spec.entrada.as_mut() {
23511 e.para = "cart".into();
23512 e.port = 9090;
23513 }
23514 assert_eq!(
23515 spec.port_for_destination("cart"),
23516 9090,
23517 "port_for_destination(entrada.para) must return entrada.port \
23518 verbatim, not the DEFAULT_SERVICO_PORT fallback"
23519 );
23520 }
23521
23522 #[test]
23523 fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
23524 // The typed `:entrada` block names `:para "cart"`, but the
23525 // queried destination is `"payment"` — a Servico that
23526 // participates in the mesh graph but is not the ingress apex.
23527 // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
23528 // canonical port floor, closing the "non-apex destination reads
23529 // the substrate default" arm. Same fixture the peer
23530 // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
23531 // pin at caixa-mesh exercises through the CNP emit-side path;
23532 // this pin exercises the shared underlying resolver directly.
23533 let spec = three_member_spec();
23534 assert_eq!(
23535 spec.port_for_destination("payment"),
23536 DEFAULT_SERVICO_PORT,
23537 "port_for_destination(non-apex-destination) must route \
23538 through the lifted DEFAULT_SERVICO_PORT canonical port floor"
23539 );
23540 }
23541
23542 #[test]
23543 fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
23544 // Internal-only Aplicacao — no `:entrada` block declared. Every
23545 // per-destination port query falls back to the lifted
23546 // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
23547 // the Aplicacao surface admits `:entrada None` (internal mesh
23548 // with no external gateway); every downstream renderer's per-
23549 // destination port axis must still resolve to a well-defined
23550 // scalar even without an ingress apex.
23551 let mut spec = three_member_spec();
23552 spec.entrada = None;
23553 assert_eq!(
23554 spec.port_for_destination("cart"),
23555 DEFAULT_SERVICO_PORT,
23556 "port_for_destination on an internal-only Aplicacao must \
23557 fall back to the lifted DEFAULT_SERVICO_PORT floor for \
23558 every destination"
23559 );
23560 assert_eq!(
23561 spec.port_for_destination("payment"),
23562 DEFAULT_SERVICO_PORT,
23563 "port_for_destination on an internal-only Aplicacao must \
23564 fall back uniformly across every destination — the fallback \
23565 is not entrada-shape-conditional"
23566 );
23567 }
23568
23569 #[test]
23570 fn port_for_destination_honors_non_default_entrada_port_verbatim() {
23571 // Structural pin against a hypothetical future refactor that
23572 // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
23573 // the resolver (a "normalize to the default when the author's
23574 // port matches the substrate default" collapse) — that would
23575 // break renderer sites that carry meaning on the emitted port
23576 // value beyond bare equality (a future per-cluster listener-
23577 // audit that keys off the author-declared port, not the
23578 // resolved-with-fallback port). Pin that a non-default
23579 // entrada.port is returned verbatim so drift here surfaces at
23580 // caixa-core build time.
23581 let mut spec = three_member_spec();
23582 if let Some(e) = spec.entrada.as_mut() {
23583 e.para = "cart".into();
23584 e.port = 8443;
23585 }
23586 assert_ne!(
23587 8443, DEFAULT_SERVICO_PORT,
23588 "test fixture must probe a port distinct from \
23589 DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
23590 );
23591 assert_eq!(
23592 spec.port_for_destination("cart"),
23593 8443,
23594 "port_for_destination(entrada.para) must return entrada.port \
23595 verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
23596 );
23597 }
23598
23599 #[test]
23600 fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
23601 // Apex-identity pair-invariant pin composing both substrate-
23602 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
23603 // and [`Entrada::destination`] — at the emit-side call shape
23604 // every per-Aplicacao renderer's ingress-apex L4 port reader
23605 // now takes. The invariant:
23606 //
23607 // spec.port_for_destination(entrada.destination()) == entrada.port
23608 //
23609 // holds by construction under today's single-destination
23610 // `:entrada` slot (`destination()` returns `entrada.para`, and
23611 // the resolver's apex arm matches `para == destination` and
23612 // returns `entrada.port`), and every downstream consumer that
23613 // composes the two accessors at the ingress apex — the
23614 // `caixa_mesh::gateway_routes` HTTPRoute per-rule
23615 // `backendRefs[0].port` emit-site path, the peer future M4 CR
23616 // materializer's admission-webhook that promotes the scalar to
23617 // a per-CR override overlay, every future per-Aplicacao snapshot
23618 // renderer's apex-facing L4 port reader — reaches through the
23619 // same composition. Pin the identity across four permutations
23620 // (`:para` × `:port` including a non-default port to exercise
23621 // the honor-verbatim arm and a non-cart `:para` to exercise
23622 // destination-agnostic identity) so a future refactor that
23623 // silently split either accessor's apex behavior surfaces at
23624 // caixa-core build time — a subtle `destination()` renaming
23625 // that returned `entrada.host.as_str()` instead of
23626 // `entrada.para.as_str()` would blow this pin loudly, closing
23627 // the last quiet failure mode the two lifts admit in composition.
23628 //
23629 // Peer discipline with the sibling caixa-mesh cross-crate pin
23630 // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
23631 // on the two-renderer pair-invariant axis; this pin encodes the
23632 // same two-consumer coherence rule at the substrate-primitive
23633 // level so the invariant survives even if every renderer is
23634 // deleted.
23635 for (para, port) in [
23636 ("cart", DEFAULT_SERVICO_PORT),
23637 ("cart", 8443u16),
23638 ("payment", 9090u16),
23639 ("catalog", 443u16),
23640 ] {
23641 let mut spec = three_member_spec();
23642 if let Some(e) = spec.entrada.as_mut() {
23643 e.para = para.into();
23644 e.port = port;
23645 }
23646 let expected_port = spec
23647 .entrada
23648 .as_ref()
23649 .expect("three_member_spec carries a typed `:entrada` block")
23650 .port;
23651 let composed_port = {
23652 let entrada = spec.entrada.as_ref().expect("entrada present");
23653 spec.port_for_destination(entrada.destination())
23654 };
23655 assert_eq!(
23656 composed_port, expected_port,
23657 "`spec.port_for_destination(entrada.destination())` must \
23658 equal `entrada.port` under today's single-destination \
23659 `:entrada` slot — this is the apex-identity contract \
23660 every downstream ingress-apex L4 port reader relies on. \
23661 Input :entrada :para: {para:?}, :entrada :port: {port}"
23662 );
23663 }
23664 }
23665
23666 #[test]
23667 fn port_for_destination_apex_arm_routes_through_destination_accessor() {
23668 // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
23669 // per-`:entrada` apex-arm membership probe must key off
23670 // [`Entrada::destination`], not the raw `.para` field access.
23671 // Structurally: setting ONLY the `:entrada :para` field to a
23672 // fresh non-cart destination on an otherwise-well-formed
23673 // Aplicacao must (1) leave `e.destination()` byte-equal to
23674 // `e.para.as_str()` (the accessor is byte-projective by
23675 // definition), and (2) cause the resolver's apex arm to fire
23676 // and return `entrada.port` at exactly that new destination
23677 // while every other destination string falls through to
23678 // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
23679 // membership check. Pins against a future silent detour that
23680 // (a) re-derived the apex-arm membership probe off
23681 // `e.para == destination` in `port_for_destination` instead of
23682 // `e.destination() == destination`, silently disagreeing with
23683 // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
23684 // consumers (`entrada.destination()` at
23685 // caixa-mesh/src/lib.rs:3173, `c.destination()` at
23686 // caixa-mesh/src/lib.rs:2739) that already reach through the
23687 // accessor, (b) accessor-side introduced a per-tenant alias
23688 // arm the caller was unaware of, silently rewriting an
23689 // author-declared `:para "cart"` value to a canary-aliased
23690 // form — the raw-field-access resolver would fall through to
23691 // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
23692 // while the peer emit-site consumers landed on the aliased
23693 // destination, splitting the ingress-apex L4 port at
23694 // cluster-apply time.
23695 //
23696 // Peer of the sibling
23697 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
23698 // (d0de220) composition pin on the per-`:membros` refusal-arm
23699 // axis — same "the shape-gate predicate must route through the
23700 // substrate-primitive typed dispatch" discipline extended onto
23701 // the per-`:entrada` apex-arm membership-probe axis. Closes
23702 // the last unlifted `.para` production-code read site on
23703 // `Entrada` in `caixa-core` — after this converge every
23704 // `caixa-core` `.para` field access outside the accessor's own
23705 // body and outside the `WitContract` per-`:contratos` sibling
23706 // axis is either a test-side field-setter or a doc-comment
23707 // reference.
23708 for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
23709 let mut spec = three_member_spec();
23710 if let Some(e) = spec.entrada.as_mut() {
23711 e.para = para.into();
23712 e.port = port;
23713 }
23714 let e = spec
23715 .entrada
23716 .as_ref()
23717 .expect("three_member_spec carries a typed `:entrada` block");
23718 assert_eq!(
23719 e.destination(),
23720 e.para.as_str(),
23721 "Entrada::destination must byte-equal the .para field \
23722 access — an accessor-side detour that no longer \
23723 projects the raw field would silently split this \
23724 drift-detection test from the port_for_destination \
23725 apex-arm membership probe",
23726 );
23727 assert_eq!(
23728 spec.port_for_destination(para),
23729 port,
23730 "port_for_destination must key off the accessor-projected \
23731 destination and return `entrada.port` on the apex arm — \
23732 input :entrada :para: {para:?}, :entrada :port: {port}",
23733 );
23734 assert_eq!(
23735 spec.port_for_destination("ghost-destination-never-a-member"),
23736 DEFAULT_SERVICO_PORT,
23737 "port_for_destination must fall through to \
23738 DEFAULT_SERVICO_PORT on a non-matching destination \
23739 under the accessor-projected membership check — input \
23740 :entrada :para: {para:?}, :entrada :port: {port}",
23741 );
23742 }
23743 }
23744
23745 #[test]
23746 fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
23747 // The canonical per-`:politicas :rate-limit` `:rate`
23748 // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
23749 // [`RateLimit::rate`] must return the `:politicas :rate-limit`
23750 // typed `u32` verbatim, byte-equal to the raw field access
23751 // across every representative value in the accept-set — `1` (the
23752 // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
23753 // the surrounding [`AplicacaoSpec::validate_politicas`] gate
23754 // carves out on the sibling `PolicyRateLimitZero` refusal),
23755 // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
23756 // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
23757 // `0` (a past-the-guard sentinel that pins the accessor doesn't
23758 // perform a silent bounds-collapse into `1` on the zero arm —
23759 // validate rejects zero but the accessor must ship the raw slot
23760 // verbatim so a validate-time gate regression surfaces at the
23761 // emit boundary rather than being silently absorbed), `u32::MAX`
23762 // (a past-the-guard sentinel that pins the accessor doesn't
23763 // perform a silent bounds-collapse through
23764 // `POLICY_RATE_LIMIT_MAX` at the return path).
23765 //
23766 // First sub-struct required-scalar accessor pin on the
23767 // `RateLimit` axis — sibling in shape to the peer
23768 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
23769 // required-`u32` accessor pin on the peer per-sub-struct
23770 // required-axis. Pins against a future silent detour that
23771 // re-derived the token capacity from a peer axis (an accidental
23772 // `self.window.as_secs() as u32` collapse that read the
23773 // rate-limit window duration as a token count), a `0 → 1`
23774 // cluster-default projection (which would silently absorb the
23775 // `PolicyRateLimitZero` refusal case at the accessor boundary),
23776 // or a bounds-collapsing accessor that clamped the return
23777 // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
23778 // gate owns the bounds; the accessor must ship the raw slot
23779 // verbatim).
23780 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
23781 let rl = RateLimit {
23782 rate,
23783 window: Duration::from_secs(1),
23784 };
23785 assert_eq!(
23786 rl.rate(),
23787 rate,
23788 "RateLimit::rate must return :politicas :rate-limit :rate \
23789 verbatim (got {}, expected {rate})",
23790 rl.rate(),
23791 );
23792 assert_eq!(
23793 rl.rate(),
23794 rl.rate,
23795 "RateLimit::rate must byte-equal the raw .rate field \
23796 access across every value in the u32 accept-set",
23797 );
23798 }
23799 }
23800
23801 #[test]
23802 fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
23803 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
23804 // `:rate-limit :rate` zero-floor arm must key off
23805 // [`RateLimit::rate`], not the raw `.rate` field access.
23806 // Structurally: a `RateLimit { rate: 0, window:
23807 // Duration::from_secs(1) }` embedded in a `:politicas
23808 // :rate-limit` slot must surface the `PolicyRateLimitZero`
23809 // refusal exactly, and a `RateLimit { rate: 1, window:
23810 // Duration::from_secs(1) }` (the lower boundary of the
23811 // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
23812 // The pair jointly pins the accessor + validate-gate composition:
23813 // any future silent detour that had the accessor return a fresh
23814 // `1` on the zero arm (a `.rate().max(1)` collapse) would
23815 // silently absorb the `PolicyRateLimitZero` refusal at the
23816 // accessor boundary and the validate gate would accept a
23817 // struct-literal `RateLimit { rate: 0, .. }` — the composition
23818 // pin catches that at caixa-core build time.
23819 //
23820 // Peer of the sibling per-`CircuitBreaker`
23821 // [`CircuitBreaker::max_failures`] (3a74062) /
23822 // [`CircuitBreaker::window`] (373957f) accessor-composition
23823 // pins on the peer required-scalar axes — same "the validate /
23824 // shape-gate predicate must route through the substrate-primitive
23825 // typed dispatch" discipline extended onto the peer
23826 // per-`RateLimit` required-`u32` composition axis.
23827 let mut spec = three_member_spec();
23828 spec.politicas = MeshPolicy {
23829 rate_limit: Some(RateLimit {
23830 rate: 0,
23831 window: Duration::from_secs(1),
23832 }),
23833 ..MeshPolicy::default()
23834 };
23835 assert!(
23836 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
23837 "validate_politicas must reject rate == 0 with \
23838 PolicyRateLimitZero — the accessor and the validate gate \
23839 must route through the same substrate-primitive typed \
23840 dispatch on the :rate zero-floor arm",
23841 );
23842 spec.politicas = MeshPolicy {
23843 rate_limit: Some(RateLimit {
23844 rate: 1,
23845 window: Duration::from_secs(1),
23846 }),
23847 ..MeshPolicy::default()
23848 };
23849 assert!(
23850 spec.validate().is_ok(),
23851 "validate_politicas must accept rate == 1 (the lower \
23852 boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
23853 );
23854 }
23855
23856 #[test]
23857 fn rate_limit_rate_projects_u32_by_copy() {
23858 // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
23859 // `u32` is `Copy` and the accessor must return by value, not by
23860 // reference. Peer of the sibling per-`CircuitBreaker`
23861 // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
23862 // peer required-scalar `:max-failures` axis, extended onto the
23863 // peer per-`RateLimit` required-`u32` copy-invariant shape —
23864 // the accessor's returned `u32` must outlive `&self` (multiple
23865 // calls must return equal values from a dropped-`&self` copy,
23866 // since the returned scalar carries no borrow), and calling the
23867 // accessor twice on the same RateLimit must yield the same
23868 // `u32` verbatim (idempotent, no side effects on `&self`).
23869 //
23870 // Pins against a future silent detour that returned `&u32`
23871 // (which would type-check but silently break every downstream
23872 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
23873 // first parameter is `u32`, and `&u32` would fold to a detached
23874 // copy at the call site with a `*` deref the sibling accessors
23875 // don't need), an accidental `.rate.wrapping_add(0)` detour that
23876 // returned a fresh copy through an arithmetic no-op (breaking a
23877 // future `const fn` regression), or a one-arm-only accessor
23878 // that returned a saturating value on some sentinel input
23879 // (breaking the pass-through invariant the sibling required-
23880 // scalar accessors carry).
23881 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
23882 let rl = RateLimit {
23883 rate,
23884 window: Duration::from_secs(1),
23885 };
23886 let first = rl.rate();
23887 let second = rl.rate();
23888 assert_eq!(
23889 first, second,
23890 "RateLimit::rate must be idempotent — two successive \
23891 calls on the same &self must return the same u32",
23892 );
23893 assert_eq!(
23894 first, rate,
23895 "RateLimit::rate must return :politicas :rate-limit :rate \
23896 verbatim by copy — got {first}, expected {rate}",
23897 );
23898 }
23899 }
23900
23901 #[test]
23902 fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
23903 // The canonical per-`:politicas :rate-limit` `:window`
23904 // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
23905 // pin: [`RateLimit::window`] must return the
23906 // `:politicas :rate-limit :window` typed `Duration` verbatim,
23907 // byte-equal to the raw field access across every
23908 // representative value in the accept-set — `Duration::from_secs(1)`
23909 // (the `"s"` canonical window, the lower row of
23910 // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
23911 // [`AplicacaoSpec::validate_politicas`] gate accepts via
23912 // [`is_canonical_rate_limit_window`]),
23913 // `Duration::from_secs(60)` (the `"m"` canonical window, the
23914 // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
23915 // window, the upper row), `Duration::ZERO` (a past-the-guard
23916 // sentinel that pins the accessor doesn't perform a silent
23917 // bounds-collapse into `Duration::from_secs(1)` on the zero
23918 // arm — validate rejects an off-set window through
23919 // `PolicyRateLimitWindowNotCanonical` but the accessor must
23920 // ship the raw slot verbatim so a validate-time gate
23921 // regression surfaces at the emit boundary rather than being
23922 // silently absorbed), `Duration::from_millis(500)` (a
23923 // sub-canonical past-the-guard sentinel that pins the accessor
23924 // doesn't silently normalize a non-canonical fractional
23925 // magnitude onto the nearest canonical row).
23926 //
23927 // Second sub-struct required-scalar accessor pin on the
23928 // `RateLimit` axis — sibling in shape to the just-landed
23929 // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
23930 // accessor pin on the peer per-sub-struct required-axis,
23931 // extended onto the per-`RateLimit` required-`Duration` axis.
23932 // Pins against a future silent detour that re-derived the
23933 // refill period from a peer axis (an accidental
23934 // `Duration::from_secs(self.rate as u64)` collapse that read
23935 // the rate-limit token capacity as a refill-interval
23936 // duration), a `Duration::ZERO → Duration::from_secs(1)`
23937 // canonical-default projection (which would silently absorb
23938 // the `PolicyRateLimitWindowNotCanonical` refusal case at the
23939 // accessor boundary), or a canonical-set-collapsing accessor
23940 // that clamped the return through [`rate_limit_window_unit`]
23941 // (the `AplicacaoSpec::validate` gate owns the canonical-set
23942 // membership; the accessor must ship the raw slot verbatim).
23943 for window in [
23944 Duration::from_secs(1),
23945 Duration::from_secs(60),
23946 Duration::from_secs(3600),
23947 Duration::ZERO,
23948 Duration::from_millis(500),
23949 ] {
23950 let rl = RateLimit { rate: 100, window };
23951 assert_eq!(
23952 rl.window(),
23953 window,
23954 "RateLimit::window must return :politicas :rate-limit :window \
23955 verbatim (got {:?}, expected {window:?})",
23956 rl.window(),
23957 );
23958 assert_eq!(
23959 rl.window(),
23960 rl.window,
23961 "RateLimit::window must byte-equal the raw .window field \
23962 access across every value in the Duration accept-set",
23963 );
23964 }
23965 }
23966
23967 #[test]
23968 fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
23969 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
23970 // `:rate-limit :window` canonical-set arm must key off
23971 // [`RateLimit::window`], not the raw `.window` field access.
23972 // Structurally: a `RateLimit { window: Duration::from_millis(500),
23973 // .. }` embedded in a `:politicas :rate-limit` slot must
23974 // surface the `PolicyRateLimitWindowNotCanonical` refusal
23975 // exactly (with the sub-canonical `Duration::from_millis(500)`
23976 // magnitude carried through verbatim), and a `RateLimit
23977 // { window: Duration::from_secs(1), .. }` (the lower row of
23978 // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
23979 // The pair jointly pins the accessor + validate-gate
23980 // composition: any future silent detour that had the accessor
23981 // normalize the off-set window to the nearest canonical row
23982 // (a `.window().max(Duration::from_secs(1))` collapse, or a
23983 // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
23984 // collapse) would silently absorb the
23985 // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
23986 // boundary — including a drift in the error's `window` payload
23987 // (the emit-side diagnostic reader keys off the offending
23988 // magnitude verbatim, so a normalization at the accessor
23989 // boundary would silently pin the wrong magnitude in the
23990 // refusal). The composition pin catches that at caixa-core
23991 // build time.
23992 //
23993 // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
23994 // (7f81a60) accessor-composition pin on the peer required-
23995 // scalar `:rate` axis — same "the validate / shape-gate
23996 // predicate must route through the substrate-primitive typed
23997 // dispatch, and the error payload must project through the
23998 // same accessor" discipline extended onto the peer
23999 // per-`RateLimit` required-`Duration` composition axis.
24000 let mut spec = three_member_spec();
24001 spec.politicas = MeshPolicy {
24002 rate_limit: Some(RateLimit {
24003 rate: 100,
24004 window: Duration::from_millis(500),
24005 }),
24006 ..MeshPolicy::default()
24007 };
24008 match spec.validate() {
24009 Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
24010 assert_eq!(
24011 window,
24012 Duration::from_millis(500),
24013 "PolicyRateLimitWindowNotCanonical must carry the \
24014 offending :window magnitude verbatim through the \
24015 accessor — got {window:?}, expected 500ms",
24016 );
24017 }
24018 other => panic!(
24019 "validate_politicas must reject non-canonical :window \
24020 with PolicyRateLimitWindowNotCanonical — the accessor \
24021 and the validate gate must route through the same \
24022 substrate-primitive typed dispatch on the :window \
24023 canonical-set arm; got {other:?}",
24024 ),
24025 }
24026 spec.politicas = MeshPolicy {
24027 rate_limit: Some(RateLimit {
24028 rate: 100,
24029 window: Duration::from_secs(1),
24030 }),
24031 ..MeshPolicy::default()
24032 };
24033 assert!(
24034 spec.validate().is_ok(),
24035 "validate_politicas must accept window == Duration::from_secs(1) \
24036 (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
24037 );
24038 }
24039
24040 #[test]
24041 fn rate_limit_window_projects_duration_by_copy() {
24042 // The by-copy pin: [`RateLimit::window`] returns `Duration`
24043 // by copy — `Duration` is `Copy` and the accessor must return
24044 // by value, not by reference. Peer of the sibling per-`RateLimit`
24045 // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
24046 // required-scalar `:rate` axis, extended onto the peer
24047 // per-`RateLimit` required-`Duration` copy-invariant shape —
24048 // the accessor's returned `Duration` must outlive `&self`
24049 // (multiple calls must return equal values from a
24050 // dropped-`&self` copy, since the returned scalar carries no
24051 // borrow), and calling the accessor twice on the same
24052 // RateLimit must yield the same `Duration` verbatim
24053 // (idempotent, no side effects on `&self`).
24054 //
24055 // Pins against a future silent detour that returned
24056 // `&Duration` (which would type-check but silently break every
24057 // downstream `Duration`-by-value consumer —
24058 // [`is_canonical_rate_limit_window`]'s first parameter is
24059 // `Duration`, and `&Duration` would fold to a detached copy at
24060 // the call site with a `*` deref the sibling accessors don't
24061 // need), an accidental `.window + Duration::ZERO` detour that
24062 // returned a fresh copy through an arithmetic no-op (breaking
24063 // a future `const fn` regression), or a one-arm-only accessor
24064 // that returned a canonical fallback on some sentinel input
24065 // (breaking the pass-through invariant the sibling required-
24066 // scalar accessors carry).
24067 for window in [
24068 Duration::from_secs(1),
24069 Duration::from_secs(60),
24070 Duration::from_secs(3600),
24071 Duration::ZERO,
24072 Duration::from_millis(500),
24073 ] {
24074 let rl = RateLimit { rate: 100, window };
24075 let first = rl.window();
24076 let second = rl.window();
24077 assert_eq!(
24078 first, second,
24079 "RateLimit::window must be idempotent — two successive \
24080 calls on the same &self must return the same Duration",
24081 );
24082 assert_eq!(
24083 first, window,
24084 "RateLimit::window must return :politicas :rate-limit :window \
24085 verbatim by copy — got {first:?}, expected {window:?}",
24086 );
24087 }
24088 }
24089}