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 targets *none* of the three known payload-
797 /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
798 /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
799 /// open on the [`WitContract`] surface. Returns the exact-inverse
800 /// disjunction of the peer trio — `true` when none of the three
801 /// prefix-set predicates matches the raw `:contratos :wit` value; the
802 /// author-declared WIT world is a pure typed capability edge with no
803 /// payload selector (the shape [`WitContract::target`] projects onto
804 /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
805 /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
806 ///
807 /// The `:contratos :wit` shape-space is closed at four arms
808 /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
809 /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
810 /// everything else on the payload-less capability arm), and every
811 /// downstream consumer that must filter contratos by shape-class
812 /// keys off the four sibling predicates (the [`WitContract::target`]
813 /// dispatch's implicit `else` after the three payload-shape arm
814 /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
815 /// every future substrate-side capability-shape-only emitter — the
816 /// M4 per-Aplicacao WIT-registry capability-import materializer, the
817 /// future `feira app graph --capability` per-Aplicacao capability-
818 /// column filter, the future per-cluster capability-scope reconciler
819 /// that skips L4/L7 emission for payload-less edges since Cilium
820 /// can't introspect WASI capability calls, the future
821 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
822 /// shape shape-count histogram). Every such consumer reaches for one
823 /// typed dispatch on the substrate primitive so the "which arm
824 /// carries the capability-only shape?" answer lives at one caixa-core
825 /// edit rather than open-coded across per-consumer
826 /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
827 /// negations, each of which would silently drop a future fourth
828 /// payload-arm addition without a compile-time signal at the
829 /// consumer site.
830 ///
831 /// Prior to this lift the "not one of the three known payload
832 /// shapes" classification sat inline at [`WitContract::target`]'s
833 /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
834 /// [`WitTarget::Capability`] admission arm after the three `if
835 /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
836 /// { … }` guards) with no named accessor for downstream consumers
837 /// to reach through. A future substrate-side capability-only
838 /// filter or a future capability-scope reconciler would have had to
839 /// re-inline the same triplet negation at every emit site with no
840 /// compile-time link back to the sibling trio, and a future arm
841 /// addition (a hypothetical fourth payload-shape prefix set — a
842 /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
843 /// import carrier per the sibling [`wit_shape_matches`] docstring's
844 /// trajectory bullet) would land the new predicate on the payload-
845 /// carrying trio and silently misclassify the new shape as
846 /// capability at every triplet-negation consumer site, propagating
847 /// the drift far from the caixa-core prefix-set commit.
848 ///
849 /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
850 /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
851 /// trio into a 4-way partition witness on the raw `:contratos :wit`
852 /// axis, mirroring the paired post-projection [`WitTarget`]
853 /// `gen_platform::IsVariant`-derived 4-way predicate set
854 /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
855 /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
856 /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
857 /// arm-set). The two typed axes — pre-projection on the raw
858 /// `:contratos :wit` string, post-projection on the validated typed
859 /// view — now carry a matched 4-arm predicate discipline: every
860 /// arm on the closed [`WitTarget`] set has a peer pre-projection
861 /// predicate on the [`WitContract`] surface, and any future
862 /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
863 /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
864 /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
865 /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
866 /// pre-projection axis through a matching peer prefix-set + peer
867 /// predicate lift by construction — the compile-time exhaustiveness
868 /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
869 /// the post-projection accessor family stays in sync, and the sibling
870 /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
871 /// partition-witness pin locks the pre-projection classification in
872 /// load-bearing so a peer prefix-set addition that widened one arm's
873 /// accept-set without shrinking the [`Self::is_capability`] accept-set
874 /// surfaces as a test failure at caixa-core build time rather than a
875 /// silent per-consumer split at renderer emit time.
876 ///
877 /// Composes byte-for-byte through the lifted peer trio
878 /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
879 /// any future rebrand of any prefix-set const flows through this
880 /// method by construction without a coordinated per-consumer rewrite
881 /// (pinned by the sibling
882 /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
883 /// composition-witness).
884 ///
885 /// Note: purely syntactic classification on the `:wit` prefix-set —
886 /// unlike [`Self::target`], which additionally rejects value-shape-
887 /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
888 /// package) via [`crate::render::is_wit_world_ref`] and payload-
889 /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
890 /// structurally malformed returns `true` from `is_capability()` (the
891 /// prefix set matches nothing), and the surrounding
892 /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
893 /// is where the [`AplicacaoError::EmptyWit`] /
894 /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
895 /// predicate is the classifier, not the validator.
896 #[must_use]
897 pub fn is_capability(&self) -> bool {
898 !self.is_http() && !self.is_pubsub() && !self.is_store()
899 }
900
901 /// True when this contract's caller equals its callee — a
902 /// structurally degenerate typed edge that no `:contratos` entry can
903 /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
904 /// Servico B" is an *inter*-Servico contract between two distinct
905 /// graph nodes). A Servico contracting with itself resolves to an
906 /// in-process call the wasm-engine never routes through the mesh at
907 /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
908 /// per-edge policy can express the intended shape — the pub-sub
909 /// path silently rendered a self-allow rule that is a no-op (intra-
910 /// pod traffic bypasses the mesh entirely), and the synchronous
911 /// paths surfaced as a misleading `ContratoCycle` whose path was
912 /// `["cart", "cart"]` — framing a self-edge as a multi-node
913 /// deadlock. Every downstream consumer that must reject the shape
914 /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
915 /// gate at caixa-core/src/aplicacao.rs:5559, every future
916 /// per-`:contratos`-edge policy resolver on the M4 CR materializer
917 /// axis, every future adjacency-graph builder that must skip self-
918 /// edges rather than fold them into an incidental cycle) now keys
919 /// off exactly one typed dispatch on the substrate primitive, so
920 /// any future rebrand on the axis (an M4-typed-caller enum whose
921 /// identity comparison rule the accessor could route through, an
922 /// operator-side per-cluster caller/callee-alias table the
923 /// materializer resolves per-CR before the equality probe, a
924 /// promotion of the pointwise `==` to a set-membership check once
925 /// SimpleOneForOne-shaped dynamic replicas come into typed scope
926 /// so a per-replica self-edge is rejected under the same predicate)
927 /// migrates as a single caixa-core edit rather than a coordinated
928 /// rewrite of every downstream self-edge consumer. Composes
929 /// byte-for-byte through the lifted [`Self::source`] /
930 /// [`Self::destination`] scalar accessors — the accessor pair every
931 /// per-`:contratos` scalar-value axis already routes through — so
932 /// any future rebrand of the underlying `:de` / `:para` storage
933 /// (a lift from `String` to a typed `ServicoName(String)` newtype,
934 /// a per-Aplicacao interning arena the M4 CR materializer authors,
935 /// a `smol_str::SmolStr` inline-buffer swap) flows through the
936 /// same one body without a coordinated per-consumer rewrite.
937 ///
938 /// Sibling in shape to the peer per-`:contratos` shape-predicate
939 /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
940 /// on the `:wit` world-ref axis — extended onto the per-edge
941 /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
942 /// partition the WIT-shape-space; `is_self_loop` partitions the
943 /// caller-callee identity-space. Named `is_self_loop()` to reflect
944 /// the graph-theoretic identity of the shape (a loop from a graph
945 /// node to itself, distinct from the sibling multi-node
946 /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
947 /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
948 /// variant already carrying the term.
949 #[must_use]
950 pub fn is_self_loop(&self) -> bool {
951 self.source() == self.destination()
952 }
953
954 /// Typed view of the contract's payload target. Enforces that the
955 /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
956 /// fields agree, and that each carried value is itself
957 /// value-shape valid:
958 ///
959 /// - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
960 /// non-empty, leading-`/` (Cilium L7 `path` + Gateway API
961 /// `PathPrefix` invariant — same shape required of `:entrada
962 /// :paths`)
963 /// - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
964 /// non-empty (NATS / Kafka publish without a subject is a
965 /// no-op subscribe, never the author's intent)
966 /// - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
967 /// non-empty (an empty slot template addresses the bucket
968 /// root, defeating the per-key isolation the slot exists for)
969 /// - Anything else ⇒ none of the three; the contract is a pure
970 /// typed capability edge with no payload selector.
971 ///
972 /// Translates the Apollo Federation discipline ("conflicts are
973 /// errors at compile time, not warnings at runtime";
974 /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
975 /// a contract whose WIT shape disagrees with its target field, or
976 /// whose target field carries a value-shape-invalid string, is a
977 /// build error — not a silent renderer drop. The returned
978 /// [`WitTarget`] view's `&str` payload is therefore guaranteed
979 /// non-empty (and absolute, for `Http`); every downstream consumer
980 /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
981 /// the M4 per-edge policy resolver) can rely on that without
982 /// re-checking.
983 pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
984 // Route the HTTP-shaped payload-target extraction through the
985 // lifted [`WitContract::endpoint`] accessor rather than the raw
986 // `self.endpoint.as_deref()` field access — the two production
987 // consumers of the per-`:contratos :endpoint` HTTP-shaped
988 // payload-carrier scalar (this method's Http-arm payload
989 // extraction, the [`AplicacaoSpec::validate`] duplicate-
990 // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
991 // off exactly one typed dispatch on the substrate primitive, so
992 // any future rebrand on the axis (an M4 per-cluster endpoint-
993 // alias rewrite, a per-CR fully-qualified path prefix the M4
994 // materializer applies per-tenant, an M4 promotion from
995 // `Option<String>` to a typed HTTP path-template enum) migrates
996 // as a single caixa-core edit rather than a coordinated rewrite
997 // of the two call sites — peer of the sibling M3 per-`:placement`
998 // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
999 // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1000 // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1001 let endpoint = self.endpoint();
1002 let subject = self.subject();
1003 // Route the store-arm payload-carrier scalar through the
1004 // lifted [`WitContract::slot`] accessor rather than the raw
1005 // `self.slot.as_deref()` field access — the two production
1006 // consumers of the per-`:contratos :slot` key/value-store-
1007 // shaped payload-carrier scalar (this method's Store-arm
1008 // payload extraction, the [`AplicacaoSpec::validate`]
1009 // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1010 // arm) now key off exactly one typed dispatch on the substrate
1011 // primitive. Closes the last unlifted per-`:contratos`
1012 // `Option<String>` axis, completing the payload-carrier
1013 // accessor family peer of the sibling per-`:contratos`
1014 // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1015 // (90de675) lifts across the HTTP / pub-sub arms.
1016 let slot = self.slot();
1017 // Route the local `(de, para, wit)` triple-projection closure
1018 // through the lifted [`WitContract::edge_triple`] typed accessor
1019 // rather than re-inlining `(self.de.clone(), self.para.clone(),
1020 // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1021 // triple-carrying diagnostic constructors below (wrong-target /
1022 // missing-target on all three payload arms + capability-with-
1023 // payload + invalid-wit) now key off exactly one typed dispatch
1024 // on the substrate-primitive composite projection, sibling to
1025 // the peer [`WitContract::edge_pair`]-routed
1026 // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1027 // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1028 // diagnostic constructors on the same per-`:contratos`
1029 // diagnostic-construction surface.
1030 let edge = || self.edge_triple();
1031
1032 // The `:wit` value drives every downstream dispatch — the
1033 // is_http/is_pubsub/is_store prefix matchers below, the
1034 // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1035 // exclusion. Until this gate landed `target()` accepted any
1036 // non-empty string and silently demoted unrecognized shapes to
1037 // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1038 // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1039 // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1040 // package, the paste-from-binary footgun a multi-line blob
1041 // accidentally landing in the slot, the un-percent-encoded
1042 // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1043 // routing, got L4-only" footgun. Empty is still pre-checked at
1044 // the [`AplicacaoSpec::validate`] call site via the narrower
1045 // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1046 // validate layer); the value-shape gate here picks up the
1047 // structurally-invalid non-empty cases the empty check misses,
1048 // and remains correct under direct `target()` calls outside
1049 // validate (the predicate's defensive empty arm returns a
1050 // parser-shaped reason rather than silently falling through to
1051 // the Capability arm). Same trajectory as c4213a4 (WitContract
1052 // endpoint/subject/slot value-shape gates lifted into
1053 // `target()`) on the peer payload axes.
1054 if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
1055 let (de, para, wit) = edge();
1056 return Err(AplicacaoError::ContratoWitInvalid {
1057 de,
1058 para,
1059 wit,
1060 reason,
1061 });
1062 }
1063
1064 if self.is_http() {
1065 if subject.is_some() || slot.is_some() {
1066 let (de, para, wit) = edge();
1067 return Err(AplicacaoError::ContratoWrongTarget {
1068 de,
1069 para,
1070 wit,
1071 expected: WitTarget::HTTP_FIELD_NAME,
1072 });
1073 }
1074 let ep = endpoint.ok_or_else(|| {
1075 let (de, para, wit) = edge();
1076 AplicacaoError::ContratoMissingTarget {
1077 de,
1078 para,
1079 wit,
1080 expected: WitTarget::HTTP_FIELD_NAME,
1081 }
1082 })?;
1083 if ep.is_empty() {
1084 let (de, para) = self.edge_pair();
1085 return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
1086 }
1087 if !ep.starts_with('/') {
1088 let (de, para) = self.edge_pair();
1089 return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1090 de,
1091 para,
1092 endpoint: ep.to_string(),
1093 });
1094 }
1095 // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1096 // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1097 // API v1 HTTPPathMatch.value admission grammar with the
1098 // sibling `:entrada :paths` axis. Until this gate landed
1099 // `target()` only refused the empty string + the missing-
1100 // leading-`/` form; a structurally invalid endpoint
1101 // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1102 // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1103 // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1104 // path-traversal segment, the >1024-byte slug) silently
1105 // passed validate and the failure surfaced at apply time
1106 // as a Cilium policy rejection / silent traffic drop, far
1107 // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1108 // grammar `:entrada :paths` already gates (55410e4), now
1109 // shared with `:contratos :endpoint` through the lifted
1110 // `crate::render::is_gateway_api_http_path` predicate.
1111 if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1112 let (de, para) = self.edge_pair();
1113 return Err(AplicacaoError::ContratoEndpointInvalid {
1114 de,
1115 para,
1116 endpoint: ep.to_string(),
1117 reason,
1118 });
1119 }
1120 return Ok(WitTarget::Http { endpoint: ep });
1121 }
1122 if self.is_pubsub() {
1123 if endpoint.is_some() || slot.is_some() {
1124 let (de, para, wit) = edge();
1125 return Err(AplicacaoError::ContratoWrongTarget {
1126 de,
1127 para,
1128 wit,
1129 expected: WitTarget::PUBSUB_FIELD_NAME,
1130 });
1131 }
1132 let s = subject.ok_or_else(|| {
1133 let (de, para, wit) = edge();
1134 AplicacaoError::ContratoMissingTarget {
1135 de,
1136 para,
1137 wit,
1138 expected: WitTarget::PUBSUB_FIELD_NAME,
1139 }
1140 })?;
1141 if s.is_empty() {
1142 let (de, para) = self.edge_pair();
1143 return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1144 }
1145 // The `:subject` lands at runtime as the NATS subject the
1146 // producer publishes to and the consumer subscribes from.
1147 // Until this gate landed `target()` only refused the
1148 // empty string; a structurally invalid subject
1149 // (`"foo..bar"` — empty token between separators,
1150 // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1151 // server's subject parser rejects, `"foo bar"` —
1152 // un-percent-encoded whitespace, `"foo.café"` —
1153 // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1154 // empty leading/trailing tokens, the >256-byte
1155 // paste-from-binary slug) silently passed validate and
1156 // the failure surfaced at runtime as a NATS server-side
1157 // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1158 // a silent message drop, far from the source caixa.lisp.
1159 // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1160 // trajectory `:contratos :endpoint` (4f0390b) and
1161 // `:contratos :wit` (6226bf4) already gate, now shared
1162 // with `:contratos :subject` through the lifted
1163 // `crate::render::is_nats_subject` predicate.
1164 if let Err(reason) = crate::render::is_nats_subject(s) {
1165 let (de, para) = self.edge_pair();
1166 return Err(AplicacaoError::ContratoSubjectInvalid {
1167 de,
1168 para,
1169 subject: s.to_string(),
1170 reason,
1171 });
1172 }
1173 return Ok(WitTarget::PubSub { subject: s });
1174 }
1175 if self.is_store() {
1176 if endpoint.is_some() || subject.is_some() {
1177 let (de, para, wit) = edge();
1178 return Err(AplicacaoError::ContratoWrongTarget {
1179 de,
1180 para,
1181 wit,
1182 expected: WitTarget::STORE_FIELD_NAME,
1183 });
1184 }
1185 let sl = slot.ok_or_else(|| {
1186 let (de, para, wit) = edge();
1187 AplicacaoError::ContratoMissingTarget {
1188 de,
1189 para,
1190 wit,
1191 expected: WitTarget::STORE_FIELD_NAME,
1192 }
1193 })?;
1194 if sl.is_empty() {
1195 let (de, para) = self.edge_pair();
1196 return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1197 }
1198 // Value-shape gate on the third (and last) typed payload
1199 // axis the `WitContract::target` dispatch carries — the
1200 // peer of [`crate::render::is_gateway_api_http_path`] for
1201 // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1202 // for `:subject` (63e18a0). Until this gate landed
1203 // `target()` only refused the empty string; a structurally
1204 // invalid slot (`"check out/$order"` — un-percent-encoded
1205 // whitespace whose runtime behavior varies unpredictably
1206 // across kv backends, `"checkout/\x01order"` — control
1207 // character that Redis admits but corrupts on next read
1208 // and DynamoDB rejects outright, `"chéckout/$order"` —
1209 // un-percent-encoded non-ASCII byte each backend re-encodes
1210 // differently, `"checkout\n/$order"` — embedded newline,
1211 // the 513-byte paste-from-binary slug) silently passed
1212 // validate and surfaced at runtime as a per-backend kv
1213 // write rejection (DynamoDB / etcd) or as a silent
1214 // next-read corruption (Redis-via-RESP3), far from the
1215 // source caixa.lisp with no field naming which `:contratos`
1216 // edge carried the typo. The lifted predicate makes the
1217 // kv-backend intersection-floor a substrate-level
1218 // invariant at validate time, not a runtime "this passed
1219 // validate but the kv backend rejected on first write"
1220 // surprise — closes the typed payload-axis value-shape
1221 // trajectory across all three legs of the four
1222 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1223 // that caixa-mesh + the future kv emitters land in.
1224 if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1225 let (de, para) = self.edge_pair();
1226 return Err(AplicacaoError::ContratoSlotInvalid {
1227 de,
1228 para,
1229 slot: sl.to_string(),
1230 reason,
1231 });
1232 }
1233 return Ok(WitTarget::Store { slot: sl });
1234 }
1235
1236 // Unrecognized WIT world — must not carry any payload target.
1237 if endpoint.is_some() || subject.is_some() || slot.is_some() {
1238 let (de, para, wit) = edge();
1239 return Err(AplicacaoError::ContratoWrongTarget {
1240 de,
1241 para,
1242 wit,
1243 expected: WitTarget::CAPABILITY_EXPECTED,
1244 });
1245 }
1246 Ok(WitTarget::Capability)
1247 }
1248}
1249
1250/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1251/// gate (see [`AplicacaoSpec::validate`]): every field that
1252/// distinguishes one contract from another, in declaration order
1253/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1254/// with equal [`ContratoIdentity`]s are the same typed edge declared
1255/// twice — the graph-edge analogue of duplicate `:membros` /
1256/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1257/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1258/// clippy's `type_complexity` lint (and so a future axis added to
1259/// `WitContract` is one alias edit, not a coordinated rewrite of
1260/// every set instantiation).
1261pub type ContratoIdentity<'a> = (
1262 &'a str,
1263 &'a str,
1264 &'a str,
1265 Option<&'a str>,
1266 Option<&'a str>,
1267 Option<&'a str>,
1268);
1269
1270/// Typed view of a [`WitContract`]'s payload target. Each variant
1271/// carries the field its WIT shape requires; constructing a `Http`
1272/// view without an endpoint is impossible by the type system.
1273///
1274/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1275/// instead of probing `Option<String>` fields one by one — the
1276/// "which payload field is set?" question is answered once, at
1277/// validation time.
1278#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1279pub enum WitTarget<'a> {
1280 /// HTTP-shaped WIT world. Carries the configured request path.
1281 Http { endpoint: &'a str },
1282 /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1283 ///
1284 /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1285 /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1286 /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1287 /// method name byte-identical to the sibling
1288 /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1289 /// arm-discriminator that routes through
1290 /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1291 /// through `matches!` on the variant), so the two arm-discriminator
1292 /// axes — target-side variant-arm and shape-side ref-prefix — reach
1293 /// every downstream consumer through the same `is_pubsub()` name.
1294 #[is_variant(name = "pubsub")]
1295 PubSub { subject: &'a str },
1296 /// Key-value-shaped WIT world. Carries the slot template.
1297 Store { slot: &'a str },
1298 /// A typed capability edge with no payload selector — the WIT
1299 /// world stands on its own (rare; reserved for plain capability
1300 /// imports or M4-and-later WIT worlds we haven't shaped yet).
1301 Capability,
1302}
1303
1304impl<'a> WitTarget<'a> {
1305 /// Canonical author-facing `:contratos` payload field name for the
1306 /// HTTP-shaped arm — the `expected: &'static str` scalar the
1307 /// [`AplicacaoError::ContratoMissingTarget`] /
1308 /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1309 /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1310 /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1311 /// the `feira app graph` verb prints. Peer of
1312 /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1313 /// on the payload-field-name axis; declared as a peer const next
1314 /// to the [`WitTarget::Http`] variant so a future rename on the
1315 /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1316 /// :endpoint …)))` field lands in exactly one place, not scattered
1317 /// across the [`WitContract::target`] gate's six `expected:`
1318 /// literals, the label template, and every downstream consumer
1319 /// that prints a per-arm prefix. Same trajectory as the peer
1320 /// [`WitTarget::label`] lift (174e96a): a single source of truth
1321 /// for the arm's shape, next to the variant declaration.
1322 pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1323 /// Canonical author-facing `:contratos` payload field name for the
1324 /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1325 /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1326 /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1327 pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1328 /// Canonical author-facing `:contratos` payload field name for the
1329 /// key/value-store-shaped arm. Peer of
1330 /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1331 /// on the payload-field-name axis; see
1332 /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1333 pub const STORE_FIELD_NAME: &'static str = "slot";
1334
1335 /// Canonical stable human-readable label the payload-less
1336 /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1337 /// the byte-string every consumer that formats a payload-less
1338 /// typed capability edge as text lands on (the
1339 /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1340 /// naming which identical edge was declared twice, the future
1341 /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1342 /// policy resolver's audit view, the operator's mesh-graph audit).
1343 /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1344 /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1345 /// author-facing label-scalar consts — the same
1346 /// "one canonical declaration per arm, next to the variant, so a
1347 /// future rename lands in one place" discipline extended to the
1348 /// payload-less arm. Until this lift landed the byte-string sat
1349 /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1350 /// match arm, once in the pin test asserting the label's
1351 /// [`WitTarget::Capability`] output — with no compile-time link
1352 /// between the two: a rebrand on either side (an operator-facing
1353 /// vocabulary shift, a per-consumer disambiguation like
1354 /// `"(capability — no payload; typed edge only)"`) would silently
1355 /// desynchronize until a downstream consumer surfaced the drift at
1356 /// runtime.
1357 pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1358
1359 /// Canonical `expected:` scalar the
1360 /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1361 /// through for the payload-less [`WitTarget::Capability`] arm — the
1362 /// byte-string authors read as "this WIT world's shape is not one
1363 /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1364 /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1365 /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1366 /// [`Self::STORE_FIELD_NAME`] consts on the
1367 /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1368 /// same "which payload field name goes in the diagnostic" dispatch
1369 /// the three payload-arm consts cover, extended to the payload-less
1370 /// arm. Until this lift landed the byte-string sat twice — once
1371 /// inline in the [`Self::target`] Capability-arm rejection at the
1372 /// production dispatch, once in the pin test asserting the
1373 /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1374 /// no compile-time link between the two: a rebrand on either side
1375 /// (an author-facing vocabulary shift to `"capability"` /
1376 /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1377 /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1378 /// [`WitTarget::Capability`] into per-shape peers) would silently
1379 /// desynchronize until a downstream consumer surfaced the drift at
1380 /// runtime. Same "one canonical declaration per arm, next to the
1381 /// variant, so a future rename lands in one place" discipline the
1382 /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1383 /// established for the payload-less arm's human-readable label
1384 /// axis; this lift extends it onto the peer diagnostic-scalar axis
1385 /// so both halves of the "how does the Capability arm surface at
1386 /// its two consumer axes (human-readable label, wrong-target
1387 /// diagnostic)" pipeline route through peer consts declared next
1388 /// to the variant.
1389 ///
1390 /// Pairwise-distinctness against the three payload-arm scalars
1391 /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1392 /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1393 /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1394 /// test — the 4-way closure of the 3-way
1395 /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1396 /// the `ContratoWrongTarget::expected` axis, matching the peer
1397 /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1398 /// scalar-value distinctness discipline the sibling M3 typed-enum
1399 /// discriminator axis already carries.
1400 pub const CAPABILITY_EXPECTED: &'static str = "none";
1401
1402 /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1403 /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1404 /// as under [`Self::graph_label`] — the sibling
1405 /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1406 /// payload-column axis (the graph verb spells payload-less as
1407 /// `(capability-only)`, distinct from the duplicate-`:contratos`
1408 /// diagnostic's `(capability — no payload)` on the human-readable
1409 /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1410 /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1411 /// family — extends the "one canonical declaration per arm, next to
1412 /// the variant, so a future rename lands in one place" discipline
1413 /// onto the third payload-less-arm consumer axis (`feira app graph`
1414 /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1415 /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1416 /// axis).
1417 ///
1418 /// Until this lift landed the byte-string sat inline in
1419 /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1420 /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1421 /// `"(capability-only)".to_string()` literal, with no compile-time link
1422 /// back to the [`WitTarget::Capability`] variant declaration nor to
1423 /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1424 /// peer consts already carrying the "one canonical declaration per
1425 /// payload-less-arm consumer axis" discipline. A rebrand on either
1426 /// side (the graph verb's operator-facing vocabulary tightening from
1427 /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1428 /// the WIT registry vocabulary sharpens, an M4 split of
1429 /// [`Self::Capability`] into per-shape peers) would silently
1430 /// desynchronize the graph-verb byte-string from the paired
1431 /// per-arm-adjacent const and land two spellings of the same axis in
1432 /// two spots.
1433 pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1434
1435 /// The `(author-facing field name, payload)` pair this typed target
1436 /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1437 /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1438 /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1439 /// [`Self::Store`], `None` for the payload-less
1440 /// [`Self::Capability`] arm.
1441 ///
1442 /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1443 /// (formats `":{field} {payload:?}"` on `Some`, falls to
1444 /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1445 /// (returns the first component) route through, so a future
1446 /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1447 /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1448 /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1449 /// exactly one new match-arm here (a compile-time exhaustiveness
1450 /// error otherwise), not a coordinated three-way rewrite of the
1451 /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1452 /// + every downstream consumer that reaches for the pair.
1453 ///
1454 /// Until this lift landed the three payload arms sat in
1455 /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1456 /// invocations (one per variant, each hand-quoting the paired
1457 /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1458 /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1459 /// "same shape, written N times" duplication THEORY.md §I.3.5
1460 /// ("Generation first, composition second, hand-authoring last;
1461 /// the duplication budget is zero") promotes to a build-time
1462 /// concern, with each per-arm site paired to its own const with no
1463 /// compile-time link between the format template and the arm's
1464 /// payload extraction.
1465 #[must_use]
1466 pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1467 match *self {
1468 WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1469 WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1470 WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1471 WitTarget::Capability => None,
1472 }
1473 }
1474
1475 /// The canonical author-facing `:contratos` payload field name
1476 /// this typed target arm carries (`Http` → `Some("endpoint")`,
1477 /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1478 /// `None` for the payload-less `Capability` arm.
1479 ///
1480 /// Routes through [`Self::payload_pair`] — the single 4-arm
1481 /// dispatch [`Self::label`] also reads — so a future variant
1482 /// addition is one match-arm edit at [`Self::payload_pair`], not a
1483 /// per-consumer rewrite. Same "exhaustive-match at one canonical
1484 /// dispatch, thin projections at each consumer" trajectory the
1485 /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1486 /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1487 #[must_use]
1488 pub const fn field_name(&self) -> Option<&'static str> {
1489 match self.payload_pair() {
1490 Some((f, _)) => Some(f),
1491 None => None,
1492 }
1493 }
1494
1495 /// The underlying scalar the payload-carrying arm carries — the
1496 /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1497 /// subject ([`Self::PubSub`] `:subject`), or slot template
1498 /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1499 /// `&'a str` storage — or `None` on the payload-less
1500 /// [`Self::Capability`] arm.
1501 ///
1502 /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1503 /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1504 /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1505 /// the paired sub-selector axis. Both per-half accessors read from
1506 /// one authoritative match, so a future [`WitTarget`] variant
1507 /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1508 /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1509 /// on [`Self::payload_pair`] and both per-half projections + every
1510 /// downstream consumer picks the new arm up by construction — no
1511 /// coordinated N-way rewrite across the paired accessor dispatches,
1512 /// the [`Self::label`] / [`Self::graph_label`] format templates,
1513 /// and every future WIT-registry-shaped consumer.
1514 ///
1515 /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
1516 /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
1517 /// controller `spec.ref.<field>` axis — same "one paired dispatch,
1518 /// both per-half projections as thin readers, every downstream
1519 /// consumer through the same match" discipline extended onto the
1520 /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
1521 /// gap between the two paired-dispatch surfaces: the peer
1522 /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
1523 /// the first-component projection until this lift; the second-
1524 /// component sibling now sits alongside so both halves reach every
1525 /// future consumer through the same substrate-primitive dispatch.
1526 ///
1527 /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
1528 #[must_use]
1529 pub const fn payload(&self) -> Option<&'a str> {
1530 match self.payload_pair() {
1531 Some((_, p)) => Some(p),
1532 None => None,
1533 }
1534 }
1535
1536 /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
1537 /// consumer that fans on the L7-HTTP-shaped payload keys off —
1538 /// returns the [`Self::Http`]-arm's author-declared request path
1539 /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
1540 /// projected target is [`Self::Http { endpoint }`], `None` on the
1541 /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
1542 /// [`Self::Capability`], each of which carries no HTTP endpoint by
1543 /// definition).
1544 ///
1545 /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
1546 /// `path:` rule payload every substrate-side L7-introspecting
1547 /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
1548 /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
1549 /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
1550 /// on the L7 introspection branch; every peer WIT shape stays
1551 /// L4-only because Cilium can't introspect NATS / key-value / plain
1552 /// capability edges), and every future L7-introspecting consumer
1553 /// of the projected target's HTTP endpoint (the future M4
1554 /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
1555 /// materializer's per-edge L7 admission-webhook overlay, the
1556 /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
1557 /// path bucket-key resolver, the future per-`:contratos`-edge
1558 /// mTLS-required overlay's HTTP-shape scope filter, the future
1559 /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
1560 /// through the same typed dispatch.
1561 ///
1562 /// Prior to this lift the sole production consumer of the projected-
1563 /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
1564 /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
1565 /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
1566 /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
1567 /// }`) — reached the payload through a raw per-arm `if let` pattern-
1568 /// match that expressed no compile-time link back to the substrate
1569 /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
1570 /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
1571 /// scalar accessor on the peer per-`:contratos` raw-field axis but
1572 /// with no post-projection peer on the typed-view surface. A future
1573 /// [`WitTarget`] variant addition that splits [`Self::Http`] into
1574 /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
1575 /// gRPC-shaped worlds per this enum's own docstring at
1576 /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
1577 /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
1578 /// would have had to be threaded through the caixa-mesh L7 emit
1579 /// branch's raw `if let` in lockstep — either coalescing the two
1580 /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
1581 /// emit path per-arm — with no substrate-primitive dispatch making
1582 /// the "which arms count as L7-HTTP-shaped for path-emission
1583 /// purposes" question the substrate's answer to give. Lifting the
1584 /// resolution to a typed method on the substrate primitive means
1585 /// every downstream L7-HTTP-facing consumer of the Aplicacao's
1586 /// projected-target HTTP endpoint reaches for exactly one typed
1587 /// dispatch — the resolver's accept-set migrates as a unit on any
1588 /// future arm-family widening, and the caixa-mesh L7 emit branch
1589 /// reads through the same substrate primitive.
1590 ///
1591 /// Peer of the sibling pre-projection [`WitContract::endpoint`]
1592 /// (7020470) `Option<&str>` scalar accessor on the raw
1593 /// `:contratos :endpoint` field-access axis — same "one typed
1594 /// dispatch on the substrate primitive, thin projections at each
1595 /// consumer" discipline extended onto the peer post-projection typed-
1596 /// view surface (the [`WitContract::endpoint`] pre-projection
1597 /// accessor returns `Some` for any author-declared `:endpoint`
1598 /// value regardless of the paired `:wit` world's HTTP-shape
1599 /// classification — the raw slot before validation crosses it —
1600 /// while this post-projection [`Self::http_endpoint`] accessor
1601 /// returns `Some` iff the target has been projected onto the
1602 /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
1603 /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
1604 /// coherence; the two accessors close the pre-projection /
1605 /// post-projection pair on the HTTP-endpoint axis). Sibling of the
1606 /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
1607 /// the three payload-carrying arms) — extends the per-arm
1608 /// projection family onto the [`Self::Http`] specialization axis
1609 /// that the pan-arm accessor's shape blends into a single arm-
1610 /// agnostic view; paired with [`Self::pubsub_subject`] /
1611 /// [`Self::store_slot`] on the sibling per-arm axes so every
1612 /// per-payload-arm shape carries a named post-projection accessor
1613 /// on the same shape as `http_endpoint`, closing the per-arm-shape
1614 /// accept-set the substrate primitive owns.
1615 #[must_use]
1616 pub const fn http_endpoint(&self) -> Option<&'a str> {
1617 match *self {
1618 WitTarget::Http { endpoint } => Some(endpoint),
1619 WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1620 }
1621 }
1622
1623 /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
1624 /// consumer that fans on the pub-sub-shaped payload keys off —
1625 /// returns the [`Self::PubSub`]-arm's author-declared event-stream
1626 /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
1627 /// the projected target is [`Self::PubSub { subject }`], `None` on
1628 /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
1629 /// [`Self::Capability`], each of which carries no NATS-shaped
1630 /// subject by definition).
1631 ///
1632 /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
1633 /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
1634 /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
1635 /// CR materializer's `spec.subjects[]` projection, the future
1636 /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
1637 /// bucket-key resolver, the future `feira app graph --pubsub`
1638 /// per-Aplicacao subject column, any future substrate-lifted
1639 /// pub-sub-shape emitter that reads a projected `WitTarget` in the
1640 /// same shape [`caixa_mesh::cilium_network_policies`] reads the
1641 /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
1642 /// future pub-sub-shape consumer reaches for the same typed
1643 /// dispatch this accessor exposes so the "which arm carries the
1644 /// subject scalar?" answer lives at one caixa-core edit rather
1645 /// than open-coded across per-consumer `if let WitTarget::PubSub
1646 /// { subject } = c.target()…` pattern-matches.
1647 ///
1648 /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
1649 /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
1650 /// the pre-projection [`WitContract::subject`] scalar accessor on
1651 /// the raw `:contratos :subject` field-access axis — same "one
1652 /// typed dispatch on the substrate primitive, thin projections at
1653 /// each consumer" discipline extended onto the per-arm pub-sub
1654 /// post-projection axis. The pre-projection accessor returns
1655 /// `Some` for any author-declared `:subject` value regardless of
1656 /// the paired `:wit` world's pub-sub-shape classification (the raw
1657 /// slot before validation crosses it); this post-projection
1658 /// accessor returns `Some` iff the target has been projected onto
1659 /// the [`Self::PubSub`] arm, i.e. only after the
1660 /// [`WitContract::target`] gate has admitted the
1661 /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
1662 /// the pre-/post-projection pair on the pub-sub-subject axis to
1663 /// match the pair the [`WitContract::endpoint`] +
1664 /// [`Self::http_endpoint`] surfaces already close on the peer
1665 /// HTTP-endpoint axis.
1666 ///
1667 /// Sibling of the unified pan-arm [`Self::payload`]
1668 /// (`Option<&'a str>` for any of the three payload-carrying arms) —
1669 /// extends the per-arm projection family onto the [`Self::PubSub`]
1670 /// specialization axis that the pan-arm accessor's shape blends
1671 /// into a single arm-agnostic view; the pair
1672 /// (`pubsub_subject`, `store_slot`) closes the trio
1673 /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
1674 /// payload arm now carries its own per-arm-shape post-projection
1675 /// accessor.
1676 #[must_use]
1677 pub const fn pubsub_subject(&self) -> Option<&'a str> {
1678 match *self {
1679 WitTarget::PubSub { subject } => Some(subject),
1680 WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1681 }
1682 }
1683
1684 /// Substrate-canonical per-arm key/value-store-slot scalar accessor
1685 /// every consumer that fans on the store-shaped payload keys off —
1686 /// returns the [`Self::Store`]-arm's author-declared slot template
1687 /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
1688 /// projected target is [`Self::Store { slot }`], `None` on the
1689 /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
1690 /// [`Self::Capability`], each of which carries no
1691 /// key/value-store slot by definition).
1692 ///
1693 /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
1694 /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
1695 /// every future substrate-side store-introspecting per-`(:de,
1696 /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
1697 /// namespace / prefix reconciler's per-slot projection, the future
1698 /// per-store-backend routing overlay's slot-shape gate, the future
1699 /// `feira app graph --store` per-Aplicacao slot column, any future
1700 /// substrate-lifted store-shape emitter that reads a projected
1701 /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
1702 /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
1703 /// Every future store-shape consumer reaches for the same typed
1704 /// dispatch this accessor exposes so the "which arm carries the
1705 /// slot scalar?" answer lives at one caixa-core edit rather than
1706 /// open-coded across per-consumer
1707 /// `if let WitTarget::Store { slot } = c.target()…`
1708 /// pattern-matches.
1709 ///
1710 /// Peer of the sibling [`Self::http_endpoint`] +
1711 /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
1712 /// axes and of the pre-projection [`WitContract::slot`] scalar
1713 /// accessor on the raw `:contratos :slot` field-access axis — same
1714 /// "one typed dispatch on the substrate primitive, thin projections
1715 /// at each consumer" discipline extended onto the per-arm store
1716 /// post-projection axis. Closes the pre-/post-projection pair on
1717 /// the store-slot axis to match the pairs the
1718 /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
1719 /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
1720 /// already close on the peer HTTP-endpoint and pub-sub-subject
1721 /// axes; the substrate-side pre-/post-projection accessor family
1722 /// now spans all three payload arms as a matched trio, so any
1723 /// future arm-shape widening (a `Rest`/`Grpc` split of
1724 /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
1725 /// lands one accessor without threading through the sibling
1726 /// pre-projection or the peer per-arm post-projection surfaces a
1727 /// compile-time exhaustiveness error at the substrate primitive,
1728 /// not a silent per-consumer split at renderer emit time.
1729 ///
1730 /// Sibling of the unified pan-arm [`Self::payload`]
1731 /// (`Option<&'a str>` for any of the three payload-carrying arms) —
1732 /// closes the per-arm projection family onto the [`Self::Store`]
1733 /// specialization axis that the pan-arm accessor's shape blends
1734 /// into a single arm-agnostic view. The trio
1735 /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
1736 /// pan-arm accept-set on every payload-carrying arm: exactly one
1737 /// per-arm accessor returns `Some(payload)` and the two peers
1738 /// return `None`, and every payload-less [`Self::Capability`]
1739 /// input returns `None` on all three — the partition the sibling
1740 /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
1741 /// pin locks in load-bearing.
1742 #[must_use]
1743 pub const fn store_slot(&self) -> Option<&'a str> {
1744 match *self {
1745 WitTarget::Store { slot } => Some(slot),
1746 WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
1747 }
1748 }
1749
1750 /// Render this typed target as a stable human-readable label
1751 /// (`:endpoint "/charge"`, `:subject "events.x"`,
1752 /// `:slot "checkout/$order"`, or `(capability — no payload)` when
1753 /// the WIT world is a pure capability edge).
1754 ///
1755 /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
1756 /// gate so the diagnostic names *which* identical edge was
1757 /// declared twice (not just which `(de, para, wit)` triple).
1758 /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1759 /// on the payload-carrying arms (`Some((field, payload)) →
1760 /// format!(":{field} {payload:?}")`) and through the lifted
1761 /// [`Self::CAPABILITY_LABEL`] const on the payload-less
1762 /// [`Self::Capability`] arm — so a future variant addition (the
1763 /// M4-and-later per-edge WIT registry may split [`Self::Http`]
1764 /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1765 /// `Queue`-shaped peer) becomes a single new match-arm on
1766 /// [`Self::payload_pair`] rather than a rewrite of this template
1767 /// (and every downstream consumer that reaches for the label
1768 /// shape: the per-edge policy resolver in M4, the `feira app
1769 /// graph` view, the operator's mesh-graph audit). Until this
1770 /// lift landed the three payload arms carried three near-identical
1771 /// per-arm `format!(":{} {…:?}", …)` invocations, and the
1772 /// [`Self::Capability`] arm carried the payload-less byte-string
1773 /// twice (once inline here, once in the pin test) — closing the
1774 /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
1775 /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
1776 /// / 4a1e490) peer-const lifts already established for the
1777 /// payload-carrying arms.
1778 #[must_use]
1779 pub fn label(&self) -> String {
1780 match self.payload_pair() {
1781 Some((field, payload)) => format!(":{field} {payload:?}"),
1782 None => Self::CAPABILITY_LABEL.to_string(),
1783 }
1784 }
1785
1786 /// Render this typed target as the `feira app graph` per-`:contratos`
1787 /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
1788 /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
1789 /// payload-less arm).
1790 ///
1791 /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
1792 /// on the payload-carrying arms (`Some((field, payload)) →
1793 /// format!("{field}={payload}")`) and through the lifted
1794 /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
1795 /// [`Self::Capability`] arm — so a future variant addition
1796 /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
1797 /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
1798 /// `Queue`-shaped peer) becomes one match-arm edit at
1799 /// [`Self::payload_pair`], propagating through this graph-verb
1800 /// projection at zero call-site cost, sibling to the peer
1801 /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
1802 /// same 4-arm dispatch.
1803 ///
1804 /// Until this lift landed the [`caixa-feira`]
1805 /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
1806 /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
1807 /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
1808 /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
1809 /// `format!("{}={endpoint}", ...)` template and hard-coding
1810 /// `"(capability-only)"` as a fifth payload-less scalar with no link
1811 /// back to the paired [`WitTarget::Capability`] variant declaration.
1812 /// A future variant addition would have had to be threaded through
1813 /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
1814 /// verb's inline match in lockstep or the two projections would
1815 /// silently disagree on the arm-set the graph verb prints — the
1816 /// duplicate-`:contratos` diagnostic reading one shape while the
1817 /// graph verb's payload column silently dropped the new arm to
1818 /// `(capability-only)`. Lifting the graph-verb projection onto the
1819 /// same substrate-primitive [`Self::payload_pair`] dispatch closes
1820 /// the axis: both projections migrate as a unit.
1821 ///
1822 /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
1823 /// quoting) shape is graph-verb-canonical — distinct from the
1824 /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
1825 /// duplicate-`:contratos` diagnostic seeds (see
1826 /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
1827 /// on the payload-less axis for the paired distinction).
1828 #[must_use]
1829 pub fn graph_label(&self) -> String {
1830 match self.payload_pair() {
1831 Some((field, payload)) => format!("{field}={payload}"),
1832 None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
1833 }
1834 }
1835}
1836
1837/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
1838/// pretty-printed byte-string every consumer that formats a typed
1839/// payload target as user-facing text lands on (the
1840/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
1841/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
1842/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
1843/// graph` per-`:contratos`-edge payload column that reaches the graph
1844/// verb through `format!("{target}")`, the future M4 per-edge policy
1845/// resolver's per-edge audit-log line, the operator's mesh-graph
1846/// per-edge inspection view) reaches for the same lifted
1847/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
1848/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
1849/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
1850/// routes through — extending the three-path-convergence
1851/// (`Debug` for structural inspection, `Display` for user-facing text,
1852/// per-arm typed accessor for the canonical byte-string) discipline the
1853/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
1854/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
1855/// onto the fourth (and only remaining) typed-shape-discriminator axis
1856/// on the caixa surface.
1857///
1858/// Pre-lift the two paths were structurally independent — every consumer
1859/// reaching for a payload byte-string past the [`WitTarget::label`]
1860/// helper had to pick between three paths ([`WitTarget::label`],
1861/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
1862/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
1863/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
1864/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
1865/// that reached for `format!("{target}")` — the canonical shape every
1866/// user-facing pretty-print site on the sibling typed-enum axes already
1867/// uses — would silently land on the `Debug` derive's structural output
1868/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
1869/// than the `label()` helper's stable byte-string (`:endpoint
1870/// "/charge"` — the author-facing `:contratos` keyword form) the
1871/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
1872/// already threads through. The two spellings would diverge silently in
1873/// every downstream diagnostic / graph / audit line reached through
1874/// `format!` rather than through the `label()` helper. Routing
1875/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
1876/// path: every `format!("{v}")` call reaches the same
1877/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
1878/// and the duplicate-`:contratos` gate already route through, so a
1879/// future variant addition (the M4-and-later per-edge WIT registry may
1880/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
1881/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
1882/// consumer at exactly one place — the [`WitTarget::payload_pair`]
1883/// match — rather than fanning out through hand-rolled per-arm
1884/// [`std::fmt::Display`] arms.
1885///
1886/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
1887/// is the typed view returned by [`WitContract::target`], not a
1888/// closed-set discriminator enum with a gen-platform Discriminant
1889/// registration, so the `Debug` derive's structural output (which every
1890/// `{v:?}` consumer still reaches) stays distinct from the `Display`
1891/// helper's stable pretty-printed byte-string. `Debug` reveals variant
1892/// shape for structural inspection; `Display` (via `label`) reveals the
1893/// stable author-facing payload projection.
1894///
1895/// Pin tests
1896/// [`tests::wit_target_display_routes_through_label_helper`] and
1897/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
1898/// assert the two paths agree byte-for-byte on every variant, so a
1899/// future variant addition or `label()` reimplementation that hand-rolls
1900/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
1901/// build error visible at caixa-core test time, not a silent
1902/// per-consumer dispatch miss at diagnostic / audit / graph time.
1903impl std::fmt::Display for WitTarget<'_> {
1904 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1905 f.write_str(&self.label())
1906 }
1907}
1908
1909// ── one Aplicacao member ─────────────────────────────────────────────
1910
1911/// A Servico participating in the Aplicacao. Same shape as
1912/// `crate::supervisor::ChildSpec` but without a restart policy —
1913/// supervision is per-Servico (each member has its own
1914/// `:supervisor`), the Aplicacao orchestrates *placement*.
1915#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1916#[serde(rename_all = "camelCase")]
1917pub struct Membro {
1918 /// Member caixa's `:nome`. Resolves through the same dep
1919 /// resolution path as `crate::dep::Dep`.
1920 pub caixa: String,
1921
1922 /// Semver constraint.
1923 pub versao: String,
1924}
1925
1926impl Membro {
1927 /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
1928 /// accessor every consumer that reads the member's Servico identity
1929 /// keys off — returns the author-declared `:membros :caixa`
1930 /// byte-string verbatim as a `&str`, borrowed from the typed slot's
1931 /// own [`String`] storage.
1932 ///
1933 /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
1934 /// participating in the Aplicacao — validated by
1935 /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
1936 /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
1937 /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
1938 /// [`validate_no_self_membership`]) — and every downstream consumer
1939 /// that fans on the member's identity keys off this scalar (the
1940 /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
1941 /// lookup, the per-`:membros` duplicate gate's dedup key, the
1942 /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
1943 /// identity, the self-membership gate, the
1944 /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
1945 /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
1946 /// CR materializer's per-member resolver).
1947 ///
1948 /// Prior to this lift the `.caixa` byte-string was read inline at
1949 /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
1950 /// set collector at
1951 /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
1952 /// [`validate_membros`] validation-side member-caixa gate at
1953 /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
1954 /// per-member duplicate-gate dedup key at
1955 /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
1956 /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
1957 /// `adj.entry(m.caixa.as_str()).or_default()`, and the
1958 /// [`validate_no_self_membership`] self-loop gate at
1959 /// `m.caixa == parent_nome`) — five open-coded field-accesses that
1960 /// expressed no compile-time link back to the typed slot. Every
1961 /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
1962 /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
1963 /// `name:` axis, so a future extension of the `:membros :caixa`
1964 /// axis to a richer author surface — a per-cluster alias table the
1965 /// operator pins through a future `:placement`-scoped slot, a
1966 /// namespace-qualified rewrite the M4 CR materializer applies
1967 /// per-CR, a per-member overlay from the future `:membros
1968 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1969 /// acknowledges — would have had to be threaded through every
1970 /// open-coded copy in lockstep or one consumer would silently
1971 /// disagree with the peers on which caixa a given member resolves
1972 /// to. A member-set lookup that treated the name as `"cart"` while
1973 /// the peer adjacency map treated it as `"tenant-a/cart"` would
1974 /// silently split the `:contratos` membership-lookup diagnostic from
1975 /// the cycle-detector's node identity — a two-consumer split at the
1976 /// validator far from the source `caixa.lisp` with no field naming
1977 /// the identity-drift root cause. Lifting the resolution rule to a
1978 /// typed method on the substrate primitive means every downstream
1979 /// consumer of the Aplicacao's per-`:membros` identity surface
1980 /// reaches for exactly one typed dispatch — the resolver's
1981 /// accept-set migrates as a unit on any future axis addition.
1982 ///
1983 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
1984 /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
1985 /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
1986 /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
1987 /// destination-Servico scalar accessors — same "one typed dispatch
1988 /// on the substrate primitive, thin projections at each consumer"
1989 /// discipline extended onto the per-`:membros` member-caixa `:nome`
1990 /// byte-string axis. Named `nome()` to match the tatara-lisp
1991 /// author-surface term the field's docstring already reaches for
1992 /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
1993 /// [`crate::dep::Dep::nome`] field-name discipline the substrate
1994 /// already carries — the accessor's name maps directly onto the
1995 /// canonical caixa-identity vocabulary rather than shadowing the
1996 /// field's storage-side `caixa` label.
1997 #[must_use]
1998 pub fn nome(&self) -> &str {
1999 self.caixa.as_str()
2000 }
2001
2002 /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2003 /// requirement scalar accessor every consumer that reads the
2004 /// member's version pin keys off — returns the author-declared
2005 /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2006 /// from the typed slot's own [`String`] storage.
2007 ///
2008 /// The `:membros :versao` slot carries the Cargo-shaped semver
2009 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2010 /// pins which release of the member-caixa the Aplicacao composes
2011 /// against — the same requirement grammar the peer `:deps :versao`
2012 /// / `:children :versao` axes carry, resolved through the shared
2013 /// [`crate::render::require_valid_versao_requirement`] cascade and
2014 /// the shared [`crate::version::parse_requirement`] parser. Every
2015 /// downstream consumer that fans on the member's version pin keys
2016 /// off this scalar (the [`validate_membros`] per-member requirement
2017 /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2018 /// …)`, the [`feira app graph`] per-member `println!(" - {} {}",
2019 /// m.nome(), m.versao_requirement())` line, every future per-cluster
2020 /// version-lock overlay the operator pins through a future
2021 /// `:placement`-scoped slot, the future
2022 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2023 /// version resolver, the future `feira app deploy` pipeline's
2024 /// per-member lacre BLAKE3-closure lookup).
2025 ///
2026 /// Prior to this lift the `.versao` byte-string was accessed inline
2027 /// at two `&str`-shaped sites — the [`validate_membros`]
2028 /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2029 /// …)` and the `feira app graph` per-member printer's `println!(
2030 /// " - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2031 /// prior to this lift) — two open-coded field-accesses that expressed
2032 /// no compile-time link back to the typed slot. A future extension of
2033 /// the `:membros :versao` axis to a richer author surface (a
2034 /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2035 /// flow, a lacre-projected concrete-version rewrite the operator
2036 /// materializes at CR-admission time, a future `:membros :versao-lock`
2037 /// per-cluster override slot) would have had to be threaded through
2038 /// every open-coded copy in lockstep or one consumer would silently
2039 /// disagree with the peers on which release constraint a given
2040 /// member resolves to. Lifting the resolution rule to a typed method
2041 /// on the substrate primitive means every downstream requirement-
2042 /// facing consumer reaches for exactly one typed dispatch — the
2043 /// resolver's accept-set migrates as a unit on any future axis
2044 /// addition.
2045 ///
2046 /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2047 /// member-caixa `:nome` scalar accessor — the pair
2048 /// `(nome(), versao_requirement())` jointly projects the
2049 /// `(caixa, versao)` field pair every renderer that fans on
2050 /// per-member identity + version pin keys off, closing the last
2051 /// unlifted per-`:membros` scalar axis so every downstream
2052 /// per-`:membros` reader now routes through a typed dispatch on the
2053 /// substrate primitive. Named `versao_requirement()` rather than
2054 /// `versao()` because the field's storage-side `.versao` label is
2055 /// already the author-surface term (`:versao`); the accessor's name
2056 /// carries the semantic role — the semver *requirement* string the
2057 /// shared [`crate::version::parse_requirement`] entry-point consumes
2058 /// — so a raw field access and a typed dispatch read differently at
2059 /// every consumer site.
2060 ///
2061 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2062 /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2063 /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2064 /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2065 /// destination-Servico scalar accessors — same "one typed dispatch
2066 /// on the substrate primitive, thin projections at each consumer"
2067 /// discipline extended onto the per-`:membros` member-`:versao`
2068 /// semver-requirement byte-string axis.
2069 #[must_use]
2070 pub fn versao_requirement(&self) -> &str {
2071 self.versao.as_str()
2072 }
2073}
2074
2075// ── mesh-level policies ──────────────────────────────────────────────
2076
2077/// Mesh policies that apply to every `:contratos` edge unless
2078/// overridden per-edge in M4. V0 is a single global policy block.
2079#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2080#[serde(rename_all = "camelCase")]
2081pub struct MeshPolicy {
2082 /// Per-call timeout. Authored as a duration string (`"30s"`).
2083 #[serde(
2084 default,
2085 skip_serializing_if = "Option::is_none",
2086 with = "supervisor::duration_codec"
2087 )]
2088 pub timeout: Option<Duration>,
2089
2090 /// Number of retries on transient failure. None = no retries.
2091 #[serde(default, skip_serializing_if = "Option::is_none")]
2092 pub retries: Option<u32>,
2093
2094 /// Circuit breaker config. Trips after N failures within W
2095 /// duration; closes after a cooldown.
2096 #[serde(default, skip_serializing_if = "Option::is_none")]
2097 pub circuit_breaker: Option<CircuitBreaker>,
2098
2099 /// Whether mTLS is required for every contrato. Default: true
2100 /// (sandboxing-by-default; explicit opt-out only).
2101 #[serde(default, skip_serializing_if = "Option::is_none")]
2102 pub mtls_required: Option<bool>,
2103
2104 /// Token-bucket rate limit. Authored as `"100/s"` or
2105 /// `"5000/m"`; stored as `(rate, window)`.
2106 #[serde(
2107 default,
2108 skip_serializing_if = "Option::is_none",
2109 with = "rate_limit_codec"
2110 )]
2111 pub rate_limit: Option<RateLimit>,
2112}
2113
2114impl MeshPolicy {
2115 /// True when no `:politicas` axis carries a value — every field is
2116 /// `None`. The same emptiness contract every other M2/M3 typed
2117 /// surface carries ([`crate::LimitsSpec::is_empty`],
2118 /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2119 /// typed slot onto a cluster artifact key off this predicate to
2120 /// decide "emit the slot" vs "skip the slot entirely", so an
2121 /// authored-but-unset `:politicas (())` round-trips to a rendered
2122 /// artifact that's structurally identical to one that omits the
2123 /// slot. Lifted as a typed predicate (rather than per-renderer
2124 /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2125 /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2126 /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2127 /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2128 /// not a coordinated rewrite of every consumer that's reaching
2129 /// for the emptiness semantic.
2130 #[must_use]
2131 pub const fn is_empty(&self) -> bool {
2132 self.timeout().is_none()
2133 && self.retries().is_none()
2134 && self.circuit_breaker().is_none()
2135 && self.mtls_required().is_none()
2136 && self.rate_limit().is_none()
2137 }
2138
2139 /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
2140 /// per-call-deadline scalar accessor every consumer of the
2141 /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
2142 /// returns the author-declared `:politicas :timeout` typed
2143 /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
2144 /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
2145 /// is `Copy`, so the accessor returns by value; no borrow of
2146 /// `&self` past the call). `None` when the slot is absent (the
2147 /// "cluster default applies — typically the gateway class's
2148 /// implementation-side per-request wall-clock cap" arm caixa-mesh's
2149 /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
2150 /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
2151 /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
2152 /// round-trips to a rendered `HTTPRoute` structurally identical to
2153 /// one that omits the slot).
2154 ///
2155 /// The `:politicas :timeout` slot carries the "no infinite blocking"
2156 /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
2157 /// the typed slot's `Option<Duration>` accept-set (zero-floor
2158 /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
2159 /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
2160 /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
2161 /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
2162 /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
2163 /// Every downstream consumer that reads the per-call cap keys off
2164 /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2165 /// renderers key off to decide "emit :politicas overlay" vs "skip
2166 /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2167 /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
2168 /// fans the deadline into every rule via
2169 /// [`crate::render::single_field_overlay`], the future M4 per-
2170 /// Aplicacao Gateway API reconciler materialization pass, the
2171 /// future per-`:contratos`-edge timeout-override overlay the
2172 /// MESH-COMPOSITION §III.2 roadmap acknowledges).
2173 ///
2174 /// Prior to this lift the `.timeout` field was accessed inline at
2175 /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
2176 /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
2177 /// …)` call — two open-coded field-accesses that expressed no
2178 /// compile-time link back to the typed slot. A future extension of
2179 /// the `:politicas :timeout` axis to a richer author surface — a
2180 /// per-`:contratos`-edge timeout override the operator pins through
2181 /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
2182 /// roadmap acknowledges, a per-cluster timeout-default overlay the
2183 /// M4 CR materializer resolves per-CR, a split of the single
2184 /// per-call `Duration` into a richer `{request, backendRequest}`
2185 /// pair once the Gateway API's per-rule `timeouts` block grows the
2186 /// upstream-facing backendRequest arm alongside the client-facing
2187 /// request arm — would have had to be threaded through both open-
2188 /// coded copies in lockstep or the emptiness predicate and the
2189 /// caixa-mesh emit path would silently disagree on which per-call
2190 /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
2191 /// whose only axis is a `Some :timeout` would satisfy `is_empty()
2192 /// == false` while the renderer's overlay-emit path silently read
2193 /// a drifted other value, or vice versa: an author's `:timeout
2194 /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
2195 /// the emptiness predicate still classified the policy as non-
2196 /// empty, and every `kubectl -n tatara-system get httproute -o yaml
2197 /// | grep -A2 timeouts` audit would land on a route whose author's
2198 /// typed slot value silently vanished at the renderer layer).
2199 /// Lifting the resolution to a typed method on the substrate
2200 /// primitive means every downstream consumer of the Aplicacao's
2201 /// per-`:politicas` deadline surface reaches for exactly one typed
2202 /// dispatch — the resolver's accept-set migrates as a unit on any
2203 /// future axis addition.
2204 ///
2205 /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
2206 /// family (sibling of the peer per-`:politicas`
2207 /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
2208 /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
2209 /// `Option<bool>` accessor — same "one typed dispatch on the
2210 /// substrate primitive, thin projections at each consumer"
2211 /// discipline extended onto the peer per-`:politicas` typed-
2212 /// [`Duration`] optional-scalar axis; closes the "optional per-slot
2213 /// numeric-Copy-T scalar" projection pattern the sibling
2214 /// `Option<u32>` / `Option<bool>` lifts opened, since every
2215 /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
2216 /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
2217 /// than a scalar). Named `timeout()` to match the storage field's
2218 /// name; the accessor's identity maps onto the canonical MESH-
2219 /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
2220 #[must_use]
2221 pub const fn timeout(&self) -> Option<Duration> {
2222 self.timeout
2223 }
2224
2225 /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
2226 /// retry-budget scalar accessor every consumer of the Aplicacao's
2227 /// Gateway API v1.x per-rule retry-cap keys off — returns the
2228 /// author-declared `:politicas :retries` typed `u32` verbatim as an
2229 /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
2230 /// storage (`Option<u32>` is `Copy`, so the accessor returns by
2231 /// value; no borrow of `&self` past the call). `None` when the slot
2232 /// is absent (the "cluster default applies — typically 'no retries
2233 /// beyond a single dispatch attempt'" arm the caixa-mesh
2234 /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2235 /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2236 /// this predicate too, so an authored-but-unset `:politicas
2237 /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2238 /// identical to one that omits the slot).
2239 ///
2240 /// The `:politicas :retries` slot carries the "transient failure
2241 /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2242 /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2243 /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2244 /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2245 /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2246 /// count scalar the caixa-mesh `retry_overlay` builder writes.
2247 /// Every downstream consumer that reads the retry cap keys off this
2248 /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2249 /// renderers key off to decide "emit :politicas overlay" vs "skip
2250 /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2251 /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2252 /// the value into every rule via [`crate::render::single_field_overlay`],
2253 /// the future M4 per-Aplicacao Gateway API reconciler
2254 /// materialization pass, the future per-`:contratos`-edge retry-
2255 /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2256 /// acknowledges).
2257 ///
2258 /// Prior to this lift the `.retries` field was accessed inline at
2259 /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2260 /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2261 /// …)` call — two open-coded field-accesses that expressed no
2262 /// compile-time link back to the typed slot. A future extension of
2263 /// the `:politicas :retries` axis to a richer author surface — a
2264 /// per-`:contratos`-edge retry override the operator pins through a
2265 /// future `:contratos :retries` slot, a per-cluster retry-default
2266 /// overlay the M4 CR materializer resolves per-CR, a promotion of
2267 /// the plain `u32` attempt-count to a richer `{attempts, codes,
2268 /// backoff}` sub-block once the Gateway API grows the peer
2269 /// `retry.codes` / `retry.backoff` axes — would have had to be
2270 /// threaded through both open-coded copies in lockstep or the
2271 /// emptiness predicate and the caixa-mesh emit path would silently
2272 /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2273 /// (a `:politicas` block whose only axis is a `Some :retries` would
2274 /// satisfy `is_empty() == false` while the renderer's overlay-emit
2275 /// path silently read a drifted other value, or vice versa: an
2276 /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2277 /// block while the emptiness predicate still classified the policy
2278 /// as non-empty). Lifting the resolution to a typed method on the
2279 /// substrate primitive means every downstream consumer of the
2280 /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2281 /// one typed dispatch — the resolver's accept-set migrates as a
2282 /// unit on any future axis addition.
2283 ///
2284 /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2285 /// family (sibling of the peer per-`:politicas`
2286 /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2287 /// same "one typed dispatch on the substrate primitive, thin
2288 /// projections at each consumer" discipline extended onto the
2289 /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2290 /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2291 /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2292 /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2293 /// fold on). Named `retries()` to match the storage field's name;
2294 /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2295 /// §III.2 vocabulary the slot's docstring already carries.
2296 #[must_use]
2297 pub const fn retries(&self) -> Option<u32> {
2298 self.retries
2299 }
2300
2301 /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2302 /// enforcement-toggle scalar accessor every consumer of the
2303 /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2304 /// — returns the author-declared `:politicas :mtls-required` typed
2305 /// bool verbatim as an `Option<bool>`, copied out of the typed
2306 /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2307 /// the accessor returns by value; no borrow of `&self` past the
2308 /// call). `None` when the slot is absent (the "cluster default
2309 /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2310 /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2311 /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2312 /// this predicate too, so an authored-but-unset `:politicas
2313 /// (:mtls-required ())` round-trips to a rendered
2314 /// `CiliumNetworkPolicy` structurally identical to one that omits
2315 /// the slot).
2316 ///
2317 /// The `:politicas :mtls-required` slot carries the "explicit opt-
2318 /// out only, sandboxing-by-default" mTLS-enforcement toggle
2319 /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2320 /// `{None, Some(true), Some(false)}` accept-set maps onto the
2321 /// Cilium `authentication.mode` bijection through
2322 /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2323 /// handshake enforced), `Some(false) → "disabled"` (handshake
2324 /// skipped — the debug-edge opt-out), `None` → omit the block
2325 /// (cluster default applies). Every downstream consumer that
2326 /// reads the toggle keys off this scalar (the
2327 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2328 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2329 /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2330 /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2331 /// ingress rule via [`crate::render::single_field_overlay`], the
2332 /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2333 /// materialization pass, the future per-`:contratos`-edge mTLS
2334 /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2335 ///
2336 /// Prior to this lift the `.mtls_required` field was accessed
2337 /// inline at two sites — [`MeshPolicy::is_empty`]'s
2338 /// `self.mtls_required.is_none()` arm and caixa-mesh's
2339 /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2340 /// two open-coded field-accesses that expressed no compile-time
2341 /// link back to the typed slot. A future extension of the
2342 /// `:politicas :mtls-required` axis to a richer author surface —
2343 /// a per-`:contratos`-edge mTLS override the operator pins through
2344 /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2345 /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2346 /// M4 CR materializer resolves per-CR, a three-valued
2347 /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2348 /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2349 /// would have had to be threaded through both open-coded copies in
2350 /// lockstep or the emptiness predicate and the caixa-mesh emit
2351 /// path would silently disagree on which toggle a given
2352 /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2353 /// axis is a `Some`
2354 /// `:mtls-required` would satisfy `is_empty() == false` while the
2355 /// renderer's overlay-emit path silently read a drifted other
2356 /// value, or vice versa). Lifting the resolution to a typed method
2357 /// on the substrate primitive means every downstream consumer of
2358 /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2359 /// for exactly one typed dispatch — the resolver's accept-set
2360 /// migrates as a unit on any future axis addition.
2361 ///
2362 /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2363 /// family (peer of the sibling per-`:placement`
2364 /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2365 /// same "one typed dispatch on the substrate primitive, thin
2366 /// projections at each consumer" discipline extended onto the
2367 /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2368 /// the "optional per-slot Copy-T scalar" projection pattern the
2369 /// sibling per-`:politicas` `:retries` (Option<u32>) /
2370 /// `:timeout` (Option<Duration>) future lifts fold on). Named
2371 /// `mtls_required()` to match the storage field's name; the
2372 /// accessor's identity maps onto the canonical MESH-COMPOSITION
2373 /// §III.2 vocabulary the slot's docstring already carries.
2374 #[must_use]
2375 pub const fn mtls_required(&self) -> Option<bool> {
2376 self.mtls_required
2377 }
2378
2379 /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2380 /// `local_rate_limit`-mesh token-bucket-declaration scalar
2381 /// accessor every consumer of the Aplicacao's per-`:politicas`
2382 /// per-`(rate, window)` rate-limit surface keys off — returns the
2383 /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2384 /// verbatim as an `Option<RateLimit>`, copied out of the typed
2385 /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2386 /// `Copy`, so the accessor returns by value; no borrow of `&self`
2387 /// past the call). `None` when the slot is absent (the "cluster
2388 /// default applies — typically 'no per-Aplicacao rate declaration,
2389 /// gateway-class per-listener default applies'" arm the future
2390 /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2391 /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2392 /// `rate_limit().is_none()` arm reads this predicate too, so an
2393 /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2394 /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2395 /// identical to one that omits the slot).
2396 ///
2397 /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2398 /// token-bucket rate declaration" contract (MESH-COMPOSITION
2399 /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2400 /// (rate lower-bounded by 1 through
2401 /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2402 /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2403 /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2404 /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2405 /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2406 /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2407 /// `:politicas` overlay emits. Every downstream consumer that
2408 /// reads the rate declaration keys off this scalar (the
2409 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2410 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2411 /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2412 /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2413 /// `rl.window` against [`is_canonical_rate_limit_window`], the
2414 /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2415 /// the future per-`:contratos`-edge rate-limit override the
2416 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2417 ///
2418 /// Prior to this lift the `.rate_limit` field was accessed inline
2419 /// at two sites — [`MeshPolicy::is_empty`]'s
2420 /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2421 /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2422 /// field-accesses that expressed no compile-time link back to the
2423 /// typed slot. A future extension of the `:politicas :rate-limit`
2424 /// axis to a richer author surface — a per-`:contratos`-edge
2425 /// rate-limit override the operator pins through a future
2426 /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2427 /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2428 /// the M4 CR materializer resolves per-CR, a promotion of the
2429 /// plain `(rate, window)` scalar pair to a richer
2430 /// `{rate, window, burst, key}` sub-block once Envoy's
2431 /// `local_rate_limit` grows the peer `burst_size` /
2432 /// `descriptor_key` axes — would have had to be threaded through
2433 /// both open-coded copies in lockstep or the emptiness predicate
2434 /// and the validate gate would silently disagree on which rate
2435 /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2436 /// block whose only axis is a `Some :rate-limit` would satisfy
2437 /// `is_empty() == false` while the validate path silently read a
2438 /// drifted other value, or vice versa: an author's
2439 /// `:rate-limit "100/s"` would omit the value-shape gate while the
2440 /// emptiness predicate still classified the policy as non-empty).
2441 /// Lifting the resolution to a typed method on the substrate
2442 /// primitive means every downstream consumer of the Aplicacao's
2443 /// per-`:politicas` rate-limit surface reaches for exactly one
2444 /// typed dispatch — the resolver's accept-set migrates as a unit
2445 /// on any future axis addition.
2446 ///
2447 /// First `Option<Copy-composite-T>`-return accessor on the M3
2448 /// mesh-slot family — closes the last un-lifted per-`:politicas`
2449 /// scalar-value axis. Peer of the sibling per-`:politicas`
2450 /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2451 /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2452 /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2453 /// "one typed dispatch on the substrate primitive, thin
2454 /// projections at each consumer" discipline extended onto the
2455 /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2456 /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2457 /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2458 /// sub-accessors rather than a top-level accessor because
2459 /// consumers reach for the axes not the aggregate). Named
2460 /// `rate_limit()` to match the storage field's name; the
2461 /// accessor's identity maps onto the canonical MESH-COMPOSITION
2462 /// §III.2 vocabulary the slot's docstring already carries.
2463 #[must_use]
2464 pub const fn rate_limit(&self) -> Option<RateLimit> {
2465 self.rate_limit
2466 }
2467
2468 /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2469 /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2470 /// declaration scalar accessor every consumer of the Aplicacao's
2471 /// per-`:politicas` breaker declaration keys off — returns the
2472 /// author-declared `:politicas :circuit-breaker` typed
2473 /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2474 /// copied out of the typed slot's own `Option<CircuitBreaker>`
2475 /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2476 /// by value; no borrow of `&self` past the call). `None` when the
2477 /// slot is absent (the "cluster default applies — typically 'no
2478 /// per-Aplicacao breaker declaration, gateway-class per-listener
2479 /// default applies'" arm the future caixa-mesh
2480 /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2481 /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2482 /// arm reads this predicate too, so an authored-but-unset
2483 /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2484 /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2485 /// that omits the slot).
2486 ///
2487 /// The `:politicas :circuit-breaker` slot carries the
2488 /// "per-Aplicacao consecutive-transient-failure trip declaration"
2489 /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2490 /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2491 /// zero-floor rejected through
2492 /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2493 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2494 /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2495 /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2496 /// canonical-form pinned through
2497 /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2498 /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2499 /// bijection the future `CiliumClusterwideEnvoyConfig`
2500 /// per-`:politicas` overlay emits. Every downstream consumer that
2501 /// reads the breaker declaration keys off this scalar (the
2502 /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2503 /// off to decide "emit :politicas overlay" vs "skip entirely", the
2504 /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2505 /// that brackets `cb.max_failures()` against
2506 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2507 /// [`POLICY_BREAKER_WINDOW_MAX`] via
2508 /// [`crate::render::require_positive_canonical_bounded_duration`],
2509 /// the future M4 per-Aplicacao Envoy reconciler materialization
2510 /// pass, the future per-`:contratos`-edge breaker override the
2511 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2512 ///
2513 /// Prior to this lift the `.circuit_breaker` field was accessed
2514 /// inline at two sites — [`MeshPolicy::is_empty`]'s
2515 /// `self.circuit_breaker.is_none()` arm and the
2516 /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2517 /// bind — two open-coded field-accesses that expressed no
2518 /// compile-time link back to the typed slot. A future extension of
2519 /// the `:politicas :circuit-breaker` axis to a richer author
2520 /// surface — a per-`:contratos`-edge breaker override the operator
2521 /// pins through a future `:contratos :circuit-breaker` slot the
2522 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2523 /// breaker-default overlay the M4 CR materializer resolves per-CR,
2524 /// a promotion of the plain `(max_failures, window)` scalar pair to
2525 /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2526 /// sub-block once Envoy's `outlier_detection` grows the peer
2527 /// ejection-percentage / ejection-time axes — would have had to be
2528 /// threaded through both open-coded copies in lockstep or the
2529 /// emptiness predicate and the validate gate would silently
2530 /// disagree on which breaker declaration a given [`MeshPolicy`]
2531 /// resolves to (a `:politicas` block whose only axis is a
2532 /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2533 /// the validate path silently read a drifted other value, or vice
2534 /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2535 /// "60s"))` would omit the value-shape gate while the emptiness
2536 /// predicate still classified the policy as non-empty). Lifting
2537 /// the resolution to a typed method on the substrate primitive
2538 /// means every downstream consumer of the Aplicacao's
2539 /// per-`:politicas` breaker surface reaches for exactly one typed
2540 /// dispatch — the resolver's accept-set migrates as a unit on any
2541 /// future axis addition.
2542 ///
2543 /// Second `Option<Copy-composite-T>`-return accessor on the M3
2544 /// mesh-slot family (sibling of the peer per-`:politicas`
2545 /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2546 /// on the same composite-Copy shape, and of the sibling per-
2547 /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2548 /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2549 /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2550 /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2551 /// same "one typed dispatch on the substrate primitive, thin
2552 /// projections at each consumer" discipline extended onto the last
2553 /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2554 /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2555 /// match the storage field's name; the accessor's identity maps
2556 /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2557 /// docstring already carries. Closes the last unlifted
2558 /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2559 /// reader now routes through a typed dispatch on the substrate
2560 /// primitive.
2561 #[must_use]
2562 pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2563 self.circuit_breaker
2564 }
2565}
2566
2567#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2568#[serde(rename_all = "camelCase")]
2569pub struct CircuitBreaker {
2570 pub max_failures: u32,
2571 #[serde(with = "supervisor::duration_codec_required")]
2572 pub window: Duration,
2573}
2574
2575impl CircuitBreaker {
2576 /// Substrate-canonical per-`:politicas :circuit-breaker`
2577 /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2578 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2579 /// breaker trip-count keys off — returns the author-declared
2580 /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2581 /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2582 /// so the accessor returns by value; no borrow of `&self` past the
2583 /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2584 /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2585 /// axis; a `CircuitBreaker` past pattern-match is definitionally
2586 /// present, and its `:max-failures` field carries the trip count as a
2587 /// required-axis scalar).
2588 ///
2589 /// The `:politicas :circuit-breaker :max-failures` axis carries the
2590 /// "consecutive-transient-failure trip threshold" contract
2591 /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2592 /// (zero-floor rejected through
2593 /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2594 /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2595 /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2596 /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2597 /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2598 /// Every downstream consumer that reads the trip threshold keys off
2599 /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2600 /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2601 /// canonical `require_positive_bounded_u32` helper, the future M4
2602 /// per-Aplicacao Envoy config reconciler materialization pass, the
2603 /// future per-`:contratos`-edge breaker-override overlay the
2604 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2605 ///
2606 /// Prior to this lift the `.max_failures` field was accessed inline
2607 /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2608 /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2609 /// open-coded field-access that expressed no compile-time link back
2610 /// to the typed sub-struct axis. A future extension of the
2611 /// `:max-failures` axis to a richer author surface — a
2612 /// per-`:contratos`-edge breaker override the operator pins through a
2613 /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2614 /// #3 roadmap acknowledges, a per-cluster max-failures-default
2615 /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2616 /// plain `u32` trip count to a richer
2617 /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2618 /// tuple once Envoy's `outlier_detection` block's peer axes come into
2619 /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2620 /// count arms — would have had to be threaded through every open-
2621 /// coded copy in lockstep or the validate gate and the future M4
2622 /// emit path would silently disagree on which trip threshold a given
2623 /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2624 /// would satisfy validate while the emit path silently read a drifted
2625 /// other value, or vice versa: a validated typed slot would land at
2626 /// the emit boundary as a no-op breaker whose trip threshold is
2627 /// structurally never reached). Lifting the resolution to a typed
2628 /// method on the substrate primitive means every downstream consumer
2629 /// of the Aplicacao's per-`:politicas :circuit-breaker`
2630 /// trip-threshold surface reaches for exactly one typed dispatch —
2631 /// the resolver's accept-set migrates as a unit on any future axis
2632 /// addition.
2633 ///
2634 /// First sub-struct scalar accessor on the M3 mesh-slot family
2635 /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2636 /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2637 /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2638 /// closes the last unlifted per-`:politicas` scalar-value axis after
2639 /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
2640 /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
2641 /// Same "one typed dispatch on the substrate primitive, thin
2642 /// projections at each consumer" discipline the peer
2643 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2644 /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2645 /// [`Membro::versao_requirement`] (a40b0e3),
2646 /// [`Entrada::destination`] (6db982c) accessors carry on their
2647 /// respective per-mesh-slot-atom scalar-value axes, extended onto the
2648 /// per-sub-struct required-`u32` axis. Named `max_failures()` to
2649 /// match the storage field's name; the accessor's identity maps onto
2650 /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2651 /// docstring already carries.
2652 #[must_use]
2653 pub const fn max_failures(&self) -> u32 {
2654 self.max_failures
2655 }
2656
2657 /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
2658 /// Envoy-outlier-detection rolling-observation-interval scalar
2659 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2660 /// breaker rolling-window duration keys off — returns the
2661 /// author-declared `:politicas :circuit-breaker :window` typed
2662 /// `Duration` verbatim, copied out of the typed slot's own
2663 /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
2664 /// by value; no borrow of `&self` past the call). Non-optional (the
2665 /// surrounding `Option<CircuitBreaker>` is the "slot present?"
2666 /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
2667 /// `CircuitBreaker` past pattern-match is definitionally present,
2668 /// and its `:window` field carries the rolling-observation interval
2669 /// as a required-axis scalar).
2670 ///
2671 /// The `:politicas :circuit-breaker :window` axis carries the
2672 /// "consecutive-transient-failure rolling-observation interval"
2673 /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2674 /// `Duration` accept-set (zero-floor rejected through
2675 /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
2676 /// residue rejected through
2677 /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
2678 /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
2679 /// Envoy `outlier_detection.interval` per-cluster
2680 /// ejection-observation-interval scalar (equivalently the future
2681 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2682 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2683 /// consumer that reads the rolling-observation interval keys off
2684 /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2685 /// integer-millisecond canonical-form + cap bracket at
2686 /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
2687 /// [`crate::render::require_positive_canonical_bounded_duration`]
2688 /// helper, the future M4 per-Aplicacao Envoy config reconciler
2689 /// materialization pass, the future per-`:contratos`-edge
2690 /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2691 /// acknowledges).
2692 ///
2693 /// Prior to this lift the `.window` field was accessed inline at
2694 /// one production site — [`AplicacaoSpec::validate_politicas`]'s
2695 /// `require_positive_canonical_bounded_duration(cb.window, …)`
2696 /// call — one open-coded field-access that expressed no compile-
2697 /// time link back to the typed sub-struct axis. A future extension
2698 /// of the `:window` axis to a richer author surface — a
2699 /// per-`:contratos`-edge window override the operator pins through
2700 /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
2701 /// #3 roadmap acknowledges, a per-cluster window-default overlay
2702 /// the M4 CR materializer resolves per-CR, a promotion of the plain
2703 /// `Duration` observation interval to a richer
2704 /// `{interval, base_ejection_time, max_ejection_percent}` tuple
2705 /// once Envoy's `outlier_detection` block's peer axes come into
2706 /// scope, a per-Envoy-cluster minimum-request-volume gate before
2707 /// the window arms — would have had to be threaded through every
2708 /// open-coded copy in lockstep or the validate gate and the future
2709 /// M4 emit path would silently disagree on which observation
2710 /// interval a given [`CircuitBreaker`] resolves to (an author's
2711 /// `:window "60s"` would satisfy validate while the emit path
2712 /// silently read a drifted other value, or vice versa: a validated
2713 /// typed slot would land at the emit boundary as a breaker whose
2714 /// observation window is structurally so wide that no realistic
2715 /// failure-rate shape can trip it). Lifting the resolution to a
2716 /// typed method on the substrate primitive means every downstream
2717 /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
2718 /// observation-window surface reaches for exactly one typed
2719 /// dispatch — the resolver's accept-set migrates as a unit on any
2720 /// future axis addition.
2721 ///
2722 /// Second sub-struct scalar accessor on the M3 mesh-slot family —
2723 /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
2724 /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
2725 /// required-axis, extended onto the per-sub-struct required-`Duration`
2726 /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
2727 /// axis. Same "one typed dispatch on the substrate primitive, thin
2728 /// projections at each consumer" discipline the peer
2729 /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2730 /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2731 /// [`Membro::versao_requirement`] (a40b0e3),
2732 /// [`Entrada::destination`] (6db982c) accessors carry on their
2733 /// respective per-mesh-slot-atom scalar-value axes, extended onto
2734 /// the per-sub-struct required-`Duration` axis. Named `window()` to
2735 /// match the storage field's name; the accessor's identity maps onto
2736 /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2737 /// docstring already carries.
2738 #[must_use]
2739 pub const fn window(&self) -> Duration {
2740 self.window
2741 }
2742}
2743
2744#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2745pub struct RateLimit {
2746 /// Requests per window.
2747 pub rate: u32,
2748 /// Window duration.
2749 pub window: Duration,
2750}
2751
2752impl RateLimit {
2753 /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
2754 /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
2755 /// every consumer of the Aplicacao's per-`:contratos`-edge
2756 /// rate-limit-bucket capacity keys off — returns the author-declared
2757 /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
2758 /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
2759 /// returns by value; no borrow of `&self` past the call). Non-optional
2760 /// (the surrounding `Option<RateLimit>` is the "slot present?"
2761 /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
2762 /// `RateLimit` past pattern-match is definitionally present, and its
2763 /// `:rate` field carries the token-bucket capacity as a required-axis
2764 /// scalar).
2765 ///
2766 /// The `:politicas :rate-limit` `:rate` axis carries the
2767 /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
2768 /// the typed slot's `u32` accept-set (zero-floor rejected through
2769 /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
2770 /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
2771 /// `local_rate_limit.token_bucket.max_tokens` per-cluster
2772 /// token-bucket-capacity scalar (equivalently the future
2773 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2774 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2775 /// consumer that reads the token-bucket capacity keys off this
2776 /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2777 /// cap bracket that gates on the canonical
2778 /// [`crate::render::require_positive_bounded_u32`] helper, the
2779 /// [`rate_limit_codec::render`] `Duration → unit` projection that
2780 /// emits the `<n>/<s|m|h>` author surface, the future M4
2781 /// per-Aplicacao Envoy config reconciler materialization pass, the
2782 /// future per-`:contratos`-edge rate-limit-override overlay the
2783 /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2784 ///
2785 /// Prior to this lift the `.rate` field was accessed inline at three
2786 /// production sites — [`AplicacaoSpec::validate_politicas`]'s
2787 /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
2788 /// [`rate_limit_codec::render`] format-arm arms (canonical-window
2789 /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
2790 /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
2791 /// field-accesses that expressed no compile-time link back to the
2792 /// typed sub-struct axis. A future extension of the `:rate` axis
2793 /// to a richer author surface — a per-`:contratos`-edge rate
2794 /// override the operator pins through a future `:contratos :rate`
2795 /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
2796 /// per-cluster rate-default overlay the M4 CR materializer resolves
2797 /// per-CR, a promotion of the plain `u32` token capacity to a
2798 /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
2799 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2800 /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
2801 /// before the token arms — would have had to be threaded through
2802 /// every open-coded copy in lockstep or the validate gate, the
2803 /// codec's render path, and the future M4 emit path would silently
2804 /// disagree on which token capacity a given [`RateLimit`] resolves
2805 /// to (an author's `:rate-limit "100/s"` would satisfy validate
2806 /// while the render / emit paths silently read a drifted other
2807 /// value, or vice versa: a validated typed slot would land at the
2808 /// emit boundary as a no-op limiter whose token capacity is
2809 /// structurally so high that no realistic per-edge traffic shape
2810 /// can drain it). Lifting the resolution to a typed method on the
2811 /// substrate primitive means every downstream consumer of the
2812 /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
2813 /// reaches for exactly one typed dispatch — the resolver's
2814 /// accept-set migrates as a unit on any future axis addition.
2815 ///
2816 /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
2817 /// in shape to the peer per-`CircuitBreaker`
2818 /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
2819 /// on the peer per-sub-struct required-axis, extended onto the
2820 /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
2821 /// required-axis scalar" projection pattern the sibling
2822 /// [`RateLimit::window`] future lift folds on. Same "one typed
2823 /// dispatch on the substrate primitive, thin projections at each
2824 /// consumer" discipline the peer [`WitContract::source`] /
2825 /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
2826 /// (0804823), [`Membro::nome`] (4a32abf),
2827 /// [`Membro::versao_requirement`] (a40b0e3),
2828 /// [`Entrada::destination`] (6db982c),
2829 /// [`CircuitBreaker::max_failures`] (3a74062),
2830 /// [`CircuitBreaker::window`] (373957f) accessors carry on their
2831 /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
2832 /// to match the storage field's name; the accessor's identity maps
2833 /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2834 /// docstring already carries.
2835 #[must_use]
2836 pub const fn rate(&self) -> u32 {
2837 self.rate
2838 }
2839
2840 /// Substrate-canonical per-`:politicas :rate-limit` `:window`
2841 /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
2842 /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2843 /// rate-limit-bucket refill period keys off — returns the
2844 /// author-declared `:politicas :rate-limit` typed `Duration`
2845 /// verbatim, copied out of the typed slot's own `Duration` storage
2846 /// (`Duration` is `Copy`, so the accessor returns by value; no
2847 /// borrow of `&self` past the call). Non-optional (the surrounding
2848 /// `Option<RateLimit>` is the "slot present?" projection at the
2849 /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
2850 /// pattern-match is definitionally present, and its `:window`
2851 /// field carries the token-bucket refill period as a required-axis
2852 /// scalar).
2853 ///
2854 /// The `:politicas :rate-limit` `:window` axis carries the
2855 /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
2856 /// — the typed slot's `Duration` accept-set (constrained to the
2857 /// three canonical windows `{1s, 60s, 3600s}` the
2858 /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
2859 /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
2860 /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
2861 /// per-cluster token-bucket-refill-period scalar (equivalently the
2862 /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2863 /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
2864 /// consumer that reads the token-bucket refill period keys off
2865 /// this scalar (the [`AplicacaoSpec::validate_politicas`]
2866 /// canonical-window gate that keys off
2867 /// [`is_canonical_rate_limit_window`], the
2868 /// [`rate_limit_codec::render`] `Duration → unit` projection that
2869 /// emits the `<n>/<s|m|h>` author surface — canonical arm via
2870 /// [`rate_limit_window_unit`] and non-canonical fallback via
2871 /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
2872 /// reconciler materialization pass, the future per-`:contratos`-
2873 /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
2874 /// roadmap acknowledges).
2875 ///
2876 /// Prior to this lift the `.window` field was accessed inline at
2877 /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
2878 /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
2879 /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
2880 /// error-payload construction on refusal, and the two
2881 /// [`rate_limit_codec::render`] arms
2882 /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
2883 /// and non-canonical-window `rl.window.as_secs()` fallback). Three
2884 /// open-coded field-accesses that expressed no compile-time link
2885 /// back to the typed sub-struct axis. A future extension of the
2886 /// `:window` axis to a richer author surface — a per-`:contratos`-
2887 /// edge window override the operator pins through a future
2888 /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
2889 /// acknowledges, a per-cluster window-default overlay the M4 CR
2890 /// materializer resolves per-CR, a promotion of the plain
2891 /// `Duration` refill period to a richer
2892 /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
2893 /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
2894 /// axis comes into scope, an addition of a `"d"` day suffix once
2895 /// Envoy's `rate_limit_action` grows daily-bucket support — would
2896 /// have had to be threaded through every open-coded copy in
2897 /// lockstep or the validate gate, the codec's render path, and
2898 /// the future M4 emit path would silently disagree on which
2899 /// refill period a given [`RateLimit`] resolves to (an author's
2900 /// `:rate-limit "100/s"` would satisfy validate while the render
2901 /// / emit paths silently read a drifted other value, or vice
2902 /// versa: a validated typed slot would land at the emit boundary
2903 /// as a limiter whose refill period is structurally so long that
2904 /// no realistic per-edge traffic shape stays inside the token
2905 /// budget). Lifting the resolution to a typed method on the
2906 /// substrate primitive means every downstream consumer of the
2907 /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
2908 /// reaches for exactly one typed dispatch — the resolver's
2909 /// accept-set migrates as a unit on any future axis addition.
2910 ///
2911 /// Second sub-struct scalar accessor on the `RateLimit` axis —
2912 /// sibling in shape to the just-landed [`RateLimit::rate`]
2913 /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
2914 /// required-axis, extended onto the per-sub-struct
2915 /// required-`Duration` axis; closes the last unlifted
2916 /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
2917 /// per-sub-struct accessor coverage is now complete across both
2918 /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
2919 /// the substrate primitive, thin projections at each consumer"
2920 /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
2921 /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
2922 /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
2923 /// (7f0fd43), [`WitContract::world_ref`] (0804823),
2924 /// [`Membro::nome`] (4a32abf),
2925 /// [`Membro::versao_requirement`] (a40b0e3),
2926 /// [`Entrada::destination`] (6db982c) accessors carry on their
2927 /// respective per-mesh-slot-atom scalar-value axes. Named
2928 /// `window()` to match the storage field's name; the accessor's
2929 /// identity maps onto the canonical MESH-COMPOSITION §III.2
2930 /// vocabulary the slot's docstring already carries.
2931 #[must_use]
2932 pub const fn window(&self) -> Duration {
2933 self.window
2934 }
2935
2936 /// Recognize this rate-limit's `:window` as a canonical
2937 /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
2938 /// exactly matches one of the three closed-set arm-Durations
2939 /// (`1s` / `60s` / `3600s`), `None` when the window carries a
2940 /// non-canonical magnitude the codec's round-trip would break on
2941 /// (sub-second residue, or a second-magnitude outside the set
2942 /// [`RateLimitUnit::ALL`] enumerates).
2943 ///
2944 /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
2945 /// returns `Some` here — the validate gate's
2946 /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
2947 /// rejects every window this accessor returns `None` on. Downstream
2948 /// consumers past validate (the codec's [`rate_limit_codec::render`]
2949 /// path, the future M4 per-Aplicacao Envoy config reconciler's
2950 /// materialization pass, the future per-`:contratos`-edge rate-limit-
2951 /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
2952 /// acknowledges) that read the typed unit off a validated slot can
2953 /// pattern-match on the returned `Some` without re-checking
2954 /// canonicality at the consumer layer — the typed enum surface is
2955 /// the load-bearing carrier of the canonicality invariant.
2956 ///
2957 /// Preferred over the free [`is_canonical_rate_limit_window`]
2958 /// module-private helper at any call site that has the typed
2959 /// [`RateLimit`] in hand (the codec's `render` arm at
2960 /// [`rate_limit_codec::render`], the validate gate's canonical-form
2961 /// arm in [`AplicacaoSpec::validate_politicas`], any future
2962 /// per-`:contratos` edge-override overlay resolver): those consumers
2963 /// reach for the typed enum without going through the
2964 /// `.window()` scalar-projection layer, and get the enum value
2965 /// directly (which the codec's render arm can then format via
2966 /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
2967 /// "typed sub-struct scalar accessor, one dispatch on the substrate
2968 /// primitive" discipline the sibling [`RateLimit::rate`] and
2969 /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
2970 /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
2971 /// projection axis (the third scalar accessor on the [`RateLimit`]
2972 /// axis, first typed-enum-return projection).
2973 ///
2974 /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
2975 /// the canonical [`RateLimitUnit`] arm now carries the same
2976 /// `const`-eval-surface posture the sibling `pub const fn`
2977 /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
2978 /// this typed sub-struct already carry, composing through the
2979 /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
2980 /// reverse-resolver in `const` context. Any downstream substrate-
2981 /// side `const`-context consumer of the typed unit (a module-scope
2982 /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
2983 /// invariant pin on a typed fixture, a future M4 admission-webhook
2984 /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
2985 /// resolver over a typed [`RateLimit`], any future `const fn`
2986 /// per-`:contratos`-edge rate-limit-override overlay resolver over
2987 /// the substrate primitive) now reaches the same typed dispatch on
2988 /// the substrate primitive at const-eval time as at runtime.
2989 ///
2990 /// Pinned load-bearing at the substrate-primitive level by
2991 /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
2992 /// eval-surface pin via `const fn` wrapper).
2993 #[must_use]
2994 pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
2995 RateLimitUnit::from_window(self.window)
2996 }
2997}
2998
2999/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
3000/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
3001/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
3002///
3003/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
3004/// the `:politicas :rate-limit` unit surface reads from
3005/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
3006/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
3007/// [`is_canonical_rate_limit_window`] predicate the
3008/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
3009/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
3010/// projection) now lives inside this typed enum's `match self` arms — a
3011/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
3012/// `rate_limit_action` grows daily-bucket support) is one new variant
3013/// plus the exhaustiveness arms on the four methods, so every consumer
3014/// picks it up by compile-time construction rather than a runtime
3015/// table-scan miss.
3016///
3017/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
3018/// scanned via `find_map` at every projection call — an untyped runtime
3019/// walk that carried no compile-time link between the parse arm's
3020/// accepted suffixes, the render arm's emitted suffixes, and the
3021/// validate gate's accepted windows. A future rate-limit-unit addition
3022/// that landed one row without threading through the other consumers
3023/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3024/// silently split the accepted-set across the three consumers — the
3025/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3026/// for a 24h window that parse can't round-trip, the validate gate
3027/// misses one canonical window. Lifting the pairs onto a typed
3028/// closed-set enum with exhaustive `match` arms makes any such
3029/// half-landed extension a caixa-core build error (the compiler enforces
3030/// arm coverage on every method), not a silent per-consumer drift
3031/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3032/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3033/// [`crate::supervisor::RestartStrategy`],
3034/// [`crate::supervisor::RestartPolicy`],
3035/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3036/// closed-set typed enums carry on their respective closed-set axes —
3037/// extended onto the seventh closed-set typed-enum discriminator axis
3038/// on the caixa typed surface (the `:politicas :rate-limit :window`
3039/// canonical-unit axis).
3040#[derive(
3041 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3042)]
3043pub enum RateLimitUnit {
3044 /// 1-second window — canonical author-surface suffix `"s"`
3045 /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3046 /// with a 1s magnitude.
3047 Second,
3048 /// 1-minute window — canonical author-surface suffix `"m"`
3049 /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3050 /// with a 60s magnitude.
3051 Minute,
3052 /// 1-hour window — canonical author-surface suffix `"h"`
3053 /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3054 /// with a 3600s magnitude.
3055 Hour,
3056}
3057
3058impl RateLimitUnit {
3059 /// Exhaustive iteration surface for every consumer that reads the
3060 /// full canonical-unit set (the byte-parity witness against the
3061 /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3062 /// webhook's accepted-suffix listing in its rejection body, any
3063 /// future round-trip fuzz harness). A future variant addition to
3064 /// [`RateLimitUnit`] extends this slice as a single edit and every
3065 /// consumer picks up the new entry by construction — the compiler-
3066 /// checked exhaustiveness on the sibling method `match` arms is the
3067 /// build-time guarantee that no arm forgets to grow.
3068 pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3069
3070 /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3071 /// string every `<n>/<unit>` rate-limit shape carries after its
3072 /// `/` separator. The single source of truth the codec's parse and
3073 /// render arms both dispatch on: the parse arm matches an incoming
3074 /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3075 /// output; the render arm emits the entry's `as_suffix` verbatim
3076 /// after the rate magnitude.
3077 #[must_use]
3078 pub const fn as_suffix(self) -> &'static str {
3079 match self {
3080 Self::Second => "s",
3081 Self::Minute => "m",
3082 Self::Hour => "h",
3083 }
3084 }
3085
3086 /// Canonical `Duration` for this unit — the token-bucket refill
3087 /// period the [`RateLimit::window`] axis carries when the surrounding
3088 /// slot's `:rate-limit` author surface named this unit.
3089 #[must_use]
3090 pub const fn window(self) -> Duration {
3091 Duration::from_secs(match self {
3092 Self::Second => 1,
3093 Self::Minute => 60,
3094 Self::Hour => 3_600,
3095 })
3096 }
3097
3098 /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3099 /// `None` when `suffix` is outside the closed-set arm-string set
3100 /// [`Self::as_suffix`] emits. The single `str → Self` projection
3101 /// [`rate_limit_codec::parse`] consumes.
3102 #[must_use]
3103 pub fn from_suffix(suffix: &str) -> Option<Self> {
3104 Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3105 }
3106
3107 /// Recognize a canonical rate-limit `Duration` as one of the three
3108 /// arms, or `None` when `window` carries sub-second residue or a
3109 /// second-magnitude outside the closed-set arm-window set
3110 /// [`Self::window`] emits. The single `Duration → Self` projection
3111 /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3112 /// both consume.
3113 ///
3114 /// `pub const fn` — the reverse `Duration → Self` projection now
3115 /// carries the same `const`-eval-surface posture the sibling
3116 /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
3117 /// projection accessors on this closed-set typed enum already
3118 /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
3119 /// typed-`RateLimit`-projection sibling composes through in `const`
3120 /// context. Routes byte-for-byte through the peer `pub const fn`
3121 /// [`Self::window`] canonical-`Duration` projection so any future
3122 /// arm-magnitude edit on the sibling accessor reaches this reverse
3123 /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
3124 /// per-arm probes each dispatch through one `pub const fn` on the
3125 /// substrate primitive rather than a hand-authored per-arm second-
3126 /// magnitude literal that would silently drift on any future
3127 /// [`Self::window`] arm-magnitude edit.
3128 ///
3129 /// Prior to the `const` lift the body dispatched through
3130 /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
3131 /// iterator-driven linear scan whose iterator methods
3132 /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
3133 /// `PartialEq` dispatch each carry non-`const` bounds on stable
3134 /// Rust 1.94, so any downstream substrate-side `const`-context
3135 /// consumer of the reverse resolver (a module-scope
3136 /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
3137 /// invariant pin on a typed fixture, a future M4
3138 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
3139 /// webhook `const fn` per-`:politicas` canonical-window floor over a
3140 /// typed [`RateLimit`] scalar, any future `const fn`
3141 /// per-`:contratos`-edge rate-limit-override overlay resolver over
3142 /// the substrate primitive that wants to fan on the canonical unit
3143 /// at compile time) surfaced as a downstream E0015 far from the
3144 /// resolver's own declaration. The `pub const fn` posture closes
3145 /// the drift structurally at caixa-core build time.
3146 ///
3147 /// Pinned load-bearing at the substrate-primitive level by
3148 /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
3149 /// eval-surface pin via `const fn` wrapper) and
3150 /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
3151 /// (composition-witness pin against the peer `Self::window` scalar
3152 /// dispatch).
3153 #[must_use]
3154 pub const fn from_window(window: Duration) -> Option<Self> {
3155 if window.subsec_nanos() != 0 {
3156 return None;
3157 }
3158 // Route through the peer `pub const fn` [`Self::window`]
3159 // canonical-`Duration` projection so any future arm-magnitude
3160 // edit on the sibling accessor reaches this reverse resolver by
3161 // construction — the per-arm `secs` comparison keys off
3162 // `Duration::as_secs` (`pub const fn`), not a hand-authored
3163 // per-arm second-magnitude literal that would silently drift.
3164 let secs = window.as_secs();
3165 if secs == Self::Second.window().as_secs() {
3166 Some(Self::Second)
3167 } else if secs == Self::Minute.window().as_secs() {
3168 Some(Self::Minute)
3169 } else if secs == Self::Hour.window().as_secs() {
3170 Some(Self::Hour)
3171 } else {
3172 None
3173 }
3174 }
3175
3176 /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3177 /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3178 /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3179 /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3180 /// consumes.
3181 ///
3182 /// The peer `Duration → &'static str` axis folded onto the substrate
3183 /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3184 /// production consumers ([`rate_limit_codec::render`] and
3185 /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3186 /// migrated (61421a6): the free helper's `Duration → &str` projection
3187 /// is now the two-step composition
3188 /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3189 /// reads through the typed accessor. This lift closes the peer
3190 /// `&str → Duration` axis by folding the vestigial module-private
3191 /// `rate_limit_window_from_unit` delegate onto this associated method
3192 /// — the codec's parse arm and every future wire-side consumer of the
3193 /// `&str → Duration` projection (a future admission-webhook that
3194 /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3195 /// before it's promoted to a validated typed slot, a future
3196 /// `feira lint` shape-probe that reads the author-surface bytes
3197 /// verbatim) now reach for exactly one typed dispatch on the
3198 /// substrate primitive.
3199 ///
3200 /// Same "closed-set typed-enum discriminator with canonical
3201 /// projections per axis" discipline the sibling [`Self::as_suffix`]
3202 /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3203 /// methods carry — this associated method closes the fifth (and last
3204 /// unlifted) projection axis on the arm-table, so the closed-set enum
3205 /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3206 /// consumer of the `:politicas :rate-limit :window` axis reaches
3207 /// through. A future rate-limit-unit addition (a `"d"` day suffix
3208 /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3209 /// `"ms"` sub-second window once high-throughput per-edge policies
3210 /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3211 /// variant plus one arm per method — the compiler enforces
3212 /// exhaustiveness on every consumer's `match self` arms and picks
3213 /// the new unit up by construction across all five projections.
3214 #[must_use]
3215 pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3216 Self::from_suffix(suffix).map(Self::window)
3217 }
3218}
3219
3220/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3221/// every consumer that formats a canonical rate-limit unit as user-
3222/// facing text (future M4 admission-webhook rejection bodies naming
3223/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3224/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3225/// codec's parse arm accepts and the render arm emits. Same
3226/// as_str-through-Display convergence discipline the sibling
3227/// [`PlacementStrategy`], [`crate::CaixaKind`],
3228/// [`crate::supervisor::RestartStrategy`], and
3229/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3230impl std::fmt::Display for RateLimitUnit {
3231 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3232 f.write_str(self.as_suffix())
3233 }
3234}
3235
3236/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3237/// validated [`MeshPolicy::timeout`] past
3238/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3239/// (inclusive on both ends, integer-millisecond magnitudes by the
3240/// canonical-form gate immediately preceding).
3241///
3242/// The typed field is `Option<Duration>` (the zero-floor arm
3243/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3244/// `Duration::ZERO`, and the canonical-form arm
3245/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3246/// sub-millisecond residue), so a programmatic struct literal
3247/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3248/// 24h) and the equivalent author-surface form
3249/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3250/// integer-hour magnitude) both round-trip cleanly through serde — a
3251/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3252/// above the documented production-playbook band (Envoy default `15s`,
3253/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3254/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3255/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3256/// at `~3600s`) silently degenerates the mesh-policy contract: the
3257/// per-call deadline is structurally so long that no realistic
3258/// synchronous-`:contratos` traversal can reach it, so the typed slot
3259/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3260/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3261/// blocking" degenerates to a nominal-only contract on the
3262/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3263/// the sibling `:politicas :retries` axis and the
3264/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3265/// `:politicas :circuit-breaker :max-failures` axis — all three close
3266/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3267/// footgun the prior zero-floor-and-canonical-form-only checks left
3268/// open.
3269///
3270/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3271/// shared duration codec emits (`"<n>h"` for any integer-hour
3272/// magnitude) — every value in the canonical authoring form's
3273/// `<integer><unit>` grammar at or below this cap renders to a clean
3274/// canonical string. The cap sits an order of magnitude above every
3275/// documented production-playbook recommendation band (Envoy default
3276/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3277/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3278/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3279/// below the clearly-pathological "effectively no timeout" floor
3280/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3281/// want for a long-running synchronous workflow, but a hard wall above
3282/// which the mesh-level deadline is structurally a non-deadline.
3283/// Lifted as a typed `pub const` so the bound has exactly one source
3284/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3285/// materializer's admission webhook and the caixa-mesh-side
3286/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3287/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3288/// other typed upper bound in this crate carries
3289/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3290/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3291/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3292/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3293pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3294
3295/// Upper-bound ceiling on the `:politicas :retries` axis — every
3296/// validated [`MeshPolicy::retries`] past
3297/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3298///
3299/// The typed slot is `Option<u32>` (`None` = no retries on transient
3300/// failure; `Some(0)` already rejected by the
3301/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3302/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3303/// .. }`) and the equivalent author-surface form
3304/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3305/// serde / the codec — a structurally unbounded `u32` ceiling. The
3306/// runtime substrate that consumes the value (Envoy's
3307/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3308/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3309/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3310/// admission cap is 10) translates a four-billion-retry policy into a
3311/// thundering-herd amplification vector on transient failure — the
3312/// caller's one request fans out to `retries` server-side calls per
3313/// edge per traversal, multiplying load by `(retries+1)^depth` across
3314/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3315/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3316/// invariant on the retry axis; both belong at the typed-slot layer.
3317///
3318/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3319/// upstream mesh-policy schema that documents one) and sits above the
3320/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3321/// every documented production playbook): a value the author can
3322/// plausibly want, but a hard wall above which the policy is
3323/// structurally a footgun. Lifted as a typed `pub const` so the bound
3324/// has exactly one source of truth — a future axis reaching for the
3325/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3326/// materializer's admission webhook, the caixa-mesh-side
3327/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3328/// one place. Same shape every other typed upper bound in this crate
3329/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3330/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3331/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3332/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3333pub const POLICY_RETRIES_MAX: u32 = 10;
3334
3335/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3336/// axis — every validated [`CircuitBreaker::max_failures`] past
3337/// [`AplicacaoSpec::validate_politicas`] lies in
3338/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3339///
3340/// The typed field is `u32` (the zero-floor arm
3341/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3342/// `0` — a breaker that trips on the first call), so a programmatic
3343/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3344/// and the equivalent author-surface form
3345/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3346/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3347/// `max_failures` value far above the documented production-playbook
3348/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3349/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3350/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3351/// typical 5–50) silently disables the breaker's protection role:
3352/// the threshold is structurally so high that no realistic
3353/// failures-per-`:window` traffic shape can reach it, so the breaker
3354/// never trips and the typed slot becomes a no-op carried on every
3355/// emitted Envoy / Cilium L7 overlay. Pairs with the
3356/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3357/// axis — both close the "structurally unbounded `u32` ceiling on a
3358/// typed policy axis" footgun the prior zero-floor-only checks left
3359/// open.
3360///
3361/// The `1000` ceiling sits an order of magnitude above every
3362/// documented upstream production-playbook recommendation band (the
3363/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3364/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3365/// the clearly-pathological "effectively no protection"
3366/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3367/// plausibly want at hyperscale, but a hard wall above which the
3368/// policy is structurally a no-op. Lifted as a typed `pub const` so
3369/// the bound has exactly one source of truth — the future M4
3370/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3371/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3372/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3373/// one place. Same shape every other typed upper bound in this crate
3374/// carries ([`POLICY_RETRIES_MAX`],
3375/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3376/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3377/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3378pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3379
3380/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3381/// every validated [`CircuitBreaker::window`] past
3382/// [`AplicacaoSpec::validate_politicas`] lies in
3383/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3384/// integer-millisecond magnitudes by the canonical-form gate
3385/// immediately preceding).
3386///
3387/// The typed field is `Duration` (the zero-floor arm
3388/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3389/// `Duration::ZERO`, and the canonical-form arm
3390/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3391/// sub-millisecond residue), so a programmatic struct literal
3392/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3393/// and the equivalent author-surface form
3394/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3395/// integer-hour magnitude) both round-trip cleanly through serde — a
3396/// structurally unbounded `Duration` ceiling. A `:window` value far
3397/// above the documented production-playbook band (Hystrix
3398/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3399/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3400/// Istio `outlierDetection.interval` default `10s`, Envoy
3401/// `outlier_detection.interval` default `10s`, AWS App Mesh
3402/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3403/// breaker's role: a rolling-window failure counter whose window is
3404/// hours long is operationally a lifetime counter, the breaker's
3405/// "recent failures" memory is structurally so long that transient
3406/// failures are never forgotten, and the typed slot becomes a no-op
3407/// trigger that trips once and stays tripped for the lifetime of the
3408/// component carried on every emitted Envoy / Cilium L7 overlay.
3409///
3410/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3411/// shared duration codec emits (`"<n>h"` for any integer-hour
3412/// magnitude) — every value in the canonical authoring form's
3413/// `<integer><unit>` grammar at or below this cap renders to a clean
3414/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3415/// cap on the first typed-`Duration` `:politicas` axis: the two
3416/// duration-typed `:politicas` axes now share a single uniform top
3417/// edge so the next typed-slot wiring (the future caixa-mesh
3418/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3419/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3420/// admission webhook) reaches for either field knowing the value is
3421/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3422/// sits two orders of magnitude above every documented upstream
3423/// production-playbook recommendation band (Hystrix / resilience4j /
3424/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3425/// and below the clearly-pathological "rolling window degenerates to
3426/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3427/// author can plausibly want for a very-low-traffic long-tail
3428/// failure-detection window, but a hard wall above which the breaker's
3429/// rolling-window contract is structurally a lifetime-counter contract.
3430/// Lifted as a typed `pub const` so the bound has exactly one source
3431/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3432/// materializer's admission webhook and the caixa-mesh-side
3433/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3434/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3435/// other typed upper bound in this crate carries
3436/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3437/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3438/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3439/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3440/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3441pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3442
3443/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3444/// every validated [`RateLimit::rate`] past
3445/// [`AplicacaoSpec::validate_politicas`] lies in
3446/// `1..=POLICY_RATE_LIMIT_MAX`.
3447///
3448/// The typed field is `u32` (the zero-floor arm
3449/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3450/// zero-rate limit denies every request, the canonical "I forgot
3451/// that 0 means deny-everything" footgun), so a programmatic struct
3452/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3453/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3454/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3455/// round-trip cleanly through serde — a structurally unbounded `u32`
3456/// ceiling. The runtime substrate consuming the value (Envoy's
3457/// `local_rate_limit.token_bucket.max_tokens`, the future
3458/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3459/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3460/// rate-limit into a no-op rate-limiter: the bucket capacity is
3461/// structurally so high no realistic per-edge traffic shape can
3462/// drain it, the limiter never trips, and the typed slot becomes a
3463/// "rate-limit declared, no enforcement" footgun — the canonical
3464/// declared-but-inert shape every other `:politicas` cap arm
3465/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3466/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3467///
3468/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3469/// above every documented upstream production-playbook recommendation
3470/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3471/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3472/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3473/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3474/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3475/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3476/// `u32::MAX`): a value the author can plausibly want at hyperscale
3477/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3478/// /h-window arm), but a hard wall above which the policy is
3479/// structurally a no-op carried verbatim on every emitted Envoy /
3480/// Cilium L7 overlay. The cap brackets all three canonical windows
3481/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3482/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3483/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3484/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3485/// has exactly one source of truth — the future M4
3486/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3487/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3488/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3489/// one place. Same shape every other typed upper bound in this crate
3490/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3491/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3492/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3493/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3494/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3495/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3496pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3497
3498// `:entrada :host` total-length and per-label cap axes route through
3499// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3500// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3501// pair of aplicacao-private aliases the previous `validate_entrada_host`
3502// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3503// = 63`) were structurally the same K8s Gateway API v1 Hostname
3504// admission-schema bounds — the total-length cap on the OpenAPI
3505// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3506// same regex — that the peer axes at the caixa-core::render level pin,
3507// so hoisting both readers onto the shared lifted constants closes the
3508// third-occurrence duplication threshold structurally: the M4
3509// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3510// label validator, the future per-`Certificate` SAN emitter, and every
3511// other per-Gateway-API-Hostname landing site reach the same one place
3512// as the `:entrada :host` gate does — no per-axis alias drift surface
3513// between them, by construction.
3514
3515/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3516/// extractor expression — the upper bound `validate_placement_shard_key`
3517/// enforces on every well-shaped shard-key past validate. The realistic
3518/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3519/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3520/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3521/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3522/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3523/// in `:shard-key`" footgun at validate time rather than at the future
3524/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3525const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3526
3527/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3528/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3529/// that maps the shared parser-shaped reason into the
3530/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3531/// is self-locating (the offending `caixa:` is named verbatim) and
3532/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3533/// fix it in one edit. Same diagnostic shape as
3534/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3535/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3536fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3537 // Empty is already gated by `MembroCaixaEmpty` at the call site;
3538 // re-checking here keeps the predicate usable from any future
3539 // call site (the M4 CR materializer) without an empty-check
3540 // footgun. The shared
3541 // [`crate::render::require_valid_dns_1123_label`] helper brackets
3542 // the empty-first + shape cascade every peer name axis
3543 // (`:placement :clusters`, `:placement :affinity`, `:contratos
3544 // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3545 // `:upgrade-from :module`) routes through, so drift between the
3546 // eight axes' accepted DNS-1123-label sets is structurally
3547 // impossible.
3548 crate::render::require_valid_dns_1123_label(
3549 caixa,
3550 || AplicacaoError::MembroCaixaEmpty,
3551 |reason| AplicacaoError::MembroCaixaInvalid {
3552 caixa: caixa.to_string(),
3553 reason,
3554 },
3555 )
3556}
3557
3558/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3559/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3560/// that maps the shared parser-shaped reason into the
3561/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3562///
3563/// Cluster names land in DNS-1123-label territory across every consumer:
3564/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3565/// the `lareira-fleet-programs` aggregator applies to scope programs to
3566/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3567/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3568/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3569/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3570/// side schema enforces the DNS-1123 label rule on admission; a
3571/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3572/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3573/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3574/// only gate and the failure surfaces as a no-match at filter time —
3575/// the workload doesn't land in the named cluster, with no diagnostic
3576/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3577/// build time mirrors the `:membros :caixa` value-shape trajectory
3578/// (3f9d7a0) on the peer name axis.
3579///
3580/// The diagnostic carries the offending `cluster:` verbatim plus a
3581/// parser-shaped `reason:` naming the specific violation, so the
3582/// author can grep their caixa.lisp for `:clusters` and fix it in
3583/// one edit. Same diagnostic shape as
3584/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3585fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3586 // Empty is already gated by `PlacementClusterEmpty` at the call
3587 // site; re-checking here keeps the predicate usable from any
3588 // future call site (the M4 CR materializer's per-cluster validator)
3589 // without an empty-check footgun. Routes through the shared
3590 // [`crate::render::require_valid_dns_1123_label`] gate the peer
3591 // name axes each land on.
3592 crate::render::require_valid_dns_1123_label(
3593 cluster,
3594 || AplicacaoError::PlacementClusterEmpty,
3595 |reason| AplicacaoError::PlacementClusterInvalid {
3596 cluster: cluster.to_string(),
3597 reason,
3598 },
3599 )
3600}
3601
3602/// Reject `:placement :affinity` hints whose shape can never legitimately
3603/// land in any downstream selector or label-keyed routing axis. Thin
3604/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3605/// shared parser-shaped reason into the
3606/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3607/// diagnostic is self-locating (the offending `:affinity` is named
3608/// verbatim) and the author can grep their caixa.lisp for
3609/// `:affinity "<hint>"` and fix it in one edit.
3610///
3611/// The `:affinity` slot carries a placement-engine hint — canonical
3612/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3613/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3614/// compression overlay and the future M4 placement-engine's per-hint
3615/// routing axis. Each downstream consumer (caixa-mesh's
3616/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3617/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3618/// `spec.placement.affinity` admission rule, the future M4 per-hint
3619/// node-affinity / pod-affinity rule generator keying off the same
3620/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3621/// selector) requires the value to be a DNS-1123 label — K8s label
3622/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3623/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3624/// admission rule the apiserver enforces.
3625///
3626/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3627/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3628/// Python-module-name leak), `:affinity "data.locality"` (the
3629/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3630/// `:affinity "data-locality-"` (boundary-hyphen violation),
3631/// `:affinity "data locality"` (paste-from-doc whitespace),
3632/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3633/// 64-byte over-cap slug silently passed the empty-only check and the
3634/// failure surfaced as a no-match at the M3 Adaptive compression
3635/// overlay's filter time (`placement.affinity` carried a malformed
3636/// value, no node matched, the workload landed on the default
3637/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3638/// the empty-:affinity / empty-shard-key / zero-:politicas /
3639/// empty-:contratos-target gates already close on every other
3640/// declare-but-no-opinion axis. Lifting the rejection to a build-time
3641/// gate closes the fifth typed slot on the Aplicacao surface to land
3642/// on the canonical DNS-1123 label floor (after the four Servico-name
3643/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
3644/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
3645/// b0e8748).
3646///
3647/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
3648/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
3649/// validated values are guaranteed-accepted by the apiserver without
3650/// re-validation at any downstream renderer or admission layer.
3651fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
3652 // Empty is gated separately at the call site for a self-locating
3653 // diagnostic; re-checking here keeps the predicate usable from any
3654 // future call site (the M4 CR materializer's per-affinity
3655 // validator) without an empty-check footgun. Routes through the
3656 // shared [`crate::render::require_valid_dns_1123_label`] gate the
3657 // peer name axes each land on.
3658 crate::render::require_valid_dns_1123_label(
3659 affinity,
3660 || AplicacaoError::PlacementAffinityEmpty,
3661 |reason| AplicacaoError::PlacementAffinityInvalid {
3662 affinity: affinity.to_string(),
3663 reason,
3664 },
3665 )
3666}
3667
3668/// Reject `:placement :shard-key` extractor expressions whose shape can
3669/// never legitimately drive the future M4 Akka-style cluster-sharding
3670/// reconciler's hash-extractor pass. Maps the per-byte / length checks
3671/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
3672/// diagnostic is self-locating (the offending `:shard-key` value is
3673/// named verbatim alongside the parser-shaped reason) and the author can
3674/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
3675/// edit.
3676///
3677/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
3678/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
3679/// expression naming the message property to hash on. The realistic
3680/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
3681/// property name; `$tenantId` — Akka entity-id placeholder;
3682/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
3683/// `${tenant}` — interpolation-style template) all sit in the printable
3684/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
3685/// multi-line blob landing in `:shard-key`, an embedded space from a
3686/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
3687/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
3688/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
3689/// check and the failure surfaces at the future M4 reconciler's hash
3690/// pass as a runtime extractor-evaluation error far from the source
3691/// `caixa.lisp`, with no field naming which member's `:shard-key`
3692/// carried the offending value.
3693///
3694/// The contract — the printable ASCII single-token intersection-floor
3695/// every Akka-style entity-id extractor implementation admits:
3696///
3697/// - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
3698/// peer DNS-1123-label-shaped `:placement :affinity` /
3699/// `:placement :clusters` identifier axes; realistic shard-keys sit
3700/// well under 32 bytes, the cap surfaces paste-from-doc multi-line
3701/// blob footguns at validate time;
3702/// - every byte in the printable ASCII range `0x21..=0x7E` —
3703/// rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
3704/// `"$tenantId\n"` from paste-from-aligned-doc /
3705/// paste-from-shell-heredoc), control characters (`\x00..\x1F`,
3706/// `\x7F` — the canonical "embedded null from a copy-paste-binary
3707/// footgun"), and non-ASCII bytes (`"$tenàntId"` —
3708/// un-Punycode-encoded IDN that round-trips inconsistently across
3709/// NFC/NFD normalization).
3710///
3711/// The accepted set is broader than the DNS-1123 label floor the peer
3712/// `:placement :clusters` / `:placement :affinity` axes use because the
3713/// `:shard-key` value is not a K8s `metadata.name` / label-selector
3714/// landing site; it's an extractor expression the future Akka-style
3715/// reconciler reads as a property reference. The realistic forms
3716/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
3717/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
3718/// but every Akka-style entity-id extractor parses. The
3719/// printable-ASCII-token floor accepts every shape any such extractor
3720/// would accept while rejecting the cross-implementation footguns
3721/// (whitespace breaks token boundaries; non-ASCII round-trips
3722/// inconsistently across YAML emitters and NFC/NFD normalization;
3723/// control characters silently corrupt the next read).
3724///
3725/// Until this gate landed `validate_placement` only refused the
3726/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
3727/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
3728/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
3729/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
3730/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
3731/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
3732/// control character from paste-from-binary, the 64-byte over-cap
3733/// paste-from-doc multi-line slug) silently passed validate. The future
3734/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
3735/// would then surface the malformed value either as a runtime
3736/// extractor-evaluation error (whitespace breaks the extractor's token
3737/// boundary, no match) or as a silently-different shard assignment
3738/// across YAML emitters (non-ASCII normalizes differently between the
3739/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
3740/// parser, the same entity ID maps to two distinct shards on a
3741/// re-render). Lifting the shape gate to caixa-build time makes the
3742/// extractor-floor invariant a structural property of every validated
3743/// `Placement`: every `Sharded` placement past `validate_placement` has
3744/// a `:shard-key` the future M4 reconciler can hash without
3745/// re-validating at the runtime layer.
3746///
3747/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
3748/// [`AplicacaoError::ContratoSubjectInvalid`] /
3749/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
3750/// on the peer `:contratos` payload axes — each lifts the
3751/// runtime-side parser's intersection-floor to a caixa-build-time gate,
3752/// closing the canonical "this passed validate but the runtime parser
3753/// rejected it" surprise.
3754fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
3755 // Empty is gated separately at the call site via the more
3756 // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
3757 // re-checking here keeps the predicate usable from any future call
3758 // site (the M4 CR materializer's per-shard-key validator) without
3759 // an empty-check footgun.
3760 if key.is_empty() {
3761 return Err(AplicacaoError::ShardedKeyEmpty);
3762 }
3763 if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
3764 return Err(AplicacaoError::ShardKeyInvalid {
3765 shard_key: key.to_string(),
3766 reason: format!(
3767 "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
3768 (got {} bytes; realistic Akka-style entity-id extractor expressions \
3769 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
3770 well under 32 bytes, this length suggests a paste-from-doc \
3771 multi-line blob landed in `:shard-key` instead of a single-token \
3772 extractor expression)",
3773 key.len()
3774 ),
3775 });
3776 }
3777 for &b in key.as_bytes() {
3778 if (0x21..=0x7E).contains(&b) {
3779 continue;
3780 }
3781 let reason = if b == b' ' {
3782 "contains a space (Akka-style entity-id extractor expressions are \
3783 single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
3784 whitespace breaks the extractor's token boundary at the runtime layer, \
3785 and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
3786 a multi-token blob in one `:shard-key` slot)"
3787 .to_string()
3788 } else if b == b'\t' {
3789 "contains a tab character (paste-from-aligned-doc footgun; the \
3790 Akka-style entity-id extractor reads `:shard-key` as a single-token \
3791 reference, embedded whitespace breaks the token boundary at the \
3792 runtime hash-extractor pass)"
3793 .to_string()
3794 } else if b == b'\n' || b == b'\r' {
3795 format!(
3796 "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
3797 paste-from-multiline-doc footgun; the Akka-style entity-id \
3798 extractor reads `:shard-key` as a single-token reference, embedded \
3799 newlines either truncate the value at the YAML emitter layer or \
3800 break the token boundary at the runtime hash-extractor pass)"
3801 )
3802 } else if b < 0x20 || b == 0x7F {
3803 format!(
3804 "contains control character 0x{b:02x} (the canonical \
3805 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
3806 control characters silently corrupt round-trip serialization \
3807 across YAML emitters and break the runtime hash-extractor's \
3808 single-token parser)"
3809 )
3810 } else {
3811 format!(
3812 "contains non-ASCII byte 0x{b:02x} (the canonical \
3813 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
3814 inconsistently across NFC/NFD normalization on APFS / ext4 / \
3815 across YAML emitter implementations — the same entity ID can \
3816 silently map to two distinct shards on a re-render. Use a \
3817 printable-ASCII extractor expression like `tenantId`, \
3818 `$tenantId`, or `metadata.tenantId`)"
3819 )
3820 };
3821 return Err(AplicacaoError::ShardKeyInvalid {
3822 shard_key: key.to_string(),
3823 reason,
3824 });
3825 }
3826 Ok(())
3827}
3828
3829/// Reject `:contratos :de` / `:contratos :para` values whose shape
3830/// can never legitimately match a validated `:membros :caixa`. Thin
3831/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3832/// shared parser-shaped reason into the
3833/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
3834/// diagnostic is self-locating (which slot — `:de` or `:para` — and
3835/// the offending value verbatim) and the author can grep their
3836/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
3837/// one edit.
3838///
3839/// Until this gate landed an empty or DNS-1123-malformed `:de` /
3840/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
3841/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
3842/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
3843/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
3844/// un-Punycode-encoded IDN) silently passed the per-axis check and
3845/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
3846/// membership lookup — diagnostic-framed as "this caixa is not in
3847/// `:membros`" when the root cause is "this `:de` value is not a
3848/// well-shaped Servico-name identifier and could never legitimately
3849/// match any validated member". Because every `:membros :caixa` is
3850/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
3851/// `names` HashSet structurally never contains an empty / malformed
3852/// string, so the membership lookup arm misframes every empty /
3853/// malformed input. Lifting the shape arm ahead of the lookup
3854/// preserves the legitimate `ContratoMemberMissing` arm (a
3855/// well-shaped `:de` that simply isn't in `:membros` — a phantom
3856/// reference) while routing every structurally-impossible-to-match
3857/// input through the narrower self-locating shape diagnostic.
3858///
3859/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3860/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
3861/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
3862/// to land on the canonical [`crate::render::is_dns_1123_label`]
3863/// floor. The `slot: &'static str` field carries the kebab-case
3864/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
3865/// per-callback-slot diagnostic shape and the
3866/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
3867/// (85f102c) cross-list-tag pattern.
3868fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
3869 // Routes through the shared
3870 // [`crate::render::require_valid_dns_1123_label`] gate the peer
3871 // name axes each land on. The `slot: &'static str` field flows
3872 // through both error variants so the diagnostic names which
3873 // per-edge axis (`:de` vs `:para`) the offending value came from.
3874 crate::render::require_valid_dns_1123_label(
3875 caixa,
3876 || AplicacaoError::ContratoCaixaEmpty { slot },
3877 |reason| AplicacaoError::ContratoCaixaInvalid {
3878 slot,
3879 caixa: caixa.to_string(),
3880 reason,
3881 },
3882 )
3883}
3884
3885/// Reject `:entrada :para` values whose shape can never legitimately
3886/// match a validated `:membros :caixa`. Thin wrapper around
3887/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
3888/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
3889/// variant, so the diagnostic is self-locating (the offending
3890/// `:entrada :para` value is named verbatim) and the author can grep
3891/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
3892///
3893/// Until this gate landed an empty or DNS-1123-malformed `:entrada
3894/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
3895/// ADR typo, `:para "my_cart"` the Python-module-name leak,
3896/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
3897/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
3898/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
3899/// silently passed the per-axis check and surfaced as
3900/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
3901/// — diagnostic-framed as "this caixa is not in `:membros`" when the
3902/// root cause is "this `:entrada :para` value is not a well-shaped
3903/// Servico-name identifier and could never legitimately match any
3904/// validated member". Because every `:membros :caixa` is shape-
3905/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
3906/// `HashSet` structurally never contains an empty / malformed string,
3907/// so the membership lookup arm misframes every empty / malformed
3908/// input. Lifting the shape arm ahead of the lookup preserves the
3909/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
3910/// simply isn't in `:membros` — a phantom reference) while routing
3911/// every structurally-impossible-to-match input through the narrower
3912/// self-locating shape diagnostic.
3913///
3914/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3915/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
3916/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
3917/// fourth and last Aplicacao-level Servico-name reference axis to
3918/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
3919/// No `slot: &'static str` field because there is only one axis
3920/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
3921/// the simpler shape mirrors [`validate_membro_caixa`] and
3922/// [`validate_placement_cluster`].
3923fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
3924 // Empty is gated separately at the call site for a self-locating
3925 // diagnostic; re-checking here keeps the predicate usable from any
3926 // future call site (the M4 CR materializer's per-`:entrada`
3927 // validator) without an empty-check footgun. Routes through the
3928 // shared [`crate::render::require_valid_dns_1123_label`] gate the
3929 // peer name axes each land on.
3930 crate::render::require_valid_dns_1123_label(
3931 para,
3932 || AplicacaoError::EntradaParaEmpty,
3933 |reason| AplicacaoError::EntradaParaInvalid {
3934 para: para.to_string(),
3935 reason,
3936 },
3937 )
3938}
3939
3940/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
3941/// would refuse at admission time. The contract — exactly the regex
3942/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
3943/// and `HTTPRoute.spec.hostnames[]`,
3944/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
3945/// (max length 253; per-label max length 63):
3946///
3947/// - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
3948/// uppercase, no underscore, no Unicode/IDN — IDN must be
3949/// pre-encoded as Punycode `xn--…` by the author);
3950/// - exactly one optional leading wildcard label (`*.`); a wildcard
3951/// in any non-leading label position is rejected;
3952/// - each `.`-separated label is 1..=63 bytes, with non-hyphen
3953/// alphanumeric at both boundaries (no `-foo`, no `foo-`);
3954/// - total length 1..=253 bytes;
3955/// - no IPv4 literal (Gateway API forbids IP literals);
3956/// - no scheme (`https://`, `http://`), no port (`:8080`), no
3957/// whitespace, no path (`/`).
3958///
3959/// Lifted as a typed gate (rather than an inline cascade in
3960/// `validate()`) so the contract lives in one place — every future
3961/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3962/// materializer's host validator, the future per-`:entrada` SAN
3963/// emission for cert-manager Certificates, the multi-`:entrada`
3964/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
3965/// for the same predicate, not its own. Same compounding shape as
3966/// `is_canonical_rate_limit_window` (808017c) and
3967/// [`WitTarget::label`] (previously the free `contrato_target_label`
3968/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
3969/// per-variant label match is compiler-checked-exhaustive).
3970///
3971/// The diagnostic carries the offending `host:` verbatim plus a
3972/// parser-shaped `reason:` naming the specific violation, so the
3973/// author can grep their caixa.lisp for `:host "<host>"` and fix it
3974/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
3975/// (9888b13).
3976fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
3977 // Empty is already gated by `EmptyEntradaHost` at the call site;
3978 // re-checking here keeps the predicate usable from any future
3979 // call site (M4 CR materializer) without an empty-check footgun.
3980 if host.is_empty() {
3981 return Err(AplicacaoError::EmptyEntradaHost);
3982 }
3983 if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
3984 return Err(AplicacaoError::EntradaHostInvalid {
3985 host: host.to_string(),
3986 reason: format!(
3987 "exceeds Gateway API v1 Hostname max length of {cap} bytes \
3988 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
3989 host.len(),
3990 cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
3991 ),
3992 });
3993 }
3994 if host.contains("://") {
3995 return Err(AplicacaoError::EntradaHostInvalid {
3996 host: host.to_string(),
3997 reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
3998 Gateway API takes the bare hostname)"
3999 .to_string(),
4000 });
4001 }
4002 if host.contains('/') {
4003 return Err(AplicacaoError::EntradaHostInvalid {
4004 host: host.to_string(),
4005 reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
4006 matching is in `:entrada :paths`)"
4007 .to_string(),
4008 });
4009 }
4010 // After the `://` scheme-prefix and `/` path arms have ruled out the
4011 // two `:`-bearing shapes the Gateway API actively rejects with
4012 // location-shaped diagnostics, any remaining `:` in the host body is
4013 // either the canonical "I put the port in the `:host` slot"
4014 // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
4015 // slot lives one axis away on the same `:entrada` block) or an
4016 // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
4017 // Hostname forbids identically to the IPv4-literal arm below. Both
4018 // shapes silently fell through the `://` and `/` arms before this
4019 // lift and surfaced as a deep `label "<rest>:<port>" contains
4020 // invalid character ':'` diagnostic from the per-byte loop near the
4021 // bottom of this predicate, which named the offending byte but not
4022 // the canonical authoring fix — for the port case the author has to
4023 // know the `:entrada` block carries a separate `:port u16` slot
4024 // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
4025 // move the value over; for the IPv6 case the author has to know
4026 // Gateway API v1 forbids IP literals across the board. The contract
4027 // doc-comment above already promises "no port (`:8080`)" verbatim
4028 // in the rejected-shape enumeration but the predicate's
4029 // implementation refused the `:` only as a side-effect of the
4030 // per-label `[a-z0-9-]` character-class loop; this arm brings the
4031 // implementation in line with the documented contract by surfacing
4032 // the canonical fix at the top-level shape gate, peer with how the
4033 // `://` arm names the scheme prefix and the `/` arm names the
4034 // `:entrada :paths` axis. Same compounding trajectory the recent
4035 // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
4036 // — the typed slot's rejected set matches the apiserver's rejected
4037 // set, structurally, with a self-locating diagnostic at the
4038 // offending axis instead of a deep parser-shape leak.
4039 if host.contains(':') {
4040 return Err(AplicacaoError::EntradaHostInvalid {
4041 host: host.to_string(),
4042 reason: "must not contain `:` (the port belongs in the `:entrada :port` \
4043 slot — a separate `u16` axis on the same `:entrada` block, \
4044 defaulting to 8080 — not in the host body; drop the `:<port>` \
4045 suffix and author the bare hostname. If you intended an IPv6 \
4046 literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
4047 Hostname forbids IP literals identically to the IPv4-literal \
4048 arm — use a DNS name)"
4049 .to_string(),
4050 });
4051 }
4052 // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
4053 // predicate — the same single source of truth every peer
4054 // ASCII-whitespace scan in caixa-core flows through: the four
4055 // typed-magnitude codec sites (`limits::parse_byte_size` backing
4056 // `:limits :memory`, `limits::parse_duration` backing `:limits
4057 // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
4058 // `aplicacao::rate_limit_codec::parse` backing `:politicas
4059 // :rate-limit`) and the shared duration codec
4060 // (`supervisor::duration_codec::parse`) backing `:supervisor
4061 // :restart-window` / `:politicas :timeout` / `:politicas
4062 // :circuit-breaker :window`. This landing closes the last string-typed
4063 // slot in caixa-core still calling `.bytes().any(|b|
4064 // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
4065 // across every typed slot now shares one predicate, so a future
4066 // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
4067 // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
4068 // deliberately excluded from the peer non-ASCII predicate) can
4069 // extend at this shared site in one edit rather than seven
4070 // independent scans diverging over time. Naming the offending byte
4071 // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
4072 // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
4073 // the offending byte verbatim" discipline every peer codec site
4074 // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4075 // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4076 if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4077 return Err(AplicacaoError::EntradaHostInvalid {
4078 host: host.to_string(),
4079 reason: format!(
4080 "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4081 Hostname is a single-token DNS name — leading, trailing, \
4082 or embedded whitespace breaks the K8s apiserver's Hostname \
4083 regex at admission time; the paste-from-aligned-doc / \
4084 paste-from-shell-history / paste-from-CSV footgun silently \
4085 lands a multi-token blob in `:entrada :host`. Strip every \
4086 whitespace byte and author the bare hostname — space \
4087 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4088 refuse identically)"
4089 ),
4090 });
4091 }
4092 // Peer of the ASCII-whitespace scan above: route the non-ASCII
4093 // subset of Unicode `White_Space` through the shared
4094 // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4095 // single source of truth every peer non-ASCII-whitespace scan in
4096 // caixa-core flows through: `limits::parse_byte_size` (`:limits
4097 // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4098 // `limits::parse_millicores` (`:limits :cpu`),
4099 // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4100 // and `supervisor::duration_codec::parse` (`:supervisor
4101 // :restart-window` / `:politicas :timeout` / `:politicas
4102 // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4103 // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4104 // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4105 // paste-from-web-doc), or an EM-SPACE-split host
4106 // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4107 // survived this predicate's ASCII byte-scan (none of the UTF-8
4108 // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4109 // `u8::is_ascii_whitespace`), then landed on the per-label
4110 // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4111 // predicate with the generic `label "…" must start and end with an
4112 // alphanumeric` diagnostic — a "far from source at build-time"
4113 // leak that names the label-shape violation but not the
4114 // paste-from-typography origin the author actually needs to fix.
4115 // Peer with the four codec sites the 1b75b38 landing pinned: the
4116 // typed slot's diagnostic axis names the offending codepoint
4117 // (`U+XXXX`) verbatim rather than laundering the value through a
4118 // downstream label-shape arm, so the author can grep their
4119 // caixa.lisp for the invisible codepoint at the surfaced position
4120 // rather than eyeball a multi-byte host for embedded NBSP / LINE
4121 // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4122 // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4123 // drift between any two typed-slot sites' non-ASCII-whitespace
4124 // rejection set becomes a single-edit fix at the shared predicate
4125 // rather than N independent inline scans diverging over time, and
4126 // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4127 // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4128 // `char::is_whitespace`" class the peer non-ASCII predicate's
4129 // doc-comment names as the follow-up trajectory) extends at the
4130 // shared predicate in one edit rather than seven.
4131 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4132 return Err(AplicacaoError::EntradaHostInvalid {
4133 host: host.to_string(),
4134 reason: format!(
4135 "contains non-ASCII Unicode whitespace character {ch:?} \
4136 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4137 single-token DNS name limited to `[a-z0-9-]` labels; \
4138 the paste-from-typography footgun silently lands an \
4139 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4140 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4141 `U+3000`, and every other member of the Unicode \
4142 `White_Space` property outside the ASCII byte range) \
4143 in `:entrada :host`, which the K8s apiserver's \
4144 Hostname regex refuses at admission time far from the \
4145 caixa.lisp source line. Strip every non-ASCII \
4146 whitespace character and author the bare hostname \
4147 with only ASCII bytes (write \"checkout.quero.cloud\" \
4148 verbatim)",
4149 codepoint = ch as u32,
4150 ),
4151 });
4152 }
4153
4154 // Strip the optional single leading wildcard label *before* the
4155 // trailing-dot check so the bare `"*."` form surfaces the more
4156 // self-locating "wildcard without domain" diagnostic instead of
4157 // the generic "trailing dot" one.
4158 let (had_wildcard, rest) = match host.strip_prefix("*.") {
4159 Some(r) => (true, r),
4160 None => (false, host),
4161 };
4162 if had_wildcard && rest.is_empty() {
4163 return Err(AplicacaoError::EntradaHostInvalid {
4164 host: host.to_string(),
4165 reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4166 });
4167 }
4168 if rest.contains('*') {
4169 return Err(AplicacaoError::EntradaHostInvalid {
4170 host: host.to_string(),
4171 reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4172 no inner or trailing `*` labels"
4173 .to_string(),
4174 });
4175 }
4176 if rest.ends_with('.') {
4177 return Err(AplicacaoError::EntradaHostInvalid {
4178 host: host.to_string(),
4179 reason: "must not have a trailing `.` (Gateway API hostnames are not \
4180 fully-qualified with a root dot; the apiserver regex rejects \
4181 trailing dots)"
4182 .to_string(),
4183 });
4184 }
4185
4186 // Reject pure IPv4 literals: four dot-separated labels, every
4187 // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4188 // literals as Hostnames.
4189 let labels: Vec<&str> = rest.split('.').collect();
4190 if labels.len() == 4
4191 && labels
4192 .iter()
4193 .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4194 {
4195 return Err(AplicacaoError::EntradaHostInvalid {
4196 host: host.to_string(),
4197 reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4198 literals; use a DNS name)"
4199 .to_string(),
4200 });
4201 }
4202
4203 // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4204 // hyphen, with non-hyphen at both boundaries.
4205 for label in &labels {
4206 if label.is_empty() {
4207 return Err(AplicacaoError::EntradaHostInvalid {
4208 host: host.to_string(),
4209 reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4210 });
4211 }
4212 if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4213 return Err(AplicacaoError::EntradaHostInvalid {
4214 host: host.to_string(),
4215 reason: format!(
4216 "label {label:?} exceeds DNS-1123 label max length of \
4217 {cap} bytes (got {} bytes)",
4218 label.len(),
4219 cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4220 ),
4221 });
4222 }
4223 let bytes = label.as_bytes();
4224 if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4225 return Err(AplicacaoError::EntradaHostInvalid {
4226 host: host.to_string(),
4227 reason: format!(
4228 "label {label:?} must start and end with an alphanumeric \
4229 (no leading or trailing `-`)"
4230 ),
4231 });
4232 }
4233 for &b in bytes {
4234 let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4235 if !valid {
4236 let msg = if b.is_ascii_uppercase() {
4237 format!(
4238 "label {label:?} contains uppercase character {ch:?} \
4239 (Gateway API hostnames are lowercase-only; use {lower:?})",
4240 ch = b as char,
4241 lower = label.to_ascii_lowercase()
4242 )
4243 } else if b == b'_' {
4244 format!(
4245 "label {label:?} contains `_` (Gateway API hostnames \
4246 allow only `[a-z0-9-]`; use `-` instead)"
4247 )
4248 } else {
4249 format!(
4250 "label {label:?} contains invalid character {ch:?} \
4251 (Gateway API hostnames allow only `[a-z0-9-]`)",
4252 ch = b as char
4253 )
4254 };
4255 return Err(AplicacaoError::EntradaHostInvalid {
4256 host: host.to_string(),
4257 reason: msg,
4258 });
4259 }
4260 }
4261 }
4262 Ok(())
4263}
4264
4265/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4266/// would refuse at admission time. Thin wrapper around
4267/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4268/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4269/// variant, preserving the more self-locating
4270/// [`AplicacaoError::EntradaPathEmpty`] /
4271/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4272/// path fails those narrower invariants first.
4273///
4274/// The contract is the canonical HTTP-path grammar — `1..=
4275/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4276/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4277/// whitespace/control/non-ASCII bytes — shared with the
4278/// `:contratos :endpoint` axis through the lifted predicate so drift
4279/// between either landing site and the K8s apiserver-side
4280/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4281/// the predicate, not a per-renderer "this passed validate but failed
4282/// admission" surprise. The diagnostic carries the offending `path:`
4283/// verbatim plus a parser-shaped `reason:` naming the specific
4284/// violation, so the author can grep their caixa.lisp for `:paths`
4285/// and fix it in one edit. Same diagnostic shape as
4286/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4287/// axis.
4288fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4289 // Empty and missing-leading-`/` are already gated at the call
4290 // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4291 // checking here keeps the per-axis narrower diagnostics in force
4292 // when the predicate is reached directly (and `is_gateway_api_http_path`
4293 // itself defends against `bytes[0]`-style indexing on empty
4294 // input).
4295 if path.is_empty() {
4296 return Err(AplicacaoError::EntradaPathEmpty);
4297 }
4298 if !path.starts_with('/') {
4299 return Err(AplicacaoError::EntradaPathNotAbsolute {
4300 path: path.to_string(),
4301 });
4302 }
4303 crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4304 AplicacaoError::EntradaPathInvalid {
4305 path: path.to_string(),
4306 reason,
4307 }
4308 })
4309}
4310
4311mod rate_limit_codec {
4312 // `Duration` is no longer named here — the codec routes through
4313 // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4314 // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4315 // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4316 // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4317 // closed-set enum's arm-table rather than through vestigial free-helper
4318 // delegates.
4319 use super::{RateLimit, RateLimitUnit};
4320 use serde::{Deserialize, Deserializer, Serializer};
4321
4322 pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4323 match v {
4324 Some(rl) => s.serialize_str(&render(*rl)),
4325 None => s.serialize_none(),
4326 }
4327 }
4328
4329 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4330 let opt: Option<String> = Option::deserialize(d)?;
4331 match opt {
4332 None => Ok(None),
4333 Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4334 }
4335 }
4336
4337 fn parse(s: &str) -> Result<RateLimit, String> {
4338 // Whitespace-rejection arm — peer with the leading-`+`
4339 // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4340 // same canonical-form render-determinism axis. Until this gate
4341 // landed the parser silently tolerated leading / trailing /
4342 // internal whitespace via the top-level `s.trim()` and the
4343 // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4344 // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4345 // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4346 // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4347 // serde silently round-tripped to `"100/s"` on the next emit
4348 // (a *different* canonical string) — breaking the THEORY.md
4349 // Part V render-determinism contract on the same
4350 // canonical-form-drift axis the leading-`+` arm below (the
4351 // 4eeae98 predecessor) and the leading-zero arm below (the
4352 // 4f46830 predecessor) already close.
4353 //
4354 // The canonical author shape is `<integer>/<s|m|h>` with no
4355 // whitespace bytes anywhere — every string [`render`] emits
4356 // carries none, so the parser's accepted set must match for
4357 // serialize / deserialize to round-trip losslessly. This gate
4358 // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4359 // `unit.trim()` calls below strict no-ops on the accepted set
4360 // (every byte-position match they would perform is now already
4361 // trimmed away by the accepted set itself), while the arm
4362 // surfaces every rejected whitespace-carrying shape with a
4363 // self-locating diagnostic naming the offending byte and the
4364 // canonical form the author intended, peer with every prior
4365 // canonical-form-drift arm on this codec.
4366 //
4367 // Routed through the lifted
4368 // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4369 // same source of truth the four peer typed-magnitude codec
4370 // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4371 // `limits::parse_millicores`, `supervisor::duration_codec`)
4372 // share. `u8::is_ascii_whitespace()` at the predicate covers
4373 // the five WhatWG-conformant ASCII whitespace bytes (space,
4374 // tab, LF, FF, CR); the "single lifted predicate" discipline
4375 // the peer non-ASCII arm below carries on the strictly-
4376 // complementary Unicode `White_Space` class extends here to
4377 // the ASCII byte set as well.
4378 if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4379 return Err(format!(
4380 "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4381 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4382 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4383 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4384 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4385 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4386 on first serialize — breaking the THEORY.md Part V render-determinism \
4387 contract every typed slot carries. Strip every whitespace byte (write \
4388 `\"100/s\"` verbatim)"
4389 ));
4390 }
4391 // Non-ASCII Unicode `White_Space` arm — the strictly-
4392 // complementary class the ASCII arm above cannot see.
4393 // `str::trim` at the top of every peer codec uses
4394 // `char::is_whitespace` (Unicode `White_Space`, strictly
4395 // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4396 // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4397 // survives the byte-scan (its UTF-8 bytes are not in
4398 // `is_ascii_whitespace`), gets silently stripped by the
4399 // top-level `s.trim()` below, and the value round-trips
4400 // through `render` to a *different* canonical form
4401 // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4402 // render-determinism contract every typed slot carries.
4403 // Closed here (`:politicas :rate-limit`) and at the three
4404 // peer codec sites (`limits::parse_byte_size`,
4405 // `limits::parse_duration`, `supervisor::duration_codec`)
4406 // through the shared
4407 // [`crate::render::find_non_ascii_whitespace_char`] predicate
4408 // — the "single lifted predicate across all four codec sites
4409 // in one follow-up run" the 24a8ad4 commit body's `Forward
4410 // compounding` bullet named as the next compounding step.
4411 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4412 return Err(format!(
4413 "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4414 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4415 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4416 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4417 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4418 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4419 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4420 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4421 silently strips it at parse entry, and the value round-trips through \
4422 `render` to a *different* canonical form (`\"100/s\"`) on first \
4423 serialize — breaking the THEORY.md Part V render-determinism contract \
4424 every typed slot carries. Strip every non-ASCII whitespace character \
4425 (write `\"100/s\"` verbatim with only ASCII bytes)",
4426 cp = ch as u32
4427 ));
4428 }
4429 let s = s.trim();
4430 let (rate_str, unit) = s
4431 .split_once('/')
4432 .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4433 let rate_trim = rate_str.trim();
4434 // The canonical authoring form for `:politicas :rate-limit` is
4435 // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4436 // non-negative integer with no decimal point and no leading
4437 // sign, so the parser's accepted set must match for
4438 // serialize/deserialize to round-trip without canonical-form
4439 // drift. Until this gate landed the parser accepted any
4440 // `u32::from_str`-shaped magnitude — and current Rust
4441 // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4442 // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4443 // serde silently round-tripped to `"100/s"` on the next emit
4444 // (a *different* canonical string) — breaking the THEORY.md
4445 // Part V render-determinism contract on the fifth typed-codec
4446 // surface in caixa-core (peer with the four duration codecs the
4447 // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4448 // already covered: `supervisor::duration_codec` backing three
4449 // typed-duration slots, `limits::parse_duration` backing
4450 // `:limits :wall-clock`, `limits::parse_byte_size` backing
4451 // `:limits :memory`). The fractional / decimal-shaped sibling
4452 // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4453 // existing rejection arm, but the diagnostic is value-laundered
4454 // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4455 // doesn't name the canonical-form remediation or the round-trip
4456 // drift the next emit would produce); this gate lifts the
4457 // fractional arm onto the same canonical-form diagnostic the
4458 // peer codecs carry.
4459 //
4460 // Strict canonical form: every byte of the magnitude is an
4461 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4462 // inputs the gate distinguishes "non-canonical-but-numeric"
4463 // (parses as f64 or i64 — surfaced with a self-locating
4464 // diagnostic naming the canonical authoring form and the
4465 // round-trip drift the rejected shape would produce on first
4466 // serialize) from "garbage" (parses as neither — surfaced with
4467 // the existing narrower `"not a u32"` wording so its
4468 // diagnostic shape remains stable for the parser-shape footgun
4469 // case).
4470 //
4471 // Routed through the lifted
4472 // [`crate::render::is_digit_only_magnitude`] predicate — the
4473 // same source of truth the four peer typed-magnitude codec
4474 // sites share.
4475 let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4476 if !digit_only {
4477 let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4478 if numeric {
4479 return Err(format!(
4480 "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4481 canonical authoring form for `:politicas :rate-limit` is \
4482 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4483 with no decimal point and no leading `+` / `-` sign. A fractional / \
4484 signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4485 through `render` to a *different* canonical form (`\"1/s\"`, \
4486 `\"100/s\"`, parser-reject) on first serialize — breaking the \
4487 THEORY.md Part V render-determinism contract every typed slot \
4488 carries. Pick an integer rate that fits the desired window \
4489 (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4490 ));
4491 }
4492 return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4493 }
4494 // Leading-zero arm — peer with the prior `"+100/s"` arm above
4495 // (4eeae98's predecessor) on the same canonical-form
4496 // render-determinism axis. The digit-only gate accepts
4497 // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4498 // them losslessly (= 100, 0, 7), but `render` emits the
4499 // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4500 // a *different* canonical string on the next emit, breaking
4501 // the THEORY.md Part V render-determinism contract the same
4502 // way `"+100/s"` did before the leading-`+` arm landed. The
4503 // single-byte magnitude `"0"` itself round-trips losslessly
4504 // through `render` (`render(0)` emits `"0/s"`) — the
4505 // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4506 // what refuses rate-zero authoring, so `"0/s"` stays in the
4507 // accepted set at this codec layer and the diagnostic
4508 // partitioning between canonical-form drift (this arm) and
4509 // semantic-zero (the downstream gate) remains stable.
4510 // Peer with the future leading-zero arms on the three peer
4511 // typed-magnitude codecs the trajectory acknowledges:
4512 // `supervisor::duration_codec`, `limits::parse_duration`,
4513 // `limits::parse_byte_size` — each carries the same
4514 // canonical-form-drift class today; this gate lands the
4515 // discipline on the fourth typed-magnitude codec in
4516 // caixa-core first because the peer `"+100/s"` arm above is
4517 // the closest predecessor on the trajectory.
4518 //
4519 // Routed through the lifted
4520 // [`crate::render::is_leading_zero_padded_magnitude`]
4521 // predicate — the same source of truth the four peer
4522 // typed-magnitude codec sites share.
4523 if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4524 return Err(format!(
4525 "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4526 canonical authoring form for `:politicas :rate-limit` is \
4527 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4528 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4529 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4530 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4531 first serialize — breaking the THEORY.md Part V render-determinism \
4532 contract every typed slot carries. Strip the leading zeros (write \
4533 `\"100/s\"` instead of `\"0100/s\"`)"
4534 ));
4535 }
4536 // The digit-only gate guarantees every byte is `[0-9]`, and
4537 // the leading-zero arm above guarantees the magnitude is
4538 // either the single byte `"0"` or starts with `[1-9]`, so
4539 // the only way `u32::from_str` can fail here is overflow
4540 // (the magnitude exceeds `u32::MAX`). Surface that with an
4541 // overflow-shaped wording so the diagnostic names the
4542 // offending magnitude verbatim rather than collapsing onto
4543 // the non-canonical arm. Same shape
4544 // `supervisor::duration_codec` (1c55a2a) carries on the peer
4545 // duration-codec axis.
4546 let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4547 format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4548 })?;
4549 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4550 // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4551 // arm reads the `&str → Duration` projection through the
4552 // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4553 // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4554 // with [`super::RateLimitUnit::window`]) rather than the vestigial
4555 // module-private `rate_limit_window_from_unit` free helper the
4556 // predecessor 61421a6 left as the last unlifted delegate on this
4557 // axis. One typed dispatch on the substrate primitive instead of
4558 // one runtime call through the free-helper delegate; the sole
4559 // production consumer of the `&str → Duration` axis (this parse
4560 // arm) now reaches for exactly one typed method on the closed-set
4561 // enum, sibling to the codec's render arm's
4562 // [`super::RateLimit::canonical_unit`] dispatch on the paired
4563 // `Duration → RateLimitUnit` axis and to the validate gate's
4564 // [`super::RateLimit::canonical_unit`] shape-probe on the
4565 // canonical-window axis. A future rate-limit-unit addition (a
4566 // `"d"` day suffix once Envoy's `rate_limit_action` grows
4567 // daily-bucket support, a `"ms"` sub-second window once
4568 // high-throughput per-edge policies come into scope per
4569 // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4570 // on the closed-set enum, and the compiler enforces exhaustiveness
4571 // on every consumer's `match self` arms — this parse arm's
4572 // accepted-suffix set, the render arm's emitted-suffix set, the
4573 // validate gate's canonical-window set, and every future
4574 // per-`:contratos`-edge rate-limit-override overlay all pick it up
4575 // by construction.
4576 let unit = unit.trim();
4577 let window = RateLimitUnit::window_from_suffix(unit)
4578 .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4579 Ok(RateLimit { rate, window })
4580 }
4581
4582 fn render(rl: RateLimit) -> String {
4583 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4584 // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4585 // this render arm reads the `Duration → RateLimitUnit` projection
4586 // through the substrate primitive [`super::RateLimit::canonical_unit`]
4587 // (returns `None` on every non-canonical window — the sub-second /
4588 // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4589 // formats the returned typed enum through its
4590 // [`std::fmt::Display`] impl (which routes through
4591 // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4592 // the substrate primitive instead of one runtime `find_map`
4593 // walk through the free-helper delegate chain
4594 // [`super::rate_limit_window_unit`] (the vestigial free helper's
4595 // sole production consumer was this arm; every other consumer of
4596 // the `Duration → unit` axis — the validate gate below and the
4597 // future M4 per-Aplicacao Envoy config reconciler — now reads
4598 // the same typed method).
4599 //
4600 // A future rate-limit-unit addition (a `"d"` day suffix once
4601 // Envoy's `rate_limit_action` grows daily-bucket support) is
4602 // one variant + one arm per method on the closed-set enum, and
4603 // the compiler enforces exhaustiveness on every consumer's
4604 // `match self` arms — the codec's `parse` accepted-suffix set,
4605 // this render arm's emitted-suffix set, the validate gate's
4606 // canonical-window set, and every future per-`:contratos`-edge
4607 // rate-limit-override overlay all pick it up by construction.
4608 if let Some(unit) = rl.canonical_unit() {
4609 format!("{}/{unit}", rl.rate())
4610 } else {
4611 // Defensive fallback for non-canonical windows. Note:
4612 // [`AplicacaoSpec::validate_politicas`] rejects any
4613 // non-canonical `:rate-limit :window` via
4614 // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4615 // a validated `RateLimit` never reaches this branch. The
4616 // emitted `<n>/<k>s` form is *not* round-trippable through
4617 // [`parse`] (which accepts only the closed-set
4618 // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4619 // explicit count) — the validate gate is what makes the
4620 // round-trip a structural property; this branch exists only
4621 // so a programmatic non-validated serialize doesn't panic.
4622 format!("{}/{}s", rl.rate(), rl.window().as_secs())
4623 }
4624 }
4625}
4626
4627// ── placement strategy ───────────────────────────────────────────────
4628
4629/// How the Aplicacao distributes across clusters. Three options:
4630///
4631/// - `SingleNode` — one cluster runs the app at a time; takeover on
4632/// death (Erlang/OTP distributed-app semantics).
4633/// - `Replicated` — every named cluster runs an instance (active-active).
4634/// - `Sharded` — entities distribute by hash key across clusters
4635/// (Akka cluster sharding).
4636#[derive(
4637 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4638)]
4639pub enum PlacementStrategy {
4640 SingleNode,
4641 Replicated,
4642 Sharded,
4643}
4644
4645/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
4646/// distribution-strategy default for the `:placement :estrategia` axis —
4647/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
4648/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
4649/// so every substrate-side consumer that resolves "what
4650/// [`PlacementStrategy`] variant does an author-omitted `:placement
4651/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
4652/// primitive [`PlacementStrategy`].
4653///
4654/// The `:placement :estrategia` default axis has three production
4655/// consumers on the substrate side today: the [`Default for
4656/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
4657/// impl's struct-literal `estrategia` field, and the serde-side
4658/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
4659/// author-omitted `:placement :estrategia` scalar through the [`Default
4660/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
4661/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
4662/// impl and implicit `PlacementStrategy::default()` routes at the sibling
4663/// consumers, with no compile-time link back to the paired
4664/// [`crate::manifest::Caixa::aplicacao_view`] fold's
4665/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
4666/// production consumer that resolves an author-omitted `:placement` slot
4667/// (entirely omitted, not just the `:estrategia` scalar within a declared
4668/// `:placement` block) through [`Placement::default`] which then routes
4669/// through this same discriminator. A future coherent rebrand of the
4670/// `:placement :estrategia` default (a widening to `Sharded` once the
4671/// substrate discovers hash-keyed distribution as the more common
4672/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
4673/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
4674/// names, a per-cluster overlay the operator pins through a future
4675/// `:placement-overrides` slot) would have had to migrate a lifted
4676/// discriminator on one path and open-coded discriminators on the peers
4677/// in lockstep or the four consumers would silently drift out of
4678/// pairing. Lifting the resolution rule to a typed `pub const` on the
4679/// substrate primitive means the M3-mesh-canonical `:placement
4680/// :estrategia` default migrates as one unit on any future axis change.
4681///
4682/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
4683/// §II.2's active-active-across-every-named-cluster arm — the closest
4684/// canonical M3 production reference the substrate carries, matching the
4685/// caixa-mesh default axis every M3 renderer already keys off (a
4686/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
4687/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
4688/// under the substrate's fleet-programs aggregator without an explicit
4689/// `:placement :estrategia` override). The two alternatives the closed
4690/// [`PlacementStrategy::ALL`] accept-set carries
4691/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
4692/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
4693/// Akka-style hash-keyed distribution across clusters,
4694/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
4695/// postures an author declares explicitly, never a posture an omitted
4696/// slot should silently assume.
4697///
4698/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
4699/// exactly one source of truth on the `:placement :estrategia` axis, on
4700/// the same substrate-primitive lift discipline the sibling M2
4701/// per-supervisor default set carries
4702/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
4703/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
4704/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
4705/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
4706/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
4707/// ([`crate::render::DEFAULT_NAMESPACE`],
4708/// [`crate::render::DEFAULT_LIBRARY_NAME`],
4709/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
4710/// the M3 mesh-primitive-defining slot family to converge onto the
4711/// substrate-primitive-lift discipline the M2 supervisor-slot family
4712/// already carries end-to-end.
4713pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
4714
4715impl Default for PlacementStrategy {
4716 fn default() -> Self {
4717 // Route the [`Default for PlacementStrategy`] impl through the
4718 // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
4719 // `pub const` rather than a raw `Self::Replicated` arm — one
4720 // source of truth for the M3-mesh-canonical active-active-
4721 // across-every-named-cluster `:placement :estrategia` default
4722 // (MESH-COMPOSITION §II.2), on the same substrate-primitive
4723 // lift discipline the sibling M2 per-supervisor default set
4724 // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
4725 // paired halves) carries end-to-end. Pinned by
4726 // `placement_strategy_default_routes_through_lifted_default`.
4727 PLACEMENT_ESTRATEGIA_DEFAULT
4728 }
4729}
4730
4731impl PlacementStrategy {
4732 /// Exhaustive iteration surface for every consumer that reads the
4733 /// full closed-set (the future M4 admission-webhook's accepted-
4734 /// strategy listing in its rejection body, a future `feira app
4735 /// placement --list` CLI-side surfacing of the accepted arm-set,
4736 /// any future round-trip fuzz harness). A future variant addition
4737 /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
4738 /// names as a trajectory item) extends this slice as a single edit
4739 /// and every consumer picks up the new entry by construction — the
4740 /// compiler-checked exhaustiveness on the sibling method `match`
4741 /// arms is the build-time guarantee that no arm forgets to grow.
4742 /// Same shape as the sibling closed-set typed enums'
4743 /// [`RateLimitUnit::ALL`] (6bce03d) and
4744 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
4745 /// surfaces — the third closed-set typed enum on the caixa surface
4746 /// to converge onto the same discipline.
4747 pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
4748
4749 /// Canonical camelCase-schema discriminator scalar this variant
4750 /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
4751 /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
4752 /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4753 /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
4754 /// every substrate consumer that dispatches on the strategy (the
4755 /// `lareira-fleet-programs` aggregator, the future `app-operator`
4756 /// reconciler, the M3 Adaptive compression pass) reads the same
4757 /// byte-string the `Serialize` derive emits — the pin test in
4758 /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
4759 /// asserts the two paths agree.
4760 #[must_use]
4761 pub const fn as_str(self) -> &'static str {
4762 match self {
4763 Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
4764 Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
4765 Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
4766 }
4767 }
4768
4769 /// Substrate-canonical reverse projection on the `:placement
4770 /// :estrategia` closed-set axis — parses the camelCase-schema
4771 /// discriminator scalar back to the typed variant, or `None` when
4772 /// `s` is outside the closed-set arm-string set [`Self::as_str`]
4773 /// emits. Dispatches on the same lifted
4774 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4775 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4776 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
4777 /// [`Self::as_str`] emitter walks, so the parse and emit halves of
4778 /// the round-trip migrate through one caixa-core edit on any future
4779 /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
4780 /// §II.5 hint names as a trajectory item lands one variant + one
4781 /// arm per method and the compiler enforces exhaustiveness on every
4782 /// consumer's `match self` arms).
4783 ///
4784 /// Prior to this lift the substrate carried only the forward
4785 /// `Self → &str` projection (the [`Self::as_str`] emitter, the
4786 /// [`std::fmt::Display`] impl routed through it, the `Serialize`
4787 /// derive that emits the same byte-string under
4788 /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
4789 /// consumer that wanted to parse a wire-form strategy scalar had to
4790 /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
4791 /// => …, "Sharded" => …, _ => … }` cascade that expressed no
4792 /// compile-time link back to the typed variant's canonical lifted
4793 /// constant. A future variant rename or a per-arm serde-attribute
4794 /// drift would silently split the wire byte-string one non-serde
4795 /// consumer parsed from the one the emitter wrote, with the
4796 /// failure surfacing at parse time far from the rebrand commit.
4797 ///
4798 /// Same closed-set-reverse-projection discipline the sibling
4799 /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
4800 /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
4801 /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
4802 /// defining `:placement :estrategia` closed-set axis, the third
4803 /// substrate-side closed-set typed enum to converge on the two-way
4804 /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
4805 /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
4806 /// and side-step the [`std::str::FromStr`]-collision clippy
4807 /// (`clippy::should_implement_trait`) the plain `from_str` name
4808 /// carries; a future explicit [`std::str::FromStr`] impl can layer
4809 /// on top by delegating to this canonical arm-dispatch method.
4810 ///
4811 /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
4812 /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
4813 /// picks the diagnostic form appropriate for its use site — a
4814 /// future `feira app placement --set` CLI-side arg-parse that wants
4815 /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
4816 /// Sharded)"` diagnostic builds one on top by iterating
4817 /// [`Self::ALL`], while the future M4 admission-webhook's rejection
4818 /// path folds `None` onto its per-CR structured refusal body.
4819 #[must_use]
4820 pub fn from_wire(s: &str) -> Option<Self> {
4821 match s {
4822 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
4823 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
4824 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
4825 _ => None,
4826 }
4827 }
4828
4829 /// Substrate-canonical per-arm predicate naming the cross-slot
4830 /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
4831 /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
4832 /// consumes the paired [`Placement::shard_key`] axis (and therefore
4833 /// requires — and is the only strategy that permits — a non-empty
4834 /// `:shard-key` on the paired slot). Today the accept-set is the
4835 /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
4836 /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
4837 /// per-entity extractor expression; `SingleNode` (Erlang/OTP
4838 /// distributed-app takeover — §II.1) and `Replicated` (active-active
4839 /// across every named cluster) have no hash-keyed routing axis to
4840 /// consume the slot and refuse a declared-but-inert `:shard-key`
4841 /// through [`AplicacaoError::ShardKeyOnNonSharded`].
4842 ///
4843 /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
4844 /// satisfies `placement.shard_key().is_some() ==
4845 /// placement.estrategia().requires_shard_key()` by construction — the
4846 /// cross-slot partition the pin
4847 /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
4848 /// locks load-bearing, so every downstream consumer that reaches for
4849 /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4850 /// CR materializer's per-CR shard-key resolver, the future
4851 /// [`feira app graph --shard-key`] per-Aplicacao column, the future
4852 /// per-cluster Akka-style cluster-sharding reconciler's per-entity
4853 /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
4854 /// shard-key requirement probe, a future author-facing tatara-lisp
4855 /// linter that flags `(:placement (:estrategia Replicated :shard-key
4856 /// "tenantId"))` shapes before `feira lint` reaches
4857 /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
4858 /// the substrate primitive — the predicate names *the cross-slot
4859 /// invariant*, not the arm identity.
4860 ///
4861 /// Prior to this lift the "does this strategy consume `:shard-key`"
4862 /// classification lived under the `gen_platform::IsVariant`-derived
4863 /// [`Self::is_sharded`] predicate at three fixture-builder sites in
4864 /// this crate (the [`tests::placement_strategy_variants_round_trip`]
4865 /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
4866 /// } else { None }` cascade, the
4867 /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
4868 /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
4869 /// "tenantId".to_string())` cascade, and the
4870 /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
4871 /// per-variant spec-mutator's identical `.is_sharded().then(…)`
4872 /// cascade). Each site conflated two semantically distinct questions:
4873 /// "is the variant `Sharded`?" (arm-identity, what
4874 /// [`Self::is_sharded`] answers) and "does the variant consume
4875 /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
4876 /// The two questions land on the same three-way answer under today's
4877 /// closed accept-set (both trip on the singleton `{Sharded}`), but a
4878 /// future arm addition that consumed `:shard-key` under a different
4879 /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
4880 /// §II.5 roadmap-hint names that hash-partitions across the cluster
4881 /// pool by client-IP hash rather than an author-declared extractor
4882 /// expression, a hypothetical `WeightedShard` variant that carries a
4883 /// shard-key + per-cluster weight table under a promoted M5
4884 /// adaptive-placement engine) or an addition that did *not* consume
4885 /// `:shard-key` on a semantically Sharded-shaped arm would silently
4886 /// split the two questions. Any consumer that read
4887 /// `.is_sharded().then(…)` for the shard-key requirement gate would
4888 /// silently misclassify the new arm as non-consuming — a fixture
4889 /// builder would omit `:shard-key` where the new arm required one and
4890 /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
4891 /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
4892 /// commit, a future M4 CR materializer would fall through the
4893 /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
4894 /// silently emit an empty extractor at the Akka reconciler layer.
4895 ///
4896 /// Lifting the classification as a substrate-primitive method on the
4897 /// closed-set typed enum names the cross-slot invariant on the
4898 /// primitive that owns the partition: every future arm addition
4899 /// declares its `:shard-key` consumption in one place (this predicate's
4900 /// `match self` arm-set), and every downstream consumer that reaches
4901 /// for the paired shape reads through one typed dispatch. Same
4902 /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
4903 /// per-arm predicate on the pre-projection WIT-shape axis and the
4904 /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
4905 /// paired predicate on the post-projection typed-view axis — a
4906 /// per-arm semantic-classification predicate paired with the
4907 /// arm-identity predicate the derive already emits, closing the drift
4908 /// footgun on the cross-slot invariant axis.
4909 ///
4910 /// Method-named `requires_shard_key` (not `has_shard_key`, not
4911 /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
4912 /// invariant reads as "this strategy *requires* the paired
4913 /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
4914 /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
4915 /// merely omit it. The `has_*` framing would read as an accessor
4916 /// (returning the presence of an already-carried value) rather than a
4917 /// requirement (naming the invariant the paired slot must satisfy).
4918 /// Returns `bool` (not `Option<()>` or a marker-type witness), same
4919 /// shape as the sibling [`WitContract::is_capability`] /
4920 /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
4921 /// arm-family, so every consumer reaches for `.requires_shard_key()`
4922 /// as a drop-in replacement for the `.is_sharded()` conflated read
4923 /// without a return-shape migration.
4924 #[must_use]
4925 pub const fn requires_shard_key(self) -> bool {
4926 match self {
4927 Self::Sharded => true,
4928 Self::SingleNode | Self::Replicated => false,
4929 }
4930 }
4931}
4932
4933// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
4934// cross-slot-invariant per-arm predicate: the module-scope const-eval
4935// assertions below trip at caixa-core build time (not test time) if a
4936// future edit rewires the predicate's arm-set away from the singleton
4937// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
4938// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
4939// runtime pin covers the same truth-table with a more descriptive
4940// diagnostic on failure; these const-eval items add a build-time failure
4941// surface strictly stronger than the runtime pin (a downstream renderer's
4942// `const`-context reader that composed against a rebound predicate would
4943// still surface here before the test suite even ran) and side-step the
4944// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
4945// would otherwise accumulate on the caixa-core module baseline.
4946const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
4947const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
4948const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
4949
4950/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
4951/// the pretty-printed byte-string every consumer that formats the strategy
4952/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
4953/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
4954/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
4955/// per-Aplicacao strategy line, the future M4 CR materializer's per-
4956/// admission-webhook rejection body) reaches for the same lifted
4957/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4958/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4959/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
4960/// `Serialize` derive already emits under
4961/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
4962/// [`PlacementStrategy::as_str`] helper already returns.
4963///
4964/// Until this lift landed the sibling OTP-shape typed enums —
4965/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
4966/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
4967/// so [`std::fmt::Display`] routes through the same discriminant string
4968/// the wire format emits) — carried a stable [`std::fmt::Display`]
4969/// surface but [`PlacementStrategy`] did not; every consumer reaching
4970/// for a strategy byte-string past the wire format had to pick between
4971/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
4972/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
4973/// derive), any two of which a future variant rename or
4974/// `#[serde(rename_all = "kebab-case")]` attribute would silently
4975/// desynchronize — with the failure surfacing as a downstream renderer /
4976/// operator's per-strategy dispatch reading one spelling while the wire
4977/// format emitted another, far from the source rebrand commit and with
4978/// no field naming the drift. Routing `Display` through
4979/// [`PlacementStrategy::as_str`] makes the three paths
4980/// (`Debug` for structural inspection, `Display` for user-facing text,
4981/// `Serialize` for the wire format) converge on the same lifted
4982/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
4983/// the diagnostic byte-string, and the pretty-printed byte-string move
4984/// as a single unit through one canonical declaration each, by
4985/// construction. Same trajectory as [`PlacementStrategy::as_str`]
4986/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
4987/// closes the third path.
4988///
4989/// Pin tests
4990/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
4991/// and
4992/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
4993/// assert the three paths agree byte-for-byte on every variant, so a
4994/// future variant rename or per-arm serde attribute drift is a build
4995/// error visible at caixa-core test time, not a silent per-consumer
4996/// dispatch miss at apply / reconcile time.
4997impl std::fmt::Display for PlacementStrategy {
4998 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4999 f.write_str(self.as_str())
5000 }
5001}
5002
5003/// Where the Aplicacao runs.
5004#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5005#[serde(rename_all = "camelCase")]
5006pub struct Placement {
5007 /// Distribution strategy.
5008 #[serde(default)]
5009 pub estrategia: PlacementStrategy,
5010
5011 /// Named clusters that host this Aplicacao. Required for
5012 /// `Replicated` and `SingleNode`; for `Sharded` declares the
5013 /// shard pool.
5014 #[serde(default)]
5015 pub clusters: Vec<String>,
5016
5017 /// Optional hint to the placement engine: `"data-locality"`,
5018 /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
5019 #[serde(default, skip_serializing_if = "Option::is_none")]
5020 pub affinity: Option<String>,
5021
5022 /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
5023 #[serde(default, skip_serializing_if = "Option::is_none")]
5024 pub shard_key: Option<String>,
5025}
5026
5027impl Placement {
5028 /// Substrate-canonical per-`:placement` Akka-cluster-sharding
5029 /// `:shard-key` extractor-expression scalar accessor every consumer
5030 /// of the Aplicacao's hash-keyed distribution routing keys off —
5031 /// returns the author-declared `:placement :shard-key` byte-string
5032 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
5033 /// own `Option<String>` storage; `None` when the slot is absent
5034 /// (the canonical shape under `:estrategia Replicated` /
5035 /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
5036 /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
5037 /// partition — `validate` refuses any `Placement` past this call
5038 /// that lands `Some` on a non-`Sharded` strategy or `None` on
5039 /// `Sharded`).
5040 ///
5041 /// The `:placement :shard-key` slot carries the Akka-style
5042 /// cluster-sharding entity-id extractor expression
5043 /// (MESH-COMPOSITION §II.4) — validated by
5044 /// [`validate_placement_shard_key`] to be a non-empty printable-
5045 /// ASCII single-token reference (`tenantId`, `$tenantId`,
5046 /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
5047 /// future M4 Akka-style cluster-sharding reconciler hashes without
5048 /// re-validating at the runtime layer), and every downstream
5049 /// consumer that reads the key keys off this scalar (the
5050 /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
5051 /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5052 /// declared-but-inert refusal diagnostic, the caixa-mesh
5053 /// per-Aplicacao `placement.shardKey` emit path the substrate
5054 /// operator's per-entity hash-routing reader consumes, the future
5055 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5056 /// per-shard-key resolver).
5057 ///
5058 /// Prior to this lift the `.shard_key` field was accessed inline at
5059 /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
5060 /// `Sharded` arm's `match &self.placement.shard_key { None => …,
5061 /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
5062 /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
5063 /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
5064 /// — two open-coded field-accesses that expressed no compile-time
5065 /// link back to the typed slot. A future extension of the
5066 /// `:placement :shard-key` axis to a richer author surface — a
5067 /// per-cluster override the operator pins through a future
5068 /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
5069 /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
5070 /// alias table the M4 CR materializer resolves per-CR, a
5071 /// per-Aplicacao dynamic `:shard-key` derivation the future
5072 /// adaptive placement engine computes from `:affinity` weights —
5073 /// would have had to be threaded through both open-coded copies in
5074 /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
5075 /// arm refusal would silently disagree on which extractor
5076 /// expression a given Placement resolves to. Lifting the resolution
5077 /// rule to a typed method on the substrate primitive means every
5078 /// downstream consumer of the Aplicacao's per-`:placement`
5079 /// hash-key surface reaches for exactly one typed dispatch — the
5080 /// resolver's accept-set migrates as a unit on any future axis
5081 /// addition.
5082 ///
5083 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
5084 /// [`WitContract::destination`] / [`WitContract::world_ref`]
5085 /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
5086 /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
5087 /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
5088 /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
5089 /// typed dispatch on the substrate primitive, thin projections at
5090 /// each consumer" discipline extended onto the per-`:placement`
5091 /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
5092 /// First `Option<&str>`-return accessor on the M3 mesh-slot family
5093 /// — opens the "optional per-slot scalar" projection pattern the
5094 /// sibling per-`:placement` `:affinity`, per-`:politicas`
5095 /// `:rate-limit` future lifts fold on. Named `shard_key()` to
5096 /// match the storage field's name; the accessor's identity name
5097 /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
5098 /// slot's docstring already carries.
5099 #[must_use]
5100 pub fn shard_key(&self) -> Option<&str> {
5101 self.shard_key.as_deref()
5102 }
5103
5104 /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
5105 /// compression-hint scalar accessor every weighting-consumer of the
5106 /// Aplicacao's per-hint routing surface keys off — returns the
5107 /// author-declared `:placement :affinity` byte-string verbatim as
5108 /// an `Option<&str>`, borrowed from the typed slot's own
5109 /// `Option<String>` storage; `None` when the slot is absent (the
5110 /// canonical shape of an Aplicacao that leaves the compression
5111 /// weighting up to the placement engine's cluster-default arm — no
5112 /// author-authored `data-locality` / `low-latency` / etc. hint
5113 /// biases the routing).
5114 ///
5115 /// The `:placement :affinity` slot carries the M3 Adaptive-
5116 /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
5117 /// by [`validate_placement_affinity`] to be a DNS-1123 label
5118 /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
5119 /// K8s-conformant label-selector shape every apiserver-side pod-
5120 /// affinity / node-affinity materializer already gates on
5121 /// admission), and every downstream consumer that reads the hint
5122 /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
5123 /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
5124 /// `placement.affinity` overlay emit path the substrate operator's
5125 /// per-hint weighting-consumer reads, the future M4
5126 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
5127 /// pod-affinity / node-affinity selector resolver).
5128 ///
5129 /// Prior to this lift the `.affinity` field was accessed inline at
5130 /// the sole caixa-core site — the
5131 /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
5132 /// `if let Some(a) = &self.placement.affinity { …
5133 /// validate_placement_affinity(a)? … }` cascade — one open-coded
5134 /// field-access that expressed no compile-time link back to the
5135 /// typed slot. A future extension of the `:placement :affinity`
5136 /// axis to a richer author surface — a per-cluster override the
5137 /// operator pins through a future `:placement :affinity-overrides`
5138 /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
5139 /// tenant hint alias table the M4 CR materializer resolves per-CR,
5140 /// a per-Aplicacao dynamic `:affinity` derivation the future
5141 /// adaptive placement engine computes from `:clusters` topology —
5142 /// would have had to be threaded through the open-coded copy in
5143 /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
5144 /// materializer reader that landed on the axis, or the per-hint
5145 /// value-shape gate and its downstream weighting consumers would
5146 /// silently disagree on which hint a given Placement resolves to.
5147 /// Lifting the resolution rule to a typed method on the substrate
5148 /// primitive means every downstream consumer of the Aplicacao's
5149 /// per-`:placement` compression-hint surface reaches for exactly
5150 /// one typed dispatch — the resolver's accept-set migrates as a
5151 /// unit on any future axis addition.
5152 ///
5153 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
5154 /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5155 /// optional-scalar axis — same "one typed dispatch on the substrate
5156 /// primitive, thin projections at each consumer" discipline extended
5157 /// onto the per-`:placement` M3-Adaptive-compression-hint
5158 /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5159 /// return accessor on the M3 mesh-slot family; closes the last
5160 /// un-lifted per-`:placement` `Option<String>` axis. Named
5161 /// `affinity()` to match the storage field's name; the accessor's
5162 /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5163 /// vocabulary the slot's docstring already carries.
5164 #[must_use]
5165 pub fn affinity(&self) -> Option<&str> {
5166 self.affinity.as_deref()
5167 }
5168
5169 /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5170 /// strategy scalar accessor every consumer that dispatches on the
5171 /// Aplicacao's per-cluster distribution shape keys off — returns the
5172 /// author-declared `:placement :estrategia` variant verbatim as a
5173 /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5174 /// `PlacementStrategy` storage.
5175 ///
5176 /// The `:placement :estrategia` slot carries the closed-set
5177 /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5178 /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5179 /// `Replicated` — active-active across every named cluster; `Sharded`
5180 /// — Akka-style hash-keyed entity distribution across the cluster pool
5181 /// per §II.4) that every downstream consumer of the Aplicacao's
5182 /// per-cluster fan-out shape keys off. Validated by
5183 /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5184 /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5185 /// matches!(estrategia, Sharded)` — the cross-slot partition the
5186 /// [`Placement::shard_key`] accessor's docstring pins), and every
5187 /// downstream consumer that reads the strategy keys off this scalar
5188 /// (the [`AplicacaoSpec::validate_placement`]
5189 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5190 /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5191 /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5192 /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5193 /// declared-but-inert refusal's
5194 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5195 /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5196 /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5197 /// emit path the substrate operator's per-strategy fan-out reader
5198 /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5199 /// materializer's per-strategy admission-webhook resolver).
5200 ///
5201 /// Prior to this lift the `.estrategia` field was accessed inline at
5202 /// four sites — the [`AplicacaoSpec::validate_placement`]
5203 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5204 /// `estrategia: self.placement.estrategia`, the same method's
5205 /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5206 /// partition dispatch, the non-`Sharded`-arm
5207 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5208 /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5209 /// per-Aplicacao strategy print line at
5210 /// `println!("… {} …", spec.placement.estrategia, …)`
5211 /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5212 /// expressed no compile-time link back to the typed slot. A future
5213 /// extension of the `:placement :estrategia` axis to a richer author
5214 /// surface (a per-cluster override the operator pins through a future
5215 /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5216 /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5217 /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5218 /// derivation the future adaptive placement engine computes from
5219 /// `:affinity` + `:clusters` topology) would have had to be threaded
5220 /// through every open-coded copy in lockstep — one consumer reading
5221 /// the raw variant while a peer read the operator-resolved variant
5222 /// would silently split the `PlacementWithoutClusters` /
5223 /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5224 /// partition-dispatch input, a two-consumer split at the validator
5225 /// far from the source `caixa.lisp` with no field naming the
5226 /// strategy-drift root cause. Lifting the resolution rule to a typed
5227 /// method on the substrate primitive means every downstream consumer
5228 /// of the Aplicacao's per-`:placement` distribution-strategy surface
5229 /// reaches for exactly one typed dispatch — the resolver's accept-set
5230 /// migrates as a unit on any future axis addition.
5231 ///
5232 /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5233 /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5234 /// same "one typed dispatch on the substrate primitive, thin
5235 /// projections at each consumer" discipline extended onto the
5236 /// per-`:placement` distribution-strategy `Copy`-composite-enum
5237 /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5238 /// family; first `Copy`-return accessor on the M3 mesh-slot
5239 /// `Placement` type — companion to the sibling per-`:placement`
5240 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5241 /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5242 /// optional-scalar axes, closing the last unlifted per-`:placement`
5243 /// scalar-value axis (the closed-set `PlacementStrategy`
5244 /// distribution-strategy discriminator) so every downstream
5245 /// per-`:placement` reader now routes through a typed dispatch on
5246 /// the substrate primitive. Named `estrategia()` to match the storage
5247 /// field's name; the accessor's identity name maps onto the
5248 /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5249 /// already carries. Declared `pub const fn` (matching the peer M3
5250 /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5251 /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5252 /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5253 /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5254 /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5255 /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5256 /// [`RateLimit`] — every one a `pub const fn`) so every future
5257 /// substrate-side `const`-context consumer of the resolved
5258 /// distribution-strategy variant (a `const _: () = assert!(…)`
5259 /// module-scope invariant pin on a per-fixture typed [`Placement`],
5260 /// a future M4 admission-webhook `const fn` resolver over a typed
5261 /// [`Placement`], any `const fn` composer that fans on the strategy
5262 /// at compile time) reaches through the same typed dispatch on the
5263 /// substrate primitive at const-eval time as at runtime. Pinned by
5264 /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
5265 /// const-eval posture at module scope via `const _:() = …` items so
5266 /// any future accidental downgrade to non-`const` trips at caixa-core
5267 /// build time.
5268 #[must_use]
5269 pub const fn estrategia(&self) -> PlacementStrategy {
5270 self.estrategia
5271 }
5272
5273 /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5274 /// per-cluster distribution-target slice accessor every consumer that
5275 /// walks the Aplicacao's declared cluster-pool keys off — returns the
5276 /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5277 /// `&[String]` slice-view, borrowed from the typed slot's own
5278 /// `Vec<String>` storage (a zero-copy slice-view over the same
5279 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5280 /// through). Non-optional: the empty slice is the load-bearing
5281 /// pre-validation sentinel every downstream consumer of the paired
5282 /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5283 /// off — every strategy in the closed
5284 /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5285 /// requires a non-empty list (`SingleNode` / `Replicated` use the
5286 /// list as hosting / takeover candidates per Erlang/OTP distributed-
5287 /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5288 /// shard pool per Akka cluster-sharding convention, §II.4), so the
5289 /// `.is_empty()` probe is the shared pre-condition every
5290 /// [`AplicacaoSpec::validate_placement`] arm heads on.
5291 ///
5292 /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5293 /// 1123-label per-cluster distribution-target list — the same
5294 /// set-not-multiset shape the sibling `:membros :caixa` /
5295 /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5296 /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5297 /// pins the shape). Every downstream consumer that fans on the list
5298 /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5299 /// pre-flight `.is_empty()` probe that trips
5300 /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5301 /// per-cluster value-shape + duplicate-detection fan-out loop, the
5302 /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5303 /// that materializes the list verbatim onto every
5304 /// programs.yaml entry the substrate operator's per-cluster
5305 /// `placement.clusters | contains .Values.cluster` filter reads,
5306 /// the `feira app graph` per-Aplicacao cluster print line, the
5307 /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5308 /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5309 /// placement engine's cluster-topology reader).
5310 ///
5311 /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5312 /// inline at three production sites — the
5313 /// [`AplicacaoSpec::validate_placement`] pre-flight
5314 /// `self.placement.clusters.is_empty()` refusal probe, the same
5315 /// method's per-cluster validate loop's
5316 /// `for c in &self.placement.clusters` traversal head, and the
5317 /// `feira app graph` per-Aplicacao print line's
5318 /// `spec.placement.clusters` `{:?}` formatter argument
5319 /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5320 /// that expressed no compile-time link back to the typed slot. A
5321 /// future extension of the `:placement :clusters` axis to a richer
5322 /// author surface (a per-tenant cluster-pool overlay the operator
5323 /// pins through a future `:placement :clusters-overrides` slot the
5324 /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5325 /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5326 /// the future M5 adaptive-placement engine computes from
5327 /// `:affinity` weights + live cluster-topology probes, a promotion
5328 /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5329 /// partition once the substrate operator's cluster-membership
5330 /// reconciler comes into typed scope) would have had to be threaded
5331 /// through all three open-coded copies in lockstep or one consumer
5332 /// would silently disagree with the peers on which cluster-pool a
5333 /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5334 /// reading the raw slot while the peer per-cluster validate loop
5335 /// read an operator-resolved slot would silently split the paired
5336 /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5337 /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5338 /// input from the pre-flight input, a three-consumer split at the
5339 /// validator and formatter far from the source `caixa.lisp` with
5340 /// no field naming the cluster-pool-drift root cause. Lifting the
5341 /// resolution rule to a typed method on the substrate primitive
5342 /// means every downstream consumer of the Aplicacao's
5343 /// per-`:placement` cluster-pool surface reaches for exactly one
5344 /// typed dispatch — the resolver's accept-set migrates as a unit
5345 /// on any future axis addition.
5346 ///
5347 /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5348 /// slot — sibling to the seed M2
5349 /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5350 /// slice-return accessor on the peer per-`:supervisor` static-
5351 /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5352 /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5353 /// primitive, thin projections at each consumer" discipline. The
5354 /// three peer `Vec`-carry axes still unlifted at the time of this
5355 /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5356 /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5357 /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5358 /// [`crate::UpgradeFromEntry::instructions`]
5359 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5360 /// — inherit this accessor's discipline as future compounding runs
5361 /// migrate their consumers onto the shared slice-return shape.
5362 /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5363 /// type, sibling to the two `Option<&str>`-return
5364 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5365 /// (74ec2d3) accessors and the `Copy`-return
5366 /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5367 /// unlifted per-`:placement` field axis (the `Vec<String>`
5368 /// distribution-target-list carrier) so every downstream
5369 /// per-`:placement` reader now routes through a typed dispatch on
5370 /// the substrate primitive. Named `clusters()` to match the storage
5371 /// field's name verbatim and the tatara-lisp author-surface term
5372 /// (`:clusters`) the field's own docstring already carries; the
5373 /// accessor's identity maps onto the canonical MESH-COMPOSITION
5374 /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5375 /// for. Returns `&[String]` (not `&Vec<String>`) because every
5376 /// downstream consumer of the cluster list treats it as a read-only
5377 /// sequence — the slice-view is the narrowest borrow that supports
5378 /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5379 /// `.len()`) without leaking the backing `Vec`'s
5380 /// grow/push/reserve surface that no consumer of the typed view
5381 /// reaches for (the storage-side `Vec` remains reachable through
5382 /// the `pub clusters` field for the mutation-carrying serde
5383 /// round-trip and per-test fixture-mutation paths).
5384 #[must_use]
5385 pub fn clusters(&self) -> &[String] {
5386 self.clusters.as_slice()
5387 }
5388}
5389
5390impl Default for Placement {
5391 fn default() -> Self {
5392 Self {
5393 // Route the struct-literal `estrategia` default arm through
5394 // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
5395 // typed `pub const` rather than the transitively-derived
5396 // [`PlacementStrategy::default`] route — one source of truth
5397 // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
5398 // active-active-across-every-named-cluster arm
5399 // (MESH-COMPOSITION §II.2) that both this struct-literal
5400 // altitude and the sibling [`Default for PlacementStrategy`]
5401 // impl already key off through the same substrate primitive.
5402 // Pinned by
5403 // `placement_default_estrategia_routes_through_lifted_default`.
5404 estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
5405 clusters: Vec::new(),
5406 affinity: None,
5407 shard_key: None,
5408 }
5409 }
5410}
5411
5412// ── external entry point ─────────────────────────────────────────────
5413
5414/// External entry point — what an outside caller sees. Renders to a
5415/// Gateway / Ingress + a route to the named member Servico.
5416#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5417#[serde(rename_all = "camelCase")]
5418pub struct Entrada {
5419 /// Public hostname (e.g. `"checkout.quero.cloud"`).
5420 pub host: String,
5421
5422 /// Member Servico the gateway routes to. Must be in `:membros`.
5423 pub para: String,
5424
5425 /// Optional path filter — if set, only matching paths route to
5426 /// this Aplicacao (the rest fall through to other route rules).
5427 #[serde(default)]
5428 pub paths: Vec<String>,
5429
5430 /// Default port on the destination Servico (the trigger.service.port).
5431 #[serde(default = "default_port")]
5432 pub port: u16,
5433}
5434
5435impl Entrada {
5436 /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5437 /// every HTTPRoute-aware renderer keys off — returns the author-
5438 /// declared `:entrada :paths` list verbatim when non-empty, and the
5439 /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5440 /// all fallback otherwise (so an Aplicacao author who declares an
5441 /// external `:entrada` block but no per-path rule surface still
5442 /// gets a route whose sole `HTTPPathMatch` matches every incoming
5443 /// request under the paired
5444 /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5445 ///
5446 /// Prior to this lift the "if `:entrada :paths` is empty use the
5447 /// substrate catch-all; else return each declared path verbatim"
5448 /// cascade lived inline at
5449 /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5450 /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5451 /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5452 /// substrate ships today, with no typed method on the substrate
5453 /// primitive that named the rule. A future path-resolution axis
5454 /// addition — a per-cluster `:entrada :default-path` override the
5455 /// operator pins through a future `:placement`-scoped slot, an
5456 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5457 /// admission-webhook floor that materializes the catch-all before
5458 /// the CR lands, a future per-`:entrada :paths` overlay from a
5459 /// per-cluster policy the future `feira app deploy` pipeline
5460 /// consumes — would have to be threaded through every renderer's
5461 /// inline copy of the cascade in lockstep or one consumer would
5462 /// silently disagree with the peers on which path list a given
5463 /// `:entrada` block resolves to. Lifting the rule to a typed
5464 /// method on the substrate primitive means every downstream
5465 /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5466 /// per-cluster overlay resolver, every future per-Aplicacao
5467 /// snapshot renderer) reaches for exactly one typed dispatch —
5468 /// the resolver's accept-set moves as a unit on any future axis
5469 /// addition.
5470 ///
5471 /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5472 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5473 /// per-`:entrada` scalar-value axes — extends the "one typed
5474 /// dispatch on the substrate primitive, thin projections at each
5475 /// consumer" discipline onto the per-`:entrada` path-list
5476 /// resolution axis every HTTPRoute-aware renderer consumes. Same
5477 /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5478 /// sibling `:politicas` primitive — one typed method on the
5479 /// substrate primitive that names the cascade every renderer
5480 /// otherwise re-inlines.
5481 #[must_use]
5482 pub fn resolved_paths(&self) -> Vec<&str> {
5483 // Route the internal cascade-head + per-entry projection reads
5484 // through the lifted [`Self::paths`] slice accessor rather than
5485 // the raw `self.paths` field access — the substrate-primitive
5486 // per-`:entrada` path-list resolver's two internal reads now
5487 // key off the canonical raw-slot surface every downstream
5488 // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5489 // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5490 // entrada summary line's `{:?}` Debug print) routes through, so
5491 // any future rebrand on the typed slot's raw-slot reader lands
5492 // at exactly one place. Same two-consumer coherence discipline
5493 // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5494 // the peer M3 mesh-slot `Vec<String>`-carry axis.
5495 if self.paths().is_empty() {
5496 vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5497 } else {
5498 self.paths().iter().map(String::as_str).collect()
5499 }
5500 }
5501
5502 /// Substrate-canonical per-`:entrada` DNS-hostname singular
5503 /// accessor every Gateway-API `Listener.hostname` reader keys off
5504 /// — returns the author-declared `:entrada :host` byte-string
5505 /// verbatim as a `&str`, borrowed from the typed slot's own
5506 /// [`String`] storage.
5507 ///
5508 /// Named the "singular" half of the DNS-hostname resolver pair on
5509 /// the substrate primitive: the parent-Gateway per-listener
5510 /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
5511 /// (`Listener.hostname: Option<PreciseHostname>` — at most one
5512 /// hostname per listener), and this accessor is the typed dispatch
5513 /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
5514 /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
5515 /// the per-HTTPRoute `spec.hostnames[]` list axis the same
5516 /// per-Aplicacao ingress-hostname surface projects onto.
5517 ///
5518 /// Prior to this lift the `entrada.host.clone()` byte-string was
5519 /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
5520 /// per-listener singular `hostname:` axis
5521 /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
5522 /// per-HTTPRoute plural `spec.hostnames[]` axis
5523 /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
5524 /// consumers read the same `entrada.host` field but the two-site
5525 /// duplication expressed no compile-time contract that the singular
5526 /// Gateway-listener filter and the plural `HTTPRoute` filter list
5527 /// stay in lockstep on future extensions of the `:entrada` slot to
5528 /// a multi-hostname author surface (an `:entrada :alt-hosts` list
5529 /// overlay, a per-cluster SNI fan-out the operator pins through a
5530 /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
5531 /// Aplicacao` CR materializer's per-listener virtual-host filter
5532 /// admission-webhook overlay). Any such extension would have to be
5533 /// threaded through every renderer's inline copy of the resolution
5534 /// in lockstep or the Gateway listener's `hostname:` filter would
5535 /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
5536 /// — a Gateway-API-conformance divergence whose apply-time symptom
5537 /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
5538 /// `NoMatchingParent` — the API server rejects the route because
5539 /// its `hostnames[]` filter doesn't intersect the parent listener's
5540 /// `hostname` filter) is far from the source `caixa.lisp` and never
5541 /// surfaces in the emitted YAML. Lifting the singular and plural
5542 /// resolvers to typed methods on the substrate primitive means
5543 /// every consumer of the Aplicacao's ingress-hostname surface
5544 /// reaches for exactly one typed dispatch, and the pair-invariant
5545 /// `hostnames() == vec![hostname()]` pinned by the sibling
5546 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
5547 /// keeps the two axes in lockstep by construction.
5548 ///
5549 /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
5550 /// (1449891) path-list resolver on the per-HTTPRoute per-rule
5551 /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
5552 /// the substrate primitive, thin projections at each consumer"
5553 /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5554 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5555 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5556 /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
5557 /// `:entrada` scalar-value + list-value axes.
5558 #[must_use]
5559 pub fn hostname(&self) -> &str {
5560 self.host.as_str()
5561 }
5562
5563 /// Substrate-canonical per-`:entrada` DNS-hostname plural
5564 /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
5565 /// keys off — returns the singleton `[hostname()]` list under
5566 /// today's single-hostname-per-Aplicacao author surface, and the
5567 /// authoritative multi-hostname list under a future
5568 /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
5569 ///
5570 /// Plural half of the DNS-hostname resolver pair — see the
5571 /// companion [`Entrada::hostname`] docstring for the two-consumer
5572 /// lift + pair-invariant discipline (`hostnames() ==
5573 /// vec![hostname()]`, pinned load-bearing by the sibling
5574 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
5575 /// test).
5576 ///
5577 /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
5578 /// per-`:entrada` plural-list resolver on the per-HTTPRoute
5579 /// per-rule path-list axis — same `Vec<&str>` shape, same
5580 /// substrate-primitive-owns-the-resolver discipline extended to
5581 /// the per-HTTPRoute virtual-host filter-list axis.
5582 #[must_use]
5583 pub fn hostnames(&self) -> Vec<&str> {
5584 vec![self.hostname()]
5585 }
5586
5587 /// Substrate-canonical per-`:entrada` destination-Servico scalar
5588 /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
5589 /// the author-declared `:entrada :para` byte-string verbatim as a
5590 /// `&str`, borrowed from the typed slot's own [`String`] storage.
5591 ///
5592 /// The `:entrada :para` slot names the single member Servico the
5593 /// external Gateway routes to (validated by
5594 /// [`AplicacaoSpec::validate`] to be a
5595 /// [`Membro::caixa`] the Aplicacao declares — a stray
5596 /// `:para` that doesn't name a member is
5597 /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
5598 /// backend-attachment miss at cluster-apply time). Under today's
5599 /// single-destination author surface `:entrada :para` is the ingress
5600 /// apex Servico's canonical identity; under a hypothetical
5601 /// future multi-backend author surface (a `:entrada
5602 /// :split :backends` weighted-fan-out overlay for canary /
5603 /// blue-green traffic-split rollouts, per-path override for
5604 /// path-based per-Servico routing beyond the single-apex model,
5605 /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5606 /// per-CR admission-webhook that promotes the scalar to a
5607 /// weighted list) this accessor is the substrate primitive's typed
5608 /// dispatch every downstream `HTTPRoute`-aware consumer routes
5609 /// through, so the resolution shape migrates as a unit on one
5610 /// caixa-core edit rather than a coordinated rewrite across every
5611 /// renderer's inline field-access.
5612 ///
5613 /// Prior to this lift the `entrada.para` byte-string was accessed
5614 /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
5615 /// `metadata.name` composer's per-destination discriminator arg
5616 /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
5617 /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
5618 /// per-HTTPRoute per-rule `backendRefs[0].name` axis
5619 /// (`entrada.para.clone()`,
5620 /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
5621 /// consumers read the same `entrada.para` field but the two-site
5622 /// duplication expressed no compile-time contract that the HTTPRoute
5623 /// name-discriminator and the per-rule backend name stay in
5624 /// lockstep on future extensions of the `:entrada` slot to a
5625 /// multi-destination author surface. Any such extension would have
5626 /// to be threaded through every renderer's inline copy of the
5627 /// destination projection in lockstep or the HTTPRoute
5628 /// `metadata.name` would silently reference a different destination
5629 /// than its own `backendRefs[]` — an operator-side
5630 /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
5631 /// grep-by-name lookup would land on a route whose `backendRefs[]`
5632 /// silently point at a peer Servico, dropping every external
5633 /// `:entrada` flow at the gateway with the destination-drift root
5634 /// cause invisible in the emitted YAML.
5635 ///
5636 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
5637 /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
5638 /// the per-listener singular / per-HTTPRoute plural filter axes and
5639 /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
5640 /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
5641 /// typed dispatch on the substrate primitive, thin projections at
5642 /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5643 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5644 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5645 /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
5646 /// sibling per-`:entrada` scalar-value + list-value axes — this
5647 /// accessor closes the last unlifted per-`:entrada` scalar axis
5648 /// (the destination-Servico byte-string) so every downstream
5649 /// per-`:entrada` reader now routes through a typed dispatch on
5650 /// the substrate primitive.
5651 #[must_use]
5652 pub fn destination(&self) -> &str {
5653 self.para.as_str()
5654 }
5655
5656 /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
5657 /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
5658 /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
5659 /// reader keys off — returns the author-declared `:entrada :port`
5660 /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
5661 /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
5662 /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
5663 /// [`AplicacaoError::EntradaPortZero`], not a silent
5664 /// admission-webhook rejection at cluster-apply time).
5665 ///
5666 /// The `:entrada :port` slot carries the destination Servico's
5667 /// canonical in-cluster L4 listener port (`trigger.service.port` on
5668 /// the `pleme-computeunit` library chart), and every downstream
5669 /// consumer that reads the port keys off this scalar (the
5670 /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
5671 /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
5672 /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
5673 /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5674 /// CR materializer's per-Aplicacao gateway port resolver).
5675 ///
5676 /// Prior to this lift the `.port` field was accessed inline at two
5677 /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
5678 /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
5679 /// the [`AplicacaoSpec::port_for_destination`] resolver's
5680 /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
5681 /// open-coded field-accesses that expressed no compile-time link
5682 /// back to the typed slot. A future extension of the `:entrada :port`
5683 /// axis to a richer author surface — a per-cluster override the
5684 /// operator pins through a future `:placement :default-port` slot the
5685 /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
5686 /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
5687 /// heterogeneous listener ports, an M4
5688 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5689 /// admission-webhook floor that promotes the scalar to a
5690 /// per-destination map — would have had to be threaded through both
5691 /// open-coded copies in lockstep or the structural-floor validator
5692 /// and the [`AplicacaoSpec::port_for_destination`] resolver would
5693 /// silently disagree on which port a given [`Entrada`] resolves to.
5694 /// Lifting the resolution rule to a typed method on the substrate
5695 /// primitive means every downstream consumer of the Aplicacao's
5696 /// per-`:entrada` L4-port surface reaches for exactly one typed
5697 /// dispatch — the resolver's accept-set migrates as a unit on any
5698 /// future axis addition.
5699 ///
5700 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
5701 /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
5702 /// accessors on the per-`:entrada` scalar-value axis — same "one
5703 /// typed dispatch on the substrate primitive, thin projections at
5704 /// each consumer" discipline extended onto the per-`:entrada`
5705 /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
5706 /// the M3 mesh-slot `Entrada` type — closes the last unlifted
5707 /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
5708 /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
5709 /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
5710 /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
5711 /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
5712 /// storage field's name; the accessor's identity name maps onto the
5713 /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
5714 /// already carries. Declared `pub const fn` (matching the peer M3
5715 /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5716 /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5717 /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5718 /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5719 /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5720 /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5721 /// [`RateLimit`], and the sibling per-`:placement`
5722 /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
5723 /// enum scalar axis — every one a `pub const fn`) so every future
5724 /// substrate-side `const`-context consumer of the resolved
5725 /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
5726 /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
5727 /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
5728 /// admission-webhook `const fn` per-CR gateway-port floor over a
5729 /// typed [`Entrada`], any `const fn` composer that fans on the port
5730 /// at compile time) reaches through the same typed dispatch on the
5731 /// substrate primitive at const-eval time as at runtime. Pinned by
5732 /// [`entrada_port_accessor_is_const_fn`] which witnesses the
5733 /// const-eval posture at module scope via `const _:() = …` items so
5734 /// any future accidental downgrade to non-`const` trips at caixa-core
5735 /// build time.
5736 #[must_use]
5737 pub const fn port(&self) -> u16 {
5738 self.port
5739 }
5740
5741 /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
5742 /// slice accessor every HTTPRoute-aware renderer keys off when it
5743 /// wants the raw author-declared path-list (not the fallback-
5744 /// applied projection [`Self::resolved_paths`] returns) — returns
5745 /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
5746 /// borrowed from the typed slot's own [`Vec<String>`] storage.
5747 ///
5748 /// Named the "raw slot" half of the per-`:entrada` path-list resolver
5749 /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
5750 /// (1449891) closes the fallback-applying arm every per-Aplicacao
5751 /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
5752 /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
5753 /// catch-all; non-empty slot → per-entry verbatim projection); this
5754 /// accessor closes the raw-slot arm every consumer that must see the
5755 /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
5756 /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
5757 /// not `Err(EntradaPathEmpty)`, so it cannot route through the
5758 /// fallback-applying sibling; the `feira app graph` per-Aplicacao
5759 /// external-gateway summary line's `{:?}` Debug print — which must
5760 /// name the author's declaration, not the substrate's fallback, so
5761 /// an author reading their graph output can grep their caixa.lisp
5762 /// for the exact list they authored) routes through.
5763 ///
5764 /// Prior to this lift the `.paths` field was accessed inline at four
5765 /// production sites: the two internal reads in [`Self::resolved_paths`]
5766 /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
5767 /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
5768 /// value-shape gate's `for p in &e.paths` traversal head, and the
5769 /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
5770 /// Debug print — four open-coded field-accesses that expressed no
5771 /// compile-time link back to the typed slot. A future extension of
5772 /// the `:entrada :paths` axis to a richer author surface — a
5773 /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
5774 /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
5775 /// spec supports through `matches[].method`), a per-path per-header
5776 /// filter overlay (`matches[].headers[]`), a per-cluster override
5777 /// the operator pins through a future `:placement :path-overlay`
5778 /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5779 /// per-CR admission-webhook that normalized the list at admission
5780 /// time — would have had to be threaded through every open-coded
5781 /// copy in lockstep or the validator's per-entry gate would silently
5782 /// disagree with the renderer's per-entry emit on which list a given
5783 /// `:entrada` block resolves to. Lifting the resolution to a typed
5784 /// method on the substrate primitive means every downstream consumer
5785 /// of the Aplicacao's per-`:entrada` path-list surface reaches for
5786 /// exactly one typed dispatch — the resolver's accept-set migrates
5787 /// as a unit on any future axis addition.
5788 ///
5789 /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
5790 /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
5791 /// carry axis — same "one typed dispatch on the substrate primitive,
5792 /// thin projections at each consumer" discipline extended onto the
5793 /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
5794 /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
5795 /// carrier) so every downstream per-`:entrada` reader now routes
5796 /// through a typed dispatch on the substrate primitive. Returns
5797 /// `&[String]` (not `&Vec<String>`) because every downstream consumer
5798 /// treats the list as a read-only sequence — the slice-view is the
5799 /// narrowest borrow that supports every present + roadmapped consumer
5800 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
5801 /// `Vec`'s grow/push/reserve surface that no consumer of the typed
5802 /// view reaches for (the storage-side `Vec` remains reachable through
5803 /// the `pub paths` field for the mutation-carrying serde round-trip
5804 /// and per-test fixture-mutation paths).
5805 #[must_use]
5806 pub fn paths(&self) -> &[String] {
5807 self.paths.as_slice()
5808 }
5809}
5810
5811/// Canonical default L4 port every typed Servico exposes on its
5812/// in-cluster K8s Service (the `trigger.service.port` axis the
5813/// `pleme-computeunit` library chart emits, the `:entrada :port` author
5814/// surface defaults to when the author omits the slot, and the
5815/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
5816/// `:entrada` block matches the per-`:contratos` destination Servico).
5817/// The single source of truth all three typed-port consumers reach for:
5818///
5819/// - [`Entrada::port`]'s serde default (via the
5820/// [`default_port`] helper this constant feeds); the author surface
5821/// `(:entrada (:host … :para …))` without an explicit `:port` slot
5822/// reads back as a typed [`Entrada`] carrying this exact value;
5823/// - the
5824/// [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
5825/// emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
5826/// fallback, fired when the typed `:entrada` block doesn't name
5827/// the per-`:contratos` destination Servico — the typed
5828/// `:contratos` graph carries no per-destination port axis (the
5829/// destination port is the destination Servico's
5830/// `lareira-<nome>` chart's `trigger.service.port`, which the
5831/// Aplicacao-level renderer has no visibility into without a
5832/// resolver round-trip), so the renderer falls back to the
5833/// substrate's canonical Servico-port assumption — by
5834/// construction the same value the destination's own
5835/// `pleme-computeunit` chart emits, the same value the
5836/// destination's own typed `:entrada :port` slot defaults to;
5837/// - every future per-Servico renderer the absorption-roadmap
5838/// acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5839/// CR materializer's per-edge port resolver, the future
5840/// per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
5841/// emitter's per-route bucket key, the future caixa-otel
5842/// collector-pipeline emitter's per-Servico scrape port).
5843///
5844/// Until this lift landed the value `8080` lived at two production-code
5845/// call-sites: the [`default_port`] helper at
5846/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
5847/// and the `.unwrap_or(8080)` literal at
5848/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
5849/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
5850/// resolver). A future Servico-port rebrand — the substrate moving the
5851/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
5852/// gateway grows direct `:80` listeners, to `8443` once the substrate
5853/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
5854/// override the operator pins through a future
5855/// `:placement :default-port` slot — without a coordinated edit on
5856/// both sides would silently emit Servicos listening on one port and
5857/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
5858/// The CNP's apply-time symptom (the policy is admitted but every L4
5859/// flow on the destination Servico's actual port silently drops because
5860/// it doesn't match the whitelisted port) is far from the rebrand
5861/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
5862/// in hubble traces, not in `kubectl describe`. Lifting the literal to
5863/// a shared constant closes the drift footgun structurally — both
5864/// consumers read from the same `u16`, so any rebrand reaches both
5865/// sites by construction.
5866///
5867/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
5868/// per-renderer canonical-K8s-axis constant — the namespace string
5869/// and the canonical Servico port both lived as duplicated literals
5870/// across caixa-core / caixa-mesh / caixa-flux before their respective
5871/// lifts. Same "the typed constant lives in one place" discipline the
5872/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
5873/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
5874/// shared-string axes.
5875///
5876/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
5877pub const DEFAULT_SERVICO_PORT: u16 = 8080;
5878
5879/// Structural floor for the typed `:entrada :port` axis — every
5880/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
5881/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
5882///
5883/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
5884/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
5885/// interprets as "let the kernel pick a free port at bind time", not a
5886/// well-defined destination the substrate's per-`:entrada` Gateway API
5887/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
5888/// carrying `port: 0` degenerates to a nominal-only routing target: the
5889/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
5890/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
5891/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
5892/// at build time rather than at `kubectl apply` time), and the
5893/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
5894/// (caixa-mesh/src/lib.rs:2657 through
5895/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
5896/// [`Entrada::port`] typed value — silently emits a policy whose
5897/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
5898/// actual listener, dropping every L4 flow at the eBPF data plane far
5899/// from the source caixa.lisp with no field naming the port-zero-drift
5900/// root cause.
5901///
5902/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
5903/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
5904/// on the top edge (unlike the peer capped-`u32` `:politicas` /
5905/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
5906/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
5907/// well below `u32::MAX` and therefore need explicit typed caps).
5908///
5909/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
5910/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
5911/// scalar every `(:entrada (:host … :para …))` slot without an explicit
5912/// `:port` inherits through the serde default hook; this constant names
5913/// the accept-set floor every declared port must satisfy. The pair is
5914/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
5915/// substrate's default must satisfy its own accept-set floor by
5916/// construction) — a future rebrand that accidentally moved
5917/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
5918/// negative-cast typo, a per-cluster override the operator pins through
5919/// a future `:placement :default-port` slot that lands out-of-range)
5920/// would silently invalidate the serde-default emission at every
5921/// author-side `(:entrada (:host … :para …))` slot — the compile-time
5922/// invariant pin
5923/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
5924/// closes the drift footgun at caixa-core build time.
5925///
5926/// Lifted as a typed `pub const` (rather than an inline `0` literal at
5927/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
5928/// has exactly one source of truth — the future M4
5929/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
5930/// gateway resolver, the future per-Servico
5931/// `computeunit.trigger.service.port` renderer's per-CR port-value
5932/// validator, and every downstream test-fixture navigator asserting
5933/// the accept-set floor all read from one place. Same shape every
5934/// other typed bracket-floor / bracket-ceiling in this crate carries
5935/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5936/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
5937/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5938/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
5939/// [`POLICY_RATE_LIMIT_MAX`]).
5940pub const SERVICO_PORT_MIN: u16 = 1;
5941
5942const fn default_port() -> u16 {
5943 DEFAULT_SERVICO_PORT
5944}
5945
5946// ── the typed view ───────────────────────────────────────────────────
5947
5948/// Typed composition view of the flat Aplicacao slots on
5949/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
5950/// validation + downstream renderer consumption.
5951#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5952#[serde(rename_all = "camelCase")]
5953pub struct AplicacaoSpec {
5954 pub membros: Vec<Membro>,
5955 pub contratos: Vec<WitContract>,
5956 pub politicas: MeshPolicy,
5957 pub placement: Placement,
5958 pub entrada: Option<Entrada>,
5959}
5960
5961impl AplicacaoSpec {
5962 /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
5963 /// per-Aplicacao member-list slice-return accessor every
5964 /// per-Aplicacao member-list reader keys off — returns the author-
5965 /// declared `:membros` list verbatim as a `&[Membro]` slice-view
5966 /// over the same backing buffer the raw `self.membros.as_slice()`
5967 /// field access borrows from.
5968 ///
5969 /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
5970 /// member list — the load-bearing identity of the application graph
5971 /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
5972 /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
5973 /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
5974 /// accessor) with a `:versao` semver-requirement string (through
5975 /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
5976 /// and every downstream consumer that fans on the member-set keys
5977 /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
5978 /// membership-lookup `HashSet<&str>` seed's collect input, the
5979 /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
5980 /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
5981 /// per-member DNS-1123 / semver-requirement / duplicate-detection
5982 /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
5983 /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
5984 /// programs.yaml per-`:membros` fan-out emitter's per-entry
5985 /// mapping-composition loop, the `feira app graph` per-Aplicacao
5986 /// member-count print line and per-member tree traversal,
5987 /// every future wasm-operator (M4) per-Aplicacao CR materializer's
5988 /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
5989 /// placement engine's per-member weight-topology reader).
5990 ///
5991 /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
5992 /// inline at six production sites — the [`AplicacaoSpec::validate`]
5993 /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
5994 /// [`AplicacaoSpec::validate_membros`]'s pre-flight
5995 /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
5996 /// probe, the same method's per-member `for m in &self.membros`
5997 /// validate-loop traversal head, the
5998 /// [`AplicacaoSpec::detect_sync_cycles`]'s
5999 /// `for m in &self.membros` adjacency-list seed, the
6000 /// [`caixa_mesh::programs_for_aplicacao`] emitter's
6001 /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
6002 /// paired with the peer `for m in &spec.membros` per-entry fan-out
6003 /// loop, and the `feira app graph` per-Aplicacao print line's
6004 /// `spec.membros.len()` count formatter argument paired with the
6005 /// peer `for m in &spec.membros` per-member tree traversal — six
6006 /// open-coded field-accesses that expressed no compile-time link
6007 /// back to the typed slot. A future extension of the `:membros`
6008 /// axis to a richer author surface (a per-cluster member-set
6009 /// overlay the operator pins through a future
6010 /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
6011 /// roadmap acknowledges, a per-tenant member-alias table the M4
6012 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
6013 /// CR at admission time, a per-Aplicacao dynamic member-set
6014 /// derivation the future adaptive-placement engine computes from
6015 /// weighted membership topology, a promotion of the plain
6016 /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
6017 /// Orleans-style virtual-actor dynamic-membership comes into typed
6018 /// scope) would have had to be threaded through all six open-coded
6019 /// copies in lockstep or one consumer would silently disagree with
6020 /// the peers on which member-set a given Aplicacao resolves to —
6021 /// the `HashSet<&str>` name-set seed reading the raw slot while
6022 /// the peer `.is_empty()` refusal probe read an operator-resolved
6023 /// slot would silently split the `:contratos` membership-lookup
6024 /// input from the pre-flight-refusal input, a six-consumer split
6025 /// at the validator + programs.yaml emitter + graph printer far
6026 /// from the source `caixa.lisp` with no field naming the member-
6027 /// set-drift root cause. Lifting the resolution rule to a typed
6028 /// method on the substrate primitive means every downstream
6029 /// consumer of the Aplicacao's per-`:membros` member-list surface
6030 /// reaches for exactly one typed dispatch — the resolver's accept-
6031 /// set migrates as a unit on any future axis addition.
6032 ///
6033 /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
6034 /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6035 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6036 /// static-child-list `Vec`-carry axis, and to the M3
6037 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6038 /// on the peer per-`:placement` distribution-target-list `Vec`-
6039 /// carry axis. Same "one typed dispatch on the substrate primitive,
6040 /// thin projections at each consumer" discipline. The two peer
6041 /// `Vec`-carry axes still unlifted at the time of this lift —
6042 /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
6043 /// WIT-typed edge list) and
6044 /// [`crate::UpgradeFromEntry::instructions`]
6045 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6046 /// — inherit this accessor's discipline as future compounding runs
6047 /// migrate their consumers onto the shared slice-return shape.
6048 /// First `&[T]`-return accessor on the top-level M3 mesh-slot
6049 /// `AplicacaoSpec` type itself, extending the discipline beyond
6050 /// the inner per-slot types ([`crate::Placement`],
6051 /// [`crate::SupervisorSpec`]) onto the outermost typed composition
6052 /// view every renderer consumes. Named `membros()` to match the
6053 /// storage field's name verbatim and the tatara-lisp author-
6054 /// surface term (`:membros`) the field's own docstring already
6055 /// carries; the accessor's identity maps onto the canonical
6056 /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
6057 /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
6058 /// every downstream consumer of the member list treats it as a
6059 /// read-only sequence — the slice-view is the narrowest borrow
6060 /// that supports every present + roadmapped consumer
6061 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6062 /// backing `Vec`'s grow/push/reserve surface that no consumer of
6063 /// the typed view reaches for (the storage-side `Vec` remains
6064 /// reachable through the `pub membros` field for the mutation-
6065 /// carrying serde round-trip and per-test fixture-mutation paths).
6066 #[must_use]
6067 pub fn membros(&self) -> &[Membro] {
6068 self.membros.as_slice()
6069 }
6070
6071 /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
6072 /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
6073 /// accessor every per-Aplicacao contract-list reader keys off —
6074 /// returns the author-declared `:contratos` list verbatim as a
6075 /// `&[WitContract]` slice-view over the same backing buffer the raw
6076 /// `self.contratos.as_slice()` field access borrows from.
6077 ///
6078 /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
6079 /// WIT-typed edge list — the load-bearing set of directed edges
6080 /// on the application graph whose nodes are the `:membros` entries
6081 /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
6082 /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
6083 /// six-tuple is the edge identity every downstream duplicate gate
6084 /// keys off). Every per-`:contratos` entry pairs a `:de` source-
6085 /// Servico caller name + a `:para` destination-Servico callee name
6086 /// (through the lifted [`WitContract::source`] +
6087 /// [`WitContract::destination`] (7f0fd43) accessor pair on the
6088 /// caller/callee-Servico axis) with a `:wit` world-reference
6089 /// (through the lifted [`WitContract::world_ref`] (0804823)
6090 /// accessor) and the target-shape-appropriate payload-carrier
6091 /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
6092 /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
6093 /// (ed22b66) accessor on the per-target-shape payload-carrier
6094 /// axis). Every downstream consumer that fans on the edge-set
6095 /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
6096 /// name-set / self-edge / target-shape / dedup fan-out loop, the
6097 /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
6098 /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
6099 /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
6100 /// grouping loop, the `feira app graph` per-Aplicacao contract-
6101 /// count print line and per-contract tree traversal, every future
6102 /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
6103 /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
6104 /// mesh-policy overlay resolver's per-contract typed-edge weight
6105 /// reader).
6106 ///
6107 /// Prior to this lift the `.contratos` `Vec<WitContract>` was
6108 /// accessed inline at four production sites — the
6109 /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
6110 /// per-edge validate-loop traversal head (which drives every
6111 /// per-edge name-set membership lookup, self-edge check,
6112 /// target-shape dispatch, and dedup `HashSet` insert), the
6113 /// [`AplicacaoSpec::detect_sync_cycles`]'s
6114 /// `for c in &self.contratos` adjacency-list seed head (which
6115 /// drives every per-edge sync-vs-pub-sub partition and per-edge
6116 /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
6117 /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
6118 /// `BTreeMap` grouping loop head (which drives every per-CNP
6119 /// fan-out emit), and the `feira app graph` per-Aplicacao print
6120 /// line's `spec.contratos.len()` count formatter argument paired
6121 /// with the peer `for c in &spec.contratos` per-contract tree
6122 /// traversal — four open-coded field-accesses that expressed no
6123 /// compile-time link back to the typed slot. A future extension
6124 /// of the `:contratos` axis to a richer author surface (a
6125 /// per-cluster contract overlay the operator pins through a
6126 /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
6127 /// federation roadmap acknowledges, a per-tenant edge-policy
6128 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6129 /// materializer resolves per-CR at admission time, a per-edge
6130 /// weight scalar the future adaptive-placement engine reads to
6131 /// bias sync-subgraph routing, a promotion of the plain
6132 /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
6133 /// once virtual-actor-style dynamic-edge composition comes into
6134 /// typed scope) would have had to be threaded through all four
6135 /// open-coded copies in lockstep or one consumer would silently
6136 /// disagree with the peers on which edge-set a given Aplicacao
6137 /// resolves to — the validator's per-edge dedup `HashSet` seed
6138 /// reading the raw slot while the peer sync-cycle adjacency-list
6139 /// seed read an operator-resolved slot would silently split the
6140 /// build-time edge-set gate from the runtime deadlock-detection
6141 /// gate, a four-consumer split at the validator, the cycle
6142 /// detector, the CNP emitter, and the graph printer far from
6143 /// the source `caixa.lisp` with no field naming the edge-set-
6144 /// drift root cause. Lifting the resolution rule to a typed method on the
6145 /// substrate primitive means every downstream consumer of the
6146 /// Aplicacao's per-`:contratos` edge-list surface reaches for
6147 /// exactly one typed dispatch — the resolver's accept-set
6148 /// migrates as a unit on any future axis addition.
6149 ///
6150 /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
6151 /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6152 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6153 /// static-child-list `Vec`-carry axis, to the M3
6154 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6155 /// on the peer per-`:placement` distribution-target-list `Vec`-
6156 /// carry axis, and to the immediately-adjacent sibling M3
6157 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
6158 /// the peer per-`:membros` node-list `Vec`-carry axis — the
6159 /// per-`:contratos` edge-list accessor is the natural pair of
6160 /// the per-`:membros` node-list accessor (graph edges over graph
6161 /// nodes; every graph-shaped consumer reads both). Same "one
6162 /// typed dispatch on the substrate primitive, thin projections
6163 /// at each consumer" discipline. The last remaining `Vec`-carry
6164 /// axis still unlifted at the time of this lift —
6165 /// [`crate::UpgradeFromEntry::instructions`]
6166 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
6167 /// list) — inherits this accessor's discipline as future
6168 /// compounding runs migrate its consumers onto the shared slice-
6169 /// return shape. Second `&[T]`-return accessor on the top-level
6170 /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
6171 /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
6172 /// `:contratos` are the two `Vec` fields on the outer typed
6173 /// composition view — `:politicas`, `:placement`, `:entrada` are
6174 /// scalar/option-shaped and already route through their per-slot
6175 /// accessor families). Named `contratos()` to match the storage
6176 /// field's name verbatim and the tatara-lisp author-surface term
6177 /// (`:contratos`) the field's own docstring already carries; the
6178 /// accessor's identity maps onto the canonical MESH-COMPOSITION
6179 /// §III.1 vocabulary the slot's docstring already reaches for.
6180 /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
6181 /// every downstream consumer of the contract list treats it as a
6182 /// read-only sequence — the slice-view is the narrowest borrow
6183 /// that supports every present + roadmapped consumer
6184 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6185 /// backing `Vec`'s grow/push/reserve surface that no consumer of
6186 /// the typed view reaches for (the storage-side `Vec` remains
6187 /// reachable through the `pub contratos` field for the mutation-
6188 /// carrying serde round-trip and per-test fixture-mutation paths).
6189 #[must_use]
6190 pub fn contratos(&self) -> &[WitContract] {
6191 self.contratos.as_slice()
6192 }
6193
6194 /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
6195 /// per-Aplicacao mesh-policy composite-reference accessor every
6196 /// per-Aplicacao policy-block reader keys off — returns the author-
6197 /// declared `:politicas` composite verbatim as a `&MeshPolicy`
6198 /// reference over the same backing storage the raw `&self.politicas`
6199 /// field access borrows from.
6200 ///
6201 /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
6202 /// mesh-policy composite — the load-bearing container of every
6203 /// mesh-level operational-policy axis every downstream mesh-artifact
6204 /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6205 /// mesh-policy overlay is the single typed surface a
6206 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6207 /// from). Every per-`:politicas` axis threads through a lifted
6208 /// per-slot accessor on the [`MeshPolicy`] type: the
6209 /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6210 /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6211 /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6212 /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6213 /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6214 /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6215 /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6216 /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6217 /// accessor. Every downstream consumer that reaches for a policy
6218 /// axis first passes through this outer accessor onto the composite
6219 /// and then dispatches onto the per-axis accessor — the two-level
6220 /// dispatch means every per-`:politicas` reader now routes through
6221 /// a typed dispatch on the substrate primitive at both altitudes.
6222 ///
6223 /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6224 /// accessed inline at four production sites — the
6225 /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6226 /// &self.politicas;` traversal seed (which drives every per-axis
6227 /// zero-floor + upper-cap + canonical-form bracket dispatch through
6228 /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6229 /// `p.rate_limit()` on the axis-level lifted accessors), the
6230 /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6231 /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6232 /// chain (which drives every per-`(:de, :para)` CNP
6233 /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6234 /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6235 /// timeout + retry overlay emitter's paired
6236 /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6237 /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6238 /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6239 /// open-coded outer-field accesses that expressed no compile-time
6240 /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6241 /// future extension of the `:politicas` outer axis to a richer
6242 /// author surface (a per-cluster policy overlay the operator pins
6243 /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6244 /// §V federation roadmap acknowledges, a per-tenant policy-alias
6245 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6246 /// resolves per-CR at admission time, a per-Aplicacao dynamic
6247 /// policy-composite derivation the future adaptive-placement engine
6248 /// computes from a per-cluster load-topology reader, a promotion of
6249 /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6250 /// partition once virtual-actor-style dynamic-mesh-policy
6251 /// composition comes into typed scope) would have had to be threaded
6252 /// through all four open-coded copies in lockstep or one consumer
6253 /// would silently disagree with the peers on which mesh-policy
6254 /// composite a given Aplicacao resolves to — the validator's
6255 /// per-axis bracket-dispatch seed reading the raw slot while the
6256 /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6257 /// would silently split the build-time policy-shape gate from the
6258 /// runtime CNP-emission gate, a four-consumer split at the
6259 /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6260 /// the source `caixa.lisp` with no field naming the policy-drift
6261 /// root cause. Lifting the resolution rule to a typed method on the
6262 /// substrate primitive means every downstream consumer of the
6263 /// Aplicacao's per-`:politicas` mesh-policy composite surface
6264 /// reaches for exactly one typed dispatch — the resolver's accept-
6265 /// set migrates as a unit on any future axis addition.
6266 ///
6267 /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6268 /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6269 /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6270 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6271 /// close the two `Vec`-carry axes on the outer typed composition
6272 /// view; the outer `:politicas` composite-reference axis is the
6273 /// natural pair to the paired outer `Vec`-carry accessors on the
6274 /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6275 /// emitter reads all four axes as one unit (graph nodes + graph
6276 /// edges + mesh policy + placement pool). Peer to the same
6277 /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6278 /// slot: every M2 `SupervisorSpec`-scoped composite reader
6279 /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6280 /// `restart_window`, `children`) already routes through the M2
6281 /// `SupervisorSpec` accessor family — this lift extends the same
6282 /// "one typed dispatch on the substrate primitive at the outer
6283 /// composition altitude" discipline to the M3 mesh-slot
6284 /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6285 /// remaining peer outer-composite axes still unlifted at the time
6286 /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6287 /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6288 /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6289 /// inherit this accessor's discipline as future compounding runs
6290 /// migrate their consumers onto the shared reference-return shape.
6291 /// Named `politicas()` to match the storage field's name verbatim
6292 /// and the tatara-lisp author-surface term (`:politicas`) the
6293 /// field's own docstring already carries; the accessor's identity
6294 /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6295 /// slot's docstring already reaches for. Returns `&MeshPolicy`
6296 /// (not the owning composite by copy or clone) because every
6297 /// downstream consumer of the mesh-policy composite treats it as a
6298 /// read-only per-axis dispatch source — the reference-view is the
6299 /// narrowest borrow that supports every present + roadmapped
6300 /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6301 /// emptiness probe) without cloning the composite through every
6302 /// consumer's fast path.
6303 #[must_use]
6304 pub fn politicas(&self) -> &MeshPolicy {
6305 &self.politicas
6306 }
6307
6308 /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6309 /// per-Aplicacao distribution-composite composite-reference accessor
6310 /// every per-Aplicacao placement-block reader keys off — returns the
6311 /// author-declared `:placement` composite verbatim as a `&Placement`
6312 /// reference over the same backing storage the raw `&self.placement`
6313 /// field access borrows from.
6314 ///
6315 /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6316 /// distribution composite — the load-bearing container of every
6317 /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6318 /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6319 /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6320 /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6321 /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6322 /// `:affinity` hint). Every per-`:placement` axis threads through a
6323 /// lifted per-slot accessor on the [`Placement`] type: the
6324 /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6325 /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6326 /// per-cluster distribution-target slice-return accessor, the
6327 /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6328 /// optional-scalar accessor, and the [`Placement::shard_key`]
6329 /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6330 /// downstream consumer that reaches for a placement axis first passes
6331 /// through this outer accessor onto the composite and then dispatches
6332 /// onto the per-axis accessor — the two-level dispatch means every
6333 /// per-`:placement` reader now routes through a typed dispatch on the
6334 /// substrate primitive at both altitudes.
6335 ///
6336 /// Prior to this lift the `.placement` `Placement` composite was
6337 /// accessed inline at three production sites — the
6338 /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6339 /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6340 /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6341 /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6342 /// cluster `.clusters()` validate-loop traversal head, the per-
6343 /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6344 /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6345 /// paired with the shape-gate cascade's `.shard_key()` /
6346 /// `.estrategia()` diagnostic-carry pair), the
6347 /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6348 /// per-entry placement-block emitter's outer
6349 /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6350 /// seed (which fans onto every per-cluster `programs[]` entry as a
6351 /// self-describing distribution overlay the aggregator filters by),
6352 /// and the `feira app graph` per-Aplicacao print line's paired
6353 /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6354 /// then-inner-accessor chains (which drive the human-readable
6355 /// distribution summary of the typed Aplicacao view) — three open-
6356 /// coded outer-field accesses that expressed no compile-time link
6357 /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6358 /// extension of the `:placement` outer axis to a richer author surface
6359 /// (a per-cluster placement overlay the operator pins through a
6360 /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6361 /// federation roadmap acknowledges, a per-tenant placement-alias
6362 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6363 /// resolves per-CR at admission time, a per-Aplicacao dynamic
6364 /// placement-composite derivation the future M5 adaptive-placement
6365 /// engine computes from a per-cluster load-topology reader, a
6366 /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6367 /// partition once Orleans-style virtual-actor dynamic-placement comes
6368 /// into typed scope) would have had to be threaded through all three
6369 /// open-coded copies in lockstep or one consumer would silently
6370 /// disagree with the peers on which placement composite a given
6371 /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6372 /// seed reading the raw slot while the peer
6373 /// `programs_for_aplicacao` emitter read an operator-resolved slot
6374 /// would silently split the build-time distribution-shape gate from
6375 /// the runtime programs.yaml distribution-annotation gate, a three-
6376 /// consumer split at the validator, the programs.yaml emitter, and
6377 /// the `feira app graph` printer far from the source `caixa.lisp`
6378 /// with no field naming the placement-drift root cause. Lifting the
6379 /// resolution rule to a typed method on the substrate primitive
6380 /// means every downstream consumer of the Aplicacao's per-
6381 /// `:placement` distribution composite surface reaches for exactly
6382 /// one typed dispatch — the resolver's accept-set migrates as a unit
6383 /// on any future axis addition.
6384 ///
6385 /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6386 /// `AplicacaoSpec` type itself — sibling to the seed
6387 /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6388 /// composite-reference accessor on the peer per-`:politicas` outer-
6389 /// composite axis, and to the paired slice-return accessors
6390 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6391 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6392 /// the two `Vec`-carry axes on the outer typed composition view; the
6393 /// outer `:placement` composite-reference axis is the natural pair
6394 /// to the peer `:politicas` composite-reference axis on the two
6395 /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6396 /// how-to-run policy overlay, `:placement` carries the where-to-run
6397 /// distribution composite — every whole-Aplicacao mesh-artifact
6398 /// emitter reads both as one unit). Same "one typed dispatch on the
6399 /// substrate primitive, thin projections at each consumer"
6400 /// discipline the peer per-`:politicas` composite-reference axis
6401 /// already routes through. The one remaining outer-composite axis
6402 /// still unlifted at the time of this lift —
6403 /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6404 /// external-gateway composite) — inherits this accessor's discipline
6405 /// as the next compounding run migrates its consumers onto the shared
6406 /// reference-return shape, closing the outer-composite altitude on
6407 /// every M3 mesh-slot axis. Named `placement()` to match the storage
6408 /// field's name verbatim and the tatara-lisp author-surface term
6409 /// (`:placement`) the field's own docstring already carries; the
6410 /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6411 /// vocabulary the slot's docstring already reaches for. Returns
6412 /// `&Placement` (not the owning composite by copy or clone) because
6413 /// every downstream consumer of the placement composite treats it as
6414 /// a read-only per-axis dispatch source — the reference-view is the
6415 /// narrowest borrow that supports every present + roadmapped consumer
6416 /// (per-axis accessor dispatch, serde composite-serialization) without
6417 /// cloning the composite through every consumer's fast path.
6418 #[must_use]
6419 pub fn placement(&self) -> &Placement {
6420 &self.placement
6421 }
6422
6423 /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6424 /// per-Aplicacao external-gateway composite optional-composite-
6425 /// reference accessor every per-Aplicacao gateway-block reader
6426 /// keys off — returns the author-declared `:entrada` composite
6427 /// verbatim as an `Option<&Entrada>` reference over the same
6428 /// backing storage the raw `self.entrada.as_ref()` field access
6429 /// borrows from, with `None` naming the internal-only mesh shape
6430 /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6431 /// gateway_routes emitter treats as "emit nothing" and the peer
6432 /// `feira app graph` printer treats as "internal-only mesh").
6433 ///
6434 /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6435 /// external-gateway composite — the load-bearing container of
6436 /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6437 /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6438 /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6439 /// hostname axis, §III.4 for the `:para` destination-Servico
6440 /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6441 /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6442 /// axis threads through a lifted per-slot accessor on the
6443 /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6444 /// Gateway-API `Listener.hostname` scalar accessor, the paired
6445 /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6446 /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6447 /// backendRefs destination-Servico scalar accessor, the
6448 /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6449 /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6450 /// scalar accessor. Every downstream consumer that reaches for
6451 /// an entrada axis first passes through this outer accessor onto
6452 /// the composite and then dispatches onto the per-axis accessor
6453 /// — the two-level dispatch means every per-`:entrada` reader
6454 /// now routes through a typed dispatch on the substrate primitive
6455 /// at both altitudes.
6456 ///
6457 /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6458 /// was accessed inline at four production sites — the
6459 /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6460 /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6461 /// (which drives every per-axis refusal on the composite: the
6462 /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6463 /// `EntradaMemberMissing` membership lookup against the
6464 /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6465 /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6466 /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6467 /// per-path shape gate on each entry of `e.paths`), the
6468 /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6469 /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6470 /// composite-projection seed (which drives the destination-
6471 /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6472 /// backendRefs port emitter fans on), the
6473 /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6474 /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6475 /// early-return seed (which drives the "no `:entrada` ⇒ no
6476 /// external artifacts" partition on the whole-Aplicacao Gateway-
6477 /// API emitter's fan-out), and the `feira app graph` per-
6478 /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6479 /// external-gateway summary emitter (which drives the human-
6480 /// readable `entrada: host → para (paths=…, port=…)` /
6481 /// `entrada: (internal-only mesh)` partition on the typed
6482 /// Aplicacao view) — four open-coded outer-field accesses that
6483 /// expressed no compile-time link back to the typed slot at the
6484 /// [`AplicacaoSpec`] altitude. A future extension of the
6485 /// `:entrada` outer axis to a richer author surface (a
6486 /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6487 /// at admission time so an Aplicacao can expose a public-web +
6488 /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6489 /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6490 /// operator can pin a per-cluster hostname override without
6491 /// re-authoring the `caixa.lisp`, a promotion of the plain
6492 /// `Option<Entrada>` to a richer `{single, multi}` partition once
6493 /// the multi-`:entrada` roadmap lands) would have had to be
6494 /// threaded through all four open-coded copies in lockstep or one
6495 /// consumer would silently disagree with the peers on which
6496 /// entrada composite a given Aplicacao resolves to — the
6497 /// validator's per-axis bracket-dispatch seed reading the raw
6498 /// slot while the peer `gateway_routes` emitter read an
6499 /// operator-resolved slot would silently split the build-time
6500 /// gateway-shape gate from the runtime Gateway + HTTPRoute
6501 /// emission gate, a four-consumer split at the validator, the
6502 /// `port_for_destination` L4-port resolver, the `gateway_routes`
6503 /// emitter, and the `feira app graph` printer far from the
6504 /// source `caixa.lisp` with no field naming the entrada-drift
6505 /// root cause. Lifting the resolution rule to a typed method on
6506 /// the substrate primitive means every downstream consumer of
6507 /// the Aplicacao's per-`:entrada` external-gateway composite
6508 /// surface reaches for exactly one typed dispatch — the
6509 /// resolver's accept-set migrates as a unit on any future axis
6510 /// addition.
6511 ///
6512 /// Third and final `&Composite`-return accessor on the top-level
6513 /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
6514 /// unlifted outer-composite axis on the outer typed composition
6515 /// view, sibling to the seed [`AplicacaoSpec::politicas`]
6516 /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
6517 /// accessor on the per-`:politicas` outer-composite axis and to
6518 /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
6519 /// distribution-composite composite-reference accessor on the
6520 /// per-`:placement` outer-composite axis; extends the outer-
6521 /// composite reference-return discipline the two peers already
6522 /// route through onto the last unlifted per-`AplicacaoSpec`
6523 /// outer-composite axis. The `:entrada` outer-composite axis is
6524 /// the natural pair to the two peer outer-composite axes on the
6525 /// three operationally-symmetric M3 mesh-slot outer composites
6526 /// (`:politicas` carries the how-to-run policy overlay,
6527 /// `:placement` carries the where-to-run distribution composite,
6528 /// `:entrada` carries the who-can-reach-it external-gateway
6529 /// composite — every whole-Aplicacao mesh-artifact emitter reads
6530 /// all three as one unit). Same "one typed dispatch on the
6531 /// substrate primitive, thin projections at each consumer"
6532 /// discipline the peer outer-composite axes already route through.
6533 /// Named `entrada()` to match the storage field's name verbatim
6534 /// and the tatara-lisp author-surface term (`:entrada`) the
6535 /// field's own docstring already carries; the accessor's
6536 /// identity maps onto the canonical MESH-COMPOSITION §III.4
6537 /// vocabulary the slot's docstring already reaches for. Returns
6538 /// `Option<&Entrada>` (not the owning composite by copy or
6539 /// clone) because every downstream consumer of the entrada
6540 /// composite treats it as a read-only per-axis dispatch source
6541 /// — the reference-view is the narrowest borrow that supports
6542 /// every present + roadmapped consumer (per-axis accessor
6543 /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
6544 /// port-fallback projection, early-return partition on the
6545 /// `None` arm) without cloning the composite through every
6546 /// consumer's fast path. The `Option` half of the return-type
6547 /// preserves the load-bearing "author-omitted `:entrada` ⇒
6548 /// internal-only mesh" partition (not a default composite the
6549 /// downstream must reject on emptiness) — the accessor projects
6550 /// the raw `Option<Entrada>` slot's presence bit through the
6551 /// reference-return unchanged.
6552 #[must_use]
6553 pub fn entrada(&self) -> Option<&Entrada> {
6554 self.entrada.as_ref()
6555 }
6556
6557 /// Validate the typed shape:
6558 /// - `:membros` is non-empty; every entry has a non-empty `:caixa`
6559 /// and a non-empty `:versao`; no two entries share the same
6560 /// `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
6561 /// not a multiset)
6562 /// - every `:contratos` :de + :para must be in `:membros`
6563 /// - no `:contratos` edge is a self-edge (`:de == :para`) — a
6564 /// contract is an inter-Servico edge, so a Servico contracting
6565 /// with itself is a build error under every WIT shape
6566 /// (MESH-COMPOSITION §III.1)
6567 /// - no two `:contratos` entries agree on
6568 /// `(de, para, wit, endpoint, subject, slot)` — the typed-graph
6569 /// edges are a set, not a multiset (peer of the `:membros` /
6570 /// `:placement :clusters` / `:entrada :paths` duplicate gates)
6571 /// - `:entrada :para` must be in `:membros`
6572 /// - `:placement Sharded` must declare `:shard-key` (non-empty);
6573 /// `:placement Replicated`/`SingleNode` must NOT declare
6574 /// `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
6575 /// consumes it (MESH-COMPOSITION §II.4), and the typed partition
6576 /// between strategy and shard-key is symmetric: every validated
6577 /// `Placement` has `shard_key.is_some()` iff `estrategia ==
6578 /// Sharded`
6579 /// - every `:placement` strategy must declare ≥1 `:clusters` entry —
6580 /// `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
6581 /// the shard pool (MESH-COMPOSITION §III.1)
6582 /// - every `:clusters` entry is non-empty and unique
6583 /// - `:placement :affinity`, when set, is non-empty
6584 /// - the synchronous-`:contratos` subgraph is acyclic
6585 /// (MESH-COMPOSITION §III.3)
6586 /// - every declared `:politicas` value is operationally meaningful
6587 /// (zero timeout, zero retries, zero breaker thresholds, zero rate
6588 /// limit are all build errors — MESH-COMPOSITION §V CSE invariants;
6589 /// omit the field instead to express "no policy on this axis")
6590 pub fn validate(&self) -> Result<(), AplicacaoError> {
6591 self.validate_membros()?;
6592 let names: std::collections::HashSet<&str> =
6593 self.membros().iter().map(Membro::nome).collect();
6594
6595 // Identity key for the typed-edge duplicate gate below: every
6596 // field that distinguishes one contract from another. Two
6597 // entries that agree on all six are *the same edge declared
6598 // twice*, the typed-graph analogue of duplicate `:membros` /
6599 // `:placement :clusters` / `:entrada :paths` entries (which
6600 // are already build errors at this layer). Rejecting it at the
6601 // validate gate closes a renderer-side footgun: caixa-mesh's
6602 // `cilium_network_policies` keys each emitted policy by
6603 // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
6604 // (de, para) and identical payload would land as two K8s
6605 // objects with colliding `metadata.name`, rejected at apply
6606 // time far from the source caixa.lisp.
6607 let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
6608 std::collections::HashSet::new();
6609 for c in self.contratos() {
6610 // Per-axis value-shape gate on every `:contratos` name
6611 // reference, before any graph-membership lookup. Empty +
6612 // DNS-1123-malformed `:de`/`:para` values silently fell
6613 // through to `ContratoMemberMissing` at the lookup arm
6614 // because every `:membros :caixa` is shape-validated
6615 // (3f9d7a0), so the `names` set structurally cannot contain
6616 // an empty / malformed string and the membership-lookup
6617 // diagnostic always misframed the root cause as
6618 // "this caixa is not in `:membros`". The shape gate runs
6619 // ahead of the lookup so structurally-impossible-to-match
6620 // inputs route through the narrower self-locating
6621 // diagnostic, preserving the legitimate "well-shaped
6622 // phantom reference" arm. `:de` runs before `:para` per
6623 // the canonical edge-direction order the existing
6624 // membership lookup, self-edge check, target dispatch,
6625 // and diagnostic strings already use.
6626 // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
6627 // + the paired [`AplicacaoError::ContratoMemberMissing`]
6628 // diagnostic's `caixa:` carrier through the lifted
6629 // [`WitContract::source`] / [`WitContract::destination`]
6630 // scalar accessors rather than the raw `&c.de` / `&c.para`
6631 // `&String`-borrow arg site + the raw `c.de.clone()` /
6632 // `c.para.clone()` field-access `String`-carry sites — the
6633 // last unlifted per-`:contratos` raw-field-access sites in
6634 // the M3 mesh-slot validator's per-edge per-arm shape-gate
6635 // arg + phantom-name diagnostic wrap-envelope emit surface.
6636 // `c.source()` is byte-identical to `&c.de` (pinned by the
6637 // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
6638 // + `wit_contract_source_borrows_from_de_storage` accessor
6639 // tests) and `c.destination()` is byte-identical to `&c.para`
6640 // (pinned by the sibling
6641 // `wit_contract_destination_returns_para_byte_equal_across_permutations`
6642 // + `wit_contract_destination_borrows_from_para_storage`
6643 // accessor tests) — so a future rebrand of either underlying
6644 // storage flows through the accessor's one body without a
6645 // coordinated per-consumer rewrite across the M3 mesh
6646 // validator's per-edge shape-gate + phantom-name refusal
6647 // arms. Peer of the sibling per-`:contratos` self-loop
6648 // arm's `.source().to_string()` / `.world_ref().to_string()`
6649 // `String`-carry sites the earlier convergence lifted onto
6650 // the same accessor pair.
6651 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
6652 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
6653 if !names.contains(c.source()) {
6654 return Err(AplicacaoError::ContratoMemberMissing {
6655 caixa: c.source().to_string(),
6656 });
6657 }
6658 if !names.contains(c.destination()) {
6659 return Err(AplicacaoError::ContratoMemberMissing {
6660 caixa: c.destination().to_string(),
6661 });
6662 }
6663 // A `:contratos` entry is an *inter*-Servico contract
6664 // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
6665 // typed edge between two distinct graph nodes. An edge whose
6666 // `:de` equals its `:para` is a Servico contracting with
6667 // itself — a degenerate edge under every WIT shape. The
6668 // synchronous shapes were caught only incidentally, and with
6669 // a misleading diagnostic: `detect_sync_cycles` reported
6670 // `cart → cart` as a `ContratoCycle` whose path is
6671 // `["cart", "cart"]` — framing a self-edge as a multi-node
6672 // deadlock. The pub-sub shape slipped through entirely
6673 // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
6674 // `nats:pub-sub` edge from a member to itself silently
6675 // validated, then rendered a `CiliumNetworkPolicy` whose
6676 // endpointSelector and fromEndpoints both name the same
6677 // program — a self-allow rule that is a no-op, since
6678 // intra-pod traffic never traverses the mesh). A self-edge's
6679 // runtime meaning is an in-process call, which doesn't go
6680 // through the mesh at all, so no `:contratos` edge can carry
6681 // it. Firing the gate before the `:wit`/`target()` shape
6682 // checks means the structural "this edge can't exist" error
6683 // precedes the narrower payload-shape diagnostics, and shape-
6684 // agnostically covers all four `WitTarget` arms (HTTP / Store
6685 // / Capability / PubSub) at one point — closing the pub-sub
6686 // hole and replacing the misleading cycle diagnostic in one
6687 // gate. Peer of the duplicate-`:contratos` / duplicate-
6688 // `:membros` set gates: both reject a structurally
6689 // ill-formed graph at the typed surface, before the renderer
6690 // emits a K8s object that fails or no-ops far from the source
6691 // caixa.lisp.
6692 // Route the per-`:contratos` structural self-edge probe
6693 // through the lifted [`WitContract::is_self_loop`] typed
6694 // predicate rather than the raw `c.de == c.para` field-
6695 // equality check — the one production consumer of the per-
6696 // `:contratos` caller-equals-callee endpoint-equality axis
6697 // now keys off exactly one typed dispatch on the substrate
6698 // primitive, so any future rebrand of the axis (an M4-typed-
6699 // caller enum whose identity comparison rule the predicate
6700 // could route through, a per-cluster caller/callee-alias
6701 // table the M4 CR materializer resolves per-CR before the
6702 // equality probe) migrates as a single caixa-core edit
6703 // rather than a coordinated rewrite of the gate + every
6704 // downstream self-edge consumer. Peer of the sibling
6705 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
6706 // [`WitContract::is_store`] shape-predicate routing on the
6707 // `:wit` world-ref axis, extended onto the per-edge
6708 // endpoint-equality axis.
6709 //
6710 // Route the paired [`AplicacaoError::ContratoSelfLoop`]
6711 // diagnostic's `caixa:` / `wit:` carriers through the
6712 // lifted [`WitContract::source`] / [`WitContract::world_ref`]
6713 // scalar accessors rather than the raw `c.de.clone()` /
6714 // `c.wit.clone()` field-access `String`-carry sites — the
6715 // last unlifted per-`:contratos` raw-field-access
6716 // `.clone()` sites in the M3 mesh-slot validator's self-
6717 // edge refusal arm. `.source().to_string()` is byte-
6718 // identical to `.de.clone()` (pinned by the sibling
6719 // `source_returns_de_byte_equal_across_permutations` accessor
6720 // test), and `.world_ref().to_string()` is byte-identical
6721 // to `.wit.clone()` (pinned by the sibling
6722 // `world_ref_returns_wit_byte_equal_across_permutations`
6723 // accessor test) — so a future rebrand of either underlying
6724 // storage flows through the accessor's one body without a
6725 // coordinated per-consumer rewrite across the M3 mesh
6726 // validator.
6727 if c.is_self_loop() {
6728 return Err(AplicacaoError::ContratoSelfLoop {
6729 caixa: c.source().to_string(),
6730 wit: c.world_ref().to_string(),
6731 });
6732 }
6733 if c.world_ref().is_empty() {
6734 let (de, para) = c.edge_pair();
6735 return Err(AplicacaoError::EmptyWit { de, para });
6736 }
6737 // Shape ↔ target consistency — surfaces "HTTP wit without
6738 // :endpoint", "NATS wit with :endpoint set", etc. as named
6739 // build errors instead of silent renderer drops. Threaded
6740 // through the duplicate-edge diagnostic below (via
6741 // [`WitTarget::label`]) so the "which typed target arm did
6742 // the duplicate carry" question is answered by the typed
6743 // enum's variant discriminator, not by re-probing the raw
6744 // `Option<String>` payload fields.
6745 let target_view = c.target()?;
6746 // Contract identity: (de, para, wit, endpoint, subject, slot).
6747 // Two contracts that match on all six are the same typed edge
6748 // declared twice — author error, not a legitimate variant of
6749 // "same caller-callee pair, different payload" (e.g.
6750 // cart→catalog at /products vs /search), which keeps distinct
6751 // identity keys via the differing endpoint payloads.
6752 //
6753 // Route the six-axis dedup key through the lifted
6754 // [`WitContract::identity`] composite-projection accessor
6755 // rather than the inline six-tuple builder — the two
6756 // substrate primitives on the per-`:contratos` identity axis
6757 // (the [`ContratoIdentity`] type alias's six axes, this
6758 // dedup-key's six tuple arms) now migrate as a unit on any
6759 // future axis addition. Peer of the sibling per-`:contratos`
6760 // composite-projection [`WitContract::edge_pair`] /
6761 // [`WitContract::edge_triple`] accessors on the
6762 // caller-callee / caller-callee-wit prefix axes; extends
6763 // the discipline onto the full-identity axis that carries
6764 // the three payload-shape arms too.
6765 let key = c.identity();
6766 crate::render::insert_first_seen(&mut seen_contracts, key, || {
6767 // Route the per-`:contratos` duplicate-gate diagnostic's
6768 // `(de, para, wit)` triple through the lifted
6769 // [`WitContract::edge_triple`] typed accessor rather
6770 // than pairing `edge_pair()` for the `(de, para)` prefix
6771 // with a raw `c.wit.clone()` for the `wit:` tail — the
6772 // paired-with-raw-field-access shape was the last
6773 // per-`:contratos` diagnostic constructor bypassing the
6774 // substrate-primitive composite projection, sibling to
6775 // the eight [`AplicacaoError::Contrato*`] triple-
6776 // carrying constructors [`WitContract::target`]'s edge
6777 // closure feeds through the same accessor.
6778 let (de, para, wit) = c.edge_triple();
6779 AplicacaoError::ContratoDuplicate {
6780 de,
6781 para,
6782 wit,
6783 target: target_view.label(),
6784 }
6785 })?;
6786 }
6787
6788 // Cycles in the synchronous-edge subgraph are build errors
6789 // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
6790 // are "acyclic by construction" because the publisher fires
6791 // and forgets, so no caller blocks on a downstream that loops
6792 // back to it.
6793 self.detect_sync_cycles()?;
6794
6795 if let Some(e) = self.entrada() {
6796 // Route the per-`:entrada` composite-reference read
6797 // through the lifted [`AplicacaoSpec::entrada`] accessor
6798 // rather than the raw `&self.entrada` field access — the
6799 // shape-and-membership gate's traversal head is now the
6800 // canonical read-side surface every per-Aplicacao entrada
6801 // consumer routes through, closing the fourth of four
6802 // open-coded outer-field accesses on the per-`:entrada`
6803 // outer-composite axis.
6804 //
6805 // Shape gate on `:entrada :para` runs ahead of the
6806 // membership lookup. Every `:membros :caixa` past
6807 // `validate_membro_caixa` is a valid DNS-1123 label
6808 // (3f9d7a0), so the `names` set structurally cannot
6809 // contain an empty / malformed string and the membership-
6810 // lookup diagnostic always misframed the root cause as
6811 // "this caixa is not in `:membros`". The shape gate
6812 // routes structurally-impossible-to-match inputs through
6813 // the narrower self-locating diagnostic, preserving the
6814 // legitimate "well-shaped phantom reference" arm — the
6815 // same trajectory the peer `:membros :caixa` (3f9d7a0),
6816 // `:placement :clusters` (6c8c00b), and `:contratos :de`
6817 // / `:para` (8d5af6b) axes already follow. This closes
6818 // the fourth and last Aplicacao-level Servico-name
6819 // reference axis on the canonical DNS-1123 floor.
6820 // Route the per-`:entrada :para` byte-string reads through
6821 // the lifted [`Entrada::destination`] accessor rather than
6822 // the raw `e.para` field access — the three
6823 // per-`AplicacaoSpec::validate` `:entrada :para` consumers
6824 // (shape-gate `validate_entrada_para` arg, membership
6825 // lookup, `EntradaMemberMissing` diagnostic carry) now key
6826 // off exactly one typed dispatch on the substrate
6827 // primitive, closing the last unlifted per-`:entrada :para`
6828 // raw-field-access axis on the M3 mesh-slot validator.
6829 // The `.destination().to_string()` at the diagnostic site
6830 // is byte-identical to `.para.clone()` — pinned by the
6831 // sibling `destination_returns_entrada_para_byte_equal` +
6832 // `destination_borrows_from_entrada_para_storage` accessor
6833 // tests — so a future rebrand of the underlying `:para`
6834 // storage (a lift from `String` to a typed
6835 // `ServicoName(String)` newtype, a per-Aplicacao interning
6836 // arena the M4 CR materializer authors, a
6837 // `smol_str::SmolStr` inline-buffer swap) flows through
6838 // the accessor's one body without a coordinated
6839 // per-consumer rewrite across the M3 mesh validator.
6840 validate_entrada_para(e.destination())?;
6841 if !names.contains(e.destination()) {
6842 return Err(AplicacaoError::EntradaMemberMissing {
6843 para: e.destination().to_string(),
6844 });
6845 }
6846 // Route the per-`:entrada :host` byte-string reads through
6847 // the lifted [`Entrada::hostname`] accessor rather than
6848 // the raw `e.host` field access — the emptiness gate and
6849 // the shape-gate `validate_entrada_host` arg now key off
6850 // exactly one typed dispatch on the substrate primitive,
6851 // closing the last unlifted per-`:entrada :host` raw-
6852 // field-access axis on the M3 mesh-slot validator. Peer
6853 // of the sibling per-`:entrada :para` convergence above
6854 // and pinned by the existing
6855 // `hostname_returns_entrada_host_byte_equal` +
6856 // `hostnames_returns_singleton_of_hostname_accessor`
6857 // accessor tests, so any future
6858 // Gateway-API-shaped host renormalization (a wildcard-
6859 // label lift, a trailing-`.` FQDN substitution, an IDNA
6860 // Punycode round-trip the SNI fan-out overlay authors)
6861 // flows through the accessor's one body without a
6862 // coordinated per-consumer rewrite across the M3 mesh
6863 // validator.
6864 if e.hostname().is_empty() {
6865 return Err(AplicacaoError::EmptyEntradaHost);
6866 }
6867 // The `:host` lands verbatim as a K8s Gateway API v1
6868 // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
6869 // both apiserver-validated against the same restrictive
6870 // pattern: lowercase RFC 1123 DNS subdomain, optional
6871 // single leading wildcard label (`*.`), max length 253,
6872 // per-label max length 63, no IP literals, no scheme,
6873 // no port. Until this gate landed `validate()` only
6874 // refused the empty string (`EmptyEntradaHost`); a
6875 // structurally invalid hostname (`"https://example.com"`,
6876 // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
6877 // `"_underscored.example.com"`, `"FOO.example.com"`,
6878 // `"checkout.quero.cloud."`) silently passed validate
6879 // and the apiserver `field is invalid` error surfaced at
6880 // `kubectl apply` time, far from the source caixa.lisp.
6881 // Lifting the gate to caixa-build time mirrors the
6882 // `:entrada :paths` value-shape trajectory (eb3456d) and
6883 // closes the last unstructured `:entrada` axis.
6884 validate_entrada_host(e.hostname())?;
6885 // Structural-floor gate on `:entrada :port`: every
6886 // validated `Entrada::port` past this gate lies in
6887 // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
6888 // type-inferred ceiling closes the top edge, so no companion
6889 // upper-cap arm is needed here — unlike the peer capped-
6890 // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
6891 // `require_positive_bounded_u32` bracket covers both edges).
6892 // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
6893 // accept-set-floor const rather than the prior inline
6894 // `if e.port == 0` byte-check so a future rebrand of the
6895 // accept-set floor (a hypothetical unprivileged-only
6896 // migration lifting the floor to `1024`, a per-cluster
6897 // scoping the operator pins through a future
6898 // `:placement :port-floor` slot as the M4 typed-slot
6899 // trajectory adds it, the future
6900 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6901 // per-Aplicacao gateway resolver reaching for the same
6902 // floor) is a one-line edit on the canonical
6903 // [`SERVICO_PORT_MIN`] declaration, not a coordinated
6904 // rewrite across the emit site + the pin test + every
6905 // future per-target renderer the substrate adds.
6906 if e.port() < SERVICO_PORT_MIN {
6907 return Err(AplicacaoError::EntradaPortZero);
6908 }
6909 // Each `:entrada :paths` entry becomes a K8s Gateway API
6910 // HTTPRoute `matches[].path.value`. The Gateway API rejects
6911 // values that don't start with `/` for `type: PathPrefix`,
6912 // and an empty value is meaningless. Surface those as build
6913 // errors (MESH-COMPOSITION §III.3) rather than apply-time
6914 // failures. Empty `:paths` itself is fine — caixa-mesh
6915 // falls back to a single `/` catch-all.
6916 let mut seen = std::collections::HashSet::new();
6917 // Route the per-entry value-shape gate's traversal head
6918 // through the lifted [`Entrada::paths`] slice accessor
6919 // rather than the raw `&e.paths` field access — the
6920 // per-Aplicacao `:entrada :paths` validate loop now keys
6921 // off the canonical raw-slot surface every downstream
6922 // per-`:entrada` path-list consumer (the sibling
6923 // [`Entrada::resolved_paths`] fallback-applying resolver
6924 // internal reads, `feira app graph`'s per-Aplicacao entrada
6925 // summary line's `{:?}` Debug print) routes through, so any
6926 // future rebrand on the typed slot's raw-slot reader lands
6927 // at exactly one place. Same convergence discipline as the
6928 // sibling [`Placement::clusters`] (a6e18d7) reader-site
6929 // convergences on the peer M3 mesh-slot `Vec<String>`-carry
6930 // axis.
6931 for p in e.paths() {
6932 if p.is_empty() {
6933 return Err(AplicacaoError::EntradaPathEmpty);
6934 }
6935 if !p.starts_with('/') {
6936 return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
6937 }
6938 // Per-entry value-shape gate: the path lands verbatim
6939 // as a K8s Gateway API HTTPRoute `matches[].path.value`
6940 // (caixa-mesh/src/lib.rs:498), apiserver-validated
6941 // against `maxLength: 1024` + the Gateway API webhook's
6942 // path-grammar rules (no `//`, no `/./`, no `/../`, no
6943 // query/fragment separators, no whitespace, no control
6944 // characters, no non-ASCII bytes). Until this gate
6945 // landed `validate` only refused the empty string and
6946 // missing-leading-slash (eb3456d); a structurally
6947 // invalid path (`"/api?q=1"`, `"/api#frag"`,
6948 // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
6949 // 1025-byte URL-shaped slug) silently passed validate
6950 // and the failure surfaced at `kubectl apply` time as
6951 // a Gateway API webhook rejection, far from the source
6952 // caixa.lisp, with no field naming the offending
6953 // `:paths` entry. Lifting the gate to caixa-build time
6954 // mirrors the `:entrada :host` value-shape trajectory
6955 // (c7d05ec) on the sibling axis — every author surface
6956 // that emits a Gateway API field now matches the
6957 // apiserver's accepted set at validate time.
6958 validate_entrada_path(p)?;
6959 crate::render::insert_first_seen(&mut seen, p.as_str(), || {
6960 AplicacaoError::EntradaPathDuplicate { path: p.clone() }
6961 })?;
6962 }
6963 }
6964
6965 self.validate_placement()?;
6966
6967 self.validate_politicas()?;
6968
6969 Ok(())
6970 }
6971
6972 /// Reject `:membros` values that are operationally meaningless. The
6973 /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
6974 /// every entry names a Servico that participates in the Aplicacao,
6975 /// and the rendered programs.yaml fan-out emits one entry per
6976 /// `:membros`. Three authoring footguns are closed here:
6977 ///
6978 /// - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
6979 /// a `programs:` entry whose `name:` is the empty string, which
6980 /// downstream `lareira-fleet-programs` rejects at template time
6981 /// with a non-localized error;
6982 /// - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
6983 /// an empty semver constraint, so the failure surfaces far from
6984 /// the source caixa.lisp;
6985 /// - duplicate `:caixa` names — two entries with the same name
6986 /// produce duplicate programs.yaml entries (one silently
6987 /// overwrites the other in the cluster's HelmRelease values), and
6988 /// contract membership lookups against `:contratos` collapse the
6989 /// two onto one node, masking authoring mistakes.
6990 ///
6991 /// Same value-shape discipline as `:placement :clusters` (where empty
6992 /// + duplicate cluster names are rejected) and `:entrada :paths`
6993 /// (where empty + duplicate path entries are rejected). Lifting these
6994 /// invariants to the typed surface mirrors the MESH-COMPOSITION
6995 /// §III.3 promise that the `:membros` set — the load-bearing identity
6996 /// of the application graph — is well-formed by construction.
6997 fn validate_membros(&self) -> Result<(), AplicacaoError> {
6998 if self.membros().is_empty() {
6999 return Err(AplicacaoError::NoMembros);
7000 }
7001 let mut seen = std::collections::HashSet::new();
7002 for m in self.membros() {
7003 // Route the `MembroCaixaEmpty` refusal-arm's per-member
7004 // empty-`:caixa` shape-gate through the typed
7005 // [`Membro::nome`] accessor rather than the raw `.caixa`
7006 // field access — the last un-lifted `.caixa` production-
7007 // code read site on the per-`:membros` member-caixa `:nome`
7008 // axis, sibling to the six caixa-core validator read sites
7009 // (member-set collector, per-member value-shape gate,
7010 // duplicate dedup key, cycle-detector adjacency-map seed,
7011 // self-loop gate) the 4a32abf lift already routed through
7012 // the accessor and the peer 54bf2f3 caixa-mesh emit-side
7013 // per-`programs[]` entry-`name:` `String`-carry converge.
7014 // Prior to this converge the `MembroCaixaEmpty` refusal
7015 // arm was the solitary consumer bypassing the typed
7016 // dispatch — the same-loop iteration's very next call
7017 // `validate_membro_caixa(m.nome())` already routed through
7018 // the accessor, so an author landing an empty-`:caixa`
7019 // entry hit the accessor on the shape-gate line but
7020 // bypassed it on the emptiness line one line above. A
7021 // future extension of the `:membros :caixa` axis to a
7022 // richer author surface (a per-cluster alias table pinned
7023 // through a future `:placement`-scoped slot, a namespace-
7024 // qualified rewrite the M4 CR materializer applies per-CR,
7025 // a per-member overlay from the future `:membros
7026 // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
7027 // that lands on the accessor would silently disagree
7028 // between the emptiness gate and every peer consumer —
7029 // an author-declared `:caixa "checkout"` value the
7030 // accessor rewrote to `""` under a future alias arm would
7031 // pass the raw `.is_empty()` gate here while the peer
7032 // `validate_membro_caixa(m.nome())` call one line below
7033 // (and every downstream emit-side consumer routing through
7034 // the accessor) tripped on the empty-value shape far from
7035 // this diagnostic. Pinned by the drift-detection test
7036 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
7037 // below.
7038 if m.nome().is_empty() {
7039 return Err(AplicacaoError::MembroCaixaEmpty);
7040 }
7041 // Every emitted cluster artifact's `metadata.name` derives
7042 // from a `:membros :caixa` value verbatim — the rendered
7043 // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
7044 // the [`crate::LABEL_PROGRAM`] label value on every CNP
7045 // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
7046 // 272), the composed `CiliumNetworkPolicy` `metadata.name`
7047 // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
7048 // `metadata.name` when the member is the `:entrada :para`
7049 // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
7050 // schema enforces the DNS-1123 label rule on admission;
7051 // a structurally invalid member name (`"Cart"`, `"my_cart"`,
7052 // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
7053 // mistaken-identity slug) silently passes the prior empty-/
7054 // duplicate-only gate and the failure surfaces at `kubectl
7055 // apply` time as a `metadata.name: Invalid value` rejection,
7056 // far from the source caixa.lisp, with no field naming the
7057 // offending `:membros` entry. Lifting the gate to caixa-build
7058 // time mirrors the `:entrada :host` value-shape trajectory
7059 // (c7d05ec) on the peer axis — every author surface that
7060 // emits a K8s name now matches the apiserver's accepted set
7061 // at validate time.
7062 validate_membro_caixa(m.nome())?;
7063 // The author surface for `:versao` is the same Cargo-shaped
7064 // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
7065 // `"*"`) every `:deps` entry carries — and the lacre pipeline
7066 // resolves both axes through the same
7067 // [`crate::version::parse_requirement`] entry-point. The
7068 // shared [`crate::render::require_valid_versao_requirement`]
7069 // helper brackets the empty-first + parse cascade both peer
7070 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
7071 // [`crate::SupervisorSpec::validate`] on `:children :versao`)
7072 // route through, so drift between the three axes' accepted
7073 // requirement sets is structurally impossible and the parse-
7074 // side no-op the empty-first arm closes (semver's empty
7075 // parse yields an implicit `*`) lives in exactly one
7076 // predicate.
7077 crate::render::require_valid_versao_requirement(
7078 m.versao_requirement(),
7079 || AplicacaoError::MembroVersaoEmpty {
7080 caixa: m.nome().to_string(),
7081 },
7082 |reason| AplicacaoError::MembroVersaoInvalid {
7083 caixa: m.nome().to_string(),
7084 versao: m.versao_requirement().to_string(),
7085 reason,
7086 },
7087 )?;
7088 crate::render::insert_first_seen(&mut seen, m.nome(), || {
7089 AplicacaoError::MembroDuplicate {
7090 caixa: m.nome().to_string(),
7091 }
7092 })?;
7093 }
7094 Ok(())
7095 }
7096
7097 /// Reject `:placement` values that are operationally meaningless or
7098 /// internally contradictory. Each strategy variant has the same
7099 /// invariants on `:clusters` (non-empty list, non-empty unique
7100 /// entries) — the §III.1 author surface is uniform on this axis,
7101 /// even though the *meaning* of the list differs by strategy
7102 /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
7103 /// shard pool).
7104 ///
7105 /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
7106 /// are the same authoring footgun closed for `:politicas` zero
7107 /// values and `:entrada` empty paths: the field is *declared* but
7108 /// carries no meaning, so downstream renderers either skip it
7109 /// silently (cluster-fanout drops the empty entry, no diagnostic)
7110 /// or apply it literally and fail at admission time. Lifting both
7111 /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
7112 /// violation is a build error" promise.
7113 ///
7114 /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
7115 /// is required exactly when `:estrategia Sharded` (hash-keyed
7116 /// distribution, Akka cluster-sharding convention, §II.4) and
7117 /// refused on `:estrategia Replicated`/`SingleNode` (where no
7118 /// hash-keyed routing axis consumes it). The partition closes the
7119 /// "I think I configured sharding" footgun where an author writes
7120 /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
7121 /// the typed slot's value silently vanishes at the renderer layer
7122 /// — every validated `Placement` past this call satisfies
7123 /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
7124 fn validate_placement(&self) -> Result<(), AplicacaoError> {
7125 // Every strategy needs at least one named cluster: `Replicated`
7126 // and `SingleNode` use the list as hosting/takeover candidates
7127 // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
7128 // §II.1), while `Sharded` uses it as the shard pool
7129 // (Akka cluster-sharding convention — §II.4). An empty list is
7130 // meaningless under any of the three.
7131 //
7132 // Route the paired pre-flight `.is_empty()` refusal probe and
7133 // the per-cluster validate loop's traversal head through the
7134 // lifted [`Placement::clusters`] slice-return accessor rather
7135 // than the raw `self.placement.clusters` field access — the
7136 // two production consumers of the per-`:placement` cluster-
7137 // pool `Vec`-carry now key off exactly one typed dispatch on
7138 // the substrate primitive, so any future rebrand on the axis
7139 // (a per-tenant cluster-pool overlay the operator pins through
7140 // a future `:placement :clusters-overrides` slot, a per-
7141 // Aplicacao dynamic cluster-pool derivation the future M5
7142 // adaptive-placement engine computes from `:affinity` weights)
7143 // migrates as a single caixa-core edit rather than a
7144 // coordinated rewrite of the paired arms — sibling of the
7145 // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
7146 // arm migration on the per-`:supervisor` static-child-list
7147 // `Vec`-carry axis.
7148 //
7149 // Route the per-`:placement` outer-composite reference read
7150 // through the lifted [`AplicacaoSpec::placement`] outer accessor
7151 // rather than the raw `&self.placement` field access — the
7152 // per-axis bracket-dispatch fan-out below (`p.clusters()`,
7153 // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
7154 // axis-level lifted accessor family) now routes through the
7155 // substrate-primitive typed dispatch at the outer composition
7156 // altitude, the same shape the peer caixa-mesh
7157 // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
7158 // and the sibling `feira app graph` per-Aplicacao print line
7159 // now key off after this accessor lift.
7160 let p = self.placement();
7161 if p.clusters().is_empty() {
7162 return Err(AplicacaoError::PlacementWithoutClusters {
7163 estrategia: p.estrategia(),
7164 });
7165 }
7166 let mut seen = std::collections::HashSet::new();
7167 for c in p.clusters() {
7168 // Per-entry value-shape gate: the cluster name lands in
7169 // every K8s context / `lareira-fleet-programs` aggregator
7170 // filter / future M4 CR materializer's per-cluster axis
7171 // a validated `:clusters` entry passes through, each
7172 // enforcing the DNS-1123 label rule on admission. Same
7173 // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
7174 // on the peer name axis — both axes' validated values
7175 // are guaranteed-accepted by the apiserver without
7176 // re-validation at any downstream renderer or admission
7177 // layer.
7178 validate_placement_cluster(c)?;
7179 crate::render::insert_first_seen(&mut seen, c.as_str(), || {
7180 AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
7181 })?;
7182 }
7183 // Route the per-`:placement :affinity` per-hint value-shape
7184 // gate through the typed [`Placement::affinity`] accessor rather
7185 // than the raw `&self.placement.affinity` field access — the
7186 // sole open-coded field-access site on the per-`:placement`
7187 // M3-Adaptive-compression-hint axis the accessor lift now owns.
7188 // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
7189 // the accessor's `Option<&str>` return type;
7190 // [`validate_placement_affinity`]'s `&str` parameter accepts
7191 // the narrower borrow without a re-allocation, so the routing
7192 // change is byte-for-byte in the pass arm and remains
7193 // byte-for-byte in every failure diagnostic
7194 // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
7195 // String` field is populated inside
7196 // [`validate_placement_affinity`] via the peer `.to_string()`
7197 // path on the same borrowed slice). Peer of the sibling
7198 // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
7199 // routing through [`Placement::shard_key`] at the caixa-core
7200 // site above — extends the "read `:placement` optional-scalars
7201 // through the typed accessor" discipline to the second
7202 // `Option<String>`-shape slot on the M3 mesh-slot family.
7203 //
7204 // Per-hint value-shape gate: the `:affinity` value lands
7205 // verbatim in the M3 Adaptive compression overlay
7206 // (caixa-mesh's `placement.affinity` emission) and every
7207 // future M4 placement-engine routing axis keying off the
7208 // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7209 // selector — each enforces the DNS-1123 label rule on
7210 // admission. Same typed-shape trajectory as `:placement
7211 // :clusters` (6c8c00b) on the sibling slot and the four
7212 // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7213 // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7214 // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7215 // on the Aplicacao surface to land on the canonical
7216 // [`crate::render::is_dns_1123_label`] floor.
7217 if let Some(a) = p.affinity() {
7218 validate_placement_affinity(a)?;
7219 }
7220 match p.estrategia() {
7221 // Route the `Sharded`-arm shape-gate cascade through the
7222 // typed [`Placement::shard_key`] accessor rather than the
7223 // raw `&self.placement.shard_key` field access — one of the
7224 // two open-coded field-access sites on the per-`:placement`
7225 // Akka-cluster-sharding-key axis the accessor lift now
7226 // owns. The `Some(k)`-bound `k` narrows from `&String` to
7227 // `&str` under the accessor's `Option<&str>` return type;
7228 // `str::is_empty` and [`validate_placement_shard_key`]'s
7229 // `&str` parameter both accept the narrower borrow without
7230 // a re-allocation.
7231 PlacementStrategy::Sharded => match p.shard_key() {
7232 None => return Err(AplicacaoError::ShardedWithoutKey),
7233 Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7234 // Per-axis value-shape gate on the Akka-cluster-sharding
7235 // `:shard-key` extractor expression. The shape gate runs
7236 // after the more self-locating `ShardedKeyEmpty` arm so
7237 // a `:shard-key ""` surfaces the narrower empty
7238 // diagnostic first; every non-empty `:shard-key` past
7239 // this call is guaranteed to be a printable-ASCII
7240 // single-token reference the future M4 Akka-style
7241 // cluster-sharding reconciler can hash without
7242 // re-validating at the runtime layer. Mirrors the
7243 // payload-axis shape gates on the peer `:contratos`
7244 // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7245 // 63e18a0 / c4213a4) — each lifts the runtime parser's
7246 // intersection-floor to a caixa-build-time gate.
7247 Some(k) => validate_placement_shard_key(k)?,
7248 },
7249 // `:shard-key` is the Akka-cluster-sharding axis
7250 // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7251 // across the cluster pool. `Replicated` (active-active across
7252 // every named cluster) and `SingleNode` (Erlang/OTP
7253 // distributed-app takeover/failover, §II.1) have no hash-keyed
7254 // routing axis to consume the slot; downstream renderers
7255 // (caixa-mesh's `placement.shardKey` overlay at
7256 // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7257 // sharding reconciler) ignore `:shard-key` outside the
7258 // `Sharded` arm by construction. Until this gate landed an
7259 // author who wrote `:placement (:estrategia Replicated
7260 // :shard-key "tenantId")` (an off-by-one strategy typo, a
7261 // copy-paste from a Sharded sibling caixa, the "I think I
7262 // configured sharding" footgun) silently passed validate and
7263 // the typed slot's value vanished at the renderer layer with
7264 // no diagnostic — the canonical "declared-but-inert" footgun
7265 // the empty-:affinity / empty-shard-key / zero-:politicas /
7266 // empty-:contratos-target gates already close on every other
7267 // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7268 // Lifting the rejection to a build-time gate closes the
7269 // Sharded ↔ non-Sharded partition over the typed
7270 // `:placement` slot: every validated `Placement` past this
7271 // call has `shard_key.is_some()` iff `estrategia ==
7272 // Sharded`, structurally — the future Akka reconciler can
7273 // reach for `placement.shard_key` knowing it's `Some` exactly
7274 // when the strategy consumes it, without re-deriving the
7275 // partition from inline strategy probes.
7276 PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7277 // Route the non-`Sharded`-arm declared-but-inert refusal
7278 // through the typed [`Placement::shard_key`] accessor —
7279 // the second of the two open-coded field-access sites the
7280 // accessor lift now owns. The `Some(k)`-bound `k` narrows
7281 // from `&String` to `&str`; the `AplicacaoError::
7282 // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7283 // materializes the owned `String` via `k.to_string()`
7284 // (peer to the sibling per-Membro `String`-carry sites
7285 // 4127bb6 routed through `m.nome().to_string()` /
7286 // `m.versao_requirement().to_string()`), so the whole
7287 // `Sharded` ↔ non-`Sharded` partition on the
7288 // `:shard-key` axis now flows through the same typed
7289 // dispatch as the sibling `Sharded`-arm shape gate.
7290 if let Some(k) = p.shard_key() {
7291 return Err(AplicacaoError::ShardKeyOnNonSharded {
7292 estrategia: p.estrategia(),
7293 shard_key: k.to_string(),
7294 });
7295 }
7296 }
7297 }
7298 Ok(())
7299 }
7300
7301 /// Reject `:politicas` values that are operationally meaningless.
7302 /// Each axis is optional — omitting it expresses "no policy on this
7303 /// axis". Carrying a *zero* value for a declared axis is the bug
7304 /// this function rejects: zero is either
7305 ///
7306 /// - re-interpreted as "infinite" by downstream proxies (Envoy's
7307 /// `RouteAction.timeout = 0s` disables the timeout entirely),
7308 /// directly contradicting MESH-COMPOSITION §V CSE invariant
7309 /// "every Aplicacao declares :politicas :timeout (no infinite
7310 /// blocking)", or
7311 /// - a renderer footgun (a 0-failure circuit breaker trips on the
7312 /// first call; a 0-rate rate-limit denies every request).
7313 ///
7314 /// Lifting these "0 means the opposite of what you think" idioms to
7315 /// the typed Aplicacao surface as build errors mirrors the §III.3
7316 /// promise that contract drift, capability leaks, and cycles are all
7317 /// build errors — not runtime surprises.
7318 fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7319 // Route the per-`:politicas` composite-reference read through
7320 // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7321 // than the raw `&self.politicas` field access — the per-axis
7322 // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7323 // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7324 // the substrate-primitive typed dispatch at the outer
7325 // composition altitude AND at every per-axis altitude, matching
7326 // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7327 // timeout/retry-overlay emitters that already key off the same
7328 // per-axis accessor family. The four-axis fan-out is now
7329 // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7330 // `p.retries` field-access sites (co-resident with the peer
7331 // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7332 // b0e741a / 21a6c3b already lifted) now route through
7333 // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7334 // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7335 // access axis on the M3 mesh-slot family.
7336 let p = self.politicas();
7337 if let Some(t) = p.timeout() {
7338 // Zero-floor + integer-millisecond canonical-form +
7339 // upper-cap bracket on the typed `:timeout` axis. See
7340 // [`crate::render::require_positive_canonical_bounded_duration`]
7341 // for the full three-arm ordering discipline (zero-floor
7342 // strictly precedes the canonical-form arm so
7343 // `Duration::ZERO` surfaces the self-locating
7344 // `PolicyTimeoutZero` diagnostic naming the omit-axis
7345 // remediation; canonical-form strictly precedes the cap
7346 // arm so a sub-millisecond above-cap `Duration` surfaces
7347 // the more fundamental round-trip-shape diagnostic first)
7348 // and the four peer typed-`Duration` sites that now share
7349 // this canonical bracket. Every validated value lies in
7350 // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7351 // granularity — the same top-and-bottom-edge discipline
7352 // [`POLICY_RETRIES_MAX`] and
7353 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7354 // capped-`u32` `:politicas` axes.
7355 crate::render::require_positive_canonical_bounded_duration(
7356 t,
7357 POLICY_TIMEOUT_MAX,
7358 || AplicacaoError::PolicyTimeoutZero,
7359 |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7360 |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7361 )?;
7362 }
7363 if let Some(r) = p.retries() {
7364 // Zero-floor + upper-cap bracket on the typed `:retries`
7365 // axis. See [`crate::render::require_positive_bounded_u32`]
7366 // for the ordering discipline (zero-floor arm strictly
7367 // precedes cap arm so `Some(0)` surfaces the self-locating
7368 // `PolicyRetriesZero` diagnostic with its omit-axis
7369 // remediation directly named, not the misleading
7370 // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7371 // this bracket landed the top edge ran all the way to
7372 // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7373 // Some(100_000), .. }` (or the equivalent author-surface
7374 // `(:retries 100000)` / `(:retries 4294967295)` typo
7375 // landing in the slot) silently passed validate. The
7376 // runtime substrate consuming the value (Envoy's
7377 // `retry_policy.num_retries`, the future
7378 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7379 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7380 // policy into a thundering-herd amplification vector —
7381 // the caller's one request fans out to `retries`
7382 // server-side calls per edge per traversal, multiplying
7383 // load by `(retries+1)^depth` across the
7384 // synchronous-`:contratos` subgraph at the precise moment
7385 // the substrate is already failing (transient failure is
7386 // the trigger), exactly the failure mode AWS App Mesh's
7387 // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7388 // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7389 // the sibling capped-`u32` `:politicas` axes
7390 // (`max_failures`, `rate_limit.rate`) and the peer capped-
7391 // `u32` axes in `:supervisor :max-restarts` +
7392 // `:limits :cpu`; all five now route through the same
7393 // canonical bracket helper.
7394 crate::render::require_positive_bounded_u32(
7395 r,
7396 POLICY_RETRIES_MAX,
7397 || AplicacaoError::PolicyRetriesZero,
7398 |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7399 )?;
7400 }
7401 if let Some(cb) = p.circuit_breaker() {
7402 // Zero-floor + upper-cap bracket on the typed
7403 // `:max-failures` axis. See
7404 // [`crate::render::require_positive_bounded_u32`] for the
7405 // ordering discipline (zero-floor arm strictly precedes
7406 // cap arm so `max_failures == 0` surfaces the
7407 // self-locating `PolicyBreakerZeroFailures` diagnostic
7408 // with its omit-axis remediation directly named, not the
7409 // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7410 // false` cap-arm miss). Until this bracket landed the top
7411 // edge ran all the way to `u32::MAX` and a struct-literal
7412 // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7413 // equivalent author-surface `(:max-failures 100000)` /
7414 // `(:max-failures 4294967295)` typo landing in the slot)
7415 // silently passed validate. The runtime substrate
7416 // consuming the value (Envoy's
7417 // `outlier_detection.consecutive_5xx`, the future
7418 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7419 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7420 // breaker policy into a no-op — the trip threshold is
7421 // structurally so high that no realistic
7422 // failures-per-`:window` traffic shape can reach it, the
7423 // breaker never trips, and every typed-slot consumer
7424 // emits an Envoy / Cilium L7 overlay carrying a
7425 // protection that is structurally never enforced. The
7426 // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7427 // peer with `retries` and `rate_limit.rate` on the same
7428 // helper.
7429 crate::render::require_positive_bounded_u32(
7430 cb.max_failures(),
7431 POLICY_BREAKER_MAX_FAILURES_MAX,
7432 || AplicacaoError::PolicyBreakerZeroFailures,
7433 |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7434 )?;
7435 // Zero-floor + integer-millisecond canonical-form +
7436 // upper-cap bracket on the typed `:window` axis. See
7437 // [`crate::render::require_positive_canonical_bounded_duration`]
7438 // for the full three-arm ordering discipline (peer to the
7439 // `:timeout` site immediately above); every validated
7440 // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7441 // (1ms..=1h), integer-millisecond granularity — the same
7442 // top-and-bottom-edge discipline
7443 // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7444 // duration-typed `:politicas :timeout` axis.
7445 crate::render::require_positive_canonical_bounded_duration(
7446 cb.window(),
7447 POLICY_BREAKER_WINDOW_MAX,
7448 || AplicacaoError::PolicyBreakerZeroWindow,
7449 |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7450 |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7451 )?;
7452 }
7453 if let Some(rl) = p.rate_limit() {
7454 // Zero-floor + upper-cap bracket on the typed
7455 // `:rate-limit` rate axis. See
7456 // [`crate::render::require_positive_bounded_u32`] for the
7457 // ordering discipline (zero-floor arm strictly precedes
7458 // cap arm so `rl.rate == 0` surfaces the self-locating
7459 // `PolicyRateLimitZero` diagnostic with its omit-axis
7460 // remediation directly named, not the misleading
7461 // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7462 // Until this bracket landed the top edge ran all the way
7463 // to `u32::MAX` and a struct-literal
7464 // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7465 // author-surface `(:rate-limit "4294967295/s")` /
7466 // `(:rate-limit "100000000/m")` typo landing in the slot)
7467 // silently passed validate. The runtime substrate
7468 // consuming the value (Envoy's
7469 // `local_rate_limit.token_bucket.max_tokens`, the future
7470 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7471 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7472 // rate-limit policy into a no-op limiter: the bucket
7473 // capacity is structurally so high that no realistic
7474 // per-edge traffic shape can drain it, the limiter never
7475 // trips, and every typed-slot consumer emits a "rate
7476 // declared" L7 overlay carrying enforcement that is
7477 // structurally never reached — the canonical
7478 // declared-but-inert footgun the sibling
7479 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7480 // the peer no-op-breaker shape. The bracket set is
7481 // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7482 // `max_failures` on the same helper. The rate bracket
7483 // strictly precedes the window-canonical gate so a
7484 // structurally absurd rate magnitude surfaces the more
7485 // fundamental amplification-shape diagnostic before the
7486 // narrower codec-round-trip-shape diagnostic on `:window`.
7487 crate::render::require_positive_bounded_u32(
7488 rl.rate(),
7489 POLICY_RATE_LIMIT_MAX,
7490 || AplicacaoError::PolicyRateLimitZero,
7491 |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7492 )?;
7493 // The `:rate-limit` author surface is the canonical
7494 // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7495 // accepts exactly the three-unit set (1s/60s/3600s) the
7496 // [`rate_limit_codec::render`] formatter emits the canonical
7497 // unit suffix for. A `RateLimit` whose `:window` is anything
7498 // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7499 // programmatically (struct literals in Rust + the typed
7500 // `Duration` field) but renders to a `<n>/<k>s` fragment
7501 // (the codec's fall-through) the parser then rejects on
7502 // round-trip — silently breaking the THEORY.md §V.2.7
7503 // render-determinism contract for any consumer that
7504 // serializes-then-deserializes the typed slot. Lifting the
7505 // canonical-window invariant to a build-time gate at
7506 // `validate_politicas` makes the codec's round-trip property
7507 // a structural property of the validated typed value:
7508 // every `RateLimit` past `AplicacaoSpec::validate` has a
7509 // window the codec round-trips losslessly, so the next
7510 // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
7511 // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
7512 // §III.2 #3) reaches for `rate_limit.window` knowing the
7513 // value is in the codec's accepted set without re-validating
7514 // at the renderer layer. Same trajectory as c4213a4 (typed
7515 // WitContract endpoint/subject/slot value-shape gates) and
7516 // the b0c8389 :behavior + :upgrade-from script-path lifts:
7517 // the typed slot's valid set matches its codec's accepted
7518 // set, structurally.
7519 // Route the canonical-window shape-gate through the substrate
7520 // primitive [`RateLimit::canonical_unit`] rather than the free
7521 // module-private [`is_canonical_rate_limit_window`] predicate:
7522 // both projections resolve `Duration → Option<RateLimitUnit>`
7523 // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
7524 // arm on the closed-set typed enum), but the accessor is the
7525 // typed method every downstream consumer of the validated slot
7526 // ([`rate_limit_codec::render`]'s canonical arm above, the
7527 // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7528 // per-`:politicas :rate-limit` admission webhook, the future
7529 // per-`:contratos`-edge rate-limit-override overlay
7530 // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
7531 // production consumers of the canonical-unit axis (the codec
7532 // render and this validate gate) now key off exactly one typed
7533 // dispatch on the substrate primitive, so any future extension
7534 // to `canonical_unit` (a per-cluster canonical-window overlay
7535 // the operator pins through a future `:contratos :rate-limit
7536 // -unit-overrides` slot, a per-tenant unit-alias table the M4
7537 // CR materializer resolves per-CR) reaches both consumers by
7538 // construction rather than a coordinated rewrite of every
7539 // free-helper call site.
7540 if rl.canonical_unit().is_none() {
7541 return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
7542 window: rl.window(),
7543 });
7544 }
7545 }
7546 Ok(())
7547 }
7548
7549 /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
7550 /// A synchronous edge is any contract whose typed [`WitTarget`] is
7551 /// `Http`, `Store`, or `Capability` — the caller blocks on the
7552 /// callee, so a cycle would deadlock at runtime. Pub-sub edges
7553 /// (`WitTarget::PubSub`) are skipped: an event publisher does not
7554 /// block on its subscribers, so they can never close a sync loop.
7555 ///
7556 /// Iterative DFS with three-coloring; the reported cycle is the
7557 /// path of caixa names traversed from the back-edge target around
7558 /// to itself, in declaration order. Adjacency lists and DFS roots
7559 /// are visited in `BTreeMap` key order so the diagnostic is
7560 /// deterministic across runs.
7561 fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
7562 use std::collections::{BTreeMap, BTreeSet};
7563
7564 #[derive(Clone, Copy, PartialEq, Eq)]
7565 enum Mark {
7566 White,
7567 Gray,
7568 Black,
7569 }
7570
7571 let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
7572 for m in self.membros() {
7573 adj.entry(m.nome()).or_default();
7574 }
7575 for c in self.contratos() {
7576 // target() was already called by validate(); re-running here
7577 // keeps detect_sync_cycles self-contained for callers that
7578 // reuse it (M4 per-edge policy resolver) without revalidating.
7579 //
7580 // The pub-sub-arm check routes through the lifted
7581 // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
7582 // arm-discriminator predicate rather than a raw `matches!(…,
7583 // WitTarget::PubSub { .. })` on the variant so a future
7584 // rebrand on the axis (an M4 per-edge WIT registry split of
7585 // [`WitTarget::PubSub`] into shape-specific peers, a
7586 // per-consumer rename that the accept-set already carries)
7587 // reaches this call site through the derive rather than a
7588 // scattered per-arm `matches!` rewrite — same
7589 // `IsVariant`-derived-arm-discriminator discipline the
7590 // peer closed-set typed enums ([`crate::CaixaKind`] via
7591 // f5bba80, [`PlacementStrategy`] via 766ec63,
7592 // [`crate::supervisor::RestartStrategy`] +
7593 // [`crate::supervisor::RestartPolicy`],
7594 // [`crate::upgrade::UpgradeInstruction`] via 915a934)
7595 // already route through on the substrate's other typed-enum
7596 // arm-discriminator axes.
7597 if c.target()?.is_pubsub() {
7598 continue;
7599 }
7600 adj.entry(c.source()).or_default().insert(c.destination());
7601 }
7602
7603 let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
7604 let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
7605
7606 // Stable DFS root order — BTreeMap iteration is sorted by key.
7607 let roots: Vec<&str> = adj.keys().copied().collect();
7608
7609 // Frame: (node, sorted-neighbours snapshot, next-edge index).
7610 for root in roots {
7611 if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
7612 continue;
7613 }
7614 let root_neighbors: Vec<&str> = adj
7615 .get(root)
7616 .map(|s| s.iter().copied().collect())
7617 .unwrap_or_default();
7618 let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
7619 color.insert(root, Mark::Gray);
7620
7621 loop {
7622 // Read+advance the top frame in one borrow scope so we
7623 // can later mutate the stack (push/pop) without holding
7624 // a borrow across.
7625 let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
7626 let node = top.0;
7627 if top.2 >= top.1.len() {
7628 (node, None)
7629 } else {
7630 let nxt = top.1[top.2];
7631 top.2 += 1;
7632 (node, Some(nxt))
7633 }
7634 });
7635 let Some((node, nxt_opt)) = step else { break };
7636 let Some(nxt) = nxt_opt else {
7637 color.insert(node, Mark::Black);
7638 stack.pop();
7639 continue;
7640 };
7641 let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
7642 match nxt_color {
7643 Mark::Gray => {
7644 // Reconstruct the cycle from `node` back through
7645 // the parent chain to `nxt`, then close.
7646 let mut cycle = Vec::new();
7647 let mut cur = node;
7648 cycle.push(cur.to_string());
7649 while cur != nxt {
7650 match parent.get(cur).copied() {
7651 Some(p) => {
7652 cur = p;
7653 cycle.push(cur.to_string());
7654 }
7655 None => break,
7656 }
7657 }
7658 cycle.reverse();
7659 cycle.push(nxt.to_string());
7660 return Err(AplicacaoError::ContratoCycle { cycle });
7661 }
7662 Mark::White => {
7663 parent.insert(nxt, node);
7664 color.insert(nxt, Mark::Gray);
7665 let nxt_neighbors: Vec<&str> = adj
7666 .get(nxt)
7667 .map(|s| s.iter().copied().collect())
7668 .unwrap_or_default();
7669 stack.push((nxt, nxt_neighbors, 0));
7670 }
7671 Mark::Black => {}
7672 }
7673 }
7674 }
7675 Ok(())
7676 }
7677
7678 /// Substrate-canonical destination-facing TCP port every emitted
7679 /// per-Aplicacao artifact must key `destination`-shaped port axes
7680 /// off. Returns the typed `:entrada :port` scalar when this
7681 /// Aplicacao's `:entrada` block names `destination` under its
7682 /// `:para` axis (the destination Servico *is* the ingress apex, so
7683 /// the substrate honors the author-declared listener port
7684 /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
7685 /// fallback otherwise (every non-apex destination — the internal
7686 /// mesh Servicos `:contratos` reach across, the future per-edge
7687 /// policy resolver's per-destination probe targets, the
7688 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
7689 /// L4 port resolver — reads the same substrate-canonical port floor
7690 /// by construction).
7691 ///
7692 /// Prior to this lift the "if :entrada matches this destination use
7693 /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
7694 /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
7695 /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
7696 /// prior to this lift), with no typed method on the substrate primitive
7697 /// that named the rule. A future per-destination port axis addition
7698 /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
7699 /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
7700 /// per-Servico listener ports land, a per-cluster override the operator
7701 /// pins through a future `:placement :default-port` slot — would have
7702 /// to be threaded through every renderer's inline cascade in lockstep
7703 /// or one consumer would silently disagree on which port a given
7704 /// destination Servico's ingress lands at. Lifting the rule to a
7705 /// typed method on the substrate primitive means the M4 CR
7706 /// materializer, the future per-edge policy resolver, and every
7707 /// downstream test-fixture navigator reach for exactly one typed
7708 /// dispatch — the resolver's accept-set moves as a unit on any
7709 /// future axis addition.
7710 ///
7711 /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
7712 /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
7713 /// the typed primitive, thin projections at each consumer"
7714 /// discipline lifts on the sibling `:contratos` payload / `:politicas
7715 /// :rate-limit` unit-suffix axes; extends the discipline onto the
7716 /// destination-facing port-resolution axis every per-Aplicacao
7717 /// L4-fallback renderer consumes.
7718 #[must_use]
7719 pub fn port_for_destination(&self, destination: &str) -> u16 {
7720 // Route the per-`:entrada` composite-reference read through
7721 // the lifted [`AplicacaoSpec::entrada`] accessor rather than
7722 // the raw `self.entrada.as_ref()` field access — the
7723 // per-destination L4-port fallback resolver's composite-
7724 // projection seed is now the canonical read-side surface
7725 // every per-Aplicacao entrada consumer routes through, peer
7726 // of the sibling `validate` per-`:entrada` shape-and-
7727 // membership gate migration on the same outer-composite
7728 // axis.
7729 // Route the per-`:entrada` apex-destination membership probe
7730 // through the lifted [`Entrada::destination`] accessor rather
7731 // than the raw `e.para == destination` field access — the last
7732 // un-lifted `.para` production-code read site on the per-
7733 // `:entrada` `:para` axis, sibling to the four caixa-core
7734 // consumer sites the peer 15ddd8c converge already routed
7735 // through the accessor (the three
7736 // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
7737 // membership gate sites: the `validate_entrada_para` DNS-1123
7738 // shape gate, the per-`:membros` membership lookup, and the
7739 // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
7740 // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
7741 // `entrada.para`-projection converge at
7742 // caixa-core/src/render.rs (the `gateway_api_http_route_name`
7743 // route-name projection site). Prior to this converge the
7744 // `port_for_destination` resolver was the solitary consumer
7745 // bypassing the typed dispatch on the `.para` axis — the two
7746 // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
7747 // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
7748 // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
7749 // reach through the same accessor family compose with this
7750 // resolver at the emit boundary via the apex-identity
7751 // invariant `spec.port_for_destination(entrada.destination())
7752 // == entrada.port` the sibling
7753 // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
7754 // pin pins across four permutations. A future extension of the
7755 // `:entrada :para` axis to a richer author surface (a per-
7756 // cluster alias overlay the operator pins through a future
7757 // `:placement`-scoped slot, a namespace-qualified rewrite the
7758 // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
7759 // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
7760 // §III.2 acknowledges) that lands on the accessor would silently
7761 // disagree between this resolver and the two `caixa-mesh` emit
7762 // sites — an author-declared `:para "cart"` value the accessor
7763 // rewrote to `"cart-v2"` under a future canary arm would leave
7764 // the resolver's membership arm falling through to
7765 // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
7766 // `.para`) while the peer emit-site consumers landed on the
7767 // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
7768 // silently disagreed on which destination port a given typed
7769 // `:entrada` resolves to at cluster-apply time. Pinned by the
7770 // drift-detection test
7771 // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
7772 // below.
7773 self.entrada()
7774 .filter(|e| e.destination() == destination)
7775 .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
7776 }
7777}
7778
7779/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
7780/// entry may name the Aplicacao's own `:nome`.
7781///
7782/// An Aplicacao that lists itself as a member is a degenerate self-edge in
7783/// the typed graph — the application graph is a DAG rooted at the Aplicacao
7784/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
7785/// Servicos that compose the app; an Aplicacao is never its own constituent),
7786/// and the lacre pipeline's closure-resolution would otherwise be handed a
7787/// node that is its own parent: a one-node cycle it either rejects far from
7788/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
7789/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
7790/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
7791/// label + lacre closure root), a member whose `:caixa` equals the
7792/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
7793/// peer.
7794///
7795/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
7796/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
7797/// gate `validate_upgrade_from_against_versao` and the supervision-tree
7798/// self-parent gate `crate::supervisor::validate_no_self_supervision`
7799/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
7800/// not a tree/mesh edge" discipline, here on the second typed-graph axis
7801/// (the Aplicacao :membros set; the supervision-tree :children list was the
7802/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
7803/// every validated Supervisor's children are distinct from its `:nome`,
7804/// every validated Aplicacao's membros are distinct from its `:nome`. The
7805/// transitive consequence is that `:entrada :para` and `:contratos`
7806/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
7807/// name the Aplicacao itself, without re-deriving the partition.
7808pub fn validate_no_self_membership(
7809 membros: &[Membro],
7810 parent_nome: &str,
7811) -> Result<(), AplicacaoError> {
7812 for m in membros {
7813 if m.nome() == parent_nome {
7814 return Err(AplicacaoError::MembroIsSelfAplicacao {
7815 caixa: parent_nome.to_string(),
7816 });
7817 }
7818 }
7819 Ok(())
7820}
7821
7822#[derive(Debug, Error, PartialEq, Eq)]
7823pub enum AplicacaoError {
7824 #[error("Aplicacao must declare at least one :membros entry")]
7825 NoMembros,
7826 #[error(
7827 ":membros entry has empty :caixa (every member must name a Servico; \
7828 omit the entry instead of carrying an empty name)"
7829 )]
7830 MembroCaixaEmpty,
7831 #[error(
7832 ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
7833 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
7834 name / label value the member name lands in; use a lowercase \
7835 alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
7836 )]
7837 MembroCaixaInvalid { caixa: String, reason: String },
7838 #[error(
7839 ":membros entry {caixa:?} has empty :versao (every member must pin a \
7840 semver constraint that resolves through the lacre pipeline)"
7841 )]
7842 MembroVersaoEmpty { caixa: String },
7843 #[error(
7844 ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
7845 requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
7846 `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
7847 carries; the lacre pipeline resolves both through the same parser)"
7848 )]
7849 MembroVersaoInvalid {
7850 caixa: String,
7851 versao: String,
7852 reason: String,
7853 },
7854 #[error(
7855 ":membros entry {caixa:?} appears more than once (the graph node set \
7856 is a set, not a multiset; duplicate members produce duplicate \
7857 programs.yaml entries and ambiguous :contratos membership lookups)"
7858 )]
7859 MembroDuplicate { caixa: String },
7860 #[error(
7861 "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
7862 never its own constituent Servico (the application graph is a DAG rooted \
7863 at the Aplicacao; :membros names the *other* caixas that compose the \
7864 app, not the app itself). Since every :nome is a globally-unique \
7865 substrate identity, a member naming the Aplicacao's own :nome is a \
7866 one-node lacre-closure recursion, not a coincidentally-named peer; \
7867 drop the self-referential :membros entry or rename it to the actual \
7868 constituent caixa."
7869 )]
7870 MembroIsSelfAplicacao { caixa: String },
7871 #[error(
7872 "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
7873 caixa declared in :membros; omit the contract or fill the {slot} field with a \
7874 member name)"
7875 )]
7876 ContratoCaixaEmpty { slot: &'static str },
7877 #[error(
7878 "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
7879 :contratos {slot} value names a member of :membros, which is itself a \
7880 DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
7881 object the member name lands in — Service, Pod, identity-based Cilium \
7882 selector; use a lowercase alphanumeric + hyphen identifier like \
7883 `\"checkout\"` or `\"cart-v2\"`)"
7884 )]
7885 ContratoCaixaInvalid {
7886 slot: &'static str,
7887 caixa: String,
7888 reason: String,
7889 },
7890 #[error("contrato references caixa {caixa:?} not declared in :membros")]
7891 ContratoMemberMissing { caixa: String },
7892 #[error(
7893 "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
7894 entry is an inter-Servico contract whose :de and :para must name distinct \
7895 :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
7896 the contract, or point :para at the member it actually calls)"
7897 )]
7898 ContratoSelfLoop { caixa: String, wit: String },
7899 #[error("contrato {de:?} → {para:?} has empty :wit")]
7900 EmptyWit { de: String, para: String },
7901 #[error(
7902 "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
7903 {reason} (the substrate dispatches `:wit` values on the canonical \
7904 lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
7905 `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
7906 demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
7907 kebab-case identifier per segment)"
7908 )]
7909 ContratoWitInvalid {
7910 de: String,
7911 para: String,
7912 wit: String,
7913 reason: String,
7914 },
7915 #[error(
7916 ":entrada :para is empty (every :entrada must route to a caixa declared in \
7917 :membros; fill the :para field with a member name)"
7918 )]
7919 EntradaParaEmpty,
7920 #[error(
7921 ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
7922 :entrada :para value names a member of :membros, which is itself a DNS-1123 \
7923 label per the K8s apiserver's `metadata.name` rule on every object the \
7924 member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
7925 Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
7926 `\"checkout\"` or `\"cart-v2\"`)"
7927 )]
7928 EntradaParaInvalid { para: String, reason: String },
7929 #[error(":entrada routes to caixa {para:?} not declared in :membros")]
7930 EntradaMemberMissing { para: String },
7931 #[error(":entrada must declare a non-empty :host")]
7932 EmptyEntradaHost,
7933 #[error(
7934 ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
7935 (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
7936 `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
7937 like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
7938 )]
7939 EntradaHostInvalid { host: String, reason: String },
7940 #[error(":entrada :port must be in 1..=65535, got 0")]
7941 EntradaPortZero,
7942 #[error(":entrada :paths entry is empty (use the empty list to match all)")]
7943 EntradaPathEmpty,
7944 #[error(
7945 ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
7946 )]
7947 EntradaPathNotAbsolute { path: String },
7948 #[error(
7949 ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
7950 value: {reason} (the K8s apiserver enforces the same shape on \
7951 `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
7952 single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
7953 requires percent-encoding `%XX` for non-ASCII and whitespace)"
7954 )]
7955 EntradaPathInvalid { path: String, reason: String },
7956 #[error(":entrada :paths entry {path:?} appears more than once")]
7957 EntradaPathDuplicate { path: String },
7958 #[error(
7959 ":placement {estrategia} requires at least one :clusters entry \
7960 (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
7961 )]
7962 PlacementWithoutClusters { estrategia: PlacementStrategy },
7963 #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
7964 PlacementClusterEmpty,
7965 #[error(
7966 ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
7967 (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
7968 in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
7969 future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
7970 — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
7971 identifier like `\"rio\"` or `\"mar-east\"`)"
7972 )]
7973 PlacementClusterInvalid { cluster: String, reason: String },
7974 #[error(":placement :clusters entry {cluster:?} appears more than once")]
7975 PlacementClusterDuplicate { cluster: String },
7976 #[error(
7977 ":placement :affinity must be non-empty when set (omit :affinity to express \
7978 `no placement hint`)"
7979 )]
7980 PlacementAffinityEmpty,
7981 #[error(
7982 ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
7983 (placement hints land verbatim in the M3 Adaptive compression overlay's \
7984 `placement.affinity` field and in every future M4 placement-engine routing \
7985 axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
7986 selector — both enforce the DNS-1123 label rule on admission; use a \
7987 lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
7988 `\"low-latency\"`, or `\"anti-affinity\"`)"
7989 )]
7990 PlacementAffinityInvalid { affinity: String, reason: String },
7991 #[error(":placement Sharded requires :shard-key")]
7992 ShardedWithoutKey,
7993 #[error(
7994 ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
7995 hashes every entity onto the same shard, defeating sharding entirely)"
7996 )]
7997 ShardedKeyEmpty,
7998 #[error(
7999 ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8000 entity-id extractor expression: {reason} (the future M4 Akka-style \
8001 cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8002 as a single-token property reference and hashes the extracted entity ID \
8003 to compute shard placement; use a printable-ASCII extractor expression \
8004 like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8005 `\"${{tenant}}\"`)"
8006 )]
8007 ShardKeyInvalid { shard_key: String, reason: String },
8008 #[error(
8009 ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8010 Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8011 convention); :estrategia Replicated runs every cluster active-active and \
8012 :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8013 distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8014 to :estrategia Sharded if hash-keyed routing is the intent"
8015 )]
8016 ShardKeyOnNonSharded {
8017 estrategia: PlacementStrategy,
8018 shard_key: String,
8019 },
8020 #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8021 ContratoMissingTarget {
8022 de: String,
8023 para: String,
8024 wit: String,
8025 expected: &'static str,
8026 },
8027 #[error(
8028 "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8029 expected `:{expected}` only"
8030 )]
8031 ContratoWrongTarget {
8032 de: String,
8033 para: String,
8034 wit: String,
8035 expected: &'static str,
8036 },
8037 #[error(
8038 "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8039 like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8040 that matches no traffic and silently drops every request)"
8041 )]
8042 ContratoEndpointEmpty { de: String, para: String },
8043 #[error(
8044 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8045 (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8046 :entrada :paths)"
8047 )]
8048 ContratoEndpointNotAbsolute {
8049 de: String,
8050 para: String,
8051 endpoint: String,
8052 },
8053 #[error(
8054 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8055 Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8056 emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8057 caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8058 shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8059 like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8060 and whitespace)"
8061 )]
8062 ContratoEndpointInvalid {
8063 de: String,
8064 para: String,
8065 endpoint: String,
8066 reason: String,
8067 },
8068 #[error(
8069 "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8070 subject is a no-op subscribe; omit :subject only if the WIT world is not \
8071 pub-sub-shaped)"
8072 )]
8073 ContratoSubjectEmpty { de: String, para: String },
8074 #[error(
8075 "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8076 NATS subject: {reason} (the NATS server's subject parser enforces the \
8077 same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8078 single-token and `>` multi-token wildcards — at publish/subscribe time; \
8079 use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8080 `\"orders.*.completed\"` — a malformed subject silently drops every \
8081 message at runtime far from the source caixa.lisp)"
8082 )]
8083 ContratoSubjectInvalid {
8084 de: String,
8085 para: String,
8086 subject: String,
8087 reason: String,
8088 },
8089 #[error(
8090 "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8091 addresses the bucket root, defeating the per-key isolation the slot exists \
8092 for; omit :slot only if the WIT world is not store-shaped)"
8093 )]
8094 ContratoSlotEmpty { de: String, para: String },
8095 #[error(
8096 "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8097 WASI keyvalue store slot template: {reason} (the substrate enforces \
8098 the printable-ASCII intersection-floor every kv backend admits — \
8099 use a single-token path / template expression like `\"checkout/$orderId\"`, \
8100 `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8101 percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8102 slot either gets rejected on write by strict backends or silently \
8103 corrupts the next read on permissive ones, far from the source caixa.lisp)"
8104 )]
8105 ContratoSlotInvalid {
8106 de: String,
8107 para: String,
8108 slot: String,
8109 reason: String,
8110 },
8111 #[error(
8112 "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
8113 or an event-sourced indirection (MESH-COMPOSITION §III.3)",
8114 cycle.join(" → ")
8115 )]
8116 ContratoCycle { cycle: Vec<String> },
8117 #[error(
8118 ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
8119 than once (the typed graph edges are a set, not a multiset; duplicate \
8120 contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
8121 values that K8s admission rejects far from the source caixa.lisp)"
8122 )]
8123 ContratoDuplicate {
8124 de: String,
8125 para: String,
8126 wit: String,
8127 target: String,
8128 },
8129 #[error(
8130 ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
8131 contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
8132 express `no per-call deadline on this axis`"
8133 )]
8134 PolicyTimeoutZero,
8135 #[error(
8136 ":politicas :retries must be > 0 when set; omit :retries to express \
8137 `no retries on transient failure`"
8138 )]
8139 PolicyRetriesZero,
8140 #[error(
8141 ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
8142 (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
8143 retry policy into a thundering-herd amplification vector on transient \
8144 failure (one caller request fans out to `(retries+1)^depth` server-side \
8145 calls across the synchronous-:contratos subgraph), exactly the failure \
8146 mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
8147 Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
8148 or omit :retries to disable retries entirely"
8149 )]
8150 PolicyRetriesExceedsCap { retries: u32 },
8151 #[error(
8152 ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
8153 breaker trips on the first call); omit :circuit-breaker to disable it"
8154 )]
8155 PolicyBreakerZeroFailures,
8156 #[error(
8157 ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
8158 mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
8159 above this cap turns the typed breaker policy into a no-op: the trip \
8160 threshold is structurally so high that no realistic failures-per-:window \
8161 traffic shape can reach it, so the breaker never trips and every typed-slot \
8162 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
8163 Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
8164 structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
8165 Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
8166 omit :circuit-breaker to disable the breaker entirely"
8167 )]
8168 PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
8169 #[error(
8170 ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
8171 tracks no failures); omit :circuit-breaker to disable it"
8172 )]
8173 PolicyBreakerZeroWindow,
8174 #[error(
8175 ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
8176 request); omit :rate-limit to disable rate limiting"
8177 )]
8178 PolicyRateLimitZero,
8179 #[error(
8180 ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
8181 (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
8182 rate-limit policy into a no-op limiter: the token-bucket capacity is \
8183 structurally so high that no realistic per-edge traffic shape can drain it, \
8184 so the limiter never trips and every typed-slot consumer (the future \
8185 CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8186 local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
8187 that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
8188 Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
8189 Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
8190 Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
8191 to disable rate limiting entirely"
8192 )]
8193 PolicyRateLimitExceedsCap { rate: u32 },
8194 #[error(
8195 ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
8196 the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
8197 rate-limit codec round-trips losslessly; got {window:?} which renders to a \
8198 non-round-trippable form (omit :rate-limit to disable, or pick one of the \
8199 three canonical windows)"
8200 )]
8201 PolicyRateLimitWindowNotCanonical { window: Duration },
8202 #[error(
8203 ":politicas :timeout must be an integer number of milliseconds — the canonical \
8204 authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8205 duration codec round-trips losslessly; got {timeout:?} which carries a \
8206 sub-millisecond residue that either truncates to a different `Duration` on \
8207 re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8208 to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8209 zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8210 (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8211 )]
8212 PolicyTimeoutNotCanonical { timeout: Duration },
8213 #[error(
8214 ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8215 (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8216 per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8217 overlays carry a deadline so long no realistic synchronous-:contratos \
8218 traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8219 CSE invariant degenerates to enforcement only at the per-Servico \
8220 `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8221 `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8222 (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8223 ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8224 maxes out at the same `3600s` ceiling) or omit :timeout to express \
8225 `no per-call deadline on this axis` (the synchronous-call deadline then \
8226 relies entirely on the per-Servico `:limits :wall-clock` axis)"
8227 )]
8228 PolicyTimeoutExceedsCap { timeout: Duration },
8229 #[error(
8230 ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8231 the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8232 the shared duration codec round-trips losslessly; got {window:?} which carries a \
8233 sub-millisecond residue that either truncates to a different `Duration` on \
8234 re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8235 Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8236 )]
8237 PolicyBreakerWindowNotCanonical { window: Duration },
8238 #[error(
8239 ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8240 (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8241 rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8242 is structurally so long that transient failures are never forgotten, the breaker \
8243 trips once and stays tripped for the lifetime of the component, and every typed-slot \
8244 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8245 outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8246 Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8247 default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8248 the breaker entirely"
8249 )]
8250 PolicyBreakerWindowExceedsCap { window: Duration },
8251}
8252
8253#[cfg(test)]
8254mod tests {
8255 use super::*;
8256
8257 fn membro(name: &str, ver: &str) -> Membro {
8258 Membro {
8259 caixa: name.into(),
8260 versao: ver.into(),
8261 }
8262 }
8263
8264 fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8265 WitContract {
8266 de: de.into(),
8267 para: para.into(),
8268 wit: "wasi:http/proxy".into(),
8269 endpoint: Some(ep.into()),
8270 subject: None,
8271 slot: None,
8272 }
8273 }
8274
8275 fn three_member_spec() -> AplicacaoSpec {
8276 AplicacaoSpec {
8277 membros: vec![
8278 membro("catalog", "^0.1"),
8279 membro("cart", "^0.1"),
8280 membro("payment", "^0.2"),
8281 ],
8282 contratos: vec![
8283 contract_http("cart", "catalog", "/products/:id"),
8284 contract_http("cart", "payment", "/charge"),
8285 ],
8286 politicas: MeshPolicy {
8287 timeout: Some(Duration::from_secs(30)),
8288 retries: Some(3),
8289 mtls_required: Some(true),
8290 ..Default::default()
8291 },
8292 placement: Placement {
8293 estrategia: PlacementStrategy::Replicated,
8294 clusters: vec!["rio".into(), "mar".into()],
8295 affinity: Some("data-locality".into()),
8296 shard_key: None,
8297 },
8298 entrada: Some(Entrada {
8299 host: "checkout.quero.cloud".into(),
8300 para: "cart".into(),
8301 paths: vec!["/api/cart".into(), "/api/products".into()],
8302 port: 8080,
8303 }),
8304 }
8305 }
8306
8307 #[test]
8308 fn happy_path_validates() {
8309 three_member_spec().validate().unwrap();
8310 }
8311
8312 #[test]
8313 fn rejects_empty_membros() {
8314 let mut s = three_member_spec();
8315 s.membros = vec![];
8316 assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8317 }
8318
8319 #[test]
8320 fn rejects_empty_membro_caixa() {
8321 // A `:caixa ""` entry has no name to render into programs.yaml
8322 // and no caixa.lisp to resolve at lacre time.
8323 let mut s = three_member_spec();
8324 s.membros[1].caixa = String::new();
8325 assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8326 }
8327
8328 #[test]
8329 fn rejects_empty_membro_versao() {
8330 // A `:versao ""` entry can't pin a semver constraint, so the
8331 // lacre pipeline fails far from the source.
8332 let mut s = three_member_spec();
8333 s.membros[2].versao = String::new();
8334 let err = s.validate().unwrap_err();
8335 assert!(
8336 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8337 "got {err:?}"
8338 );
8339 }
8340
8341 #[test]
8342 fn rejects_duplicate_membro_caixa() {
8343 // Two `:membros` entries with the same `:caixa` collapse to one
8344 // node in the membership HashSet, which masks `:contratos`
8345 // membership errors and produces duplicate programs.yaml entries.
8346 let mut s = three_member_spec();
8347 s.membros.push(membro("cart", "^0.2"));
8348 let err = s.validate().unwrap_err();
8349 assert!(
8350 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8351 "got {err:?}"
8352 );
8353 }
8354
8355 #[test]
8356 fn rejects_invalid_membro_versao_requirement() {
8357 // The fail-before-pass-after pin: a non-empty but malformed
8358 // semver requirement (`"^bad-version"`) silently passed
8359 // `validate()` on every pre-gate codebase because the prior
8360 // shape only refused the empty string. The parse failure
8361 // surfaced far downstream at lacre-resolve time with a
8362 // `semver::Error` that didn't name which `:membros` entry
8363 // carried the typo. The new gate moves the check to caixa-build
8364 // time at the source caixa.lisp.
8365 let mut s = three_member_spec();
8366 s.membros[2].versao = "^bad-version".into();
8367 let err = s.validate().unwrap_err();
8368 assert!(
8369 matches!(
8370 err,
8371 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8372 if caixa == "payment" && versao == "^bad-version"
8373 ),
8374 "got {err:?}"
8375 );
8376 }
8377
8378 #[test]
8379 fn rejects_membro_versao_with_double_caret_typo() {
8380 // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8381 // Cargo-shaped requirement on first glance but fails the parser
8382 // because semver doesn't accept stacked operators. Pin this
8383 // adjacent-shape footgun explicitly so a future relaxation that
8384 // accepts "looks-canonical-but-isn't" forms surfaces here.
8385 let mut s = three_member_spec();
8386 s.membros[0].versao = "^^0.1".into();
8387 let err = s.validate().unwrap_err();
8388 assert!(
8389 matches!(
8390 err,
8391 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8392 if caixa == "catalog" && versao == "^^0.1"
8393 ),
8394 "got {err:?}"
8395 );
8396 }
8397
8398 #[test]
8399 fn rejects_membro_versao_with_v_prefixed_tag() {
8400 // `"v0.1"` is the canonical "git-tag-shape leaking into the
8401 // semver requirement slot" typo — an author copies the
8402 // publish-side git-tag string verbatim into `:versao`, but
8403 // Cargo's semver parser rejects the leading `v` (only digits +
8404 // canonical operators are valid in the major-version
8405 // position). The gate's diagnostic names which member entry
8406 // carried the v-prefix so the fix is one edit, not a grep
8407 // through every member's `:versao`. (Note: bare `x`-glob
8408 // shorthands like `^0.1.x` are *accepted* by the semver crate
8409 // as an `*` wildcard on the patch axis — they're a Cargo-side
8410 // valid shape, not a typo, so the gate intentionally lets them
8411 // through.)
8412 let mut s = three_member_spec();
8413 s.membros[1].versao = "v0.1".into();
8414 let err = s.validate().unwrap_err();
8415 assert!(
8416 matches!(
8417 err,
8418 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8419 if caixa == "cart" && versao == "v0.1"
8420 ),
8421 "got {err:?}"
8422 );
8423 }
8424
8425 #[test]
8426 fn accepts_canonical_membro_versao_forms() {
8427 // The four Cargo-shaped requirement forms `:deps :versao`
8428 // already accepts via `crate::parse_requirement` must pass the
8429 // membros gate without re-validating at the resolver layer.
8430 // Pin every leg so a future tightening of the canonical set
8431 // surfaces here as a test failure.
8432 for form in [
8433 "^0.1", // caret — minor-range pin (the most common shape)
8434 "~0.1.2", // tilde — patch-range pin
8435 "0.1.0", // exact — single-version pin
8436 "*", // wildcard — explicitly any-version (semver::VersionReq::STAR)
8437 ">=0.1, <2", // multi-range — comma-separated comparators
8438 ] {
8439 let mut s = three_member_spec();
8440 for m in &mut s.membros {
8441 m.versao = form.into();
8442 }
8443 s.validate()
8444 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8445 }
8446 }
8447
8448 #[test]
8449 fn membro_versao_empty_takes_precedence_over_invalid() {
8450 // Order pin: the existing `MembroVersaoEmpty` diagnostic
8451 // (which doesn't try to parse) fires before the new
8452 // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8453 // `:versao` keeps its narrower error message — `parse_requirement`
8454 // would also reject `""`, but the empty-string arm is the more
8455 // self-locating diagnostic for the author.
8456 let mut s = three_member_spec();
8457 s.membros[1].versao = String::new();
8458 let err = s.validate().unwrap_err();
8459 assert!(
8460 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8461 "got {err:?}"
8462 );
8463 }
8464
8465 #[test]
8466 fn membro_versao_invalid_fires_before_duplicate_check() {
8467 // Order pin: a malformed requirement on a non-duplicate entry
8468 // surfaces *its own* diagnostic (which names the offending
8469 // `:versao` string), even when a later entry would otherwise
8470 // collapse onto an earlier name. The per-entry shape gate runs
8471 // inline before the duplicate-key insert, parallel to
8472 // `membros_validation_runs_before_contratos_membership_check`
8473 // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8474 let mut s = three_member_spec();
8475 s.membros[0].versao = "^bad".into();
8476 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8477 let err = s.validate().unwrap_err();
8478 assert!(
8479 matches!(
8480 err,
8481 AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8482 ),
8483 "got {err:?}"
8484 );
8485 }
8486
8487 #[test]
8488 fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8489 // The diagnostic-shape pin: the error names the offending
8490 // `:versao` value verbatim so the author can grep their
8491 // caixa.lisp without re-running the build, and carries a
8492 // non-empty `reason` from `semver::VersionReq::parse` so the
8493 // parser's own wording flows through to the diagnostic.
8494 let mut s = three_member_spec();
8495 s.membros[2].versao = "not-a-req".into();
8496 let err = s.validate().unwrap_err();
8497 let AplicacaoError::MembroVersaoInvalid {
8498 caixa,
8499 versao,
8500 reason,
8501 } = err
8502 else {
8503 panic!("expected MembroVersaoInvalid, got other variant");
8504 };
8505 assert_eq!(caixa, "payment");
8506 assert_eq!(versao, "not-a-req");
8507 assert!(
8508 !reason.is_empty(),
8509 "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
8510 );
8511 }
8512
8513 #[test]
8514 fn membro_versao_invalid_runs_before_contratos_check() {
8515 // A malformed `:versao` on any member must surface its own
8516 // diagnostic (which names *which* member to fix) before any
8517 // `:contratos` membership lookup raises `ContratoMemberMissing`.
8518 // The `:contratos` gate runs after `validate_membros`, so this
8519 // is structurally guaranteed — pin it explicitly so a future
8520 // refactor that reorders the gates surfaces here.
8521 let mut s = three_member_spec();
8522 s.membros[1].versao = "^^0.1".into();
8523 // Add a contrato whose `:para` doesn't exist — would normally
8524 // raise ContratoMemberMissing at the membership lookup, but
8525 // the membros gate must fire first.
8526 s.contratos
8527 .push(contract_http("cart", "phantom", "/never-reached"));
8528 let err = s.validate().unwrap_err();
8529 assert!(
8530 matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
8531 "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
8532 );
8533 }
8534
8535 #[test]
8536 fn membros_validation_runs_before_contratos_membership_check() {
8537 // If `:membros` carries a duplicate, the membership-collapse
8538 // would silently accept a `:contratos :para "phantom"` so long
8539 // as some entry hashes to "phantom". Pinning order: the
8540 // duplicate-membros error fires first, regardless of whether
8541 // contratos reference real members.
8542 let mut s = three_member_spec();
8543 s.membros = vec![
8544 membro("cart", "^0.1"),
8545 membro("cart", "^0.2"),
8546 membro("catalog", "^0.1"),
8547 membro("payment", "^0.1"),
8548 ];
8549 let err = s.validate().unwrap_err();
8550 assert!(
8551 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8552 "got {err:?}"
8553 );
8554 }
8555
8556 #[test]
8557 fn distinct_membros_validate() {
8558 // Pin the happy-path: every `:membros` entry has a non-empty
8559 // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
8560 // The fixture already satisfies this; this test makes the
8561 // invariant explicit so a future refactor of the fixture can't
8562 // silently break the guarantee.
8563 three_member_spec().validate().unwrap();
8564 }
8565
8566 // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
8567
8568 #[test]
8569 fn rejects_membro_caixa_with_uppercase() {
8570 // The canonical "I copied the Servico's display name verbatim"
8571 // typo — caixa names are lowercase per K8s DNS-1123 label rule,
8572 // but author tools often round-trip a TitleCase or CamelCase
8573 // identifier from an ADR or a sketch. Pin the diagnostic names
8574 // the offending name and suggests the lower-cased fix in one
8575 // edit, mirroring the `rejects_entrada_host_with_uppercase`
8576 // gate's shape (c7d05ec).
8577 let mut s = three_member_spec();
8578 s.membros[1].caixa = "Cart".into();
8579 let err = s.validate().unwrap_err();
8580 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8581 panic!("expected MembroCaixaInvalid, got other variant");
8582 };
8583 assert_eq!(caixa, "Cart");
8584 assert!(
8585 reason.contains("uppercase"),
8586 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8587 );
8588 assert!(
8589 reason.contains("\"cart\""),
8590 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
8591 );
8592 }
8593
8594 #[test]
8595 fn rejects_membro_caixa_with_underscore() {
8596 // The canonical "I'm thinking of a Python module / Postgres
8597 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
8598 // label schema. K8s rejects `metadata.name: my_cart` at admission
8599 // time with an opaque `field is invalid` (no source-citing
8600 // diagnostic). The gate moves it to caixa-build time.
8601 let mut s = three_member_spec();
8602 s.membros[0].caixa = "my_cart".into();
8603 let err = s.validate().unwrap_err();
8604 assert!(
8605 matches!(
8606 err,
8607 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8608 if caixa == "my_cart" && reason.contains('_')
8609 ),
8610 "got {err:?}"
8611 );
8612 }
8613
8614 #[test]
8615 fn rejects_membro_caixa_with_dot() {
8616 // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
8617 // subdomain — even though K8s `metadata.name` itself accepts
8618 // dots (DNS-1123 subdomain rule), this string also lands as a
8619 // K8s Service name (DNS-1035 label — no dots) and as a label
8620 // value on identity-based Cilium selectors. The strictest floor
8621 // among the use sites wins. The "I want to namespace my member
8622 // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
8623 let mut s = three_member_spec();
8624 s.membros[2].caixa = "team.cart".into();
8625 let err = s.validate().unwrap_err();
8626 assert!(
8627 matches!(
8628 err,
8629 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8630 if caixa == "team.cart" && reason.contains('.')
8631 ),
8632 "got {err:?}"
8633 );
8634 }
8635
8636 #[test]
8637 fn rejects_membro_caixa_with_leading_hyphen() {
8638 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
8639 // with an alphanumeric. The K8s apiserver rejects `-cart`
8640 // outright; the renderer would emit a `metadata.name: "-cart"`
8641 // that fails admission far from the source caixa.lisp.
8642 let mut s = three_member_spec();
8643 s.membros[0].caixa = "-cart".into();
8644 let err = s.validate().unwrap_err();
8645 assert!(
8646 matches!(
8647 err,
8648 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8649 if caixa == "-cart" && reason.contains("start and end")
8650 ),
8651 "got {err:?}"
8652 );
8653 }
8654
8655 #[test]
8656 fn rejects_membro_caixa_with_trailing_hyphen() {
8657 // The symmetric arm of the boundary rule. Pin separately so
8658 // both ends of the label are covered against a future relaxation
8659 // that only checks one boundary.
8660 let mut s = three_member_spec();
8661 s.membros[1].caixa = "cart-".into();
8662 let err = s.validate().unwrap_err();
8663 assert!(
8664 matches!(
8665 err,
8666 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8667 if caixa == "cart-"
8668 ),
8669 "got {err:?}"
8670 );
8671 }
8672
8673 #[test]
8674 fn rejects_membro_caixa_with_unicode() {
8675 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8676 // (`xn--…`) by the author before it reaches K8s. The byte-by-
8677 // byte ASCII validity check rejects multi-byte UTF-8 sequences
8678 // by the first byte that fails the `[a-z0-9-]` predicate.
8679 let mut s = three_member_spec();
8680 s.membros[2].caixa = "café".into();
8681 let err = s.validate().unwrap_err();
8682 assert!(
8683 matches!(
8684 err,
8685 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8686 if caixa == "café"
8687 ),
8688 "got {err:?}"
8689 );
8690 }
8691
8692 #[test]
8693 fn rejects_membro_caixa_with_whitespace() {
8694 // Whitespace is the canonical "I pasted from a sketch / doc"
8695 // footgun. The apiserver rejects every `metadata.name` value
8696 // carrying whitespace; pin the gate fires at the right boundary.
8697 let mut s = three_member_spec();
8698 s.membros[0].caixa = "my cart".into();
8699 let err = s.validate().unwrap_err();
8700 assert!(
8701 matches!(
8702 err,
8703 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8704 if caixa == "my cart"
8705 ),
8706 "got {err:?}"
8707 );
8708 }
8709
8710 #[test]
8711 fn rejects_membro_caixa_too_long() {
8712 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
8713 // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
8714 // exactly. The gate's reason names both the cap and the actual
8715 // length so the author can shorten in one edit.
8716 let mut s = three_member_spec();
8717 let too_long = "a".repeat(64);
8718 s.membros[1].caixa = too_long.clone();
8719 let err = s.validate().unwrap_err();
8720 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8721 panic!("expected MembroCaixaInvalid");
8722 };
8723 assert_eq!(caixa, too_long);
8724 assert!(
8725 reason.contains("63") && reason.contains("64"),
8726 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
8727 );
8728 }
8729
8730 #[test]
8731 fn membro_caixa_max_length_validates() {
8732 // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
8733 // so a future tightening (e.g. dropping to 62) surfaces here as
8734 // a regression, mirroring `entrada_host_max_length_validates`
8735 // (c7d05ec).
8736 let mut s = three_member_spec();
8737 s.membros[2].caixa = "a".repeat(63);
8738 s.entrada.as_mut().unwrap().para = "a".repeat(63);
8739 // remove contratos referencing the renamed member; they'd
8740 // raise ContratoMemberMissing otherwise
8741 s.contratos
8742 .retain(|c| c.de != "payment" && c.para != "payment");
8743 s.validate().unwrap();
8744 }
8745
8746 #[test]
8747 fn accepts_canonical_membro_caixa_forms() {
8748 // The DNS-1123 label shapes a caixa author is realistically
8749 // going to write: single-word lowercase, hyphen-joined, ending
8750 // in a digit-suffixed version (`cart-v2`), starting with a
8751 // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
8752 // DNS-1035 which requires a letter at position 0), single-
8753 // character (`a` — boundary). Pin every leg so a future
8754 // tightening that bans (e.g.) digit-start identifiers surfaces
8755 // here.
8756 for form in [
8757 "checkout",
8758 "cart",
8759 "cart-v2",
8760 "a",
8761 "c0",
8762 "3rd-party-shim",
8763 "x-1-2-3-4",
8764 ] {
8765 let mut s = three_member_spec();
8766 // Renaming a member also requires updating downstream refs;
8767 // drop everything else and rebuild a minimal spec around
8768 // just the one renamed member.
8769 s.membros = vec![membro(form, "^0.1")];
8770 s.contratos = vec![];
8771 s.entrada = None;
8772 s.validate()
8773 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8774 }
8775 }
8776
8777 #[test]
8778 fn membro_caixa_empty_takes_precedence_over_invalid() {
8779 // Order pin: the existing `MembroCaixaEmpty` diagnostic
8780 // (which doesn't try to parse) fires before the new
8781 // `MembroCaixaInvalid` parse-side diagnostic, so an empty
8782 // `:caixa` keeps its narrower error message — the new gate
8783 // would also reject `""`, but the empty-string arm is the more
8784 // self-locating diagnostic for the author. Mirrors the
8785 // `entrada_host_empty_takes_precedence_over_invalid` pin
8786 // (c7d05ec).
8787 let mut s = three_member_spec();
8788 s.membros[1].caixa = String::new();
8789 let err = s.validate().unwrap_err();
8790 assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
8791 }
8792
8793 #[test]
8794 fn membro_caixa_invalid_fires_before_versao_check() {
8795 // Order pin: an invalid-shape `:caixa` surfaces *its own*
8796 // diagnostic (which names the offending caixa name), even when
8797 // the same entry's `:versao` is also empty/invalid. The shape
8798 // gate runs first because the diagnostic is more self-locating —
8799 // an empty/invalid `:versao` on an invalid-shape caixa name is
8800 // a downstream-fix-after-the-caixa-rename concern.
8801 let mut s = three_member_spec();
8802 s.membros[1].caixa = "Cart".into();
8803 s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
8804 let err = s.validate().unwrap_err();
8805 assert!(
8806 matches!(
8807 err,
8808 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
8809 ),
8810 "got {err:?}"
8811 );
8812 }
8813
8814 #[test]
8815 fn membro_caixa_invalid_fires_before_duplicate_check() {
8816 // Order pin: a malformed-shape `:caixa` on an earlier entry
8817 // surfaces *its own* diagnostic, even when a later entry would
8818 // otherwise collapse onto a duplicate name. The per-entry shape
8819 // gate runs inline before the duplicate-key insert, parallel
8820 // to `membro_versao_invalid_fires_before_duplicate_check`.
8821 let mut s = three_member_spec();
8822 s.membros[0].caixa = "Catalog".into();
8823 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8824 let err = s.validate().unwrap_err();
8825 assert!(
8826 matches!(
8827 err,
8828 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
8829 ),
8830 "got {err:?}"
8831 );
8832 }
8833
8834 #[test]
8835 fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
8836 // The diagnostic-shape pin: the error names the offending
8837 // `:caixa` value verbatim so the author can grep their
8838 // caixa.lisp without re-running the build, and carries a
8839 // non-empty `reason` naming the specific violation. Same
8840 // shape every typed-shape gate enshrines (c7d05ec's
8841 // `entrada_host_diagnostic_carries_offending_host`,
8842 // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
8843 let mut s = three_member_spec();
8844 s.membros[2].caixa = "BAD_NAME".into();
8845 let err = s.validate().unwrap_err();
8846 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8847 panic!("expected MembroCaixaInvalid");
8848 };
8849 assert_eq!(caixa, "BAD_NAME");
8850 assert!(
8851 !reason.is_empty(),
8852 "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
8853 );
8854 }
8855
8856 #[test]
8857 fn rejects_contrato_with_unknown_de() {
8858 let mut s = three_member_spec();
8859 s.contratos.push(contract_http("phantom", "catalog", "/x"));
8860 let err = s.validate().unwrap_err();
8861 assert!(
8862 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8863 );
8864 }
8865
8866 #[test]
8867 fn rejects_contrato_with_unknown_para() {
8868 let mut s = three_member_spec();
8869 s.contratos.push(contract_http("cart", "phantom", "/x"));
8870 let err = s.validate().unwrap_err();
8871 assert!(
8872 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8873 );
8874 }
8875
8876 #[test]
8877 fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
8878 // The read-path pin: the phantom-`:de` refusal arm's
8879 // `ContratoMemberMissing.caixa` carrier must be observed through
8880 // the lifted [`WitContract::source`] accessor, not the raw
8881 // `.de.clone()` field-access `String`-carry. Peer of the sibling
8882 // per-`:contratos` self-loop arm's `.source().to_string()` /
8883 // `.world_ref().to_string()` `String`-carry sites the earlier
8884 // convergence lifted onto the same accessor pair. A future
8885 // silent detour that reintroduced the raw `.de.clone()` at the
8886 // wrap envelope while the shape-gate and membership lookup
8887 // routed through the accessor would surface here as a byte-equal
8888 // miss between the fired diagnostic's `caixa:` field and the
8889 // offending edge's `.source()` — pinning the accessor as the
8890 // sole read path across the phantom-name refusal arm's arg +
8891 // wrap-envelope emit surface.
8892 let mut s = three_member_spec();
8893 let phantom = contract_http("phantom", "catalog", "/x");
8894 s.contratos.push(phantom.clone());
8895 let err = s.validate().unwrap_err();
8896 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8897 panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
8898 };
8899 assert_eq!(
8900 caixa,
8901 phantom.source(),
8902 "ContratoMemberMissing.caixa on the phantom-:de arm must \
8903 byte-equal WitContract::source — the wrap envelope must \
8904 route through the lifted accessor rather than the raw \
8905 .de.clone() field-access String-carry"
8906 );
8907 }
8908
8909 #[test]
8910 fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8911 // The symmetric read-path pin on the `:para` phantom-name
8912 // refusal arm — same shape as the sibling `:de` pin above but
8913 // on the callee-Servico axis. Pins the wrap envelope's
8914 // `caixa:` field is observed through the lifted
8915 // [`WitContract::destination`] accessor, not the raw
8916 // `.para.clone()` field-access `String`-carry.
8917 let mut s = three_member_spec();
8918 let phantom = contract_http("cart", "phantom", "/x");
8919 s.contratos.push(phantom.clone());
8920 let err = s.validate().unwrap_err();
8921 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8922 panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
8923 };
8924 assert_eq!(
8925 caixa,
8926 phantom.destination(),
8927 "ContratoMemberMissing.caixa on the phantom-:para arm must \
8928 byte-equal WitContract::destination — the wrap envelope \
8929 must route through the lifted accessor rather than the raw \
8930 .para.clone() field-access String-carry"
8931 );
8932 }
8933
8934 #[test]
8935 fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
8936 // The read-path pin on the `:de` DNS-1123-malformed shape-gate
8937 // refusal arm — the `validate_contrato_caixa` arg must be
8938 // observed through the lifted [`WitContract::source`] accessor,
8939 // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
8940 // value routes through the shared
8941 // [`crate::render::require_valid_dns_1123_label`] floor with the
8942 // accessor-projected value; the fired
8943 // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
8944 // the offending edge's `.source()`, pinning that the arg + the
8945 // downstream `caixa: caixa.to_string()` wrap route through the
8946 // same accessor's read path.
8947 let mut s = three_member_spec();
8948 let malformed = contract_http("BAD_NAME", "catalog", "/x");
8949 s.contratos.push(malformed.clone());
8950 let err = s.validate().unwrap_err();
8951 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8952 panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
8953 };
8954 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8955 assert_eq!(
8956 caixa,
8957 malformed.source(),
8958 "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
8959 byte-equal WitContract::source — the shape-gate arg + wrap \
8960 envelope must route through the lifted accessor rather \
8961 than the raw &c.de &String-borrow"
8962 );
8963 }
8964
8965 #[test]
8966 fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8967 // Symmetric arm to the sibling `:de` malformed-shape pin above,
8968 // on the `:para` axis. Pins the shape-gate arg + wrap envelope
8969 // route through the lifted [`WitContract::destination`]
8970 // accessor. `:para` runs after the `:de` shape gate in the
8971 // canonical edge-direction order, so the `:de` value must be
8972 // well-shaped for the `:para` gate to fire — the `cart` :de is
8973 // canonical.
8974 let mut s = three_member_spec();
8975 let malformed = contract_http("cart", "BAD_NAME", "/x");
8976 s.contratos.push(malformed.clone());
8977 let err = s.validate().unwrap_err();
8978 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8979 panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
8980 };
8981 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8982 assert_eq!(
8983 caixa,
8984 malformed.destination(),
8985 "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
8986 byte-equal WitContract::destination — the shape-gate arg + \
8987 wrap envelope must route through the lifted accessor \
8988 rather than the raw &c.para &String-borrow"
8989 );
8990 }
8991
8992 // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
8993
8994 #[test]
8995 fn rejects_contrato_de_empty() {
8996 // `:de ""` previously fell through to `ContratoMemberMissing`
8997 // (with `caixa: ""`) because the validated `:membros :caixa`
8998 // set never contains the empty string. The narrower
8999 // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
9000 // the offending slot.
9001 let mut s = three_member_spec();
9002 s.contratos.push(contract_http("", "catalog", "/x"));
9003 let err = s.validate().unwrap_err();
9004 assert_eq!(
9005 err,
9006 AplicacaoError::ContratoCaixaEmpty {
9007 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9008 },
9009 "got {err:?}"
9010 );
9011 }
9012
9013 #[test]
9014 fn rejects_contrato_para_empty() {
9015 // Symmetric arm to `:de ""` — `:para ""` previously fell
9016 // through to `ContratoMemberMissing { caixa: "" }`.
9017 let mut s = three_member_spec();
9018 s.contratos.push(contract_http("cart", "", "/x"));
9019 let err = s.validate().unwrap_err();
9020 assert_eq!(
9021 err,
9022 AplicacaoError::ContratoCaixaEmpty {
9023 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9024 },
9025 "got {err:?}"
9026 );
9027 }
9028
9029 #[test]
9030 fn rejects_contrato_de_with_uppercase() {
9031 // The canonical "I copied the Servico's TitleCase display
9032 // name from an ADR" typo. Until this gate landed `:de "Cart"`
9033 // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
9034 // as "this caixa isn't in `:membros`" when the root cause is
9035 // "this `:de` value's shape can never legitimately match a
9036 // validated member (DNS-1123 labels are lowercase)". The
9037 // narrower diagnostic names the offending slot, the value
9038 // verbatim, and the parser-shaped reason.
9039 let mut s = three_member_spec();
9040 s.contratos.push(contract_http("Cart", "catalog", "/x"));
9041 let err = s.validate().unwrap_err();
9042 let AplicacaoError::ContratoCaixaInvalid {
9043 slot,
9044 caixa,
9045 reason,
9046 } = err
9047 else {
9048 panic!("expected ContratoCaixaInvalid, got other variant");
9049 };
9050 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9051 assert_eq!(caixa, "Cart");
9052 assert!(
9053 reason.contains("uppercase"),
9054 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9055 );
9056 }
9057
9058 #[test]
9059 fn rejects_contrato_para_with_underscore() {
9060 // The canonical "I'm thinking of a Python module" leak —
9061 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9062 // Pin the `:para` axis surfaces the same diagnostic shape as
9063 // the `:de` axis on the underscore violation.
9064 let mut s = three_member_spec();
9065 s.contratos.push(contract_http("cart", "my_catalog", "/x"));
9066 let err = s.validate().unwrap_err();
9067 assert!(
9068 matches!(
9069 err,
9070 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9071 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
9072 ),
9073 "got {err:?}"
9074 );
9075 }
9076
9077 #[test]
9078 fn rejects_contrato_de_with_dot() {
9079 // A `:contratos :de` value is a single DNS-1123 *label*, not
9080 // a subdomain — mirroring the `:membros :caixa` floor. The
9081 // strictest floor among the use sites wins.
9082 let mut s = three_member_spec();
9083 s.contratos
9084 .push(contract_http("team.cart", "catalog", "/x"));
9085 let err = s.validate().unwrap_err();
9086 assert!(
9087 matches!(
9088 err,
9089 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9090 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
9091 ),
9092 "got {err:?}"
9093 );
9094 }
9095
9096 #[test]
9097 fn rejects_contrato_para_with_unicode() {
9098 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9099 // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
9100 // validity check rejects multi-byte UTF-8 by the first
9101 // non-`[a-z0-9-]` byte.
9102 let mut s = three_member_spec();
9103 s.contratos.push(contract_http("cart", "café", "/x"));
9104 let err = s.validate().unwrap_err();
9105 assert!(
9106 matches!(
9107 err,
9108 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9109 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
9110 ),
9111 "got {err:?}"
9112 );
9113 }
9114
9115 #[test]
9116 fn rejects_contrato_de_with_leading_hyphen() {
9117 // DNS-1123 boundary rule: labels must start and end with an
9118 // alphanumeric. K8s rejects `-cart` outright; the narrower
9119 // shape diagnostic now names the violation at caixa-build
9120 // time rather than the misframed membership-lookup arm.
9121 let mut s = three_member_spec();
9122 s.contratos.push(contract_http("-cart", "catalog", "/x"));
9123 let err = s.validate().unwrap_err();
9124 assert!(
9125 matches!(
9126 err,
9127 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9128 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
9129 ),
9130 "got {err:?}"
9131 );
9132 }
9133
9134 #[test]
9135 fn contrato_de_empty_takes_precedence_over_invalid() {
9136 // Order pin: the `ContratoCaixaEmpty` arm fires before the
9137 // `ContratoCaixaInvalid` parse-side arm — same empty-first
9138 // cascade `validate_membro_caixa` / `validate_placement_cluster`
9139 // / `validate_entrada_host` already establish on their peer
9140 // name axes. The empty string is a structurally distinct
9141 // authoring footgun (the author left the field blank, vs.
9142 // typed a malformed value), so it gets its own diagnostic.
9143 let mut s = three_member_spec();
9144 s.contratos.push(contract_http("", "catalog", "/x"));
9145 let err = s.validate().unwrap_err();
9146 assert_eq!(
9147 err,
9148 AplicacaoError::ContratoCaixaEmpty {
9149 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9150 }
9151 );
9152 }
9153
9154 #[test]
9155 fn contrato_de_shape_fires_before_para_shape() {
9156 // Per-axis order pin: within one `:contratos` entry, the `:de`
9157 // shape gate fires before the `:para` shape gate — same
9158 // edge-direction order the existing `ContratoMemberMissing` /
9159 // `ContratoSelfLoop` / target-dispatch checks use, so the
9160 // diagnostic for a contract with both `:de` and `:para`
9161 // malformed is stable. Authors fixing the surfaced `:de`
9162 // first will see `:para`'s diagnostic on re-run.
9163 let mut s = three_member_spec();
9164 s.contratos.push(contract_http("Cart", "Catalog", "/x"));
9165 let err = s.validate().unwrap_err();
9166 assert!(
9167 matches!(
9168 err,
9169 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9170 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9171 ),
9172 "got {err:?}"
9173 );
9174 }
9175
9176 #[test]
9177 fn contrato_shape_fires_before_membership_lookup() {
9178 // The load-bearing pin: an invalid-shape `:de` surfaces its
9179 // *own* diagnostic, not the misframed `ContratoMemberMissing`.
9180 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9181 // an invalid-shape `:de` could never legitimately match any
9182 // member — the prior `ContratoMemberMissing` diagnostic was
9183 // a structural impossibility framed as a graph-membership
9184 // failure. The shape gate now routes every such input through
9185 // the narrower self-locating diagnostic.
9186 let mut s = three_member_spec();
9187 s.contratos.push(contract_http("Cart", "catalog", "/x"));
9188 let err = s.validate().unwrap_err();
9189 assert!(
9190 matches!(
9191 err,
9192 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
9193 ),
9194 "got {err:?}"
9195 );
9196 // And the symmetric case: an invalid-shape `:para` surfaces
9197 // its own diagnostic too, even when `:de` is well-shaped.
9198 let mut s = three_member_spec();
9199 s.contratos.push(contract_http("cart", "Catalog", "/x"));
9200 let err = s.validate().unwrap_err();
9201 assert!(
9202 matches!(
9203 err,
9204 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9205 ),
9206 "got {err:?}"
9207 );
9208 }
9209
9210 #[test]
9211 fn contrato_shape_fires_before_self_edge_check() {
9212 // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9213 // bugs: the shape violation (uppercase) and the self-edge
9214 // violation. The narrower per-axis shape diagnostic surfaces
9215 // first because fixing the shape may reveal that the author
9216 // also meant to point `:para` at a different member — the
9217 // self-edge framing is only useful once both endpoints have
9218 // valid shape.
9219 let mut s = three_member_spec();
9220 s.contratos.push(contract_http("Cart", "Cart", "/x"));
9221 let err = s.validate().unwrap_err();
9222 assert!(
9223 matches!(
9224 err,
9225 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9226 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9227 ),
9228 "got {err:?}"
9229 );
9230 }
9231
9232 #[test]
9233 fn contrato_well_shaped_phantom_still_raises_member_missing() {
9234 // Strict-improvement pin: a well-shaped `:de` that simply
9235 // isn't in `:membros` (a phantom reference — author meant
9236 // to add the member but didn't, or renamed and missed an
9237 // update) still surfaces `ContratoMemberMissing`, unchanged.
9238 // The shape gate only intercepts inputs that could never
9239 // legitimately match a validated member; legitimately-shaped
9240 // phantom references remain on the graph-membership axis.
9241 let mut s = three_member_spec();
9242 s.contratos
9243 .push(contract_http("phantom-shim", "catalog", "/x"));
9244 let err = s.validate().unwrap_err();
9245 assert!(
9246 matches!(
9247 err,
9248 AplicacaoError::ContratoMemberMissing { ref caixa }
9249 if caixa == "phantom-shim"
9250 ),
9251 "got {err:?}"
9252 );
9253 }
9254
9255 #[test]
9256 fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9257 // The diagnostic-shape pin: the error names the offending
9258 // slot (`:de` or `:para`) verbatim and the offending value
9259 // verbatim plus a non-empty parser-shaped reason, so the
9260 // author can grep their caixa.lisp for `:de "<name>"` /
9261 // `:para "<name>"` and fix it in one edit. Same diagnostic
9262 // shape as `MembroCaixaInvalid` (3f9d7a0) and
9263 // `PlacementClusterInvalid` (6c8c00b).
9264 let mut s = three_member_spec();
9265 s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9266 let err = s.validate().unwrap_err();
9267 let AplicacaoError::ContratoCaixaInvalid {
9268 slot,
9269 caixa,
9270 reason,
9271 } = err
9272 else {
9273 panic!("expected ContratoCaixaInvalid, got {err:?}");
9274 };
9275 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9276 assert_eq!(caixa, "BAD_NAME");
9277 assert!(
9278 !reason.is_empty(),
9279 "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9280 );
9281 }
9282
9283 #[test]
9284 fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9285 // Scalar-value pin: the two author-facing kebab-case labels the
9286 // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9287 // admits on the `:contratos` per-entry endpoint-shape axis,
9288 // one arm per typed sub-slot. Mirrors the peer scalar-value
9289 // pin the sibling top-level M2 / M3 / Supervisor
9290 // author-facing-label consts carry
9291 // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9292 // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9293 // slot itself), so every altitude of the typed-slot algebra
9294 // shares the same "one canonical byte-string per arm"
9295 // discipline. A future rebrand (`:de` → `:from` matching the
9296 // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9297 // sibling, `:para` → `:to` matching the same, or
9298 // `:de`/`:para` → `:source`/`:target` matching the WIT
9299 // world's `import`/`export` half-vocabulary) lands as an
9300 // edit to exactly one const, and every consumer that reaches
9301 // for the label picks it up at build time rather than at
9302 // runtime as a downstream `ContratoCaixaEmpty` /
9303 // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9304 // diagnostic mismatch far from the rename's commit.
9305 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9306 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9307 }
9308
9309 #[test]
9310 fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9311 // Production-through-const pin: the two per-axis labels the
9312 // per-`:contratos` entry endpoint-shape gate at
9313 // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9314 // argument to [`validate_contrato_caixa`] route through the
9315 // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9316 // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9317 // future rebrand that reaches the const but not the gate (or
9318 // vice versa) surfaces here at build time rather than at
9319 // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9320 // `slot: <stale-kebab-case>` diagnostic far from the rename's
9321 // commit. Mirror of the peer
9322 // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9323 // pin (882f498) on the sibling M3 top-level slot axis.
9324 let mut s = three_member_spec();
9325 s.contratos.push(contract_http("", "catalog", "/x"));
9326 assert_eq!(
9327 s.validate().unwrap_err(),
9328 AplicacaoError::ContratoCaixaEmpty {
9329 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9330 }
9331 );
9332 let mut s = three_member_spec();
9333 s.contratos.push(contract_http("cart", "", "/x"));
9334 assert_eq!(
9335 s.validate().unwrap_err(),
9336 AplicacaoError::ContratoCaixaEmpty {
9337 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9338 }
9339 );
9340 }
9341
9342 #[test]
9343 fn accepts_canonical_contrato_caixa_forms() {
9344 // The DNS-1123 label shapes a caixa author is realistically
9345 // going to write on a `:contratos :de` / `:para`. Pin every
9346 // leg so a future tightening that bans (e.g.) digit-start
9347 // identifiers surfaces here, mirroring
9348 // `accepts_canonical_membro_caixa_forms` on the peer name
9349 // axis.
9350 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9351 let mut s = three_member_spec();
9352 s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9353 s.contratos = vec![contract_http("checkout", form, "/x")];
9354 s.entrada = None;
9355 s.validate().unwrap_or_else(|e| {
9356 panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9357 });
9358
9359 let mut s = three_member_spec();
9360 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9361 s.contratos = vec![contract_http(form, "catalog", "/x")];
9362 s.entrada = None;
9363 s.validate().unwrap_or_else(|e| {
9364 panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9365 });
9366 }
9367 }
9368
9369 #[test]
9370 fn rejects_empty_wit() {
9371 let mut s = three_member_spec();
9372 s.contratos.push(WitContract {
9373 de: "cart".into(),
9374 para: "catalog".into(),
9375 wit: "".into(),
9376 endpoint: None,
9377 subject: None,
9378 slot: None,
9379 });
9380 let err = s.validate().unwrap_err();
9381 assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9382 }
9383
9384 #[test]
9385 fn rejects_entrada_to_unknown_member() {
9386 let mut s = three_member_spec();
9387 s.entrada.as_mut().unwrap().para = "phantom".into();
9388 assert!(matches!(
9389 s.validate().unwrap_err(),
9390 AplicacaoError::EntradaMemberMissing { .. }
9391 ));
9392 }
9393
9394 // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9395
9396 #[test]
9397 fn rejects_entrada_para_empty() {
9398 // `:para ""` previously fell through to
9399 // `EntradaMemberMissing { para: "" }` because the validated
9400 // `:membros :caixa` set never contains the empty string. The
9401 // narrower `EntradaParaEmpty` diagnostic now names the
9402 // offending slot directly — same empty-first cascade
9403 // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9404 // `ContratoCaixaEmpty` establish on the peer name axes.
9405 let mut s = three_member_spec();
9406 s.entrada.as_mut().unwrap().para = String::new();
9407 let err = s.validate().unwrap_err();
9408 assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9409 }
9410
9411 #[test]
9412 fn rejects_entrada_para_with_uppercase() {
9413 // The canonical "I copied the Servico's TitleCase display
9414 // name from an ADR" typo. Until this gate landed `:para "Cart"`
9415 // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9416 // as "this caixa isn't in `:membros`" when the root cause is
9417 // "this `:para` value's shape can never legitimately match a
9418 // validated member (DNS-1123 labels are lowercase)". The
9419 // narrower diagnostic names the value verbatim plus the
9420 // parser-shaped reason.
9421 let mut s = three_member_spec();
9422 s.entrada.as_mut().unwrap().para = "Cart".into();
9423 let err = s.validate().unwrap_err();
9424 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9425 panic!("expected EntradaParaInvalid, got other variant");
9426 };
9427 assert_eq!(para, "Cart");
9428 assert!(
9429 reason.contains("uppercase"),
9430 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9431 );
9432 }
9433
9434 #[test]
9435 fn rejects_entrada_para_with_underscore() {
9436 // The canonical "I'm thinking of a Python module" leak —
9437 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9438 let mut s = three_member_spec();
9439 s.entrada.as_mut().unwrap().para = "my_cart".into();
9440 let err = s.validate().unwrap_err();
9441 assert!(
9442 matches!(
9443 err,
9444 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9445 if para == "my_cart" && reason.contains('_')
9446 ),
9447 "got {err:?}"
9448 );
9449 }
9450
9451 #[test]
9452 fn rejects_entrada_para_with_dot() {
9453 // An `:entrada :para` value is a single DNS-1123 *label*, not
9454 // a subdomain — mirroring the `:membros :caixa` floor. The
9455 // strictest floor among the use sites wins.
9456 let mut s = three_member_spec();
9457 s.entrada.as_mut().unwrap().para = "team.cart".into();
9458 let err = s.validate().unwrap_err();
9459 assert!(
9460 matches!(
9461 err,
9462 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9463 if para == "team.cart" && reason.contains('.')
9464 ),
9465 "got {err:?}"
9466 );
9467 }
9468
9469 #[test]
9470 fn rejects_entrada_para_with_unicode() {
9471 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9472 // (`xn--…`) before it reaches K8s.
9473 let mut s = three_member_spec();
9474 s.entrada.as_mut().unwrap().para = "café".into();
9475 let err = s.validate().unwrap_err();
9476 assert!(
9477 matches!(
9478 err,
9479 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9480 ),
9481 "got {err:?}"
9482 );
9483 }
9484
9485 #[test]
9486 fn rejects_entrada_para_with_leading_hyphen() {
9487 // DNS-1123 boundary rule: labels must start and end with an
9488 // alphanumeric. K8s rejects `-cart` outright.
9489 let mut s = three_member_spec();
9490 s.entrada.as_mut().unwrap().para = "-cart".into();
9491 let err = s.validate().unwrap_err();
9492 assert!(
9493 matches!(
9494 err,
9495 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9496 if para == "-cart" && reason.contains("start and end")
9497 ),
9498 "got {err:?}"
9499 );
9500 }
9501
9502 #[test]
9503 fn rejects_entrada_para_with_trailing_hyphen() {
9504 // Symmetric boundary arm.
9505 let mut s = three_member_spec();
9506 s.entrada.as_mut().unwrap().para = "cart-".into();
9507 let err = s.validate().unwrap_err();
9508 assert!(
9509 matches!(
9510 err,
9511 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9512 if para == "cart-" && reason.contains("start and end")
9513 ),
9514 "got {err:?}"
9515 );
9516 }
9517
9518 #[test]
9519 fn rejects_entrada_para_too_long() {
9520 // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
9521 // bytes per label. K8s rejects longer names at admission on
9522 // every `metadata.name` axis.
9523 let mut s = three_member_spec();
9524 s.entrada.as_mut().unwrap().para = "a".repeat(64);
9525 let err = s.validate().unwrap_err();
9526 assert!(
9527 matches!(
9528 err,
9529 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9530 if para.len() == 64 && reason.contains("max length")
9531 ),
9532 "got {err:?}"
9533 );
9534 }
9535
9536 #[test]
9537 fn entrada_para_empty_takes_precedence_over_invalid() {
9538 // Order pin: the `EntradaParaEmpty` arm fires before the
9539 // `EntradaParaInvalid` parse-side arm — same empty-first
9540 // cascade `validate_membro_caixa` / `validate_placement_cluster`
9541 // / `validate_contrato_caixa` already establish.
9542 let mut s = three_member_spec();
9543 s.entrada.as_mut().unwrap().para = String::new();
9544 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
9545 }
9546
9547 #[test]
9548 fn entrada_para_shape_fires_before_membership_lookup() {
9549 // The load-bearing pin: an invalid-shape `:para` surfaces its
9550 // *own* diagnostic, not the misframed `EntradaMemberMissing`.
9551 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9552 // an invalid-shape `:para` could never legitimately match any
9553 // member — the prior `EntradaMemberMissing` diagnostic framed
9554 // a structural impossibility as a graph-membership failure.
9555 let mut s = three_member_spec();
9556 s.entrada.as_mut().unwrap().para = "Cart".into();
9557 let err = s.validate().unwrap_err();
9558 assert!(
9559 matches!(
9560 err,
9561 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9562 ),
9563 "got {err:?}"
9564 );
9565 }
9566
9567 #[test]
9568 fn entrada_para_shape_fires_before_host_gate() {
9569 // Per-`:entrada` order pin: the `:para` shape gate fires
9570 // before the `:host` gate, mirroring the existing
9571 // `entrada_host_member_missing_takes_precedence_over_host_invalid`
9572 // ordering where the member-lookup arm preceded the host gate.
9573 // The shape gate slots ahead of that, so a malformed `:para`
9574 // surfaces its own diagnostic even when `:host` is also wrong.
9575 let mut s = three_member_spec();
9576 let e = s.entrada.as_mut().unwrap();
9577 e.para = "Cart".into();
9578 e.host = "BAD HOST".into();
9579 let err = s.validate().unwrap_err();
9580 assert!(
9581 matches!(
9582 err,
9583 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9584 ),
9585 "got {err:?}"
9586 );
9587 }
9588
9589 #[test]
9590 fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
9591 // Strict-improvement pin: a well-shaped `:para` that simply
9592 // isn't in `:membros` (a phantom reference — author meant to
9593 // add the member but didn't, or renamed and missed an
9594 // update) still surfaces `EntradaMemberMissing`, unchanged.
9595 // The shape gate only intercepts inputs that could never
9596 // legitimately match a validated member.
9597 let mut s = three_member_spec();
9598 s.entrada.as_mut().unwrap().para = "phantom-shim".into();
9599 let err = s.validate().unwrap_err();
9600 assert!(
9601 matches!(
9602 err,
9603 AplicacaoError::EntradaMemberMissing { ref para }
9604 if para == "phantom-shim"
9605 ),
9606 "got {err:?}"
9607 );
9608 }
9609
9610 #[test]
9611 fn entrada_para_invalid_diagnostic_carries_offending_para() {
9612 // The diagnostic-shape pin: the error names the offending
9613 // `:para` value verbatim plus a non-empty parser-shaped
9614 // reason, so the author can grep their caixa.lisp for
9615 // `:para "<name>"` and fix it in one edit. Same diagnostic
9616 // shape as `MembroCaixaInvalid` (3f9d7a0),
9617 // `PlacementClusterInvalid` (6c8c00b), and
9618 // `ContratoCaixaInvalid` (8d5af6b).
9619 let mut s = three_member_spec();
9620 s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
9621 let err = s.validate().unwrap_err();
9622 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9623 panic!("expected EntradaParaInvalid, got {err:?}");
9624 };
9625 assert_eq!(para, "BAD_NAME");
9626 assert!(
9627 !reason.is_empty(),
9628 "EntradaParaInvalid `reason` must carry a parser-shaped wording"
9629 );
9630 }
9631
9632 #[test]
9633 fn accepts_canonical_entrada_para_forms() {
9634 // Positive-control sweep covering the DNS-1123 label shapes a
9635 // caixa author is realistically going to write on `:entrada
9636 // :para`. Pin every leg so a future tightening that bans
9637 // (e.g.) digit-start identifiers surfaces here, mirroring
9638 // `accepts_canonical_membro_caixa_forms` and
9639 // `accepts_canonical_contrato_caixa_forms` on the peer name
9640 // axes.
9641 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9642 let mut s = three_member_spec();
9643 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9644 s.contratos = vec![contract_http(form, "catalog", "/x")];
9645 s.entrada = Some(Entrada {
9646 host: "checkout.quero.cloud".into(),
9647 para: form.into(),
9648 paths: vec!["/api".into()],
9649 port: 8080,
9650 });
9651 s.validate().unwrap_or_else(|e| {
9652 panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
9653 });
9654 }
9655 }
9656
9657 #[test]
9658 fn rejects_replicated_without_clusters() {
9659 let mut s = three_member_spec();
9660 s.placement.clusters = vec![];
9661 assert!(matches!(
9662 s.validate().unwrap_err(),
9663 AplicacaoError::PlacementWithoutClusters { .. }
9664 ));
9665 }
9666
9667 #[test]
9668 fn rejects_sharded_without_key() {
9669 let mut s = three_member_spec();
9670 s.placement.estrategia = PlacementStrategy::Sharded;
9671 s.placement.shard_key = None;
9672 s.placement.clusters = vec!["rio".into()];
9673 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
9674 }
9675
9676 #[test]
9677 fn sharded_with_key_validates() {
9678 let mut s = three_member_spec();
9679 s.placement.estrategia = PlacementStrategy::Sharded;
9680 s.placement.shard_key = Some("$tenantId".into());
9681 s.validate().unwrap();
9682 }
9683
9684 #[test]
9685 fn round_trip_via_json_preserves_shape() {
9686 let s = three_member_spec();
9687 let json = serde_json::to_string(&s.membros).unwrap();
9688 let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
9689 assert_eq!(back, s.membros);
9690
9691 let json = serde_json::to_string(&s.contratos).unwrap();
9692 let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
9693 assert_eq!(back, s.contratos);
9694
9695 let json = serde_json::to_string(&s.placement).unwrap();
9696 let back: Placement = serde_json::from_str(&json).unwrap();
9697 assert_eq!(back, s.placement);
9698
9699 let json = serde_json::to_string(&s.entrada).unwrap();
9700 let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
9701 assert_eq!(back, s.entrada);
9702 }
9703
9704 #[test]
9705 fn rate_limit_round_trip_seconds() {
9706 let policy = MeshPolicy {
9707 rate_limit: Some(RateLimit {
9708 rate: 100,
9709 window: Duration::from_secs(1),
9710 }),
9711 ..Default::default()
9712 };
9713 let json = serde_json::to_string(&policy).unwrap();
9714 assert!(json.contains("\"100/s\""));
9715 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9716 assert_eq!(back.rate_limit.unwrap().rate, 100);
9717 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
9718 }
9719
9720 #[test]
9721 fn rate_limit_round_trip_minutes() {
9722 let policy = MeshPolicy {
9723 rate_limit: Some(RateLimit {
9724 rate: 5000,
9725 window: Duration::from_secs(60),
9726 }),
9727 ..Default::default()
9728 };
9729 let json = serde_json::to_string(&policy).unwrap();
9730 assert!(json.contains("\"5000/m\""));
9731 }
9732
9733 #[test]
9734 fn circuit_breaker_round_trip() {
9735 let policy = MeshPolicy {
9736 circuit_breaker: Some(CircuitBreaker {
9737 max_failures: 5,
9738 window: Duration::from_secs(60),
9739 }),
9740 ..Default::default()
9741 };
9742 let json = serde_json::to_string(&policy).unwrap();
9743 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9744 assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
9745 assert_eq!(
9746 back.circuit_breaker.unwrap().window,
9747 Duration::from_secs(60)
9748 );
9749 }
9750
9751 #[test]
9752 fn rejects_http_contrato_without_endpoint() {
9753 let mut s = three_member_spec();
9754 s.contratos.push(WitContract {
9755 de: "cart".into(),
9756 para: "catalog".into(),
9757 wit: "wasi:http/proxy".into(),
9758 endpoint: None,
9759 subject: None,
9760 slot: None,
9761 });
9762 let err = s.validate().unwrap_err();
9763 assert!(matches!(
9764 err,
9765 AplicacaoError::ContratoMissingTarget {
9766 expected: WitTarget::HTTP_FIELD_NAME,
9767 ..
9768 }
9769 ));
9770 }
9771
9772 #[test]
9773 fn rejects_http_contrato_with_subject() {
9774 let mut s = three_member_spec();
9775 s.contratos.push(WitContract {
9776 de: "cart".into(),
9777 para: "catalog".into(),
9778 wit: "wasi:http/proxy".into(),
9779 endpoint: Some("/x".into()),
9780 subject: Some("not.allowed.here".into()),
9781 slot: None,
9782 });
9783 let err = s.validate().unwrap_err();
9784 assert!(matches!(
9785 err,
9786 AplicacaoError::ContratoWrongTarget {
9787 expected: WitTarget::HTTP_FIELD_NAME,
9788 ..
9789 }
9790 ));
9791 }
9792
9793 #[test]
9794 fn rejects_pubsub_contrato_without_subject() {
9795 let mut s = three_member_spec();
9796 s.contratos.push(WitContract {
9797 de: "cart".into(),
9798 para: "catalog".into(),
9799 wit: "nats:pub-sub".into(),
9800 endpoint: None,
9801 subject: None,
9802 slot: None,
9803 });
9804 let err = s.validate().unwrap_err();
9805 assert!(matches!(
9806 err,
9807 AplicacaoError::ContratoMissingTarget {
9808 expected: WitTarget::PUBSUB_FIELD_NAME,
9809 ..
9810 }
9811 ));
9812 }
9813
9814 #[test]
9815 fn rejects_pubsub_contrato_with_endpoint() {
9816 let mut s = three_member_spec();
9817 s.contratos.push(WitContract {
9818 de: "cart".into(),
9819 para: "catalog".into(),
9820 wit: "kafka:topic".into(),
9821 endpoint: Some("/wrong".into()),
9822 subject: Some("topic.x".into()),
9823 slot: None,
9824 });
9825 let err = s.validate().unwrap_err();
9826 assert!(matches!(
9827 err,
9828 AplicacaoError::ContratoWrongTarget {
9829 expected: WitTarget::PUBSUB_FIELD_NAME,
9830 ..
9831 }
9832 ));
9833 }
9834
9835 #[test]
9836 fn rejects_store_contrato_without_slot() {
9837 let mut s = three_member_spec();
9838 s.contratos.push(WitContract {
9839 de: "cart".into(),
9840 para: "catalog".into(),
9841 wit: "wasi:keyvalue/store".into(),
9842 endpoint: None,
9843 subject: None,
9844 slot: None,
9845 });
9846 let err = s.validate().unwrap_err();
9847 assert!(matches!(
9848 err,
9849 AplicacaoError::ContratoMissingTarget {
9850 expected: WitTarget::STORE_FIELD_NAME,
9851 ..
9852 }
9853 ));
9854 }
9855
9856 // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
9857
9858 #[test]
9859 fn rejects_http_contrato_with_empty_endpoint() {
9860 // `Some("")` for an HTTP endpoint passes the presence check
9861 // (target() previously returned WitTarget::Http { endpoint: "" })
9862 // but renders as a `path: ""` Cilium L7 rule that matches no
9863 // traffic. Same value-shape footgun closed for :entrada :paths
9864 // entries (eb3456d).
9865 let mut s = three_member_spec();
9866 s.contratos.push(WitContract {
9867 de: "cart".into(),
9868 para: "catalog".into(),
9869 wit: "wasi:http/proxy".into(),
9870 endpoint: Some(String::new()),
9871 subject: None,
9872 slot: None,
9873 });
9874 let err = s.validate().unwrap_err();
9875 assert!(
9876 matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
9877 if de == "cart" && para == "catalog"),
9878 "got {err:?}"
9879 );
9880 }
9881
9882 #[test]
9883 fn rejects_http_contrato_with_relative_endpoint() {
9884 // Cilium L7 :path + Gateway API PathPrefix both require a
9885 // leading `/`. Same shape required of :entrada :paths
9886 // (eb3456d). Lifted into target() so every consumer of the
9887 // typed WitTarget view inherits the guarantee.
9888 let mut s = three_member_spec();
9889 s.contratos.push(WitContract {
9890 de: "cart".into(),
9891 para: "catalog".into(),
9892 wit: "wasi:http/proxy".into(),
9893 endpoint: Some("products/:id".into()),
9894 subject: None,
9895 slot: None,
9896 });
9897 let err = s.validate().unwrap_err();
9898 assert!(
9899 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9900 if endpoint == "products/:id"),
9901 "got {err:?}"
9902 );
9903 }
9904
9905 #[test]
9906 fn rejects_pubsub_contrato_with_empty_subject() {
9907 // NATS / Kafka publish without a subject is a no-op subscribe;
9908 // never the author's intent. Same empty-string rejection as
9909 // :membros :caixa, :placement :clusters entries, :entrada
9910 // :paths entries — every value carried by every typed slot is
9911 // value-shape-checked at validate().
9912 let mut s = three_member_spec();
9913 s.contratos.push(WitContract {
9914 de: "cart".into(),
9915 para: "catalog".into(),
9916 wit: "nats:pub-sub".into(),
9917 endpoint: None,
9918 subject: Some(String::new()),
9919 slot: None,
9920 });
9921 let err = s.validate().unwrap_err();
9922 assert!(
9923 matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
9924 if de == "cart" && para == "catalog"),
9925 "got {err:?}"
9926 );
9927 }
9928
9929 #[test]
9930 fn rejects_store_contrato_with_empty_slot() {
9931 // An empty slot template addresses the bucket root, defeating
9932 // the per-key isolation the slot exists for — a footgun on
9933 // `wasi:keyvalue/store` whose closest analog is the empty
9934 // shard-key rejected on :placement Sharded (c7c7799).
9935 let mut s = three_member_spec();
9936 s.contratos.push(WitContract {
9937 de: "cart".into(),
9938 para: "catalog".into(),
9939 wit: "wasi:keyvalue/store".into(),
9940 endpoint: None,
9941 subject: None,
9942 slot: Some(String::new()),
9943 });
9944 let err = s.validate().unwrap_err();
9945 assert!(
9946 matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
9947 if de == "cart" && para == "catalog"),
9948 "got {err:?}"
9949 );
9950 }
9951
9952 #[test]
9953 fn http_contrato_root_endpoint_validates() {
9954 // Pin the boundary case: a single-`/` endpoint is the catch-all
9955 // form the Gateway HTTPRoute renderer falls back to when
9956 // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
9957 // must remain a valid contrato endpoint too.
9958 let mut s = three_member_spec();
9959 s.contratos.push(contract_http("cart", "catalog", "/"));
9960 s.validate().unwrap();
9961 }
9962
9963 // ── :contratos :endpoint value-shape gate ────────────────────────────
9964 //
9965 // Mirrors the `:entrada :paths` value-shape suite on the peer
9966 // HTTP-path axis. Until this gate landed `WitContract::target()`
9967 // only refused the empty string + the missing-leading-`/` form
9968 // (c4213a4); a structurally invalid endpoint passed validate and
9969 // landed verbatim as a Cilium L7 `path:` rule
9970 // (caixa-mesh/src/lib.rs:311) that either silently dropped all
9971 // traffic or was rejected at apply time by Cilium policy admission.
9972 // Every authoring footgun the K8s Gateway API webhook / Cilium
9973 // policy validator would catch on admission now becomes a caixa-
9974 // build-time `ContratoEndpointInvalid` with the offending
9975 // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
9976 // shape as `EntradaPathInvalid` on the sibling axis; same shared
9977 // predicate (`crate::render::is_gateway_api_http_path`) ensures
9978 // drift between the two axes' rule enforcement is a build error
9979 // at the predicate.
9980
9981 fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
9982 // Fresh spec per call so the would-be-duplicate edge
9983 // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
9984 // `three_member_spec`'s pre-existing
9985 // `(cart, catalog, …, /products/:id)` entry — only the
9986 // endpoint payload differs.
9987 let mut s = three_member_spec();
9988 s.contratos.push(contract_http("cart", "catalog", ep));
9989 s.validate().unwrap_err()
9990 }
9991
9992 #[test]
9993 fn rejects_http_contrato_endpoint_with_query() {
9994 // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
9995 // silently rendered as a Cilium L7 `path: "/charge?token=X"`
9996 // rule the L7 matcher would never satisfy.
9997 let err = contrato_endpoint_err("/charge?token=X");
9998 assert!(
9999 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10000 if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
10001 "got {err:?}"
10002 );
10003 }
10004
10005 #[test]
10006 fn rejects_http_contrato_endpoint_with_fragment() {
10007 let err = contrato_endpoint_err("/charge#frag");
10008 assert!(
10009 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10010 if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
10011 "got {err:?}"
10012 );
10013 }
10014
10015 #[test]
10016 fn rejects_http_contrato_endpoint_with_whitespace() {
10017 let err = contrato_endpoint_err("/foo bar");
10018 assert!(
10019 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10020 if endpoint == "/foo bar" && reason.contains("whitespace")),
10021 "got {err:?}"
10022 );
10023 }
10024
10025 #[test]
10026 fn rejects_http_contrato_endpoint_with_control_char() {
10027 let err = contrato_endpoint_err("/api/\x01bar");
10028 assert!(
10029 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10030 if endpoint == "/api/\x01bar" && reason.contains("control character")),
10031 "got {err:?}"
10032 );
10033 }
10034
10035 #[test]
10036 fn rejects_http_contrato_endpoint_with_non_ascii() {
10037 let err = contrato_endpoint_err("/api/café");
10038 assert!(
10039 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10040 if endpoint == "/api/café" && reason.contains("non-ASCII")),
10041 "got {err:?}"
10042 );
10043 }
10044
10045 #[test]
10046 fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
10047 let err = contrato_endpoint_err("/api//cart");
10048 assert!(
10049 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10050 if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
10051 "got {err:?}"
10052 );
10053 }
10054
10055 #[test]
10056 fn rejects_http_contrato_endpoint_with_dot_segment() {
10057 let err = contrato_endpoint_err("/api/./cart");
10058 assert!(
10059 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10060 if endpoint == "/api/./cart" && reason.contains("`.` segment")),
10061 "got {err:?}"
10062 );
10063 }
10064
10065 #[test]
10066 fn rejects_http_contrato_endpoint_with_parent_segment() {
10067 // Path-traversal in a contrato endpoint is the canonical
10068 // "L7 rule that the workload's HTTP server's path-resolution
10069 // logic interprets differently than the policy enforcer"
10070 // footgun. Rejected outright at validate time.
10071 let err = contrato_endpoint_err("/api/../etc");
10072 assert!(
10073 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10074 if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
10075 "got {err:?}"
10076 );
10077 }
10078
10079 #[test]
10080 fn rejects_http_contrato_endpoint_too_long() {
10081 // 1025-byte endpoint — one over the Gateway API
10082 // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
10083 // path matcher has no inherent length limit but the policy
10084 // CR itself rides through the K8s apiserver, which enforces
10085 // ConfigMap-shaped limits; sharing the Gateway API cap is the
10086 // conservative floor.
10087 let big = format!("/api/{}", "a".repeat(1020));
10088 assert_eq!(big.len(), 1025);
10089 let err = contrato_endpoint_err(&big);
10090 assert!(
10091 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10092 if endpoint == &big && reason.contains("max length of 1024")),
10093 "got {err:?}"
10094 );
10095 }
10096
10097 #[test]
10098 fn http_contrato_endpoint_max_length_validates() {
10099 // 1024-byte endpoint — exactly the cap. Boundary pin: drift
10100 // in the cap surfaces here and at
10101 // `rejects_http_contrato_endpoint_too_long` simultaneously,
10102 // mirroring `entrada_path_max_length_validates` on the peer
10103 // axis.
10104 let big = format!("/api/{}", "a".repeat(1019));
10105 assert_eq!(big.len(), 1024);
10106 let mut s = three_member_spec();
10107 s.contratos.push(contract_http("cart", "catalog", &big));
10108 s.validate().unwrap();
10109 }
10110
10111 #[test]
10112 fn http_contrato_endpoint_accepts_canonical_forms() {
10113 // Positive-set sweep: every canonical HTTP-path shape the
10114 // sibling `:entrada :paths` axis accepts (the bare-root `/`,
10115 // plain paths, hidden-file-style `.config` segments distinct
10116 // from the `.` segment, digit-bearing segments, the canonical
10117 // route-template `:param` form, trailing-slash form,
10118 // percent-encoded segments, the `/foo..bar` interior-`..`-
10119 // substring forms that are NOT `..` segments) must remain a
10120 // valid contrato endpoint too. Drift between this list and
10121 // the entrada path positive sweep surfaces at the shared
10122 // `is_gateway_api_http_path` substrate-side suite — one
10123 // source of truth. Uses a fresh `(payment, catalog)` edge so
10124 // none of the swept endpoints collide with the pre-existing
10125 // `(cart, catalog, /products/:id)` / `(cart, payment,
10126 // /charge)` entries in `three_member_spec`.
10127 for ep in [
10128 "/",
10129 "/charge",
10130 "/v1/charge",
10131 "/api/.config",
10132 "/products/:id",
10133 "/api/cart/",
10134 "/api/caf%C3%A9",
10135 "/foo..bar",
10136 "/...",
10137 ] {
10138 let mut s = three_member_spec();
10139 s.contratos.push(contract_http("payment", "catalog", ep));
10140 s.validate()
10141 .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
10142 }
10143 }
10144
10145 #[test]
10146 fn contrato_endpoint_empty_takes_precedence_over_invalid() {
10147 // Ordering pin: `ContratoEndpointEmpty` is the more self-
10148 // locating diagnostic on `""` and must lead — the value-
10149 // shape gate is only reached after the empty-check fires.
10150 // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
10151 // on the peer axis.
10152 let mut s = three_member_spec();
10153 s.contratos.push(WitContract {
10154 de: "cart".into(),
10155 para: "catalog".into(),
10156 wit: "wasi:http/proxy".into(),
10157 endpoint: Some(String::new()),
10158 subject: None,
10159 slot: None,
10160 });
10161 let err = s.validate().unwrap_err();
10162 assert!(
10163 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10164 "got {err:?}"
10165 );
10166 }
10167
10168 #[test]
10169 fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
10170 // Ordering pin: an endpoint without a leading `/` surfaces the
10171 // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
10172 // value-shape gate is only consulted on endpoints that already
10173 // satisfy the absolute-prefix invariant. Mirrors
10174 // `entrada_path_not_absolute_takes_precedence_over_invalid`.
10175 let err = contrato_endpoint_err("bad path");
10176 assert!(
10177 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10178 if endpoint == "bad path"),
10179 "got {err:?}"
10180 );
10181 }
10182
10183 #[test]
10184 fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
10185 // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
10186 // `:para` + a non-empty reason flow through verbatim so the
10187 // author can grep their caixa.lisp for the offending contrato
10188 // block and fix it in one edit. Same shape as
10189 // `entrada_path_diagnostic_carries_offending_path`.
10190 let err = contrato_endpoint_err("/api?q=1");
10191 match err {
10192 AplicacaoError::ContratoEndpointInvalid {
10193 de,
10194 para,
10195 endpoint,
10196 reason,
10197 } => {
10198 assert_eq!(de, "cart");
10199 assert_eq!(para, "catalog");
10200 assert_eq!(endpoint, "/api?q=1");
10201 assert!(!reason.is_empty(), "reason field must be non-empty");
10202 }
10203 other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
10204 }
10205 }
10206
10207 #[test]
10208 fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10209 // The compounding theorem: every &str inside a WitTarget
10210 // returned by target() is non-empty (and absolute, for Http).
10211 // Renderers downstream of typed_view() can rely on this
10212 // without re-checking — the type system carries the proof.
10213 let http = contract_http("cart", "catalog", "/x");
10214 match http.target().unwrap() {
10215 WitTarget::Http { endpoint } => {
10216 assert!(!endpoint.is_empty());
10217 assert!(endpoint.starts_with('/'));
10218 }
10219 other => panic!("expected Http, got {other:?}"),
10220 }
10221 let nats = WitContract {
10222 de: "a".into(),
10223 para: "b".into(),
10224 wit: "nats:pub-sub".into(),
10225 endpoint: None,
10226 subject: Some("topic.x".into()),
10227 slot: None,
10228 };
10229 match nats.target().unwrap() {
10230 WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10231 other => panic!("expected PubSub, got {other:?}"),
10232 }
10233 let kv = WitContract {
10234 de: "a".into(),
10235 para: "b".into(),
10236 wit: "wasi:keyvalue/store".into(),
10237 endpoint: None,
10238 subject: None,
10239 slot: Some("checkout/$orderId".into()),
10240 };
10241 match kv.target().unwrap() {
10242 WitTarget::Store { slot } => assert!(!slot.is_empty()),
10243 other => panic!("expected Store, got {other:?}"),
10244 }
10245 }
10246
10247 #[test]
10248 fn target_diagnostic_names_offending_endpoint_value() {
10249 // When the malformed endpoint string is non-trivial, the
10250 // diagnostic carries the actual value back to the author —
10251 // not a generic "endpoint malformed" error.
10252 let bad = WitContract {
10253 de: "src".into(),
10254 para: "dst".into(),
10255 wit: "wasi:http/proxy".into(),
10256 endpoint: Some("api/v1/charge".into()),
10257 subject: None,
10258 slot: None,
10259 };
10260 match bad.target().unwrap_err() {
10261 AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10262 assert_eq!(de, "src");
10263 assert_eq!(para, "dst");
10264 assert_eq!(endpoint, "api/v1/charge");
10265 }
10266 other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10267 }
10268 }
10269
10270 #[test]
10271 fn rejects_unknown_wit_with_target_set() {
10272 let mut s = three_member_spec();
10273 s.contratos.push(WitContract {
10274 de: "cart".into(),
10275 para: "catalog".into(),
10276 wit: "custom:exchange".into(),
10277 endpoint: Some("/leaked".into()),
10278 subject: None,
10279 slot: None,
10280 });
10281 let err = s.validate().unwrap_err();
10282 assert!(matches!(
10283 err,
10284 AplicacaoError::ContratoWrongTarget {
10285 expected: WitTarget::CAPABILITY_EXPECTED,
10286 ..
10287 }
10288 ));
10289 }
10290
10291 #[test]
10292 fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10293 // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10294 // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10295 // fourth arm of the same "which payload field name goes in the
10296 // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10297 // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10298 // consts cover on the peer HTTP / PubSub / Store arms
10299 // (`wit_target_field_name_pins_per_variant`). Until this lift
10300 // landed the byte-string sat twice — once inline in the
10301 // [`WitContract::target`] Capability-arm rejection at the
10302 // production dispatch, once in `rejects_unknown_wit_with_target_set`
10303 // pinning against the same literal — with no compile-time link
10304 // between them. Same "one canonical declaration, next to the
10305 // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10306 // lift established for the payload-less arm's human-readable
10307 // label axis; this test is the shape peer of
10308 // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10309 // pair (routes-through-const + scalar-value pin) on the
10310 // wrong-target diagnostic-scalar axis.
10311 //
10312 // Fail-before-pass-after was verified locally by mutating the
10313 // const declaration to `"capability"` — the scalar-value pin
10314 // below fires (`"capability" != "none"`) and the routes-through
10315 // assertion below still holds (production and const walk in
10316 // lockstep), which is the correct behavior: a rename on the
10317 // const drifts here first, not at a downstream consumer.
10318 assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10319
10320 let mut s = three_member_spec();
10321 s.contratos.push(WitContract {
10322 de: "cart".into(),
10323 para: "catalog".into(),
10324 wit: "custom:exchange".into(),
10325 endpoint: Some("/leaked".into()),
10326 subject: None,
10327 slot: None,
10328 });
10329 match s.validate().unwrap_err() {
10330 AplicacaoError::ContratoWrongTarget { expected, .. } => {
10331 assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10332 }
10333 other => panic!("expected ContratoWrongTarget, got {other:?}"),
10334 }
10335 }
10336
10337 #[test]
10338 fn unknown_wit_capability_only_validates() {
10339 let mut s = three_member_spec();
10340 s.contratos.push(WitContract {
10341 de: "cart".into(),
10342 para: "catalog".into(),
10343 // A WIT world we haven't yet shaped — accept it as a typed
10344 // capability edge so authors aren't blocked while the WIT
10345 // registry catches up. No payload field may be carried.
10346 wit: "custom:exchange".into(),
10347 endpoint: None,
10348 subject: None,
10349 slot: None,
10350 });
10351 s.validate().unwrap();
10352 let added = s.contratos.last().unwrap();
10353 assert_eq!(added.target().unwrap(), WitTarget::Capability);
10354 }
10355
10356 #[test]
10357 fn target_typed_view_round_trips_each_shape() {
10358 let http = contract_http("cart", "catalog", "/products/:id");
10359 assert_eq!(
10360 http.target().unwrap(),
10361 WitTarget::Http {
10362 endpoint: "/products/:id"
10363 }
10364 );
10365 let nats = WitContract {
10366 de: "a".into(),
10367 para: "b".into(),
10368 wit: "nats:pub-sub".into(),
10369 endpoint: None,
10370 subject: Some("topic.x".into()),
10371 slot: None,
10372 };
10373 assert_eq!(
10374 nats.target().unwrap(),
10375 WitTarget::PubSub { subject: "topic.x" }
10376 );
10377 let kv = WitContract {
10378 de: "a".into(),
10379 para: "b".into(),
10380 wit: "wasi:keyvalue/store".into(),
10381 endpoint: None,
10382 subject: None,
10383 slot: Some("checkout/$orderId".into()),
10384 };
10385 assert_eq!(
10386 kv.target().unwrap(),
10387 WitTarget::Store {
10388 slot: "checkout/$orderId"
10389 }
10390 );
10391 }
10392
10393 #[test]
10394 fn wit_contract_kind_predicates() {
10395 let http = contract_http("a", "b", "/x");
10396 assert!(http.is_http());
10397 assert!(!http.is_pubsub());
10398 assert!(!http.is_store());
10399 assert!(!http.is_capability());
10400
10401 let nats = WitContract {
10402 de: "a".into(),
10403 para: "b".into(),
10404 wit: "nats:pub-sub".into(),
10405 endpoint: None,
10406 subject: Some("topic.x".into()),
10407 slot: None,
10408 };
10409 assert!(nats.is_pubsub());
10410 assert!(!nats.is_http());
10411 assert!(!nats.is_capability());
10412
10413 let kv = WitContract {
10414 de: "a".into(),
10415 para: "b".into(),
10416 wit: "wasi:keyvalue/store".into(),
10417 endpoint: None,
10418 subject: None,
10419 slot: Some("checkout/$orderId".into()),
10420 };
10421 assert!(kv.is_store());
10422 assert!(!kv.is_http());
10423 assert!(!kv.is_capability());
10424
10425 // Fourth arm on the paired closed-set predicate family: the
10426 // payload-less capability edge that projects to the payload-
10427 // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10428 // Extends the 3-arm predicate sweep this test opened to cover
10429 // the closed 4-way partition [`WitContract::is_capability`]
10430 // closes on the pre-projection WIT-shape axis, matched with the
10431 // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10432 // 4-arm predicate set.
10433 let cap = WitContract {
10434 de: "a".into(),
10435 para: "b".into(),
10436 wit: "custom:capability-only".into(),
10437 endpoint: None,
10438 subject: None,
10439 slot: None,
10440 };
10441 assert!(cap.is_capability());
10442 assert!(!cap.is_http());
10443 assert!(!cap.is_pubsub());
10444 assert!(!cap.is_store());
10445 }
10446
10447 // ── :contratos :wit value-shape gate ─────────────────────────────────
10448 //
10449 // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10450 // dispatch-discriminator axis. Until this gate landed
10451 // `WitContract::target()` accepted any non-empty string and
10452 // silently demoted unrecognized shapes to a capability-only L4
10453 // edge — the canonical "I thought I had L7 HTTP routing, got
10454 // L4-only" footgun. Every authoring footgun the WIT registry's
10455 // own grammar rejects (uppercase, hyphen-for-colon typo,
10456 // whitespace, empty package, doubled `@`, …) now becomes a
10457 // caixa-build-time `ContratoWitInvalid` with the offending
10458 // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10459 // as `ContratoEndpointInvalid` on the sibling axis; same shared
10460 // predicate (`crate::render::is_wit_world_ref`) ensures drift
10461 // between any two axes' rule enforcement is a build error at the
10462 // predicate, not piecemeal across renderers.
10463
10464 fn contrato_wit_err(wit: &str) -> AplicacaoError {
10465 // Fresh spec per call so the new contract doesn't collide on
10466 // identity with `three_member_spec`'s pre-existing entries.
10467 // The new edge uses `(payment, catalog)` — a pair the fixture
10468 // doesn't already declare — with no payload field set, so the
10469 // wit-shape gate fires before any payload-shape arm.
10470 let mut s = three_member_spec();
10471 s.contratos.push(WitContract {
10472 de: "payment".into(),
10473 para: "catalog".into(),
10474 wit: wit.into(),
10475 endpoint: None,
10476 subject: None,
10477 slot: None,
10478 });
10479 s.validate().unwrap_err()
10480 }
10481
10482 #[test]
10483 fn rejects_wit_with_uppercase_namespace() {
10484 // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10485 // didn't match the lowercase `wasi:http/` prefix is_http() keys
10486 // off, so the dispatch fell through to the capability arm and
10487 // the contract silently rendered as an L4-only Cilium edge.
10488 // The new gate surfaces the uppercase typo at validate time
10489 // with the offending `:wit` named.
10490 let err = contrato_wit_err("WASI:http/proxy");
10491 assert!(
10492 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10493 if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10494 "got {err:?}"
10495 );
10496 }
10497
10498 #[test]
10499 fn rejects_wit_with_hyphen_for_colon_typo() {
10500 // The canonical "I forgot the `:` separator" typo — pre-gate
10501 // this passed as Capability silently, so the renderer emitted
10502 // an L4-only policy where the author expected L7 HTTP rules.
10503 let err = contrato_wit_err("wasi-http/proxy");
10504 assert!(
10505 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10506 if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
10507 "got {err:?}"
10508 );
10509 }
10510
10511 #[test]
10512 fn rejects_wit_with_multiple_colons() {
10513 // Doubled `:` — the namespace/package split has nowhere to
10514 // anchor, so the dispatch silently demotes to Capability.
10515 let err = contrato_wit_err("wasi:http:proxy");
10516 assert!(
10517 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10518 if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
10519 "got {err:?}"
10520 );
10521 }
10522
10523 #[test]
10524 fn rejects_wit_with_empty_package() {
10525 // `wasi:` — namespace alone with no package. Pre-gate this
10526 // failed neither the is_http nor is_pubsub nor is_store
10527 // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
10528 // a bare `wasi:`), so it silently demoted to Capability.
10529 let err = contrato_wit_err("wasi:");
10530 assert!(
10531 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10532 if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
10533 "got {err:?}"
10534 );
10535 }
10536
10537 #[test]
10538 fn rejects_wit_with_underscore() {
10539 // Underscore — WIT identifiers are kebab-case, same rule
10540 // DNS-1123 enforces on its peer axes. The diagnostic carries
10541 // the explicit "use `-` instead" remediation.
10542 let err = contrato_wit_err("wasi:http_proxy");
10543 assert!(
10544 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10545 if wit == "wasi:http_proxy" && reason.contains('_')),
10546 "got {err:?}"
10547 );
10548 }
10549
10550 #[test]
10551 fn rejects_wit_with_whitespace() {
10552 // Whitespace mid-token — the prefix check matches but the
10553 // package-and-onward parse silently demoted to Capability.
10554 let err = contrato_wit_err("wasi:http proxy");
10555 assert!(
10556 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10557 if wit == "wasi:http proxy" && reason.contains("whitespace")),
10558 "got {err:?}"
10559 );
10560 }
10561
10562 #[test]
10563 fn rejects_wit_with_non_ascii() {
10564 // Un-percent-encoded non-ASCII byte — the canonical "I copied
10565 // the package name from a doc with smart quotes / accented
10566 // characters" footgun.
10567 let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
10568 assert!(
10569 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10570 if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
10571 "got {err:?}"
10572 );
10573 }
10574
10575 #[test]
10576 fn rejects_wit_with_consecutive_hyphens() {
10577 // `pub--sub` — WIT identifiers join words with single hyphens.
10578 let err = contrato_wit_err("nats:pub--sub");
10579 assert!(
10580 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10581 if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
10582 "got {err:?}"
10583 );
10584 }
10585
10586 #[test]
10587 fn rejects_wit_with_trailing_at_no_version() {
10588 // `wasi:http/proxy@` — the version-suffix author started to
10589 // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
10590 // parser would reject this; surface it at validate time.
10591 let err = contrato_wit_err("wasi:http/proxy@");
10592 assert!(
10593 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10594 if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
10595 "got {err:?}"
10596 );
10597 }
10598
10599 #[test]
10600 fn rejects_wit_too_long() {
10601 // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
10602 // The legitimate-shape arms all pass (lowercase, single `:`,
10603 // kebab-case identifiers); only the cap arm fires. Surfaces
10604 // the paste-from-binary / accidental-multi-line-blob landing
10605 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10606 // on the peer axis.
10607 let big = format!("wasi:{}", "a".repeat(124));
10608 assert_eq!(big.len(), 129);
10609 let err = contrato_wit_err(&big);
10610 assert!(
10611 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10612 if wit == &big && reason.contains("max length of 128")),
10613 "got {err:?}"
10614 );
10615 }
10616
10617 #[test]
10618 fn wit_max_length_validates() {
10619 // 128-byte WIT reference — exactly the cap. Boundary pin:
10620 // drift in the cap surfaces here and at `rejects_wit_too_long`
10621 // simultaneously, mirroring
10622 // `http_contrato_endpoint_max_length_validates` on the peer
10623 // axis.
10624 let big = format!("wasi:{}", "a".repeat(123));
10625 assert_eq!(big.len(), 128);
10626 let mut s = three_member_spec();
10627 s.contratos.push(WitContract {
10628 de: "payment".into(),
10629 para: "catalog".into(),
10630 wit: big,
10631 endpoint: None,
10632 subject: None,
10633 slot: None,
10634 });
10635 s.validate().unwrap();
10636 }
10637
10638 #[test]
10639 fn wit_accepts_canonical_forms_at_aplicacao_layer() {
10640 // Positive-set sweep through the AplicacaoSpec::validate
10641 // surface (rather than the substrate-side predicate directly)
10642 // — pins every shape the existing test fixtures + the
10643 // checkout-aplicacao example carry, so the gate's accept-set
10644 // matches the substrate's emit-set. Drift between this list
10645 // and `render::tests::wit_world_ref_accepts_canonical_forms`
10646 // surfaces at the substrate layer's positive sweep — one
10647 // source of truth for the rule.
10648 for wit in [
10649 "wasi:http/proxy",
10650 "wasi:keyvalue/store",
10651 "nats:pub-sub",
10652 "kafka:topic",
10653 "custom:exchange",
10654 "pleme:cap/audit",
10655 "wasi:http/proxy@0.2.0",
10656 ] {
10657 // Payload field paired to the dispatched WIT shape so the
10658 // shape-↔-target arm doesn't fire instead of the wit-shape
10659 // arm we're exercising. Routes off the same
10660 // `wit_shape_is_http` / `wit_shape_is_pubsub` /
10661 // `wit_shape_is_store` free functions the production
10662 // `WitContract::is_http` / `is_pubsub` / `is_store`
10663 // methods delegate to (both consult the lifted
10664 // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
10665 // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
10666 // future prefix addition to the routing accept-set
10667 // reaches this test's payload-dispatch arm by
10668 // construction — no per-test-site drift can hide a
10669 // shape-→-target-slot mismatch that would silently
10670 // demote a canonical `:wit` value to the
10671 // `(None, None, None)` capability-only arm and let the
10672 // `AplicacaoSpec::validate` positive sweep pass on a
10673 // shape it should exercise as HTTP / pub-sub / store.
10674 let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
10675 (Some("/x".into()), None, None)
10676 } else if wit_shape_is_pubsub(wit) {
10677 (None, Some("topic.x".into()), None)
10678 } else if wit_shape_is_store(wit) {
10679 (None, None, Some("bucket/$key".into()))
10680 } else {
10681 (None, None, None)
10682 };
10683 let mut s = three_member_spec();
10684 s.contratos.push(WitContract {
10685 de: "payment".into(),
10686 para: "catalog".into(),
10687 wit: wit.into(),
10688 endpoint,
10689 subject,
10690 slot,
10691 });
10692 s.validate()
10693 .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
10694 }
10695 }
10696
10697 #[test]
10698 fn wit_shape_predicates_accept_canonical_prefix_set() {
10699 // Positive-set sweep pinning every prefix in
10700 // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
10701 // WIT_STORE_SHAPE_PREFIXES against the three free-function
10702 // dispatch predicates. The six prefixes are the load-bearing
10703 // routing keys the substrate's WIT-shape dispatch consults
10704 // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
10705 // key/value-store-slot admission); any drift between the
10706 // free-function accept-set and this list surfaces here
10707 // rather than at apply time as a silent
10708 // shape-→-capability-only demotion.
10709 assert!(wit_shape_is_http("wasi:http/proxy"));
10710 assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
10711 assert!(wit_shape_is_http("http:incoming"));
10712
10713 assert!(wit_shape_is_pubsub("nats:pub-sub"));
10714 assert!(wit_shape_is_pubsub("kafka:topic"));
10715
10716 assert!(wit_shape_is_store("wasi:keyvalue/store"));
10717 assert!(wit_shape_is_store("kv:cache/session"));
10718 }
10719
10720 #[test]
10721 fn wit_shape_predicates_reject_uncanonical_forms() {
10722 // Negative-set pin: the six canonical prefixes are
10723 // lowercase-only (mirrors the `is_wit_world_ref` substrate
10724 // predicate's lowercase invariant — see its docstring on the
10725 // "I thought I had L7 HTTP routing, got L4-only" footgun).
10726 // The empty string, an uppercase-prefixed form, a hyphen-
10727 // instead-of-colon typo, and a bare kebab identifier all miss
10728 // every shape arm — reachable-by-construction only via the
10729 // `is_wit_world_ref` gate that admission-checks the `:wit`
10730 // value first, but pinned here so any future
10731 // free-function change (e.g. a case-insensitive
10732 // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
10733 // this unit level.
10734 for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
10735 assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
10736 assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
10737 assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
10738 }
10739 }
10740
10741 #[test]
10742 fn wit_shape_predicates_partition_canonical_set() {
10743 // Every canonical prefix routes to exactly one shape arm —
10744 // the three prefix sets are pairwise disjoint. Pins the
10745 // routing property [`WitContract::target`] relies on: an
10746 // `is_http()` return of `true` guarantees `is_pubsub()` and
10747 // `is_store()` return `false`, so the shape-→-target-slot
10748 // dispatch (endpoint vs subject vs slot) is unambiguous.
10749 // Drift (e.g. a future `"kv:"` moved into the HTTP set
10750 // without removal from the store set) would silently route
10751 // one prefix to two arms and the first-matching-arm order
10752 // becomes load-bearing — this pin surfaces it as a build
10753 // error instead.
10754 for prefix in WIT_HTTP_SHAPE_PREFIXES {
10755 let sample = format!("{prefix}x");
10756 assert!(wit_shape_is_http(&sample));
10757 assert!(!wit_shape_is_pubsub(&sample));
10758 assert!(!wit_shape_is_store(&sample));
10759 }
10760 for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
10761 let sample = format!("{prefix}x");
10762 assert!(!wit_shape_is_http(&sample));
10763 assert!(wit_shape_is_pubsub(&sample));
10764 assert!(!wit_shape_is_store(&sample));
10765 }
10766 for prefix in WIT_STORE_SHAPE_PREFIXES {
10767 let sample = format!("{prefix}x");
10768 assert!(!wit_shape_is_http(&sample));
10769 assert!(!wit_shape_is_pubsub(&sample));
10770 assert!(wit_shape_is_store(&sample));
10771 }
10772 }
10773
10774 #[test]
10775 fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
10776 // Positive pin: [`wit_shape_matches`] is exactly the
10777 // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
10778 // parameterized on the accept-set. Two-prefix accept-set,
10779 // one-prefix accept-set, and empty accept-set (which must
10780 // reject everything, including the empty string — an empty
10781 // `any()` fold returns `false`) all pinned so a future
10782 // reimplementation that swaps `starts_with` for `contains`,
10783 // `==`, or a case-folded comparator surfaces at unit-test
10784 // time.
10785 let two = &["wasi:http/", "http:"];
10786 assert!(wit_shape_matches("wasi:http/proxy", two));
10787 assert!(wit_shape_matches("http:incoming", two));
10788 assert!(!wit_shape_matches("wasi:keyvalue/store", two));
10789
10790 let one = &["nats:"];
10791 assert!(wit_shape_matches("nats:pub-sub", one));
10792 assert!(!wit_shape_matches("kafka:topic", one));
10793
10794 // Empty accept-set matches nothing — the identity element
10795 // for the disjunctive `any()` fold across the prefix set.
10796 // Reachable via a future `wit_shape_is_<name>` const paired
10797 // to a still-empty prefix table on a nascent shape-arm draft.
10798 let empty: &[&str] = &[];
10799 assert!(!wit_shape_matches("wasi:http/proxy", empty));
10800 assert!(!wit_shape_matches("", empty));
10801
10802 // starts_with, not contains: a prefix embedded mid-string
10803 // never matches. Pins the routing invariant [`WitContract::target`]
10804 // relies on (an authored `:wit "custom:wasi:http/"` string
10805 // does not silently route through the HTTP arm just because
10806 // it happens to contain the canonical HTTP prefix).
10807 assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
10808 }
10809
10810 #[test]
10811 fn wit_shape_predicates_delegate_to_wit_shape_matches() {
10812 // Equivalence pin: each per-shape predicate is exactly
10813 // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
10814 // every canonical prefix + the empty string + one negative
10815 // sample against every peer so a future predicate that grew
10816 // its own inline `iter().any(starts_with)` (rather than
10817 // delegating through the lifted combinator) drifts loudly here
10818 // — the peer-const table's contents must agree with the
10819 // predicate's accept-set by construction.
10820 let samples = [
10821 String::new(),
10822 "wasi:http/proxy".to_string(),
10823 "http:incoming".to_string(),
10824 "nats:pub-sub".to_string(),
10825 "kafka:topic".to_string(),
10826 "wasi:keyvalue/store".to_string(),
10827 "kv:cache/session".to_string(),
10828 "custom-shape".to_string(),
10829 "WASI:HTTP/proxy".to_string(),
10830 ];
10831 for wit in &samples {
10832 assert_eq!(
10833 wit_shape_is_http(wit),
10834 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
10835 "wit_shape_is_http drifted from combinator on {wit:?}",
10836 );
10837 assert_eq!(
10838 wit_shape_is_pubsub(wit),
10839 wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
10840 "wit_shape_is_pubsub drifted from combinator on {wit:?}",
10841 );
10842 assert_eq!(
10843 wit_shape_is_store(wit),
10844 wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
10845 "wit_shape_is_store drifted from combinator on {wit:?}",
10846 );
10847 }
10848 }
10849
10850 #[test]
10851 fn wit_contract_shape_methods_delegate_to_free_functions() {
10852 // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
10853 // `is_store` are `&self` conveniences on top of the free
10854 // functions — for every canonical prefix the method's return
10855 // matches its free-function peer. Sweeps the union of the
10856 // three prefix sets so a future method that grew its own
10857 // inline prefix logic (rather than delegating) drifts loudly
10858 // here on the first prefix the free function accepts and the
10859 // method doesn't.
10860 for shape_set in [
10861 WIT_HTTP_SHAPE_PREFIXES,
10862 WIT_PUBSUB_SHAPE_PREFIXES,
10863 WIT_STORE_SHAPE_PREFIXES,
10864 ] {
10865 for prefix in shape_set {
10866 let c = WitContract {
10867 de: "cart".into(),
10868 para: "catalog".into(),
10869 wit: format!("{prefix}x"),
10870 endpoint: None,
10871 subject: None,
10872 slot: None,
10873 };
10874 assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
10875 assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
10876 assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
10877 }
10878 }
10879 }
10880
10881 #[test]
10882 fn wit_contract_is_capability_partitions_the_wit_shape_space() {
10883 // 4-way partition-witness pin: for every canonical prefix in
10884 // the payload-arm accept-sets, exactly one of the four
10885 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
10886 // [`WitContract::is_store`] / [`WitContract::is_capability`]
10887 // predicates returns `true` and the other three return `false`
10888 // — the four-arm partition witness that locks the substrate's
10889 // WIT-shape-space closure on the pre-projection axis load-
10890 // bearing. A future arm addition (a hypothetical fourth
10891 // payload-shape prefix set, a `wasi:sockets/*` transport-layer
10892 // shape) that landed on one of the payload-arm predicates
10893 // without shrinking [`WitContract::is_capability`]'s accept-set
10894 // would surface here as two arms returning `true` simultaneously
10895 // — a partition-witness break the pin catches at caixa-core
10896 // build time rather than a silent per-consumer misclassification
10897 // at renderer emit time. Peer of the sibling `WitTarget`-side
10898 // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
10899 // partition-witness pin on the post-projection payload-scalar
10900 // arm-set — extends the discipline onto the pre-projection
10901 // 4-arm shape-space.
10902 for shape_set in [
10903 WIT_HTTP_SHAPE_PREFIXES,
10904 WIT_PUBSUB_SHAPE_PREFIXES,
10905 WIT_STORE_SHAPE_PREFIXES,
10906 ] {
10907 for prefix in shape_set {
10908 let c = WitContract {
10909 de: "cart".into(),
10910 para: "catalog".into(),
10911 wit: format!("{prefix}x"),
10912 endpoint: None,
10913 subject: None,
10914 slot: None,
10915 };
10916 let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
10917 .iter()
10918 .filter(|&&b| b)
10919 .count();
10920 assert_eq!(
10921 hits,
10922 1,
10923 "WitContract WIT-shape 4-way predicate partition must \
10924 admit exactly one arm per canonical prefix; got {hits} \
10925 hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
10926 is_capability={})",
10927 c.wit,
10928 c.is_http(),
10929 c.is_pubsub(),
10930 c.is_store(),
10931 c.is_capability(),
10932 );
10933 }
10934 }
10935 // Capability-arm sweep: two representative capability shapes
10936 // (a bare WIT world outside the three payload-arm prefix sets,
10937 // and the deliberately-shaped empty string that
10938 // [`crate::render::is_wit_world_ref`] rejects at
10939 // [`WitContract::target`] time but which the pure classifier
10940 // still admits — see the method docstring's "purely syntactic
10941 // classification" note). Both must land on the fourth arm
10942 // exclusively, so the partition witness holds across the full
10943 // 4-arm closure.
10944 for wit in ["custom:capability-only", ""] {
10945 let c = WitContract {
10946 de: "cart".into(),
10947 para: "catalog".into(),
10948 wit: wit.into(),
10949 endpoint: None,
10950 subject: None,
10951 slot: None,
10952 };
10953 let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
10954 .iter()
10955 .filter(|&&b| b)
10956 .count();
10957 assert_eq!(
10958 hits, 1,
10959 "WitContract WIT-shape 4-way predicate partition must \
10960 admit exactly one arm on Capability-shaped wit={wit:?}"
10961 );
10962 assert!(
10963 c.is_capability(),
10964 "wit={wit:?} must project onto the Capability arm"
10965 );
10966 }
10967 }
10968
10969 #[test]
10970 fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
10971 // Composition-witness pin: [`WitContract::is_capability`] is the
10972 // exact-inverse disjunction of the sibling payload-arm predicate
10973 // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
10974 // [`WitContract::is_store`]. A future reimplementation that
10975 // grew its own prefix-set scan (e.g. inlining a fourth
10976 // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
10977 // own today) rather than delegating to the sibling trio would
10978 // drift loudly here — the composition contract binds the
10979 // fourth-arm predicate to the exact-inverse of the three
10980 // payload-arm predicates, so any rebrand of any prefix-set const
10981 // flows through this method by construction without a
10982 // coordinated per-consumer rewrite. Sweeps the union of the
10983 // three payload-arm prefix sets plus two Capability-shaped
10984 // shapes (a bare non-prefix-matching WIT world, the deliberately-
10985 // empty string the pure classifier still admits per the method
10986 // docstring's "purely syntactic classification" note).
10987 let mut cases: Vec<String> = Vec::new();
10988 for shape_set in [
10989 WIT_HTTP_SHAPE_PREFIXES,
10990 WIT_PUBSUB_SHAPE_PREFIXES,
10991 WIT_STORE_SHAPE_PREFIXES,
10992 ] {
10993 for prefix in shape_set {
10994 cases.push(format!("{prefix}x"));
10995 }
10996 }
10997 cases.push("custom:capability-only".to_string());
10998 cases.push(String::new());
10999 for wit in cases {
11000 let c = WitContract {
11001 de: "cart".into(),
11002 para: "catalog".into(),
11003 wit: wit.clone(),
11004 endpoint: None,
11005 subject: None,
11006 slot: None,
11007 };
11008 assert_eq!(
11009 c.is_capability(),
11010 !c.is_http() && !c.is_pubsub() && !c.is_store(),
11011 "WitContract::is_capability must equal \
11012 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
11013 );
11014 }
11015 }
11016
11017 #[test]
11018 fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
11019 // Cross-projection-witness pin: whenever [`WitContract::target`]
11020 // succeeds, the pre-projection [`WitContract::is_capability`]
11021 // classification agrees with the post-projection
11022 // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
11023 // predicate — the 4-arm typed partition on the substrate's
11024 // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
11025 // partition on the pre-projection axis line up by construction.
11026 // A future divergence between the two axes (a peer
11027 // [`WitTarget`] variant addition that landed on the typed-view
11028 // surface without a peer prefix-set + [`WitContract`] predicate
11029 // extension, or vice versa) would surface here at caixa-core
11030 // build time rather than a silent per-consumer split at renderer
11031 // emit time. Peer of the sibling pre-/post-projection
11032 // agreement pins the payload-carrier trio
11033 // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11034 // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
11035 // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
11036 // post-projection — b11bb49 trio lift) already carry across the
11037 // three payload arms — this pin closes the pair on the fourth
11038 // payload-less arm.
11039 let http = WitContract {
11040 de: "cart".into(),
11041 para: "catalog".into(),
11042 wit: "wasi:http/proxy".into(),
11043 endpoint: Some("/x".into()),
11044 subject: None,
11045 slot: None,
11046 };
11047 assert!(!http.is_capability());
11048 assert!(!http.target().unwrap().is_capability());
11049
11050 let nats = WitContract {
11051 de: "cart".into(),
11052 para: "catalog".into(),
11053 wit: "nats:pub-sub".into(),
11054 endpoint: None,
11055 subject: Some("events.x".into()),
11056 slot: None,
11057 };
11058 assert!(!nats.is_capability());
11059 assert!(!nats.target().unwrap().is_capability());
11060
11061 let kv = WitContract {
11062 de: "cart".into(),
11063 para: "catalog".into(),
11064 wit: "wasi:keyvalue/store".into(),
11065 endpoint: None,
11066 subject: None,
11067 slot: Some("checkout/$orderId".into()),
11068 };
11069 assert!(!kv.is_capability());
11070 assert!(!kv.target().unwrap().is_capability());
11071
11072 let cap = WitContract {
11073 de: "cart".into(),
11074 para: "catalog".into(),
11075 wit: "custom:capability-only".into(),
11076 endpoint: None,
11077 subject: None,
11078 slot: None,
11079 };
11080 assert!(cap.is_capability());
11081 assert!(cap.target().unwrap().is_capability());
11082 }
11083
11084 #[test]
11085 fn empty_wit_takes_precedence_over_invalid() {
11086 // Ordering pin: `EmptyWit` is the more self-locating
11087 // diagnostic on `""` and must lead — the value-shape gate is
11088 // only reached after the empty-check fires. Mirrors
11089 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11090 // the peer payload axis.
11091 let mut s = three_member_spec();
11092 s.contratos.push(WitContract {
11093 de: "payment".into(),
11094 para: "catalog".into(),
11095 wit: String::new(),
11096 endpoint: None,
11097 subject: None,
11098 slot: None,
11099 });
11100 let err = s.validate().unwrap_err();
11101 assert!(
11102 matches!(err, AplicacaoError::EmptyWit { .. }),
11103 "got {err:?}"
11104 );
11105 }
11106
11107 #[test]
11108 fn wit_invalid_fires_before_payload_shape_arm() {
11109 // Ordering pin: a malformed `:wit` surfaces *its own*
11110 // diagnostic (which names the offending wit verbatim) before
11111 // any payload-field check — a contrato whose wit is
11112 // structurally invalid AND carries a wrong target field
11113 // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
11114 // because the dispatch on the wit is what decides which
11115 // payload field is "right" in the first place. Without this
11116 // ordering, the author would see "wrong target field" for a
11117 // wit that hasn't even been parsed, which doesn't name the
11118 // root cause.
11119 let mut s = three_member_spec();
11120 s.contratos.push(WitContract {
11121 de: "payment".into(),
11122 para: "catalog".into(),
11123 // Hyphen-for-colon typo + endpoint set: pre-gate this
11124 // raised `ContratoWrongTarget { expected: "none" }` (the
11125 // Capability arm rejecting the endpoint), masking the
11126 // real authoring mistake (the wit isn't `wasi:http/proxy`).
11127 wit: "wasi-http/proxy".into(),
11128 endpoint: Some("/x".into()),
11129 subject: None,
11130 slot: None,
11131 });
11132 let err = s.validate().unwrap_err();
11133 assert!(
11134 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
11135 if wit == "wasi-http/proxy"),
11136 "got {err:?}"
11137 );
11138 }
11139
11140 #[test]
11141 fn wit_invalid_diagnostic_carries_offending_wit() {
11142 // Diagnostic-shape pin — the offending `:wit` + `:de` +
11143 // `:para` + a non-empty reason flow through verbatim so the
11144 // author can grep their caixa.lisp for the offending contrato
11145 // block and fix it in one edit. Same shape as
11146 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
11147 let err = contrato_wit_err("WASI:HTTP/proxy");
11148 match err {
11149 AplicacaoError::ContratoWitInvalid {
11150 de,
11151 para,
11152 wit,
11153 reason,
11154 } => {
11155 assert_eq!(de, "payment");
11156 assert_eq!(para, "catalog");
11157 assert_eq!(wit, "WASI:HTTP/proxy");
11158 assert!(!reason.is_empty(), "reason field must be non-empty");
11159 }
11160 other => panic!("expected ContratoWitInvalid, got {other:?}"),
11161 }
11162 }
11163
11164 // ── :contratos :subject value-shape gate ─────────────────────────────
11165 //
11166 // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
11167 // suites on the peer payload axes. Until this gate landed
11168 // `WitContract::target()` only refused the empty string; a
11169 // structurally invalid subject silently passed validate and the
11170 // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
11171 // Subject'` on publish / subscribe, or as a silent message drop,
11172 // far from the source caixa.lisp. Every authoring footgun the
11173 // NATS server's subject parser would catch on admission now
11174 // becomes a caixa-build-time `ContratoSubjectInvalid` with the
11175 // offending `:subject` + `:de` + `:para` named verbatim. Same
11176 // diagnostic shape as `ContratoEndpointInvalid` /
11177 // `ContratoWitInvalid` on the peer payload axes; same shared
11178 // predicate (`crate::render::is_nats_subject`) ensures drift
11179 // between any two axes' rule enforcement is a build error at the
11180 // predicate, not piecemeal across renderers.
11181
11182 fn contrato_subject_err(subject: &str) -> AplicacaoError {
11183 // Fresh spec per call so the new contract doesn't collide on
11184 // identity with `three_member_spec`'s pre-existing entries.
11185 // The new edge uses `(payment, catalog)` — a pair the fixture
11186 // doesn't already declare — with `:wit "nats:pub-sub"` and the
11187 // varying `:subject`, so the subject-shape gate fires cleanly
11188 // after the wit-shape gate (which `"nats:pub-sub"` passes).
11189 let mut s = three_member_spec();
11190 s.contratos.push(WitContract {
11191 de: "payment".into(),
11192 para: "catalog".into(),
11193 wit: "nats:pub-sub".into(),
11194 endpoint: None,
11195 subject: Some(subject.into()),
11196 slot: None,
11197 });
11198 s.validate().unwrap_err()
11199 }
11200
11201 #[test]
11202 fn rejects_pubsub_contrato_subject_with_whitespace() {
11203 // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
11204 // landed at the NATS server as a malformed subject the parser
11205 // rejects with `-ERR 'Invalid Subject'`. Now caught at the
11206 // source caixa.lisp.
11207 let err = contrato_subject_err("foo bar");
11208 assert!(
11209 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11210 if subject == "foo bar" && reason.contains("whitespace")),
11211 "got {err:?}"
11212 );
11213 }
11214
11215 #[test]
11216 fn rejects_pubsub_contrato_subject_with_control_char() {
11217 let err = contrato_subject_err("foo\x01bar");
11218 assert!(
11219 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11220 if subject == "foo\x01bar" && reason.contains("control character")),
11221 "got {err:?}"
11222 );
11223 }
11224
11225 #[test]
11226 fn rejects_pubsub_contrato_subject_with_non_ascii() {
11227 // Un-percent-encoded non-ASCII byte — the canonical "I copied
11228 // the subject from a doc with smart quotes / accented
11229 // characters" footgun.
11230 let err = contrato_subject_err("foo.caf\u{e9}");
11231 assert!(
11232 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11233 if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
11234 "got {err:?}"
11235 );
11236 }
11237
11238 #[test]
11239 fn rejects_pubsub_contrato_subject_with_leading_dot() {
11240 // Empty leading token — NATS rejects.
11241 let err = contrato_subject_err(".foo");
11242 assert!(
11243 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11244 if subject == ".foo" && reason.contains("must not start with `.`")),
11245 "got {err:?}"
11246 );
11247 }
11248
11249 #[test]
11250 fn rejects_pubsub_contrato_subject_with_trailing_dot() {
11251 // Empty trailing token — NATS rejects. The remediation
11252 // (use `>` instead) is in the reason string.
11253 let err = contrato_subject_err("foo.");
11254 assert!(
11255 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11256 if subject == "foo." && reason.contains("must not end with `.`")),
11257 "got {err:?}"
11258 );
11259 }
11260
11261 #[test]
11262 fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
11263 // The canonical "I forgot to fill in the middle segment"
11264 // typo — `"foo..bar"`. NATS rejects empty tokens.
11265 let err = contrato_subject_err("foo..bar");
11266 assert!(
11267 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11268 if subject == "foo..bar" && reason.contains("consecutive `.`")),
11269 "got {err:?}"
11270 );
11271 }
11272
11273 #[test]
11274 fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
11275 // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
11276 // as the final segment. Pre-gate this passed as a typed edge
11277 // and surfaced at runtime as a NATS subscribe rejection.
11278 let err = contrato_subject_err("foo.>.bar");
11279 assert!(
11280 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11281 if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
11282 "got {err:?}"
11283 );
11284 }
11285
11286 #[test]
11287 fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
11288 // `foo*.bar` — NATS wildcards are standalone tokens. The
11289 // remediation is in the reason string.
11290 let err = contrato_subject_err("foo*.bar");
11291 assert!(
11292 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11293 if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
11294 "got {err:?}"
11295 );
11296 }
11297
11298 #[test]
11299 fn rejects_pubsub_contrato_subject_with_invalid_char() {
11300 // `foo,bar` — comma is not a valid NATS subject character.
11301 // Pinned separately from the wildcard arms so the invalid-
11302 // character diagnostic is in force.
11303 let err = contrato_subject_err("foo,bar");
11304 assert!(
11305 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11306 if subject == "foo,bar" && reason.contains("invalid character")),
11307 "got {err:?}"
11308 );
11309 }
11310
11311 #[test]
11312 fn rejects_pubsub_contrato_subject_too_long() {
11313 // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
11314 // The legitimate-shape arms all pass (one all-`a` token, no
11315 // `.`, no wildcards); only the cap arm fires. Surfaces the
11316 // paste-from-binary / accidental-multi-line-blob landing
11317 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
11318 // on the peer axis.
11319 let big = "a".repeat(257);
11320 assert_eq!(big.len(), 257);
11321 let err = contrato_subject_err(&big);
11322 assert!(
11323 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11324 if subject == &big && reason.contains("max length of 256")),
11325 "got {err:?}"
11326 );
11327 }
11328
11329 #[test]
11330 fn pubsub_contrato_subject_max_length_validates() {
11331 // 256-byte subject — exactly the cap. Boundary pin: drift in
11332 // the cap surfaces here and at
11333 // `rejects_pubsub_contrato_subject_too_long` simultaneously,
11334 // mirroring `http_contrato_endpoint_max_length_validates` and
11335 // `wit_max_length_validates` on the peer axes.
11336 let big = "a".repeat(256);
11337 assert_eq!(big.len(), 256);
11338 let mut s = three_member_spec();
11339 s.contratos.push(WitContract {
11340 de: "payment".into(),
11341 para: "catalog".into(),
11342 wit: "nats:pub-sub".into(),
11343 endpoint: None,
11344 subject: Some(big),
11345 slot: None,
11346 });
11347 s.validate().unwrap();
11348 }
11349
11350 #[test]
11351 fn pubsub_contrato_subject_accepts_canonical_forms() {
11352 // Positive-set sweep: every canonical NATS subject shape the
11353 // substrate-side `is_nats_subject` predicate accepts (the
11354 // multi-dot `events.order.charged`, the snake_case / kebab-
11355 // case / mixed-case tokens, the digit-bearing tokens, the
11356 // single-token wildcard `*` at every segment position, and
11357 // the trailing `>` multi-token wildcard) must remain a valid
11358 // contrato subject too. Drift between this list and the
11359 // substrate-side `nats_subject_accepts_canonical_forms` sweep
11360 // surfaces at the shared predicate — one source of truth.
11361 // Uses a fresh `(payment, catalog)` edge so none of the swept
11362 // subjects collide with the pre-existing entries in
11363 // `three_member_spec`.
11364 for subject in [
11365 "checkout.events.charge.failed",
11366 "rio.events.order.charged",
11367 "orders",
11368 "orders.123",
11369 "snake_case.token",
11370 "kebab-case.token",
11371 "MixedCase.Token",
11372 "orders.*.charged",
11373 "*.events.*",
11374 "orders.>",
11375 ] {
11376 let mut s = three_member_spec();
11377 s.contratos.push(WitContract {
11378 de: "payment".into(),
11379 para: "catalog".into(),
11380 wit: "nats:pub-sub".into(),
11381 endpoint: None,
11382 subject: Some(subject.into()),
11383 slot: None,
11384 });
11385 s.validate()
11386 .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
11387 }
11388 }
11389
11390 #[test]
11391 fn contrato_subject_empty_takes_precedence_over_invalid() {
11392 // Ordering pin: `ContratoSubjectEmpty` is the more self-
11393 // locating diagnostic on `""` and must lead — the value-shape
11394 // gate is only reached after the empty-check fires. Mirrors
11395 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11396 // the peer payload axis.
11397 let mut s = three_member_spec();
11398 s.contratos.push(WitContract {
11399 de: "payment".into(),
11400 para: "catalog".into(),
11401 wit: "nats:pub-sub".into(),
11402 endpoint: None,
11403 subject: Some(String::new()),
11404 slot: None,
11405 });
11406 let err = s.validate().unwrap_err();
11407 assert!(
11408 matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
11409 "got {err:?}"
11410 );
11411 }
11412
11413 #[test]
11414 fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
11415 // Diagnostic-shape pin — the offending `:subject` + `:de` +
11416 // `:para` + a non-empty reason flow through verbatim so the
11417 // author can grep their caixa.lisp for the offending contrato
11418 // block and fix it in one edit. Same shape as
11419 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
11420 // and `wit_invalid_diagnostic_carries_offending_wit`.
11421 let err = contrato_subject_err("foo..bar");
11422 match err {
11423 AplicacaoError::ContratoSubjectInvalid {
11424 de,
11425 para,
11426 subject,
11427 reason,
11428 } => {
11429 assert_eq!(de, "payment");
11430 assert_eq!(para, "catalog");
11431 assert_eq!(subject, "foo..bar");
11432 assert!(!reason.is_empty(), "reason field must be non-empty");
11433 }
11434 other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
11435 }
11436 }
11437
11438 #[test]
11439 fn target_view_pubsub_subject_passes_through_to_typed_view() {
11440 // The compounding theorem on the pub-sub axis: every
11441 // `WitTarget::PubSub { subject }` returned by `target()` carries
11442 // a NATS-server-accepted subject. Renderers downstream of
11443 // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
11444 // NATS Stream/Consumer CR emitter, the future `feira app graph`
11445 // view's subject labeller) can rely on this without re-checking
11446 // — the type system carries the proof. Mirrors
11447 // `target_view_payload_is_guaranteed_nonempty_after_target_call`
11448 // on the peer axes.
11449 let nats = WitContract {
11450 de: "a".into(),
11451 para: "b".into(),
11452 wit: "nats:pub-sub".into(),
11453 endpoint: None,
11454 subject: Some("orders.events.*.charged".into()),
11455 slot: None,
11456 };
11457 match nats.target().unwrap() {
11458 WitTarget::PubSub { subject } => {
11459 assert_eq!(subject, "orders.events.*.charged");
11460 }
11461 other => panic!("expected PubSub, got {other:?}"),
11462 }
11463 }
11464
11465 // ── :contratos :slot value-shape gate ────────────────────────────────
11466 //
11467 // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
11468 // (63e18a0) value-shape suites on the peer payload axes. Until this
11469 // gate landed `WitContract::target()` only refused the empty string
11470 // for the Store arm; a structurally invalid slot (raw whitespace,
11471 // control character, non-ASCII byte, paste-from-binary multi-line
11472 // blob) silently passed validate and surfaced at runtime as a
11473 // per-backend kv write rejection or a silent next-read corruption,
11474 // far from the source caixa.lisp with no field naming which
11475 // `:contratos` edge carried the typo. Every authoring footgun the
11476 // kv backend intersection-floor would catch on write now becomes a
11477 // caixa-build-time `ContratoSlotInvalid` with the offending
11478 // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
11479 // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
11480 // peer payload axes; same shared predicate
11481 // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
11482 // any two axes' rule enforcement is a build error at the
11483 // predicate, not piecemeal across renderers. Closes the typed
11484 // payload-axis value-shape trajectory across all three legs of the
11485 // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
11486
11487 fn contrato_slot_err(slot: &str) -> AplicacaoError {
11488 // Fresh spec per call so the new contract doesn't collide on
11489 // identity with `three_member_spec`'s pre-existing entries
11490 // and doesn't close a synchronous cycle the cycle detector
11491 // would reject before the slot-shape gate fires. The new edge
11492 // uses `(payment, catalog)` — a pair the fixture doesn't
11493 // already declare in either direction (the fixture carries
11494 // `cart -> catalog` and `cart -> payment`, so `payment ->
11495 // catalog` doesn't form a cycle on the sync subgraph) — with
11496 // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
11497 // slot-shape gate fires cleanly after the wit-shape gate
11498 // (which `"wasi:keyvalue/store"` passes). Same edge pair the
11499 // peer `contrato_subject_err` helper uses (63e18a0).
11500 let mut s = three_member_spec();
11501 s.contratos.push(WitContract {
11502 de: "payment".into(),
11503 para: "catalog".into(),
11504 wit: "wasi:keyvalue/store".into(),
11505 endpoint: None,
11506 subject: None,
11507 slot: Some(slot.into()),
11508 });
11509 s.validate().unwrap_err()
11510 }
11511
11512 #[test]
11513 fn rejects_store_contrato_slot_with_whitespace() {
11514 // Fail-before-pass-after pin — pre-gate `"check out/$order"`
11515 // silently landed at the kv backend with whitespace whose
11516 // runtime behavior varies unpredictably across backends (etcd
11517 // accepts, Redis accepts then breaks on next CLI op, DynamoDB
11518 // rejects on write). Now caught at the source caixa.lisp.
11519 let err = contrato_slot_err("check out/$order");
11520 assert!(
11521 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11522 if slot == "check out/$order" && reason.contains("whitespace")),
11523 "got {err:?}"
11524 );
11525 }
11526
11527 #[test]
11528 fn rejects_store_contrato_slot_with_tab() {
11529 // Tab byte arm-pinned separately from the space arm so a
11530 // future relaxation that admits one but not the other surfaces
11531 // here.
11532 let err = contrato_slot_err("check\tout");
11533 assert!(
11534 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11535 if slot == "check\tout" && reason.contains("whitespace")),
11536 "got {err:?}"
11537 );
11538 }
11539
11540 #[test]
11541 fn rejects_store_contrato_slot_with_control_char() {
11542 // SOH (0x01) — distinct from the whitespace arm. Redis admits
11543 // and corrupts on RESP protocol framing; DynamoDB rejects on
11544 // write.
11545 let err = contrato_slot_err("checkout/\x01order");
11546 assert!(
11547 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11548 if slot == "checkout/\x01order" && reason.contains("control character")),
11549 "got {err:?}"
11550 );
11551 }
11552
11553 #[test]
11554 fn rejects_store_contrato_slot_with_newline() {
11555 // Embedded newline — the canonical "the paste-from-binary slug
11556 // spans multiple lines" footgun. Distinct from the whitespace
11557 // arm because `\n` is a control character (0x0A).
11558 let err = contrato_slot_err("checkout\norder");
11559 assert!(
11560 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11561 if slot == "checkout\norder" && reason.contains("control character")),
11562 "got {err:?}"
11563 );
11564 }
11565
11566 #[test]
11567 fn rejects_store_contrato_slot_with_non_ascii() {
11568 // Un-percent-encoded non-ASCII byte — the canonical "I copied
11569 // the slot from a doc with accented characters" footgun. Each
11570 // kv backend re-encodes non-ASCII differently (etcd preserves
11571 // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
11572 // rejects), so the typed slot's value set is the intersection-
11573 // floor every backend admits identically (printable ASCII).
11574 let err = contrato_slot_err("ch\u{e9}ckout/$order");
11575 assert!(
11576 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11577 if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
11578 "got {err:?}"
11579 );
11580 }
11581
11582 #[test]
11583 fn rejects_store_contrato_slot_too_long() {
11584 // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
11585 // legitimate-shape arms all pass (a single all-`a` token, no
11586 // separators); only the cap arm fires. Surfaces the paste-
11587 // from-binary / accidental-multi-line-blob landing footgun.
11588 // Mirrors `rejects_pubsub_contrato_subject_too_long` and
11589 // `rejects_http_contrato_endpoint_too_long` on the peer
11590 // payload axes.
11591 let big = "a".repeat(513);
11592 assert_eq!(big.len(), 513);
11593 let err = contrato_slot_err(&big);
11594 assert!(
11595 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11596 if slot == &big && reason.contains("max length of 512")),
11597 "got {err:?}"
11598 );
11599 }
11600
11601 #[test]
11602 fn store_contrato_slot_max_length_validates() {
11603 // 512-byte slot — exactly the cap. Boundary pin: drift in the
11604 // cap surfaces here and at `rejects_store_contrato_slot_too_long`
11605 // simultaneously, mirroring
11606 // `pubsub_contrato_subject_max_length_validates` and
11607 // `http_contrato_endpoint_max_length_validates` on the peer
11608 // payload axes.
11609 let big = "a".repeat(512);
11610 assert_eq!(big.len(), 512);
11611 let mut s = three_member_spec();
11612 s.contratos.push(WitContract {
11613 de: "payment".into(),
11614 para: "catalog".into(),
11615 wit: "wasi:keyvalue/store".into(),
11616 endpoint: None,
11617 subject: None,
11618 slot: Some(big),
11619 });
11620 s.validate().unwrap();
11621 }
11622
11623 #[test]
11624 fn store_contrato_slot_accepts_canonical_forms() {
11625 // Positive-set sweep: every canonical kv slot template the
11626 // substrate-side `is_wasi_keyvalue_slot` predicate accepts
11627 // (single-token identifiers, path-namespaced `$`-templates,
11628 // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
11629 // snake_case / kebab-case / MixedCase tokens, digit-bearing
11630 // tokens, percent-encoded fragments) must remain valid
11631 // contrato slots too. Drift between this list and the
11632 // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
11633 // surfaces at the shared predicate — one source of truth.
11634 // Uses a fresh `(payment, catalog)` edge so none of the swept
11635 // slots collide with the pre-existing entries in
11636 // `three_member_spec`.
11637 for slot in [
11638 "checkout",
11639 "checkout/$orderId",
11640 "users:{tenant}/{id}",
11641 "session.<sid>",
11642 "session.tokens.<sid>",
11643 "snake_case_key",
11644 "kebab-case-key",
11645 "MixedCase",
11646 "shard0",
11647 "v2/key",
11648 "users/caf%C3%A9",
11649 ] {
11650 let mut s = three_member_spec();
11651 s.contratos.push(WitContract {
11652 de: "payment".into(),
11653 para: "catalog".into(),
11654 wit: "wasi:keyvalue/store".into(),
11655 endpoint: None,
11656 subject: None,
11657 slot: Some(slot.into()),
11658 });
11659 s.validate()
11660 .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
11661 }
11662 }
11663
11664 #[test]
11665 fn contrato_slot_empty_takes_precedence_over_invalid() {
11666 // Ordering pin: `ContratoSlotEmpty` is the more self-locating
11667 // diagnostic on `""` and must lead — the value-shape gate is
11668 // only reached after the empty-check fires. Mirrors
11669 // `contrato_subject_empty_takes_precedence_over_invalid` and
11670 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11671 // the peer payload axes.
11672 let mut s = three_member_spec();
11673 s.contratos.push(WitContract {
11674 de: "payment".into(),
11675 para: "catalog".into(),
11676 wit: "wasi:keyvalue/store".into(),
11677 endpoint: None,
11678 subject: None,
11679 slot: Some(String::new()),
11680 });
11681 let err = s.validate().unwrap_err();
11682 assert!(
11683 matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
11684 "got {err:?}"
11685 );
11686 }
11687
11688 #[test]
11689 fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
11690 // Diagnostic-shape pin — the offending `:slot` + `:de` +
11691 // `:para` + a non-empty reason flow through verbatim so the
11692 // author can grep their caixa.lisp for the offending contrato
11693 // block and fix it in one edit. Same shape as
11694 // `contrato_subject_invalid_diagnostic_carries_offending_subject`
11695 // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
11696 // on the peer payload axes.
11697 let err = contrato_slot_err("check out/$order");
11698 match err {
11699 AplicacaoError::ContratoSlotInvalid {
11700 de,
11701 para,
11702 slot,
11703 reason,
11704 } => {
11705 assert_eq!(de, "payment");
11706 assert_eq!(para, "catalog");
11707 assert_eq!(slot, "check out/$order");
11708 assert!(!reason.is_empty(), "reason field must be non-empty");
11709 }
11710 other => panic!("expected ContratoSlotInvalid, got {other:?}"),
11711 }
11712 }
11713
11714 #[test]
11715 fn target_view_store_slot_passes_through_to_typed_view() {
11716 // The compounding theorem on the store axis: every
11717 // `WitTarget::Store { slot }` returned by `target()` carries a
11718 // kv-backend-accepted slot template. Renderers downstream of
11719 // `typed_view()` (the future per-Servico `:capabilities
11720 // wasi:keyvalue/store` axis emitter, the future `feira app
11721 // graph` view's slot labeller, the future kv-provider CR
11722 // materializer) can rely on this without re-checking — the
11723 // type system carries the proof. Mirrors
11724 // `target_view_pubsub_subject_passes_through_to_typed_view` on
11725 // the peer payload axis.
11726 let store = WitContract {
11727 de: "a".into(),
11728 para: "b".into(),
11729 wit: "wasi:keyvalue/store".into(),
11730 endpoint: None,
11731 subject: None,
11732 slot: Some("checkout/$orderId".into()),
11733 };
11734 match store.target().unwrap() {
11735 WitTarget::Store { slot } => {
11736 assert_eq!(slot, "checkout/$orderId");
11737 }
11738 other => panic!("expected Store, got {other:?}"),
11739 }
11740 }
11741
11742 #[test]
11743 fn rejects_self_loop_in_synchronous_contratos() {
11744 // A synchronous self-edge (`cart → cart` over HTTP) is now
11745 // rejected by the dedicated `ContratoSelfLoop` gate — a precise
11746 // "this edge is degenerate" diagnostic — rather than incidentally
11747 // by the cycle detector framing it as a `["cart", "cart"]`
11748 // multi-node deadlock.
11749 let mut s = three_member_spec();
11750 s.contratos.push(contract_http("cart", "cart", "/loop"));
11751 let err = s.validate().unwrap_err();
11752 match err {
11753 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
11754 assert_eq!(caixa, "cart");
11755 assert_eq!(wit, "wasi:http/proxy");
11756 }
11757 other => panic!("expected ContratoSelfLoop, got {other:?}"),
11758 }
11759 }
11760
11761 #[test]
11762 fn rejects_self_loop_in_pubsub_contratos() {
11763 // The cycle detector excludes pub-sub edges (acyclic by
11764 // construction), so before the explicit gate a `nats:pub-sub`
11765 // self-edge silently validated and rendered a self-allow CNP.
11766 // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
11767 let mut s = three_member_spec();
11768 s.contratos.push(WitContract {
11769 de: "payment".into(),
11770 para: "payment".into(),
11771 wit: "nats:pub-sub".into(),
11772 endpoint: None,
11773 subject: Some("rio.events.payment".into()),
11774 slot: None,
11775 });
11776 let err = s.validate().unwrap_err();
11777 match err {
11778 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
11779 assert_eq!(caixa, "payment");
11780 assert_eq!(wit, "nats:pub-sub");
11781 }
11782 other => panic!("expected ContratoSelfLoop, got {other:?}"),
11783 }
11784 }
11785
11786 #[test]
11787 fn self_loop_fires_before_payload_shape_check() {
11788 // The structural "this edge can't exist" error precedes the
11789 // narrower payload-shape diagnostics: a self-edge carrying an
11790 // otherwise-malformed endpoint still reports ContratoSelfLoop,
11791 // not ContratoEndpointInvalid.
11792 let mut s = three_member_spec();
11793 s.contratos.push(WitContract {
11794 de: "cart".into(),
11795 para: "cart".into(),
11796 wit: "wasi:http/proxy".into(),
11797 endpoint: Some("not-absolute".into()),
11798 subject: None,
11799 slot: None,
11800 });
11801 match s.validate().unwrap_err() {
11802 AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
11803 other => panic!("expected ContratoSelfLoop, got {other:?}"),
11804 }
11805 }
11806
11807 #[test]
11808 fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
11809 // A self-edge naming a non-member reports the more fundamental
11810 // ContratoMemberMissing first (the member doesn't exist), so the
11811 // self-loop gate is reached only once both endpoints resolve.
11812 let mut s = three_member_spec();
11813 s.contratos.push(contract_http("ghost", "ghost", "/loop"));
11814 match s.validate().unwrap_err() {
11815 AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
11816 other => panic!("expected ContratoMemberMissing, got {other:?}"),
11817 }
11818 }
11819
11820 #[test]
11821 fn rejects_two_node_synchronous_cycle() {
11822 let mut s = three_member_spec();
11823 // existing edges: cart → catalog, cart → payment
11824 // adding catalog → cart closes a 2-cycle on the HTTP subgraph
11825 s.contratos
11826 .push(contract_http("catalog", "cart", "/refresh"));
11827 let err = s.validate().unwrap_err();
11828 match err {
11829 AplicacaoError::ContratoCycle { cycle } => {
11830 // Cycle traversal should mention both endpoints, with
11831 // the back-edge target appearing as both first and last
11832 // element to close the loop.
11833 assert!(cycle.len() >= 3);
11834 assert_eq!(cycle.first(), cycle.last());
11835 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
11836 assert!(body.contains("cart"));
11837 assert!(body.contains("catalog"));
11838 }
11839 other => panic!("expected ContratoCycle, got {other:?}"),
11840 }
11841 }
11842
11843 #[test]
11844 fn rejects_three_node_synchronous_cycle() {
11845 let mut s = three_member_spec();
11846 // Reset to a clean 3-cycle: catalog → cart → payment → catalog
11847 s.contratos = vec![
11848 contract_http("catalog", "cart", "/x"),
11849 contract_http("cart", "payment", "/y"),
11850 contract_http("payment", "catalog", "/z"),
11851 ];
11852 let err = s.validate().unwrap_err();
11853 match err {
11854 AplicacaoError::ContratoCycle { cycle } => {
11855 assert_eq!(cycle.first(), cycle.last());
11856 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
11857 assert_eq!(body.len(), 3);
11858 assert!(body.contains("cart"));
11859 assert!(body.contains("catalog"));
11860 assert!(body.contains("payment"));
11861 }
11862 other => panic!("expected ContratoCycle, got {other:?}"),
11863 }
11864 }
11865
11866 #[test]
11867 fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
11868 // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
11869 // "acyclic by construction" — so a cycle whose closing edge
11870 // is pub-sub should NOT raise ContratoCycle.
11871 let mut s = three_member_spec();
11872 s.contratos = vec![
11873 contract_http("catalog", "cart", "/x"),
11874 contract_http("cart", "payment", "/y"),
11875 // Closing edge is pub-sub — async; not a sync deadlock.
11876 WitContract {
11877 de: "payment".into(),
11878 para: "catalog".into(),
11879 wit: "nats:pub-sub".into(),
11880 endpoint: None,
11881 subject: Some("checkout.events.charge.completed".into()),
11882 slot: None,
11883 },
11884 ];
11885 s.validate().expect("pub-sub edge breaks the sync cycle");
11886 }
11887
11888 #[test]
11889 fn store_edge_counts_as_synchronous_for_cycle_detection() {
11890 // wasi:keyvalue/store is request/response; a cycle through one
11891 // *is* a sync deadlock, just like HTTP.
11892 let mut s = three_member_spec();
11893 s.contratos = vec![
11894 contract_http("catalog", "cart", "/x"),
11895 WitContract {
11896 de: "cart".into(),
11897 para: "catalog".into(),
11898 wit: "wasi:keyvalue/store".into(),
11899 endpoint: None,
11900 subject: None,
11901 slot: Some("session/$id".into()),
11902 },
11903 ];
11904 let err = s.validate().unwrap_err();
11905 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
11906 }
11907
11908 #[test]
11909 fn capability_edge_counts_as_synchronous_for_cycle_detection() {
11910 // Capability-only edges (unknown WIT shape, no payload) default
11911 // to synchronous — safer; authors with truly async capability
11912 // semantics can model them as pub-sub explicitly.
11913 let mut s = three_member_spec();
11914 s.contratos = vec![
11915 contract_http("catalog", "cart", "/x"),
11916 WitContract {
11917 de: "cart".into(),
11918 para: "catalog".into(),
11919 wit: "custom:exchange".into(),
11920 endpoint: None,
11921 subject: None,
11922 slot: None,
11923 },
11924 ];
11925 let err = s.validate().unwrap_err();
11926 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
11927 }
11928
11929 #[test]
11930 fn long_acyclic_chain_validates() {
11931 // A long sync chain (no back-edges) must validate even when
11932 // every node is reachable from the first.
11933 let mut s = three_member_spec();
11934 s.membros = vec![
11935 membro("a", "^0.1"),
11936 membro("b", "^0.1"),
11937 membro("c", "^0.1"),
11938 membro("d", "^0.1"),
11939 membro("e", "^0.1"),
11940 ];
11941 s.contratos = vec![
11942 contract_http("a", "b", "/1"),
11943 contract_http("b", "c", "/2"),
11944 contract_http("c", "d", "/3"),
11945 contract_http("d", "e", "/4"),
11946 ];
11947 s.entrada.as_mut().unwrap().para = "a".into();
11948 s.validate().unwrap();
11949 }
11950
11951 #[test]
11952 fn diamond_acyclic_validates() {
11953 // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
11954 let mut s = three_member_spec();
11955 s.membros = vec![
11956 membro("a", "^0.1"),
11957 membro("b", "^0.1"),
11958 membro("c", "^0.1"),
11959 membro("d", "^0.1"),
11960 ];
11961 s.contratos = vec![
11962 contract_http("a", "b", "/1"),
11963 contract_http("a", "c", "/2"),
11964 contract_http("b", "d", "/3"),
11965 contract_http("c", "d", "/4"),
11966 ];
11967 s.entrada.as_mut().unwrap().para = "a".into();
11968 s.validate().unwrap();
11969 }
11970
11971 // ── duplicate-`:contratos` build-error gate ──────────────────────────
11972
11973 #[test]
11974 fn rejects_duplicate_http_contrato() {
11975 // Fail-before-pass-after pin: the fixture's `cart → catalog`
11976 // HTTP edge appears once. Push an identical entry — same
11977 // (de, para, wit, endpoint) — and validate() must reject it.
11978 // Until this gate landed the typed surface accepted the
11979 // duplicate silently and caixa-mesh's `cilium_network_policies`
11980 // emitted two ``CiliumNetworkPolicy`` objects with identical
11981 // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
11982 // admission rejects on `kubectl apply` far from the source.
11983 let mut s = three_member_spec();
11984 s.contratos
11985 .push(contract_http("cart", "catalog", "/products/:id"));
11986 let err = s.validate().unwrap_err();
11987 assert!(
11988 matches!(
11989 err,
11990 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11991 if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
11992 ),
11993 "got {err:?}"
11994 );
11995 }
11996
11997 #[test]
11998 fn rejects_duplicate_pubsub_contrato() {
11999 // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
12000 // edges with identical (de, para, subject) are degenerate;
12001 // pin that the typed surface refuses both at validate time.
12002 let mut s = three_member_spec();
12003 let pubsub = WitContract {
12004 de: "payment".into(),
12005 para: "cart".into(),
12006 wit: "nats:pub-sub".into(),
12007 endpoint: None,
12008 subject: Some("checkout.events.charge.failed".into()),
12009 slot: None,
12010 };
12011 s.contratos.push(pubsub.clone());
12012 s.contratos.push(pubsub);
12013 let err = s.validate().unwrap_err();
12014 assert!(
12015 matches!(
12016 err,
12017 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12018 if de == "payment" && para == "cart" && wit == "nats:pub-sub"
12019 ),
12020 "got {err:?}"
12021 );
12022 }
12023
12024 #[test]
12025 fn rejects_duplicate_store_contrato() {
12026 // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
12027 // edges with identical (de, para, slot) collapse to one mesh-
12028 // policy edge; pin the build error.
12029 let mut s = three_member_spec();
12030 let store = WitContract {
12031 de: "cart".into(),
12032 para: "payment".into(),
12033 wit: "wasi:keyvalue/store".into(),
12034 endpoint: None,
12035 subject: None,
12036 slot: Some("checkout/$orderId".into()),
12037 };
12038 // Drop the conflicting HTTP `cart → payment` edge from the
12039 // fixture so the duplicate-store pair is the only one
12040 // distinguishable on this pair.
12041 s.contratos
12042 .retain(|c| !(c.de == "cart" && c.para == "payment"));
12043 s.contratos.push(store.clone());
12044 s.contratos.push(store);
12045 let err = s.validate().unwrap_err();
12046 assert!(
12047 matches!(
12048 err,
12049 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12050 if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
12051 ),
12052 "got {err:?}"
12053 );
12054 }
12055
12056 #[test]
12057 fn rejects_duplicate_capability_contrato() {
12058 // Same gate on the pure-capability axis (no payload selector).
12059 // Two contracts with identical (de, para, wit) and no
12060 // endpoint/subject/slot are duplicate edges; pin so a future
12061 // `target_label` change can't accidentally collapse the
12062 // capability arm into a None-shaped key that compares equal
12063 // to a populated one.
12064 let mut s = three_member_spec();
12065 let capability = WitContract {
12066 de: "cart".into(),
12067 para: "catalog".into(),
12068 wit: "pleme:cap/audit".into(),
12069 endpoint: None,
12070 subject: None,
12071 slot: None,
12072 };
12073 s.contratos.push(capability.clone());
12074 s.contratos.push(capability);
12075 let err = s.validate().unwrap_err();
12076 match err {
12077 AplicacaoError::ContratoDuplicate {
12078 de,
12079 para,
12080 wit,
12081 target,
12082 } => {
12083 assert_eq!(de, "cart");
12084 assert_eq!(para, "catalog");
12085 assert_eq!(wit, "pleme:cap/audit");
12086 assert!(
12087 target.contains("capability"),
12088 "capability-edge duplicate diagnostic must surface the \
12089 no-payload shape (got target = {target:?})"
12090 );
12091 }
12092 other => panic!("expected ContratoDuplicate, got {other:?}"),
12093 }
12094 }
12095
12096 #[test]
12097 fn accepts_distinct_http_paths_between_same_pair() {
12098 // Negative pin: two HTTP contracts cart → catalog at distinct
12099 // endpoints (`/products/:id` and `/search`) are *not*
12100 // duplicates — they're distinct typed edges differing on the
12101 // payload axis. The duplicate-gate must not over-match here,
12102 // since the cart-calls-catalog-on-multiple-paths shape is the
12103 // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
12104 // example: cart calls catalog at /products/:id, payment at
12105 // /charge — same shape extends to two paths on one para).
12106 let mut s = three_member_spec();
12107 s.contratos
12108 .push(contract_http("cart", "catalog", "/search"));
12109 s.validate()
12110 .expect("distinct endpoints between same (de, para) must validate");
12111 }
12112
12113 #[test]
12114 fn accepts_same_endpoint_on_different_pairs() {
12115 // Negative pin: the same `/charge` endpoint reused on two
12116 // different (de, para) pairs is two distinct edges, not a
12117 // duplicate. Pinning this shape so the gate's identity key
12118 // includes both `de` and `para` (not just `(wit, endpoint)`).
12119 let mut s = three_member_spec();
12120 s.contratos
12121 .push(contract_http("payment", "catalog", "/charge"));
12122 s.validate()
12123 .expect("same endpoint reused on distinct (de, para) must validate");
12124 }
12125
12126 #[test]
12127 fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
12128 // Pin the diagnostic shape: the duplicate-edge error names
12129 // *which* target field carried the conflict, so the author
12130 // doesn't have to re-grep the source caixa.lisp to find it.
12131 // Same self-locating diagnostic discipline as
12132 // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
12133 let mut s = three_member_spec();
12134 s.contratos
12135 .push(contract_http("cart", "catalog", "/products/:id"));
12136 let err = s.validate().unwrap_err();
12137 let msg = format!("{err}");
12138 assert!(
12139 msg.contains("\"/products/:id\""),
12140 "duplicate-contrato diagnostic must name the offending \
12141 :endpoint payload (got: {msg:?})"
12142 );
12143 assert!(
12144 msg.contains("cart") && msg.contains("catalog"),
12145 "diagnostic must name both endpoints of the duplicate edge \
12146 (got: {msg:?})"
12147 );
12148 }
12149
12150 #[test]
12151 fn duplicate_contrato_gate_runs_after_membership_check() {
12152 // Order pin: a duplicate contract whose `:de` is *also* not in
12153 // `:membros` surfaces the membership error first — the
12154 // missing-member diagnostic is more locating than the
12155 // duplicate-edge one (the author has to fix the membership
12156 // before the duplicate is meaningful). Same ordering
12157 // discipline as `membros_validation_runs_before_contratos_membership_check`.
12158 let mut s = three_member_spec();
12159 s.contratos.push(contract_http("phantom", "catalog", "/x"));
12160 s.contratos.push(contract_http("phantom", "catalog", "/x"));
12161 let err = s.validate().unwrap_err();
12162 assert!(
12163 matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
12164 "membership-missing must fire before duplicate-edge (got {err:?})"
12165 );
12166 }
12167
12168 #[test]
12169 fn duplicate_contrato_gate_runs_after_target_shape_check() {
12170 // Order pin: a contract with a malformed target (e.g. an HTTP
12171 // wit world with an empty :endpoint) surfaces the target-shape
12172 // error first, not the duplicate one. Even when two such
12173 // malformed entries are identical, the per-contract `target()`
12174 // check fires inside the loop *before* the duplicate-key
12175 // insert, so the diagnostic remains the most-locating one.
12176 let mut s = three_member_spec();
12177 let malformed = WitContract {
12178 de: "cart".into(),
12179 para: "catalog".into(),
12180 wit: "wasi:http/proxy".into(),
12181 endpoint: Some(String::new()),
12182 subject: None,
12183 slot: None,
12184 };
12185 s.contratos.push(malformed.clone());
12186 s.contratos.push(malformed);
12187 let err = s.validate().unwrap_err();
12188 assert!(
12189 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
12190 "endpoint-empty must fire before duplicate-edge (got {err:?})"
12191 );
12192 }
12193
12194 #[test]
12195 fn wit_target_label_pins_per_variant_format() {
12196 // Label format is the single source of truth every duplicate-
12197 // `:contratos` diagnostic + every future `feira app graph`
12198 // consumer routes through. Pin the shape per variant so a
12199 // future edit to `WitTarget::label` (e.g. a JSON emitter that
12200 // strips the leading `:`, or a rename from `endpoint` →
12201 // `path`) surfaces as a red-red test rather than as a silent
12202 // downstream diagnostic drift. Together with the exhaustive
12203 // `match` on `WitTarget` inside `label()`, adding a future
12204 // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
12205 // peer, per-edge WIT registry variants) is a compile error at
12206 // the label site — not a fall-through into the `Capability`
12207 // "no payload" default the prior raw-field-probe helper
12208 // silently landed on.
12209 assert_eq!(
12210 WitTarget::Http {
12211 endpoint: "/charge",
12212 }
12213 .label(),
12214 "\
12215:endpoint \"/charge\""
12216 );
12217 assert_eq!(
12218 WitTarget::PubSub {
12219 subject: "events.checkout.paid",
12220 }
12221 .label(),
12222 "\
12223:subject \"events.checkout.paid\""
12224 );
12225 assert_eq!(
12226 WitTarget::Store {
12227 slot: "checkout/$order",
12228 }
12229 .label(),
12230 "\
12231:slot \"checkout/$order\""
12232 );
12233 assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
12234 // Capability-arm label routes through the lifted
12235 // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
12236 // declaration per arm, next to the variant" discipline the
12237 // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
12238 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12239 // consts already carry extends to the payload-less arm; the
12240 // byte-string equality pin below plus this label-routes-
12241 // through-the-const pin make a future rebrand on either the
12242 // const declaration or the `label()` template a build error
12243 // here rather than a downstream consumer surprise.
12244 assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
12245 assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
12246 }
12247
12248 #[test]
12249 fn wit_target_display_routes_through_label_helper() {
12250 // Fail-before-pass-after pin on the fourth (and only remaining)
12251 // typed-shape-discriminator axis to converge onto the
12252 // three-path-convergence discipline the sibling M3
12253 // [`PlacementStrategy`] (0a2f653) and M2
12254 // [`crate::supervisor::RestartStrategy`] /
12255 // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
12256 // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
12257 // through [`WitTarget::label`], so every consumer reaching for
12258 // `format!("{v}")` on a typed payload target lands on the same
12259 // stable author-facing byte-string [`WitTarget::label`] returns
12260 // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
12261 // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
12262 // `:contratos` gate seeds via [`WitTarget::label`] at
12263 // aplicacao.rs:5491 already threads through.
12264 //
12265 // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
12266 // through to the `Debug` derive's structural output
12267 // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
12268 // rather than the [`WitTarget::label`] helper's stable byte-
12269 // string (`:endpoint "/charge"` — the author-facing `:contratos`
12270 // keyword form). Every future consumer that reaches for
12271 // `format!("{target}")` — the canonical shape every user-facing
12272 // pretty-print site on the sibling typed-enum axes
12273 // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
12274 // [`crate::supervisor::RestartPolicy`]) already uses — would
12275 // silently land under a different byte-string than the
12276 // [`WitTarget::label`] callers that the duplicate-`:contratos`
12277 // diagnostic already threads through, with the mismatch
12278 // surfacing as a downstream diagnostic / graph / audit line
12279 // reading one spelling while the substrate's own gate emitted
12280 // another.
12281 //
12282 // Pin the routing here so a future
12283 // `impl std::fmt::Display for WitTarget<'_>` reimplementation
12284 // that hand-rolls the per-arm formatting instead of delegating
12285 // to [`WitTarget::label`] fails at caixa-core build time.
12286 for variant in [
12287 WitTarget::Http {
12288 endpoint: "/charge",
12289 },
12290 WitTarget::PubSub {
12291 subject: "events.checkout.paid",
12292 },
12293 WitTarget::Store {
12294 slot: "checkout/$order",
12295 },
12296 WitTarget::Capability,
12297 ] {
12298 assert_eq!(
12299 variant.to_string(),
12300 variant.label(),
12301 "WitTarget::{variant:?} Display must route through \
12302 WitTarget::label (single source of truth: the lifted \
12303 payload_pair 4-arm dispatch the label helper already \
12304 threads through)"
12305 );
12306 }
12307 }
12308
12309 #[test]
12310 fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
12311 // Consumer-side pin on the three-path convergence:
12312 // [`std::fmt::Display`] agrees byte-for-byte with the
12313 // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
12314 // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
12315 // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
12316 // Pre-lift the two paths were structurally independent — the
12317 // substrate-side gate reached for `target_view.label()` while a
12318 // future downstream diagnostic / graph / audit line reaching
12319 // for `format!("{target}")` would silently land on the `Debug`
12320 // derive's structural output. Pin the two paths byte-for-byte
12321 // here so any future variant addition (M4 `Rest`/`Grpc` split
12322 // of [`WitTarget::Http`], `Queue`-shaped peer of
12323 // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
12324 // match error at [`WitTarget::payload_pair`] rather than a
12325 // silent per-consumer dispatch miss.
12326 for variant in [
12327 WitTarget::Http {
12328 endpoint: "/charge",
12329 },
12330 WitTarget::PubSub {
12331 subject: "events.checkout.paid",
12332 },
12333 WitTarget::Store {
12334 slot: "checkout/$order",
12335 },
12336 WitTarget::Capability,
12337 ] {
12338 assert_eq!(
12339 format!("{variant}"),
12340 variant.label(),
12341 "WitTarget::{variant:?} Display byte-string must match \
12342 the AplicacaoError::ContratoDuplicate `target:` carrier \
12343 the AplicacaoSpec::validate duplicate-`:contratos` gate \
12344 seeds via WitTarget::label — three-path convergence: \
12345 Display + label + payload_pair all resolve to the same \
12346 per-arm byte-string"
12347 );
12348 }
12349 }
12350
12351 #[test]
12352 fn wit_target_payload_pair_pins_per_variant() {
12353 // Pin the per-arm `(field-name, payload)` pair single-sourced
12354 // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
12355 // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
12356 // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
12357 // and [`WitTarget::field_name`] (returns the first component)
12358 // route through. Until this lift landed [`WitTarget::label`]
12359 // dispatched on the same three arms with a per-arm
12360 // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
12361 // paired [`WitTarget::HTTP_FIELD_NAME`] /
12362 // [`WitTarget::PUBSUB_FIELD_NAME`] /
12363 // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
12364 // canonical "same shape, written N times" duplication
12365 // THEORY.md §I.3.5 promotes to a build-time concern. A future
12366 // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
12367 // [`WitTarget::Http`], `Queue`-shaped peer of
12368 // [`WitTarget::Store`]) is one match-arm edit at
12369 // [`WitTarget::payload_pair`], visible here as a compile-time
12370 // exhaustiveness error on both this pin and the label-format
12371 // pin above.
12372 assert_eq!(
12373 WitTarget::Http {
12374 endpoint: "/charge"
12375 }
12376 .payload_pair(),
12377 Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
12378 );
12379 assert_eq!(
12380 WitTarget::PubSub {
12381 subject: "events.x",
12382 }
12383 .payload_pair(),
12384 Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
12385 );
12386 assert_eq!(
12387 WitTarget::Store {
12388 slot: "checkout/$order",
12389 }
12390 .payload_pair(),
12391 Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
12392 );
12393 assert_eq!(WitTarget::Capability.payload_pair(), None);
12394 }
12395
12396 #[test]
12397 fn wit_target_field_name_pins_per_variant() {
12398 // Pin the per-arm author-facing `:contratos` payload field
12399 // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
12400 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12401 // + returned by [`WitTarget::field_name`]. Every downstream
12402 // consumer (the [`WitContract::target`] gate's `expected:`
12403 // scalar, the [`WitTarget::label`] template's keyword prefix,
12404 // the `feira app graph` verb's `endpoint=…` prefix) routes
12405 // through the same three peer consts, so a rename on the
12406 // author-surface `(defcaixa … :contratos ((:de … :para …
12407 // :wit … :endpoint …)))` field lands in exactly one place.
12408 assert_eq!(
12409 WitTarget::Http {
12410 endpoint: "/charge"
12411 }
12412 .field_name(),
12413 Some(WitTarget::HTTP_FIELD_NAME),
12414 );
12415 assert_eq!(
12416 WitTarget::PubSub {
12417 subject: "events.x",
12418 }
12419 .field_name(),
12420 Some(WitTarget::PUBSUB_FIELD_NAME),
12421 );
12422 assert_eq!(
12423 WitTarget::Store {
12424 slot: "checkout/$order",
12425 }
12426 .field_name(),
12427 Some(WitTarget::STORE_FIELD_NAME),
12428 );
12429 // Capability arm carries no payload field — the diagnostic
12430 // never reports `expected: "capability"` because the gate's
12431 // Capability arm accepts no payload at all (it fires the
12432 // "expected: none" WrongTarget error instead), so the field-
12433 // name method returns None here rather than a placeholder.
12434 assert_eq!(WitTarget::Capability.field_name(), None);
12435
12436 // Peer const scalar values pinned so a rename on either side
12437 // (author-surface field name in the `(defcaixa …)` DSL, or
12438 // the diagnostic's `expected:` scalar) can't drift without
12439 // failing here first.
12440 assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
12441 assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
12442 assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
12443 }
12444
12445 #[test]
12446 fn wit_target_payload_pins_per_variant() {
12447 // Pin the per-arm payload scalar single-sourced onto the
12448 // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
12449 // [`WitTarget::payload`] — the peer per-half projection to
12450 // [`WitTarget::field_name`] on the paired sub-selector axis. The
12451 // three payload-carrying arms round-trip their author-declared
12452 // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
12453 // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
12454 // the payload-less [`WitTarget::Capability`] arm returns `None`.
12455 // Same shape as the sibling `wit_target_field_name_pins_per_variant`
12456 // (c6ec2af) pin on the Component-0 projection axis, extended
12457 // onto the Component-1 projection axis so both per-half readers
12458 // on the paired dispatch carry their own byte-shape pin.
12459 assert_eq!(
12460 WitTarget::Http {
12461 endpoint: "/charge",
12462 }
12463 .payload(),
12464 Some("/charge"),
12465 );
12466 assert_eq!(
12467 WitTarget::PubSub {
12468 subject: "events.x",
12469 }
12470 .payload(),
12471 Some("events.x"),
12472 );
12473 assert_eq!(
12474 WitTarget::Store {
12475 slot: "checkout/$order",
12476 }
12477 .payload(),
12478 Some("checkout/$order"),
12479 );
12480 assert_eq!(WitTarget::Capability.payload(), None);
12481 }
12482
12483 #[test]
12484 fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
12485 // Per-variant equivalence pin: for every arm of [`WitTarget`],
12486 // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
12487 // byte-for-byte. Guards the drift surface where a future refactor
12488 // that split one accessor off the shared match onto its own
12489 // dispatch — a well-meaning "inline the pair back into per-half
12490 // fields for one crate-internal caller who only wanted one half"
12491 // or a scratch `impl` shadowing the derived projection — would
12492 // silently desynchronize [`WitTarget::payload`] from the
12493 // authoritative [`WitTarget::payload_pair`] dispatch, and every
12494 // downstream consumer that thinks "the payload half of the pair"
12495 // would drift from the diagnostic / graph consumers reading the
12496 // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
12497 // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
12498 // per-half projection pin (`gitrefspec_ref_pair_projects_
12499 // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
12500 // FluxCD source-controller `spec.ref.<field>` axis — same "one
12501 // paired dispatch, both per-half projections agree byte-for-
12502 // byte" discipline extended onto the M3 `:contratos` payload-
12503 // arm surface.
12504 for variant in [
12505 WitTarget::Http {
12506 endpoint: "/charge",
12507 },
12508 WitTarget::PubSub {
12509 subject: "events.checkout.paid",
12510 },
12511 WitTarget::Store {
12512 slot: "checkout/$order",
12513 },
12514 WitTarget::Capability,
12515 ] {
12516 let via_projection = variant.payload();
12517 let via_pair = variant.payload_pair().map(|(_, p)| p);
12518 assert_eq!(
12519 via_projection, via_pair,
12520 "WitTarget::{variant:?} payload() must equal \
12521 payload_pair().map(|(_, p)| p) byte-for-byte — a \
12522 regression that splits the two per-half projections off \
12523 their shared match would silently desynchronize the \
12524 payload accessor from the paired dispatch every \
12525 diagnostic / graph consumer reads through",
12526 );
12527 }
12528 }
12529
12530 #[test]
12531 fn wit_target_http_endpoint_pins_per_variant() {
12532 // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
12533 // [`WitTarget::http_endpoint`] 2-arm dispatch — the
12534 // substrate-primitive per-arm post-projection accessor every
12535 // L7-HTTP-facing consumer routes through, sibling to the peer
12536 // WitContract pre-projection [`WitContract::endpoint`] (7020470)
12537 // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
12538 // arm round-trips its author-declared endpoint verbatim as
12539 // `Some("/charge")`; the three sibling arms
12540 // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
12541 // [`WitTarget::Capability`]) each return `None` because they
12542 // carry no HTTP endpoint by definition. Same fail-before-pass-
12543 // after per-variant discipline as the sibling
12544 // `wit_target_payload_pins_per_variant` (5d6dc92) /
12545 // `wit_target_field_name_pins_per_variant` (c6ec2af) /
12546 // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
12547 // the peer pan-arm / per-half projection axes — extended onto
12548 // the per-arm HTTP-shape post-projection axis so a future
12549 // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
12550 // [`WitTarget::Http`], a `Queue`-shaped peer of
12551 // [`WitTarget::Store`]) trips a compile-time exhaustiveness
12552 // error on the sibling [`WitTarget::http_endpoint`] match arms
12553 // whose payload the L7-HTTP-shape accept-set is meant to bound.
12554 assert_eq!(
12555 WitTarget::Http {
12556 endpoint: "/charge",
12557 }
12558 .http_endpoint(),
12559 Some("/charge"),
12560 );
12561 assert_eq!(
12562 WitTarget::PubSub {
12563 subject: "events.checkout.paid",
12564 }
12565 .http_endpoint(),
12566 None,
12567 );
12568 assert_eq!(
12569 WitTarget::Store {
12570 slot: "checkout/$order",
12571 }
12572 .http_endpoint(),
12573 None,
12574 );
12575 assert_eq!(WitTarget::Capability.http_endpoint(), None);
12576 }
12577
12578 #[test]
12579 fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
12580 // Per-variant coherence pin: for every arm of [`WitTarget`],
12581 // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
12582 // arm (both project the same author-declared request-path
12583 // scalar), and returns `None` on every sibling arm regardless of
12584 // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
12585 // Store carry their own payload the pan-arm accessor surfaces,
12586 // but that payload is not an HTTP endpoint — the per-arm
12587 // accessor must not leak it through the HTTP-shape channel).
12588 // Guards the drift surface where a future refactor that
12589 // conflated the per-arm HTTP projection with the pan-arm
12590 // [`WitTarget::payload`] projection — a well-meaning "one
12591 // accessor for the L7 branch, one for the graph" collapse that
12592 // routes both through the same 4-arm dispatch — would silently
12593 // widen the L7-HTTP-shape accept-set onto pub-sub / store
12594 // payloads at the caixa-mesh L7 emit branch, admitting a
12595 // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
12596 // rule with the operator-side apply-time symptom (Cilium's
12597 // eBPF data-plane rejects every ingress edge whose L7 filter
12598 // doesn't match the wire-format HTTP request line) far from
12599 // the source refactor. Sibling to the peer
12600 // `wit_target_payload_matches_payload_pair_second_component_
12601 // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
12602 // extended onto the per-arm HTTP specialization axis so both
12603 // the pan-arm and the per-arm projections carry their own
12604 // byte-shape coherence witness against the substrate's typed
12605 // arm-family accept-set.
12606 for variant in [
12607 WitTarget::Http {
12608 endpoint: "/charge",
12609 },
12610 WitTarget::PubSub {
12611 subject: "events.checkout.paid",
12612 },
12613 WitTarget::Store {
12614 slot: "checkout/$order",
12615 },
12616 WitTarget::Capability,
12617 ] {
12618 let per_arm = variant.http_endpoint();
12619 let pan_arm = variant.payload();
12620 if variant.is_http() {
12621 assert_eq!(
12622 per_arm, pan_arm,
12623 "WitTarget::{variant:?} http_endpoint() must equal \
12624 payload() on the Http arm — a per-arm-vs-pan-arm \
12625 split would silently drift the L7 emit branch's \
12626 path-scalar source from the graph verb's payload \
12627 scalar source",
12628 );
12629 } else {
12630 assert_eq!(
12631 per_arm, None,
12632 "WitTarget::{variant:?} http_endpoint() must return \
12633 None on non-Http arms — a leak that surfaced a \
12634 pub-sub :subject or a key/value :slot through the \
12635 HTTP-endpoint accessor would silently widen the \
12636 Cilium L7 HTTP `path:` rule accept-set onto \
12637 protocol shapes Cilium's eBPF data-plane can't \
12638 introspect",
12639 );
12640 }
12641 }
12642 }
12643
12644 #[test]
12645 fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
12646 // Per-variant coherence pin: for every arm of [`WitTarget`],
12647 // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
12648 // drift surface where a future extension of the
12649 // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
12650 // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
12651 // accessor to cover both peers) landed without a paired
12652 // extension of the [`gen_platform::IsVariant`]-derived
12653 // `is_http()` predicate's accept-set, or vice versa — a
12654 // regression that split the "which arms count as HTTP-shaped
12655 // for L7-path emission?" answer between two dispatch surfaces
12656 // the substrate ships. Sibling to the peer
12657 // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
12658 // on the paired dispatch axis — extended onto the per-arm
12659 // predicate-vs-accessor coherence axis so the gen-platform
12660 // IsVariant predicate and the substrate-lifted per-arm
12661 // accessor carry one shared answer to "is this the HTTP arm?".
12662 for variant in [
12663 WitTarget::Http {
12664 endpoint: "/charge",
12665 },
12666 WitTarget::PubSub {
12667 subject: "events.checkout.paid",
12668 },
12669 WitTarget::Store {
12670 slot: "checkout/$order",
12671 },
12672 WitTarget::Capability,
12673 ] {
12674 assert_eq!(
12675 variant.http_endpoint().is_some(),
12676 variant.is_http(),
12677 "WitTarget::{variant:?} http_endpoint().is_some() must \
12678 equal is_http() — a drift would split the L7 emit \
12679 branch's arm-set gate from the substrate-derived \
12680 shape-discrimination predicate on the same axis",
12681 );
12682 }
12683 }
12684
12685 #[test]
12686 fn wit_target_pubsub_subject_pins_per_variant() {
12687 // Fail-before-pass-after pin: the substrate-canonical per-arm
12688 // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
12689 // is the single dispatch every future pub-sub-facing consumer
12690 // routes through, sibling to the peer [`WitContract::subject`]
12691 // (63e18a0) pre-projection scalar accessor on the raw-field
12692 // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
12693 // post-projection per-arm accessor on the sibling HTTP-shape
12694 // axis. The [`WitTarget::PubSub`] arm round-trips its
12695 // author-declared subject verbatim as
12696 // `Some("events.checkout.paid")`; the three sibling arms each
12697 // return `None` because they carry no NATS-shaped subject by
12698 // definition. Same fail-before-pass-after per-variant discipline
12699 // as the sibling `wit_target_http_endpoint_pins_per_variant`
12700 // pin on the peer per-arm axis — extended onto the per-arm
12701 // pub-sub-shape post-projection axis so a future [`WitTarget`]
12702 // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
12703 // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
12704 // compile-time exhaustiveness error on the sibling
12705 // [`WitTarget::pubsub_subject`] match arms whose payload the
12706 // pub-sub-shape accept-set is meant to bound.
12707 assert_eq!(
12708 WitTarget::PubSub {
12709 subject: "events.checkout.paid",
12710 }
12711 .pubsub_subject(),
12712 Some("events.checkout.paid"),
12713 );
12714 assert_eq!(
12715 WitTarget::Http {
12716 endpoint: "/charge",
12717 }
12718 .pubsub_subject(),
12719 None,
12720 );
12721 assert_eq!(
12722 WitTarget::Store {
12723 slot: "checkout/$order",
12724 }
12725 .pubsub_subject(),
12726 None,
12727 );
12728 assert_eq!(WitTarget::Capability.pubsub_subject(), None);
12729 }
12730
12731 #[test]
12732 fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
12733 // Per-variant coherence pin: for every arm of [`WitTarget`],
12734 // `.pubsub_subject()` equals `.payload()` on the
12735 // [`WitTarget::PubSub`] arm (both project the same
12736 // author-declared subject scalar), and returns `None` on every
12737 // sibling arm regardless of whether [`WitTarget::payload`]
12738 // itself returns `Some` (Http / Store carry their own payload
12739 // the pan-arm accessor surfaces, but that payload is not a
12740 // pub-sub subject — the per-arm accessor must not leak it
12741 // through the pub-sub-shape channel). Sibling to the peer
12742 // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
12743 // coherence pin on the per-arm HTTP-shape axis — extended onto
12744 // the per-arm pub-sub specialization axis so both per-arm
12745 // projections carry their own byte-shape coherence witness
12746 // against the substrate's typed arm-family accept-set.
12747 for variant in [
12748 WitTarget::Http {
12749 endpoint: "/charge",
12750 },
12751 WitTarget::PubSub {
12752 subject: "events.checkout.paid",
12753 },
12754 WitTarget::Store {
12755 slot: "checkout/$order",
12756 },
12757 WitTarget::Capability,
12758 ] {
12759 let per_arm = variant.pubsub_subject();
12760 let pan_arm = variant.payload();
12761 if variant.is_pubsub() {
12762 assert_eq!(
12763 per_arm, pan_arm,
12764 "WitTarget::{variant:?} pubsub_subject() must equal \
12765 payload() on the PubSub arm — a per-arm-vs-pan-arm \
12766 split would silently drift the pub-sub-shape emit \
12767 branch's subject-scalar source from the graph verb's \
12768 payload scalar source",
12769 );
12770 } else {
12771 assert_eq!(
12772 per_arm, None,
12773 "WitTarget::{variant:?} pubsub_subject() must return \
12774 None on non-PubSub arms — a leak that surfaced an \
12775 HTTP :endpoint or a key/value :slot through the \
12776 pub-sub-subject accessor would silently widen the \
12777 downstream NATS-shape accept-set onto protocol \
12778 shapes NATS servers can't route",
12779 );
12780 }
12781 }
12782 }
12783
12784 #[test]
12785 fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
12786 // Per-variant coherence pin: for every arm of [`WitTarget`],
12787 // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
12788 // drift surface where a future extension of the
12789 // [`WitTarget::pubsub_subject`] accessor's accept-set landed
12790 // without a paired extension of the [`gen_platform::IsVariant`]-
12791 // derived `is_pubsub()` predicate's accept-set, or vice versa
12792 // — a regression that split the "which arms count as pub-sub-
12793 // shaped for subject emission?" answer between two dispatch
12794 // surfaces the substrate ships. Sibling to the peer
12795 // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
12796 // pin on the per-arm HTTP-shape axis — extended onto the
12797 // per-arm pub-sub predicate-vs-accessor coherence axis so the
12798 // gen-platform IsVariant predicate and the substrate-lifted
12799 // per-arm accessor carry one shared answer to "is this the
12800 // PubSub arm?".
12801 for variant in [
12802 WitTarget::Http {
12803 endpoint: "/charge",
12804 },
12805 WitTarget::PubSub {
12806 subject: "events.checkout.paid",
12807 },
12808 WitTarget::Store {
12809 slot: "checkout/$order",
12810 },
12811 WitTarget::Capability,
12812 ] {
12813 assert_eq!(
12814 variant.pubsub_subject().is_some(),
12815 variant.is_pubsub(),
12816 "WitTarget::{variant:?} pubsub_subject().is_some() must \
12817 equal is_pubsub() — a drift would split the pub-sub \
12818 emit branch's arm-set gate from the substrate-derived \
12819 shape-discrimination predicate on the same axis",
12820 );
12821 }
12822 }
12823
12824 #[test]
12825 fn wit_target_store_slot_pins_per_variant() {
12826 // Fail-before-pass-after pin: the substrate-canonical per-arm
12827 // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
12828 // is the single dispatch every future store-facing consumer
12829 // routes through, sibling to the peer [`WitContract::slot`]
12830 // pre-projection scalar accessor on the raw-field axis and to
12831 // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
12832 // [`WitTarget::pubsub_subject`] post-projection per-arm
12833 // accessors on the sibling per-payload-arm axes. The
12834 // [`WitTarget::Store`] arm round-trips its author-declared
12835 // slot verbatim as `Some("checkout/$order")`; the three
12836 // sibling arms each return `None` because they carry no
12837 // WASI-key/value slot by definition. Same fail-before-pass-
12838 // after per-variant discipline as the sibling
12839 // `wit_target_http_endpoint_pins_per_variant` +
12840 // `wit_target_pubsub_subject_pins_per_variant` pins on the
12841 // peer per-arm axes — extended onto the per-arm store-shape
12842 // post-projection axis so a future [`WitTarget`] variant
12843 // addition trips a compile-time exhaustiveness error on the
12844 // sibling [`WitTarget::store_slot`] match arms whose payload
12845 // the store-shape accept-set is meant to bound.
12846 assert_eq!(
12847 WitTarget::Store {
12848 slot: "checkout/$order",
12849 }
12850 .store_slot(),
12851 Some("checkout/$order"),
12852 );
12853 assert_eq!(
12854 WitTarget::Http {
12855 endpoint: "/charge",
12856 }
12857 .store_slot(),
12858 None,
12859 );
12860 assert_eq!(
12861 WitTarget::PubSub {
12862 subject: "events.checkout.paid",
12863 }
12864 .store_slot(),
12865 None,
12866 );
12867 assert_eq!(WitTarget::Capability.store_slot(), None);
12868 }
12869
12870 #[test]
12871 fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
12872 // Per-variant coherence pin: for every arm of [`WitTarget`],
12873 // `.store_slot()` equals `.payload()` on the
12874 // [`WitTarget::Store`] arm (both project the same
12875 // author-declared slot scalar), and returns `None` on every
12876 // sibling arm regardless of whether [`WitTarget::payload`]
12877 // itself returns `Some`. Sibling to the peer
12878 // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
12879 // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
12880 // pins on the per-arm HTTP and PubSub axes — closes the
12881 // per-arm-vs-pan-arm byte-shape coherence trio across all
12882 // three payload arms.
12883 for variant in [
12884 WitTarget::Http {
12885 endpoint: "/charge",
12886 },
12887 WitTarget::PubSub {
12888 subject: "events.checkout.paid",
12889 },
12890 WitTarget::Store {
12891 slot: "checkout/$order",
12892 },
12893 WitTarget::Capability,
12894 ] {
12895 let per_arm = variant.store_slot();
12896 let pan_arm = variant.payload();
12897 if variant.is_store() {
12898 assert_eq!(
12899 per_arm, pan_arm,
12900 "WitTarget::{variant:?} store_slot() must equal \
12901 payload() on the Store arm — a per-arm-vs-pan-arm \
12902 split would silently drift the store-shape emit \
12903 branch's slot-scalar source from the graph verb's \
12904 payload scalar source",
12905 );
12906 } else {
12907 assert_eq!(
12908 per_arm, None,
12909 "WitTarget::{variant:?} store_slot() must return \
12910 None on non-Store arms — a leak that surfaced an \
12911 HTTP :endpoint or a NATS :subject through the \
12912 key/value-slot accessor would silently widen the \
12913 downstream WASI-key/value slot accept-set onto \
12914 protocol shapes the kv backends can't route",
12915 );
12916 }
12917 }
12918 }
12919
12920 #[test]
12921 fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
12922 // Per-variant coherence pin: for every arm of [`WitTarget`],
12923 // `.store_slot().is_some()` iff `.is_store()`. Guards the
12924 // drift surface where a future extension of the
12925 // [`WitTarget::store_slot`] accessor's accept-set landed
12926 // without a paired extension of the [`gen_platform::IsVariant`]-
12927 // derived `is_store()` predicate's accept-set. Sibling to the
12928 // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
12929 // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
12930 // pins — closes the per-arm predicate-vs-accessor coherence
12931 // trio across all three payload arms so the gen-platform
12932 // IsVariant predicate and the substrate-lifted per-arm
12933 // accessor carry one shared answer to "is this the Store arm?".
12934 for variant in [
12935 WitTarget::Http {
12936 endpoint: "/charge",
12937 },
12938 WitTarget::PubSub {
12939 subject: "events.checkout.paid",
12940 },
12941 WitTarget::Store {
12942 slot: "checkout/$order",
12943 },
12944 WitTarget::Capability,
12945 ] {
12946 assert_eq!(
12947 variant.store_slot().is_some(),
12948 variant.is_store(),
12949 "WitTarget::{variant:?} store_slot().is_some() must \
12950 equal is_store() — a drift would split the store-shape \
12951 emit branch's arm-set gate from the substrate-derived \
12952 shape-discrimination predicate on the same axis",
12953 );
12954 }
12955 }
12956
12957 #[test]
12958 fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
12959 // Fail-before-pass-after cross-axis pin on the trio
12960 // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
12961 // payload-carrying arm of [`WitTarget`], exactly one per-arm
12962 // accessor returns `Some(payload)` and the two peers return
12963 // `None`; and on the payload-less [`WitTarget::Capability`]
12964 // arm, all three return `None`. Guards the drift surface where
12965 // a future extension of one per-arm accessor's accept-set (e.g.
12966 // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
12967 // that widened `http_endpoint` to cover both peers without
12968 // narrowing the peer `pubsub_subject` / `store_slot` accept-
12969 // sets to keep the partition mutually exclusive) landed without
12970 // threading through the peer per-arm accessors — the resulting
12971 // silent overlap would land the same edge's payload on two
12972 // downstream per-shape emit branches at once, or leak a
12973 // pub-sub subject through the store-slot channel, at renderer
12974 // emit time far from the substrate primitive's arm-widening
12975 // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
12976 // 3-way pin on the payload-field-name axis — extended onto the
12977 // per-arm-accessor payload-projection axis so the substrate-
12978 // owned partition invariant is load-bearing at every per-arm
12979 // consumer's read site.
12980 let payload_variants = [
12981 (
12982 WitTarget::Http {
12983 endpoint: "/charge",
12984 },
12985 "http",
12986 ),
12987 (
12988 WitTarget::PubSub {
12989 subject: "events.checkout.paid",
12990 },
12991 "pubsub",
12992 ),
12993 (
12994 WitTarget::Store {
12995 slot: "checkout/$order",
12996 },
12997 "store",
12998 ),
12999 ];
13000 for (variant, own_arm_label) in payload_variants {
13001 let own_arm_hit = match own_arm_label {
13002 "http" => variant.is_http(),
13003 "pubsub" => variant.is_pubsub(),
13004 "store" => variant.is_store(),
13005 other => panic!("unknown own-arm label {other:?}"),
13006 };
13007 let per_arm_results = [
13008 ("http_endpoint", variant.http_endpoint()),
13009 ("pubsub_subject", variant.pubsub_subject()),
13010 ("store_slot", variant.store_slot()),
13011 ];
13012 let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
13013 assert_eq!(
13014 some_count, 1,
13015 "WitTarget::{variant:?} must land exactly one per-arm \
13016 post-projection accessor's Some result — the trio \
13017 (http_endpoint, pubsub_subject, store_slot) must \
13018 partition the payload arm-set; got {per_arm_results:?}",
13019 );
13020 assert!(
13021 own_arm_hit,
13022 "WitTarget::{variant:?} own-arm gen-platform predicate \
13023 must return true on its own arm — a partition failure \
13024 upstream of this pin",
13025 );
13026 assert!(
13027 variant.payload().is_some(),
13028 "WitTarget::{variant:?} pan-arm payload() must return \
13029 Some on every payload-carrying arm the trio partitions",
13030 );
13031 }
13032 // The payload-less Capability arm must return None on every
13033 // per-arm accessor — the partition's terminal-fallback shape.
13034 let cap = WitTarget::Capability;
13035 assert_eq!(cap.http_endpoint(), None);
13036 assert_eq!(cap.pubsub_subject(), None);
13037 assert_eq!(cap.store_slot(), None);
13038 assert_eq!(
13039 cap.payload(),
13040 None,
13041 "WitTarget::Capability pan-arm payload() must return None — \
13042 the trio's payload-less-arm coherence witness",
13043 );
13044 }
13045
13046 #[test]
13047 fn wit_target_field_names_are_pairwise_distinct() {
13048 // Distinctness pin: if any two of the three payload-field-name
13049 // scalars ever collapse (e.g. an accidental `endpoint` copy-
13050 // paste over the `subject` const), the [`WitContract::target`]
13051 // gate's diagnostic would point authors at the wrong field —
13052 // an "expected `:endpoint`" error on a pub-sub edge would
13053 // silently misroute the fix. Same cross-axis-distinctness
13054 // discipline as the peer M3 `:placement :estrategia` variant-
13055 // discriminator scalar-value pins (cc8f749) applied to the
13056 // payload-field-name axis.
13057 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
13058 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
13059 assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
13060 }
13061
13062 #[test]
13063 fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
13064 // Fail-before-pass-after pin: the graph-verb payload column's
13065 // per-arm `{field}={payload}` byte-string is derived through the
13066 // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
13067 // payload-carrying arms, not through a hand-rolled per-arm match
13068 // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
13069 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13070 // inline. A future variant addition — the M4-and-later per-edge
13071 // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
13072 // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
13073 // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
13074 // and both [`WitTarget::label`] (duplicate-`:contratos`
13075 // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
13076 // payload column) pick up the new arm from the same dispatch.
13077 // Prior to this lift the graph verb open-coded the 4-arm match
13078 // in caixa-feira, so a variant addition would have to be threaded
13079 // through both projections in lockstep or the graph verb would
13080 // silently drop the new arm to `(capability-only)`.
13081 for variant in [
13082 WitTarget::Http {
13083 endpoint: "/charge",
13084 },
13085 WitTarget::PubSub {
13086 subject: "events.checkout.paid",
13087 },
13088 WitTarget::Store {
13089 slot: "checkout/$order",
13090 },
13091 ] {
13092 let (field, payload) = variant
13093 .payload_pair()
13094 .expect("payload arm must expose (field, payload)");
13095 assert_eq!(
13096 variant.graph_label(),
13097 format!("{field}={payload}"),
13098 "WitTarget::{variant:?} graph_label must route the \
13099 `{{field}}={{payload}}` template through payload_pair — \
13100 a regression to a hand-rolled per-arm match at the graph \
13101 verb would silently disagree with a future variant \
13102 addition landed only at payload_pair"
13103 );
13104 }
13105 }
13106
13107 #[test]
13108 fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
13109 // Fail-before-pass-after pin on the payload-less arm: the graph
13110 // verb's `(capability-only)` byte-string routes through the
13111 // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
13112 // [`WitTarget::Capability`] arm, not through an inline
13113 // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
13114 // per-`:contratos` payload column. Peer of the sibling
13115 // [`wit_target_label_pins_per_variant_format`] Capability-arm
13116 // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
13117 // extended here onto the third payload-less-arm consumer axis
13118 // (graph verb, sibling to the duplicate-`:contratos` diagnostic
13119 // axis and the wrong-target diagnostic axis).
13120 assert_eq!(
13121 WitTarget::Capability.graph_label(),
13122 WitTarget::CAPABILITY_GRAPH_LABEL,
13123 );
13124 assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
13125 }
13126
13127 #[test]
13128 fn wit_target_capability_graph_label_distinct_from_capability_label() {
13129 // Cross-consumer-axis distinctness pin: the graph-verb
13130 // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
13131 // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
13132 // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
13133 // payload)`) surface the payload-less arm on two distinct
13134 // consumer axes; a collapse (an accidental rebrand that lands
13135 // one spelling on both consts, a copy-paste that unifies them
13136 // "for consistency") would silently merge the two byte-strings
13137 // and lose the vocabulary distinction the graph verb's
13138 // compact-column form and the diagnostic's descriptive-clause
13139 // form each carry on purpose. Peer of the sibling 4-way
13140 // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
13141 // pin on the `ContratoWrongTarget::expected` scalar-value axis —
13142 // extended here onto the cross-consumer-axis distinctness of the
13143 // two payload-less-arm consts.
13144 assert_ne!(
13145 WitTarget::CAPABILITY_GRAPH_LABEL,
13146 WitTarget::CAPABILITY_LABEL,
13147 "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
13148 and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
13149 diagnostic) must remain distinct — a collapse would silently \
13150 merge two consumer axes onto one spelling"
13151 );
13152 }
13153
13154 #[test]
13155 fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
13156 // 4-way distinctness pin extending the sibling
13157 // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
13158 // (which covers only the HTTP / PubSub / Store payload arms)
13159 // onto the fourth scalar the shared
13160 // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
13161 // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
13162 // (`"none"`), the payload-less Capability-arm rejection scalar.
13163 //
13164 // All four [`WitTarget::HTTP_FIELD_NAME`] /
13165 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13166 // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
13167 // dispatch surface [`WitContract::target`] writes onto the
13168 // `ContratoWrongTarget::expected` field — the same `&'static
13169 // str` axis authors read as "this WIT world's shape admits
13170 // (only|not) `:<field>`". Pairwise-distinctness is the invariant
13171 // downstream consumers rely on: an `expected: "endpoint"`
13172 // diagnostic on a Capability-shaped edge tells the author to
13173 // add a `:endpoint "…"` slot to a WIT world that admits none,
13174 // silently misrouting the fix. Until this pin landed the three
13175 // payload-arm consts were distinctness-guarded by the sibling
13176 // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
13177 // scalar (d4f54f2) sat unguarded — a rebrand collision (the
13178 // author-facing vocabulary shift from `"none"` to `"endpoint"`
13179 // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
13180 // into per-shape peers) would have silently landed one
13181 // Capability-arm rejection on a payload-arm's `expected:` byte-
13182 // string and desynchronized the diagnostic from the author's
13183 // typed shape.
13184 //
13185 // Same 4-way pairwise-distinctness pin discipline as the peer
13186 // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
13187 // (cc8f749) applies on the sibling M3 closed-set typed-enum
13188 // scalar-value dispatch axis; extends the pin trajectory the
13189 // sibling `wit_target_field_names_are_pairwise_distinct`
13190 // 3-way pin opened to cover the last unguarded corner on the
13191 // `ContratoWrongTarget::expected` scalar-value axis.
13192 //
13193 // Fail-before-pass-after locally verified by mutating
13194 // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
13195 // — this pin fires as expected; restoring passes.
13196 let all = [
13197 WitTarget::HTTP_FIELD_NAME,
13198 WitTarget::PUBSUB_FIELD_NAME,
13199 WitTarget::STORE_FIELD_NAME,
13200 WitTarget::CAPABILITY_EXPECTED,
13201 ];
13202 for (i, a) in all.iter().enumerate() {
13203 for (j, b) in all.iter().enumerate() {
13204 if i != j {
13205 assert_ne!(
13206 a, b,
13207 "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
13208 STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
13209 pairwise distinct — got duplicate {a:?} at indices \
13210 {i} and {j}; all four scalars thread through the \
13211 shared `AplicacaoError::ContratoWrongTarget::expected` \
13212 &'static str axis, so a collapse silently misdirects \
13213 the diagnostic on which typed shape the WIT world admits",
13214 );
13215 }
13216 }
13217 }
13218 }
13219
13220 #[test]
13221 fn wit_target_is_variant_predicates_partition_the_arm_set() {
13222 // Fail-before-pass-after pin on the
13223 // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
13224 // each of the four variants exactly one of the generated
13225 // `is_http` / `is_pubsub` / `is_store` / `is_capability`
13226 // predicates returns `true` and the other three return
13227 // `false`. Prior to this derive the only production
13228 // arm-discriminator on [`WitTarget`] — the sync-cycle
13229 // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
13230 // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
13231 // the variant that expressed no compile-time link back to
13232 // the closed-set typed dispatch a future fifth
13233 // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
13234 // split of [`WitTarget::PubSub`] into shape-specific peers,
13235 // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
13236 // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
13237 // to thread through in lockstep or the DFS exclusion would
13238 // silently disagree with the peer diagnostic templates on
13239 // which arms carry sync-versus-async semantics. Peer of the
13240 // sibling [`crate::CaixaKind`] (f5bba80),
13241 // [`PlacementStrategy`] (766ec63),
13242 // [`crate::supervisor::RestartStrategy`],
13243 // [`crate::supervisor::RestartPolicy`], and
13244 // [`crate::upgrade::UpgradeInstruction`] (915a934)
13245 // `IsVariant` derives on the sibling closed-set typed-enum
13246 // discriminator axes — extends the same one-typed-dispatch-
13247 // per-variant discipline onto the last unlifted closed-set
13248 // typed-enum discriminator on the caixa surface (the M3
13249 // mesh-slot per-`:contratos` target-arm axis), closing the
13250 // arm-discriminator convergence trajectory across every
13251 // closed-set typed enum in caixa-core.
13252 let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
13253 (
13254 WitTarget::Http { endpoint: "/x" },
13255 [true, false, false, false],
13256 ),
13257 (
13258 WitTarget::PubSub {
13259 subject: "events.x",
13260 },
13261 [false, true, false, false],
13262 ),
13263 (
13264 WitTarget::Store { slot: "kv/x" },
13265 [false, false, true, false],
13266 ),
13267 (WitTarget::Capability, [false, false, false, true]),
13268 ];
13269 for (variant, expected) in rows {
13270 let observed = [
13271 variant.is_http(),
13272 variant.is_pubsub(),
13273 variant.is_store(),
13274 variant.is_capability(),
13275 ];
13276 assert_eq!(
13277 observed, expected,
13278 "WitTarget::{variant:?} is_* predicates must partition \
13279 the arm set (http, pubsub, store, capability); got {observed:?}"
13280 );
13281 }
13282 }
13283
13284 #[test]
13285 fn wit_target_is_variant_predicates_are_const_fn() {
13286 // The [`gen_platform::IsVariant`] derive emits `const fn`
13287 // predicates on the peer [`crate::CaixaKind`] +
13288 // [`crate::upgrade::UpgradeInstruction`] +
13289 // [`crate::supervisor::RestartStrategy`] +
13290 // [`crate::supervisor::RestartPolicy`] +
13291 // [`PlacementStrategy`] closed-set typed enums — pin the
13292 // same posture on [`WitTarget`] so a future accidental
13293 // downgrade to non-`const` (an added runtime helper reachable
13294 // only from a non-`const` context, a manual hand-rolled
13295 // `impl` that shadows the derive-generated method) trips at
13296 // caixa-core build time rather than surfacing as a downstream
13297 // `const`-context regression far from the derive declaration.
13298 //
13299 // Unlike the peer unit-variant enums (`CaixaKind` /
13300 // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
13301 // whose `const` constructors need no arguments, the three
13302 // payload-carrying [`WitTarget`] arms are const-constructed
13303 // through `&'static str` payloads — the same `'static`
13304 // lifetime the closed-set typed enum's four-arm partition
13305 // pin above already threads through.
13306 const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
13307 const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
13308 const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
13309 const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
13310 const IS_HTTP: bool = HTTP.is_http();
13311 const IS_PUBSUB: bool = PUBSUB.is_pubsub();
13312 const IS_STORE: bool = STORE.is_store();
13313 const IS_CAPABILITY: bool = CAPABILITY.is_capability();
13314 assert!(IS_HTTP);
13315 assert!(IS_PUBSUB);
13316 assert!(IS_STORE);
13317 assert!(IS_CAPABILITY);
13318 }
13319
13320 #[test]
13321 fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
13322 // Consumer-side pin on the sole production converge site:
13323 // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
13324 // edges from the synchronous-subgraph DFS via the lifted
13325 // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
13326 // predicate (rebound from the prior raw
13327 // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
13328 // variant). Byte-equivalent today (`is_pubsub` is the
13329 // derive-generated `matches!(self, Self::PubSub { .. })` by
13330 // construction, the `#[is_variant(name = "pubsub")]` override
13331 // aliasing the auto-derived `is_pub_sub` back to the sibling
13332 // [`WitContract::is_pubsub`] name); pin the behavior so a
13333 // future accidental drift (a rebind onto a peer arm
13334 // predicate, a manual hand-rolled `impl` that shadows the
13335 // derive-generated method with different semantics, a peer
13336 // arm rename that shifts which variant carries sync-versus-
13337 // async semantics) trips at caixa-core test time rather than
13338 // at some downstream operator's runtime dispatch far from the
13339 // rebind commit.
13340 //
13341 // The fixture constructs a two-Servico Aplicacao with one
13342 // pub-sub edge that would close a sync-cycle if the DFS did
13343 // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
13344 // pub-sub exclusion means the DFS sees only the `b → a` HTTP
13345 // edge, which is not a cycle. A regression in the converge
13346 // (a rebind that reads the pub-sub arm as sync) would report
13347 // `AplicacaoError::ContratoCycle`.
13348 let s = AplicacaoSpec {
13349 membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
13350 contratos: vec![
13351 // Pub-sub edge: DFS must skip via is_pubsub().
13352 WitContract {
13353 de: "a".into(),
13354 para: "b".into(),
13355 wit: "nats:pub-sub".into(),
13356 endpoint: None,
13357 subject: Some("events.x".into()),
13358 slot: None,
13359 },
13360 // HTTP edge: DFS must include.
13361 WitContract {
13362 de: "b".into(),
13363 para: "a".into(),
13364 wit: "wasi:http/proxy".into(),
13365 endpoint: Some("/x".into()),
13366 subject: None,
13367 slot: None,
13368 },
13369 ],
13370 politicas: MeshPolicy::default(),
13371 placement: Placement {
13372 estrategia: PlacementStrategy::Replicated,
13373 clusters: vec!["rio".into()],
13374 affinity: None,
13375 shard_key: None,
13376 },
13377 entrada: None,
13378 };
13379 s.validate()
13380 .expect("pub-sub edge must be excluded from sync-cycle DFS");
13381 }
13382
13383 #[test]
13384 fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
13385 // Consumer-side pin: the same three peer consts thread through
13386 // both the [`WitTarget::label`] template (leading-`:` keyword
13387 // prefix in the duplicate-`:contratos` diagnostic) and the
13388 // [`WitContract::target`] gate's [`AplicacaoError::
13389 // ContratoMissingTarget`] `expected:` scalar (the field the
13390 // author needs to add). Pin both routes at once so a future
13391 // refactor can't accidentally split them onto separate string
13392 // literals — the "one place, everywhere reaches for it"
13393 // invariant the peer const set carries.
13394 let http_label = WitTarget::Http { endpoint: "/x" }.label();
13395 assert!(
13396 http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
13397 "label must lead with :{} keyword (got {http_label:?})",
13398 WitTarget::HTTP_FIELD_NAME,
13399 );
13400
13401 let mut s = three_member_spec();
13402 s.contratos.push(WitContract {
13403 de: "cart".into(),
13404 para: "catalog".into(),
13405 wit: "kafka:topic".into(),
13406 endpoint: None,
13407 subject: None,
13408 slot: None,
13409 });
13410 match s.validate().unwrap_err() {
13411 AplicacaoError::ContratoMissingTarget { expected, .. } => {
13412 assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
13413 }
13414 other => panic!("expected ContratoMissingTarget, got {other:?}"),
13415 }
13416 }
13417
13418 #[test]
13419 fn duplicate_pubsub_diagnostic_names_offending_subject() {
13420 // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
13421 // on the pub-sub target axis: the duplicate-edge diagnostic
13422 // must name the `:subject` payload verbatim (not just the
13423 // `(de, para, wit)` triple). Prior to lifting the label onto
13424 // [`WitTarget::label`] the diagnostic derived the label from
13425 // raw [`WitContract`] `Option<String>` probes — a future
13426 // `WitTarget` variant addition (M4 per-edge WIT registry)
13427 // would silently fall through to the `Capability` "no
13428 // payload" default without a compiler warning. Pinning the
13429 // pub-sub arm's format closes the second of three
13430 // payload-carrying `WitTarget` arms this diagnostic threads
13431 // through.
13432 let mut s = three_member_spec();
13433 let pubsub = WitContract {
13434 de: "payment".into(),
13435 para: "cart".into(),
13436 wit: "nats:pub-sub".into(),
13437 endpoint: None,
13438 subject: Some("events.checkout.paid".into()),
13439 slot: None,
13440 };
13441 s.contratos.push(pubsub.clone());
13442 s.contratos.push(pubsub);
13443 let err = s.validate().unwrap_err();
13444 let msg = format!("{err}");
13445 assert!(
13446 msg.contains(":subject \"events.checkout.paid\""),
13447 "duplicate-pubsub diagnostic must name the offending \
13448 :subject payload (got: {msg:?})"
13449 );
13450 }
13451
13452 #[test]
13453 fn duplicate_store_diagnostic_names_offending_slot() {
13454 // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
13455 // key-value target axis: the diagnostic must name the `:slot`
13456 // payload verbatim. Third of three payload-carrying
13457 // `WitTarget` arms this diagnostic threads through, closing
13458 // the per-arm label pin trilogy (`Http` — 6841,
13459 // `PubSub` + `Store` — this test + peer above).
13460 let mut s = three_member_spec();
13461 let store = WitContract {
13462 de: "cart".into(),
13463 para: "payment".into(),
13464 wit: "wasi:keyvalue/store".into(),
13465 endpoint: None,
13466 subject: None,
13467 slot: Some("checkout/$orderId".into()),
13468 };
13469 s.contratos
13470 .retain(|c| !(c.de == "cart" && c.para == "payment"));
13471 s.contratos.push(store.clone());
13472 s.contratos.push(store);
13473 let err = s.validate().unwrap_err();
13474 let msg = format!("{err}");
13475 assert!(
13476 msg.contains(":slot \"checkout/$orderId\""),
13477 "duplicate-store diagnostic must name the offending :slot \
13478 payload (got: {msg:?})"
13479 );
13480 }
13481
13482 #[test]
13483 fn rejects_entrada_path_without_leading_slash() {
13484 let mut s = three_member_spec();
13485 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
13486 let err = s.validate().unwrap_err();
13487 assert!(
13488 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
13489 "got {err:?}"
13490 );
13491 }
13492
13493 #[test]
13494 fn rejects_empty_entrada_path() {
13495 let mut s = three_member_spec();
13496 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
13497 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
13498 }
13499
13500 #[test]
13501 fn rejects_duplicate_entrada_paths() {
13502 let mut s = three_member_spec();
13503 s.entrada.as_mut().unwrap().paths = vec![
13504 "/api/cart".into(),
13505 "/api/products".into(),
13506 "/api/cart".into(),
13507 ];
13508 let err = s.validate().unwrap_err();
13509 assert!(
13510 matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
13511 "got {err:?}"
13512 );
13513 }
13514
13515 #[test]
13516 fn rejects_zero_entrada_port() {
13517 let mut s = three_member_spec();
13518 s.entrada.as_mut().unwrap().port = 0;
13519 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
13520 }
13521
13522 // ── :entrada :paths value-shape gate ─────────────────────────────
13523 //
13524 // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
13525 // sibling `:paths` axis. Every authoring footgun the K8s Gateway
13526 // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
13527 // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
13528 // time now becomes a caixa-build-time `EntradaPathInvalid` with
13529 // the offending `:paths` entry named verbatim.
13530
13531 #[test]
13532 fn rejects_entrada_path_with_query() {
13533 // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
13534 // silently passed validate and the Gateway API webhook
13535 // rejected it at apply time with no source citation.
13536 let mut s = three_member_spec();
13537 s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
13538 let err = s.validate().unwrap_err();
13539 assert!(
13540 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13541 if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
13542 "got {err:?}"
13543 );
13544 }
13545
13546 #[test]
13547 fn rejects_entrada_path_with_fragment() {
13548 let mut s = three_member_spec();
13549 s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
13550 let err = s.validate().unwrap_err();
13551 assert!(
13552 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13553 if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
13554 "got {err:?}"
13555 );
13556 }
13557
13558 #[test]
13559 fn rejects_entrada_path_with_space() {
13560 let mut s = three_member_spec();
13561 s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
13562 let err = s.validate().unwrap_err();
13563 assert!(
13564 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13565 if path == "/api/my cart" && reason.contains("whitespace")),
13566 "got {err:?}"
13567 );
13568 }
13569
13570 #[test]
13571 fn rejects_entrada_path_with_tab() {
13572 let mut s = three_member_spec();
13573 s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
13574 let err = s.validate().unwrap_err();
13575 assert!(
13576 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13577 if path == "/api/\tcart" && reason.contains("whitespace")),
13578 "got {err:?}"
13579 );
13580 }
13581
13582 #[test]
13583 fn rejects_entrada_path_with_control_char() {
13584 // 0x01 (SOH) — a non-whitespace control char surfaces the
13585 // distinct "control character" reason arm, separate from
13586 // the whitespace arm. Pinned so a future refactor that
13587 // collapses the two arms can't accidentally drop the more
13588 // self-locating diagnostic.
13589 let mut s = three_member_spec();
13590 s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
13591 let err = s.validate().unwrap_err();
13592 assert!(
13593 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13594 if path == "/api/\x01cart" && reason.contains("control character")),
13595 "got {err:?}"
13596 );
13597 }
13598
13599 #[test]
13600 fn rejects_entrada_path_with_non_ascii() {
13601 // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
13602 // unreserved-set rule rejects. The Gateway API webhook
13603 // rejects literal non-ASCII bytes; percent-encoding is the
13604 // only way to author non-ASCII in a path.
13605 let mut s = three_member_spec();
13606 s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
13607 let err = s.validate().unwrap_err();
13608 assert!(
13609 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13610 if path == "/api/café" && reason.contains("non-ASCII")),
13611 "got {err:?}"
13612 );
13613 }
13614
13615 #[test]
13616 fn rejects_entrada_path_with_consecutive_slashes() {
13617 let mut s = three_member_spec();
13618 s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
13619 let err = s.validate().unwrap_err();
13620 assert!(
13621 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13622 if path == "/api//cart" && reason.contains("consecutive `/`")),
13623 "got {err:?}"
13624 );
13625 }
13626
13627 #[test]
13628 fn rejects_entrada_path_with_dot_segment() {
13629 let mut s = three_member_spec();
13630 s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
13631 let err = s.validate().unwrap_err();
13632 assert!(
13633 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13634 if path == "/api/./cart" && reason.contains("`.` segment")),
13635 "got {err:?}"
13636 );
13637 }
13638
13639 #[test]
13640 fn rejects_entrada_path_with_trailing_dot_segment() {
13641 // The bare `/.` and the trailing `/foo/.` are both rejected
13642 // by the Gateway API webhook; pinned separately so a future
13643 // narrowing that catches only the inner form surfaces here.
13644 let mut s = three_member_spec();
13645 s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
13646 let err = s.validate().unwrap_err();
13647 assert!(
13648 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13649 if path == "/api/." && reason.contains("`.` segment")),
13650 "got {err:?}"
13651 );
13652 }
13653
13654 #[test]
13655 fn rejects_entrada_path_with_parent_segment() {
13656 let mut s = three_member_spec();
13657 s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
13658 let err = s.validate().unwrap_err();
13659 assert!(
13660 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13661 if path == "/api/../etc" && reason.contains("`..` parent-segment")),
13662 "got {err:?}"
13663 );
13664 }
13665
13666 #[test]
13667 fn rejects_entrada_path_with_trailing_parent_segment() {
13668 // Trailing `/..` — symmetric arm of the parent-segment rule,
13669 // pinned separately so a future relaxation that only checks
13670 // the inner form (`/../`) surfaces here.
13671 let mut s = three_member_spec();
13672 s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
13673 let err = s.validate().unwrap_err();
13674 assert!(
13675 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13676 if path == "/api/.." && reason.contains("`..` parent-segment")),
13677 "got {err:?}"
13678 );
13679 }
13680
13681 #[test]
13682 fn rejects_entrada_path_too_long() {
13683 // 1025-byte path — one over the Gateway API HTTPPathMatch.value
13684 // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
13685 // ASCII-alphanumeric body so only the length rule fires.
13686 let mut s = three_member_spec();
13687 let big = format!("/api/{}", "a".repeat(1020));
13688 assert_eq!(big.len(), 1025);
13689 s.entrada.as_mut().unwrap().paths = vec![big.clone()];
13690 let err = s.validate().unwrap_err();
13691 assert!(
13692 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13693 if path == &big && reason.contains("max length of 1024")),
13694 "got {err:?}"
13695 );
13696 }
13697
13698 #[test]
13699 fn entrada_path_max_length_validates() {
13700 // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
13701 // maxLength cap. Boundary pin: drift in the cap surfaces here
13702 // and at `rejects_entrada_path_too_long` simultaneously.
13703 let mut s = three_member_spec();
13704 let big = format!("/api/{}", "a".repeat(1019));
13705 assert_eq!(big.len(), 1024);
13706 s.entrada.as_mut().unwrap().paths = vec![big];
13707 s.validate().unwrap();
13708 }
13709
13710 #[test]
13711 fn entrada_accepts_canonical_paths() {
13712 // Positive-control sweep — every form the Gateway API
13713 // apiserver accepts must round-trip through validate. Covers
13714 // the root catch-all, plain paths, dot-prefixed segments
13715 // (hidden-file-style, distinct from `.` and `..` segments
13716 // which are rejected), digit-bearing segments, the canonical
13717 // route-template `:param` form (`:` is RFC 3986 reserved-set
13718 // valid in paths), trailing-slash form, percent-encoded
13719 // segments, and an interior `..` *substring* (`/foo..bar` is
13720 // not the `..` segment and is allowed).
13721 for path in [
13722 "/",
13723 "/api/cart",
13724 "/healthz",
13725 "/api/.config",
13726 "/v1/products",
13727 "/products/:id",
13728 "/api/cart/",
13729 "/api/caf%C3%A9",
13730 "/foo..bar",
13731 "/...",
13732 ] {
13733 let mut s = three_member_spec();
13734 s.entrada.as_mut().unwrap().paths = vec![path.into()];
13735 s.validate()
13736 .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
13737 }
13738 }
13739
13740 #[test]
13741 fn entrada_path_empty_takes_precedence_over_invalid() {
13742 // Ordering pin: `EntradaPathEmpty` is the more self-locating
13743 // diagnostic on `""` and must lead — `validate_entrada_path`
13744 // is only reached after the empty-check fires at the call
13745 // site. (The predicate itself defends against direct
13746 // invocation by returning the same error on `""`.)
13747 let mut s = three_member_spec();
13748 s.entrada.as_mut().unwrap().paths = vec!["".into()];
13749 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
13750 }
13751
13752 #[test]
13753 fn entrada_path_not_absolute_takes_precedence_over_invalid() {
13754 // Ordering pin: a path without a leading `/` surfaces the
13755 // narrower `EntradaPathNotAbsolute` diagnostic first; the
13756 // value-shape gate is only consulted on paths that already
13757 // satisfy the absolute-prefix invariant.
13758 let mut s = three_member_spec();
13759 // `bad path` would fire the whitespace rule under the
13760 // value-shape gate, but missing-leading-`/` is the more
13761 // self-locating diagnostic.
13762 s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
13763 let err = s.validate().unwrap_err();
13764 assert!(
13765 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
13766 "got {err:?}"
13767 );
13768 }
13769
13770 #[test]
13771 fn entrada_path_invalid_fires_before_duplicate_check() {
13772 // Ordering pin: a malformed path on the *first* entry of a
13773 // would-be duplicate pair fires the value-shape gate before
13774 // the duplicate gate, mirroring the
13775 // `placement_cluster_invalid_fires_before_duplicate_check`
13776 // (6cbb900) pattern on the peer axis.
13777 let mut s = three_member_spec();
13778 s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
13779 let err = s.validate().unwrap_err();
13780 assert!(
13781 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
13782 "got {err:?}"
13783 );
13784 }
13785
13786 #[test]
13787 fn entrada_path_diagnostic_carries_offending_path() {
13788 // Diagnostic-shape pin — the offending path + a non-empty
13789 // reason flow through verbatim so the author can grep their
13790 // caixa.lisp for `:paths` and fix it in one edit. Same shape
13791 // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
13792 let mut s = three_member_spec();
13793 s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
13794 let err = s.validate().unwrap_err();
13795 match err {
13796 AplicacaoError::EntradaPathInvalid { path, reason } => {
13797 assert_eq!(path, "/api?q=1");
13798 assert!(!reason.is_empty(), "reason field must be non-empty");
13799 }
13800 other => panic!("expected EntradaPathInvalid, got {other:?}"),
13801 }
13802 }
13803
13804 #[test]
13805 fn rejects_entrada_path_with_curly_brace_template_form() {
13806 // Per-axis pin on the shared `is_gateway_api_http_path`
13807 // reserved-byte arm: the canonical "I wrote an OpenAPI
13808 // path-template `{id}` instead of the Gateway API `:id` form"
13809 // footgun the K8s apiserver would otherwise catch at admission
13810 // time on every `HTTPRoute.spec.rules[].matches[].path.value`
13811 // landing site, far from the caixa.lisp. Surfaces as
13812 // `EntradaPathInvalid` carrying the offending path verbatim
13813 // plus the canonical `%7B`/`%7D` percent-encoding remediation
13814 // — the substrate-side `gateway_api_http_path_rejects_every_
13815 // reserved_printable_ascii_byte` predicate-level sweep pins the
13816 // full eleven-byte set; this per-axis pin confirms the
13817 // diagnostic flows through to the `EntradaPathInvalid` variant.
13818 let mut s = three_member_spec();
13819 s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
13820 let err = s.validate().unwrap_err();
13821 assert!(
13822 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13823 if path == "/api/cart/{id}"
13824 && reason.contains("reserved character")
13825 && reason.contains("'{'")
13826 && reason.contains("%7B")),
13827 "got {err:?}"
13828 );
13829 }
13830
13831 #[test]
13832 fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
13833 // Per-axis peer of `rejects_entrada_path_with_curly_brace_
13834 // template_form` on the sibling `:contratos :endpoint` axis.
13835 // Same shared `is_gateway_api_http_path` reserved-byte arm
13836 // fires through `ContratoEndpointInvalid`, with the offending
13837 // endpoint + `:de` + `:para` + reason flowing through verbatim.
13838 // Pins that the lifted predicate's tightening lands on both
13839 // caller axes simultaneously — one source of truth for the
13840 // Gateway API HTTPPathMatch.value accepted set.
13841 let err = contrato_endpoint_err("/api/cart/{id}");
13842 assert!(
13843 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13844 if endpoint == "/api/cart/{id}"
13845 && reason.contains("reserved character")
13846 && reason.contains("'{'")
13847 && reason.contains("%7B")),
13848 "got {err:?}"
13849 );
13850 }
13851
13852 // ── :entrada :host value-shape gate ──────────────────────────────
13853 //
13854 // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
13855 // the sibling `:host` axis. Every authoring footgun the K8s
13856 // Gateway API v1 apiserver would catch at admission time becomes
13857 // a caixa-build-time `EntradaHostInvalid` with the offending
13858 // `:host` named verbatim. Same diagnostic shape as
13859 // `MembroVersaoInvalid` (9888b13).
13860
13861 #[test]
13862 fn rejects_entrada_host_with_scheme() {
13863 // Fail-before-pass-after pin — pre-gate codebases silently
13864 // accepted `https://…` and the apiserver rejected it at apply
13865 // time with no source citation.
13866 let mut s = three_member_spec();
13867 s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
13868 let err = s.validate().unwrap_err();
13869 assert!(
13870 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
13871 if host == "https://checkout.quero.cloud"),
13872 "got {err:?}"
13873 );
13874 }
13875
13876 #[test]
13877 fn rejects_entrada_host_with_port() {
13878 // The `:8080` port suffix is the canonical "I forgot the port
13879 // belongs in `:entrada :port`" footgun. The top-level `:` arm
13880 // (introduced after the per-label loop-only impl silently
13881 // surfaced a deep "label \"cloud:8080\" contains invalid
13882 // character ':'" leak) names the canonical fix verbatim — the
13883 // `:entrada :port` slot.
13884 let mut s = three_member_spec();
13885 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
13886 let err = s.validate().unwrap_err();
13887 assert!(
13888 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
13889 if host == "checkout.quero.cloud:8080"
13890 && reason.contains(":entrada :port")),
13891 "got {err:?}"
13892 );
13893 }
13894
13895 #[test]
13896 fn rejects_entrada_host_with_trailing_colon() {
13897 // Trailing `:` (e.g. an in-progress `:host "example.com:"`
13898 // edit) — the per-label loop would land it as a deep
13899 // "label \"com:\" must start and end with an alphanumeric"
13900 // / "contains invalid character ':'" leak. The top-level
13901 // `:` arm pre-empts with the canonical `:port` slot
13902 // diagnostic.
13903 let mut s = three_member_spec();
13904 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
13905 let err = s.validate().unwrap_err();
13906 assert!(
13907 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
13908 if host == "checkout.quero.cloud:"
13909 && reason.contains(":entrada :port")),
13910 "got {err:?}"
13911 );
13912 }
13913
13914 #[test]
13915 fn rejects_entrada_host_unbracketed_ipv6_literal() {
13916 // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
13917 // literals across the board (peer with `rejects_entrada_host_
13918 // ipv4_literal` above for the four-label-all-digit IPv4 arm).
13919 // Before this top-level `:` arm landed the per-label loop
13920 // surfaced a single-label byte-class diagnostic that named the
13921 // `:` byte but not the IP-literal prohibition. The top-level
13922 // `:` arm names both the `:port` slot and the IP-literal
13923 // prohibition verbatim, so an author whose `:host "2001:..."`
13924 // value lands here gets a self-locating fix either way.
13925 let mut s = three_member_spec();
13926 s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
13927 let err = s.validate().unwrap_err();
13928 assert!(
13929 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
13930 if host == "2001:db8::1"
13931 && reason.contains("IPv6")),
13932 "got {err:?}"
13933 );
13934 }
13935
13936 #[test]
13937 fn rejects_entrada_host_wildcard_with_port() {
13938 // Wildcard host with port suffix — the `*.` strip and the
13939 // per-label loop on `["foo", "quero", "cloud:8080"]` would
13940 // surface the deep byte-class leak. The top-level `:` arm sits
13941 // upstream of the `*.` strip, so it names the canonical `:port`
13942 // fix verbatim regardless of whether the host is wildcard-led.
13943 let mut s = three_member_spec();
13944 s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
13945 let err = s.validate().unwrap_err();
13946 assert!(
13947 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
13948 if host == "*.quero.cloud:8080"
13949 && reason.contains(":entrada :port")),
13950 "got {err:?}"
13951 );
13952 }
13953
13954 #[test]
13955 fn rejects_entrada_host_with_path() {
13956 let mut s = three_member_spec();
13957 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
13958 let err = s.validate().unwrap_err();
13959 assert!(
13960 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
13961 if host == "checkout.quero.cloud/api"),
13962 "got {err:?}"
13963 );
13964 }
13965
13966 #[test]
13967 fn rejects_entrada_host_with_uppercase() {
13968 // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
13969 // rejected, not silently lower-cased.
13970 let mut s = three_member_spec();
13971 s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
13972 let err = s.validate().unwrap_err();
13973 assert!(
13974 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13975 if reason.contains("uppercase")),
13976 "got {err:?}"
13977 );
13978 }
13979
13980 #[test]
13981 fn rejects_entrada_host_with_underscore() {
13982 // RFC 1123 allows `[a-z0-9-]` only; underscore is the
13983 // canonical "I'm thinking of HTTP cookies / SRV records" leak.
13984 let mut s = three_member_spec();
13985 s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
13986 let err = s.validate().unwrap_err();
13987 assert!(
13988 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13989 if reason.contains('_')),
13990 "got {err:?}"
13991 );
13992 }
13993
13994 #[test]
13995 fn rejects_entrada_host_ipv4_literal() {
13996 // Gateway API v1 explicitly forbids IP literals as Hostnames.
13997 let mut s = three_member_spec();
13998 s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
13999 let err = s.validate().unwrap_err();
14000 assert!(
14001 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14002 if reason.contains("IPv4")),
14003 "got {err:?}"
14004 );
14005 }
14006
14007 #[test]
14008 fn rejects_entrada_host_with_trailing_dot() {
14009 // The Gateway API regex anchors at end-of-string with no
14010 // trailing `.` allowance — the FQDN root-dot form is rejected.
14011 let mut s = three_member_spec();
14012 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
14013 let err = s.validate().unwrap_err();
14014 assert!(
14015 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14016 if host == "checkout.quero.cloud."),
14017 "got {err:?}"
14018 );
14019 }
14020
14021 #[test]
14022 fn rejects_entrada_host_with_leading_dot() {
14023 let mut s = three_member_spec();
14024 s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
14025 let err = s.validate().unwrap_err();
14026 assert!(
14027 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14028 if reason.contains("empty label")),
14029 "got {err:?}"
14030 );
14031 }
14032
14033 #[test]
14034 fn rejects_entrada_host_with_consecutive_dots() {
14035 let mut s = three_member_spec();
14036 s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
14037 let err = s.validate().unwrap_err();
14038 assert!(
14039 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14040 if reason.contains("empty label")),
14041 "got {err:?}"
14042 );
14043 }
14044
14045 #[test]
14046 fn rejects_entrada_host_with_leading_hyphen_label() {
14047 let mut s = three_member_spec();
14048 s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
14049 let err = s.validate().unwrap_err();
14050 assert!(
14051 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14052 if reason.contains("alphanumeric")),
14053 "got {err:?}"
14054 );
14055 }
14056
14057 #[test]
14058 fn rejects_entrada_host_with_trailing_hyphen_label() {
14059 let mut s = three_member_spec();
14060 s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
14061 let err = s.validate().unwrap_err();
14062 assert!(
14063 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14064 if reason.contains("alphanumeric")),
14065 "got {err:?}"
14066 );
14067 }
14068
14069 #[test]
14070 fn rejects_entrada_host_with_inner_wildcard() {
14071 // Gateway API allows `*` only as the first label (`*.foo`);
14072 // any inner or trailing `*` is rejected.
14073 let mut s = three_member_spec();
14074 s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
14075 let err = s.validate().unwrap_err();
14076 assert!(
14077 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14078 if reason.contains("wildcard")),
14079 "got {err:?}"
14080 );
14081 }
14082
14083 #[test]
14084 fn rejects_entrada_host_bare_wildcard() {
14085 // `*.` with no domain is meaningless; Gateway API rejects it.
14086 let mut s = three_member_spec();
14087 s.entrada.as_mut().unwrap().host = "*.".into();
14088 let err = s.validate().unwrap_err();
14089 assert!(
14090 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14091 if reason.contains("wildcard")),
14092 "got {err:?}"
14093 );
14094 }
14095
14096 #[test]
14097 fn rejects_entrada_host_with_whitespace() {
14098 let mut s = three_member_spec();
14099 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
14100 let err = s.validate().unwrap_err();
14101 assert!(
14102 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14103 if reason.contains("whitespace")),
14104 "got {err:?}"
14105 );
14106 }
14107
14108 #[test]
14109 fn rejects_entrada_host_space_names_offending_byte() {
14110 // Embedded space in the `:entrada :host` axis surfaces the
14111 // byte-naming diagnostic through the lifted
14112 // `find_ascii_whitespace_byte` predicate. Peer with the
14113 // sibling `parse_rejects_leading_whitespace` pins on
14114 // `supervisor::duration_codec` (a7ae622) — same "the
14115 // diagnostic carries the offending byte's `0x{b:02x}` shape"
14116 // discipline extended from the shared duration codec to the
14117 // Gateway API v1 Hostname axis.
14118 let mut s = three_member_spec();
14119 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
14120 let err = s.validate().unwrap_err();
14121 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14122 panic!("expected EntradaHostInvalid, got {err:?}");
14123 };
14124 assert!(
14125 reason.contains("ASCII whitespace byte"),
14126 "expected byte-naming diagnostic, got {reason:?}"
14127 );
14128 assert!(
14129 reason.contains("0x20"),
14130 "expected offending space byte 0x20, got {reason:?}"
14131 );
14132 }
14133
14134 #[test]
14135 fn rejects_entrada_host_tab_names_offending_byte() {
14136 // Embedded tab byte in the `:entrada :host` axis — the
14137 // canonical paste-from-YAML-block-scalar / paste-from-
14138 // indented-doc footgun. Pins that the lifted predicate covers
14139 // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
14140 // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
14141 // not just the leading-space case the pre-lift `.bytes().any`
14142 // arm's opaque "must not contain whitespace" reason already
14143 // covered. Peer with `parse_rejects_tab_byte` on
14144 // `supervisor::duration_codec` (a7ae622).
14145 let mut s = three_member_spec();
14146 s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
14147 let err = s.validate().unwrap_err();
14148 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14149 panic!("expected EntradaHostInvalid, got {err:?}");
14150 };
14151 assert!(
14152 reason.contains("ASCII whitespace byte"),
14153 "expected byte-naming diagnostic, got {reason:?}"
14154 );
14155 assert!(
14156 reason.contains("0x09"),
14157 "expected offending tab byte 0x09, got {reason:?}"
14158 );
14159 }
14160
14161 #[test]
14162 fn rejects_entrada_host_lf_names_offending_byte() {
14163 // Embedded LF byte in the `:entrada :host` axis — the
14164 // canonical paste-from-shell-heredoc / paste-from-multiline-
14165 // doc footgun the caixa-mesh YAML emitter would silently
14166 // reinterpret at the Gateway API v1 HTTPRoute admission
14167 // layer (an embedded LF byte in a YAML plain scalar either
14168 // truncates the value at the emitter or crashes the parser
14169 // on the k8s-apiserver side). Pins the third representative
14170 // of the full ASCII-whitespace set through the shared
14171 // predicate.
14172 let mut s = three_member_spec();
14173 s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
14174 let err = s.validate().unwrap_err();
14175 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14176 panic!("expected EntradaHostInvalid, got {err:?}");
14177 };
14178 assert!(
14179 reason.contains("ASCII whitespace byte"),
14180 "expected byte-naming diagnostic, got {reason:?}"
14181 );
14182 assert!(
14183 reason.contains("0x0a"),
14184 "expected offending LF byte 0x0a, got {reason:?}"
14185 );
14186 }
14187
14188 #[test]
14189 fn rejects_entrada_host_nbsp_names_offending_codepoint() {
14190 // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
14191 // axis — the canonical paste-from-typography /
14192 // paste-from-word-processor footgun. Before the non-ASCII
14193 // Unicode `White_Space` scan lifted through the shared
14194 // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
14195 // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
14196 // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
14197 // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
14198 // with the far-from-source `label "…" must start and end
14199 // with an alphanumeric` diagnostic — burying the
14200 // paste-from-typography origin under a label-shape leak.
14201 // Peer with the sibling non-ASCII-whitespace pins at
14202 // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
14203 // — 1b75b38), `limits::parse_duration`,
14204 // `limits::parse_millicores`, and the shared duration codec
14205 // — same "the diagnostic carries the offending Unicode
14206 // codepoint's `U+XXXX` shape" discipline extended from every
14207 // typed-magnitude codec to the Gateway API v1 Hostname axis.
14208 let mut s = three_member_spec();
14209 s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
14210 let err = s.validate().unwrap_err();
14211 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14212 panic!("expected EntradaHostInvalid, got {err:?}");
14213 };
14214 assert!(
14215 reason.contains("non-ASCII Unicode whitespace character"),
14216 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14217 );
14218 assert!(
14219 reason.contains("U+00A0"),
14220 "expected offending NBSP codepoint U+00A0, got {reason:?}"
14221 );
14222 }
14223
14224 #[test]
14225 fn rejects_entrada_host_line_separator_names_offending_codepoint() {
14226 // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
14227 // `:entrada :host` axis — the canonical paste-from-web-doc /
14228 // paste-from-published-HTML footgun. `char::is_whitespace`
14229 // returns true for `U+2028` per the Unicode `White_Space`
14230 // property, so `str::trim` at any downstream site would
14231 // silently strip it — same drift class as NBSP but on a
14232 // different codepoint region. Pins the second representative
14233 // (non-Latin-1 `char::is_whitespace` member) through the
14234 // shared predicate. Peer with
14235 // `parse_byte_size_rejects_internal_line_separator` on
14236 // `limits::parse_byte_size` (1b75b38).
14237 let mut s = three_member_spec();
14238 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
14239 let err = s.validate().unwrap_err();
14240 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14241 panic!("expected EntradaHostInvalid, got {err:?}");
14242 };
14243 assert!(
14244 reason.contains("non-ASCII Unicode whitespace character"),
14245 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14246 );
14247 assert!(
14248 reason.contains("U+2028"),
14249 "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
14250 );
14251 }
14252
14253 #[test]
14254 fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
14255 // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
14256 // labels in the `:entrada :host` axis — the canonical
14257 // paste-from-CJK-typography footgun (CJK IMEs default to
14258 // full-width whitespace when the space bar is pressed in
14259 // Japanese / Chinese input modes). Pins the third
14260 // representative of the non-ASCII Unicode `White_Space` set
14261 // through the shared predicate: the CJK block, distinct from
14262 // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
14263 // SEPARATOR `U+2028` — covering the same axis breadth the
14264 // sibling `parse_byte_size_rejects_trailing_ideographic_space`
14265 // (1b75b38) pins on `limits::parse_byte_size`.
14266 let mut s = three_member_spec();
14267 s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
14268 let err = s.validate().unwrap_err();
14269 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14270 panic!("expected EntradaHostInvalid, got {err:?}");
14271 };
14272 assert!(
14273 reason.contains("non-ASCII Unicode whitespace character"),
14274 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14275 );
14276 assert!(
14277 reason.contains("U+3000"),
14278 "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
14279 );
14280 }
14281
14282 #[test]
14283 fn rejects_entrada_host_too_long() {
14284 // Total length cap = 253; build a 254-byte host out of two
14285 // 63-byte labels + one 62-byte label + dots.
14286 let mut s = three_member_spec();
14287 let big = format!(
14288 "{}.{}.{}.{}",
14289 "a".repeat(63),
14290 "b".repeat(63),
14291 "c".repeat(63),
14292 "d".repeat(254 - 63 * 3 - 3)
14293 );
14294 assert_eq!(big.len(), 254);
14295 s.entrada.as_mut().unwrap().host = big;
14296 let err = s.validate().unwrap_err();
14297 assert!(
14298 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14299 if reason.contains("max length of 253")),
14300 "got {err:?}"
14301 );
14302 }
14303
14304 #[test]
14305 fn rejects_entrada_host_label_too_long() {
14306 let mut s = three_member_spec();
14307 // 64-byte label — one over the per-label cap.
14308 s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
14309 let err = s.validate().unwrap_err();
14310 assert!(
14311 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14312 if reason.contains("label max length of 63")),
14313 "got {err:?}"
14314 );
14315 }
14316
14317 #[test]
14318 fn entrada_host_diagnostic_carries_offending_host() {
14319 // Diagnostic-shape pin — the offending host + a non-empty
14320 // reason flow through verbatim so the author can grep their
14321 // caixa.lisp for `:host "<host>"` and fix it in one edit.
14322 let mut s = three_member_spec();
14323 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
14324 let err = s.validate().unwrap_err();
14325 match err {
14326 AplicacaoError::EntradaHostInvalid { host, reason } => {
14327 assert_eq!(host, "checkout.quero.cloud:8080");
14328 assert!(!reason.is_empty(), "reason field must be non-empty");
14329 }
14330 other => panic!("expected EntradaHostInvalid, got {other:?}"),
14331 }
14332 }
14333
14334 #[test]
14335 fn entrada_host_empty_takes_precedence_over_invalid() {
14336 // Ordering pin: `EmptyEntradaHost` is the more self-locating
14337 // diagnostic on `""` and must lead — `validate_entrada_host`
14338 // is only reached after the empty-check fires at the call
14339 // site. (The predicate itself defends against direct
14340 // invocation by returning the same error on `""`.)
14341 let mut s = three_member_spec();
14342 s.entrada.as_mut().unwrap().host = String::new();
14343 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
14344 }
14345
14346 #[test]
14347 fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
14348 // Ordering pin: a missing :para member is the more
14349 // self-locating diagnostic and fires before the host gate.
14350 let mut s = three_member_spec();
14351 let e = s.entrada.as_mut().unwrap();
14352 e.para = "ghost".into();
14353 e.host = "BAD HOST".into();
14354 let err = s.validate().unwrap_err();
14355 assert!(
14356 matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
14357 "got {err:?}"
14358 );
14359 }
14360
14361 #[test]
14362 fn entrada_host_invalid_fires_before_port_zero() {
14363 // Ordering pin: the host gate fires before the port gate so
14364 // a malformed host is named even when the port is also wrong.
14365 let mut s = three_member_spec();
14366 let e = s.entrada.as_mut().unwrap();
14367 e.host = "Checkout.quero.cloud".into();
14368 e.port = 0;
14369 let err = s.validate().unwrap_err();
14370 assert!(
14371 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14372 if host == "Checkout.quero.cloud"),
14373 "got {err:?}"
14374 );
14375 }
14376
14377 #[test]
14378 fn entrada_accepts_canonical_hosts() {
14379 // Positive-control sweep — every form the Gateway API
14380 // apiserver accepts must round-trip through validate. Covers
14381 // a plain DNS subdomain, a leading wildcard, a single-label
14382 // host (cluster-internal), a max-length-edge label, a
14383 // hyphen-bearing label, and a Punycode IDN label.
14384 for host in [
14385 "checkout.quero.cloud",
14386 "*.quero.cloud",
14387 "checkout",
14388 // 63-byte label — exactly the per-label cap.
14389 "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
14390 "foo-bar.quero.cloud",
14391 // Punycode IDN — valid because the author pre-encoded.
14392 "xn--bcher-kva.example.com",
14393 ] {
14394 let mut s = three_member_spec();
14395 s.entrada.as_mut().unwrap().host = host.into();
14396 s.validate()
14397 .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
14398 }
14399 }
14400
14401 #[test]
14402 fn entrada_host_max_length_validates() {
14403 // 253-byte host is the cap exactly — must validate. Build a
14404 // 253-byte host out of three 63-byte labels + one 61-byte
14405 // label + 3 dots = 252 bytes, then pad one byte to 253.
14406 let mut s = three_member_spec();
14407 let host = format!(
14408 "{}.{}.{}.{}",
14409 "a".repeat(63),
14410 "b".repeat(63),
14411 "c".repeat(63),
14412 "d".repeat(253 - 63 * 3 - 3)
14413 );
14414 assert_eq!(host.len(), 253);
14415 s.entrada.as_mut().unwrap().host = host;
14416 s.validate().unwrap();
14417 }
14418
14419 #[test]
14420 fn entrada_host_total_length_cap_threads_lifted_render_const() {
14421 // Cross-crate-side pin: the aplicacao-side `:entrada :host`
14422 // total-length gate now reads the K8s Gateway API v1 Hostname
14423 // `maxLength: 253` cap from the lifted
14424 // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
14425 // of truth — the same constant every future Gateway-API-Hostname
14426 // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
14427 // materializer's per-host validator, the future per-`Certificate`
14428 // SAN emitter for cert-manager, the multi-`:entrada`
14429 // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
14430 // from. Before the lift, the aplicacao-side reader consumed a
14431 // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
14432 // 253-byte value as the peer render-side canonical bounds
14433 // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
14434 // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
14435 // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
14436 // module boundary — a future 253-byte drift on either side would
14437 // silently split into two axes' worth of admission-schema mismatch
14438 // without a build-time signal. Pin the cap through a fresh 254-
14439 // byte host that hits the total-length arm, then read the reason
14440 // for the exact byte count the shared constant carries: any future
14441 // regression on the lift (a private alias reintroduced, a hard-
14442 // coded literal at the arm, a mismatch between the aplicacao-side
14443 // and render-side canonicals) surfaces as this pin's diagnostic
14444 // failing to match, not as a per-cluster admission rejection far
14445 // from the caixa.lisp source line.
14446 let mut s = three_member_spec();
14447 let over_cap = format!(
14448 "{}.{}.{}.{}",
14449 "a".repeat(63),
14450 "b".repeat(63),
14451 "c".repeat(63),
14452 "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
14453 );
14454 assert_eq!(
14455 over_cap.len(),
14456 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
14457 );
14458 s.entrada.as_mut().unwrap().host = over_cap;
14459 let err = s.validate().unwrap_err();
14460 match err {
14461 AplicacaoError::EntradaHostInvalid { reason, .. } => {
14462 let needle = format!(
14463 "max length of {} bytes",
14464 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
14465 );
14466 assert!(
14467 reason.contains(&needle),
14468 "diagnostic must name the lifted \
14469 GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
14470 );
14471 }
14472 other => panic!("expected EntradaHostInvalid, got {other:?}"),
14473 }
14474 }
14475
14476 #[test]
14477 fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
14478 // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
14479 // on the per-label-cap axis. Before the lift, the aplicacao-side
14480 // per-label arm consumed a private const alias
14481 // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
14482 // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
14483 // split from it at the module boundary — every `.`-separated
14484 // label in a Gateway API v1 Hostname is a DNS-1123 label under
14485 // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
14486 // so the private alias's 63 and the canonical const's 63 were
14487 // pinning the same underlying rule twice. Pin the cap through a
14488 // 64-byte label that hits the per-label arm, then read the reason
14489 // for the exact byte count the shared constant carries: any
14490 // future drift on either side (a private alias reintroduced, a
14491 // hard-coded literal at the arm, a mismatch between the two
14492 // 63-byte pins) surfaces at this pin's diagnostic rather than at
14493 // a per-cluster admission rejection whose "field is invalid"
14494 // opacity misframes the root cause.
14495 let mut s = three_member_spec();
14496 let over_cap_label = format!(
14497 "{}.quero.cloud",
14498 "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
14499 );
14500 s.entrada.as_mut().unwrap().host = over_cap_label;
14501 let err = s.validate().unwrap_err();
14502 match err {
14503 AplicacaoError::EntradaHostInvalid { reason, .. } => {
14504 let needle = format!(
14505 "label max length of {} bytes",
14506 crate::render::DNS_1123_LABEL_MAX_LEN,
14507 );
14508 assert!(
14509 reason.contains(&needle),
14510 "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
14511 cap verbatim on the per-label arm, got: {reason:?}",
14512 );
14513 }
14514 other => panic!("expected EntradaHostInvalid, got {other:?}"),
14515 }
14516 }
14517
14518 #[test]
14519 fn entrada_with_empty_paths_validates() {
14520 // Empty `:paths` is the documented "match every path" form;
14521 // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
14522 let mut s = three_member_spec();
14523 s.entrada.as_mut().unwrap().paths = vec![];
14524 s.validate().unwrap();
14525 }
14526
14527 #[test]
14528 fn entrada_root_path_validates() {
14529 // The author-supplied bare-root `:entrada :paths` entry is the
14530 // same byte-shape the peer emit-side catch-all constant
14531 // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
14532 // the author's `:paths` list is empty — sweeping the test-side
14533 // probe literal onto the lifted const closes the two-axis pin
14534 // (author-side admit + emit-side canonical fallback) around
14535 // one `&'static str`, so a future rebrand of the catch-all
14536 // reaches both consumers by construction. Peer to
14537 // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
14538 // on the canonical-literal pin surface.
14539 let mut s = three_member_spec();
14540 s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
14541 s.validate().unwrap();
14542 }
14543
14544 #[test]
14545 fn placement_strategy_variants_round_trip() {
14546 for s in [
14547 PlacementStrategy::SingleNode,
14548 PlacementStrategy::Replicated,
14549 PlacementStrategy::Sharded,
14550 ] {
14551 let p = Placement {
14552 estrategia: s,
14553 clusters: vec!["rio".into()],
14554 affinity: None,
14555 // Route the paired `:shard-key` fixture-builder through the
14556 // typed cross-slot invariant predicate
14557 // [`PlacementStrategy::requires_shard_key`] rather than the
14558 // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
14559 // arm-identity predicate — the two answer the same
14560 // question under today's closed accept-set but a future
14561 // arm addition that consumed `:shard-key` under a
14562 // non-`Sharded` name would silently mis-attach the
14563 // fixture's `:shard-key` if the builder read through the
14564 // arm-identity predicate. The cross-slot-invariant
14565 // predicate migrates through one caixa-core edit on any
14566 // future arm addition; the fixture keeps producing a
14567 // `validate()`-passing round-trip by construction.
14568 shard_key: if s.requires_shard_key() {
14569 Some("$key".into())
14570 } else {
14571 None
14572 },
14573 };
14574 let json = serde_json::to_string(&p).unwrap();
14575 let back: Placement = serde_json::from_str(&json).unwrap();
14576 assert_eq!(back, p);
14577 }
14578 }
14579
14580 #[test]
14581 fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
14582 // The fail-before-pass-after pin: pre-lift there was no
14583 // single-source binding between the [`PlacementStrategy`]
14584 // variant name the `Serialize` derive emits and the byte-
14585 // string every downstream cluster-side dispatcher (the
14586 // `lareira-fleet-programs` aggregator's per-entry strategy
14587 // branch, the future `app-operator` reconciler, the M3
14588 // Adaptive compression pass's per-strategy weighting) probes
14589 // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
14590 // future `#[serde(rename_all = "kebab-case")]` attribute on
14591 // the enum — or a variant rename in the source — would
14592 // silently rebrand the emitted scalar under one spelling
14593 // while every downstream dispatcher still probed the other,
14594 // with the failure surfacing at the aggregator's dispatch
14595 // step or the operator's reconcile posture (workloads coming
14596 // up under the `default()` `Replicated` arm rather than the
14597 // typed slot's declared strategy) far from the source
14598 // rebrand commit and with no field naming the drift. Pinning
14599 // the two paths (the `Serialize` derive's serialized string
14600 // AND the [`PlacementStrategy::as_str`] helper) to the same
14601 // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
14602 // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
14603 // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
14604 // makes any future drift on either endpoint fail here at
14605 // caixa-core build time.
14606 for (variant, expected) in [
14607 (
14608 PlacementStrategy::SingleNode,
14609 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
14610 ),
14611 (
14612 PlacementStrategy::Replicated,
14613 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
14614 ),
14615 (
14616 PlacementStrategy::Sharded,
14617 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
14618 ),
14619 ] {
14620 let json = serde_json::to_string(&variant).unwrap();
14621 assert_eq!(
14622 json,
14623 format!("\"{expected}\""),
14624 "PlacementStrategy::{variant:?} must serialize to {expected:?}"
14625 );
14626 assert_eq!(
14627 variant.as_str(),
14628 expected,
14629 "PlacementStrategy::{variant:?}.as_str() must return the lifted \
14630 M3_PLACEMENT_ESTRATEGIA_* constant"
14631 );
14632 }
14633 }
14634
14635 #[test]
14636 fn m3_placement_estrategia_consts_are_pairwise_distinct() {
14637 // Cross-arm drift-detection pin on the M3
14638 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
14639 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
14640 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
14641 // scalar-value pentad: a future collapse of two canonical
14642 // variant byte-strings onto the same value (an accidental
14643 // copy-paste flip of
14644 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
14645 // read `"SingleNode"`, a per-arm rebrand that lands one const
14646 // without touching its paired peer) would silently reroute
14647 // every downstream operator's per-strategy dispatch onto the
14648 // sibling arm's reconcile branch and pass every
14649 // propagation-probe test that expected only the stale arm's
14650 // value — a `Replicated`-declared Aplicacao would come up
14651 // under the `SingleNode` primary-and-standby reconcile
14652 // posture, so every-cluster active-active workload would
14653 // silently collapse onto one-cluster-runs-at-a-time takeover
14654 // semantics against its declared strategy, with no field
14655 // naming the strategy-value drift root cause. Peer of the
14656 // sibling
14657 // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
14658 // (09ffb2d) /
14659 // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
14660 // (ccdf955) /
14661 // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
14662 // (d739850) distinctness pins on the sibling OTP-shape /
14663 // caixa-kind closed-set typed-enum discriminator axes — the
14664 // fourth (and structurally the M3 mesh-primitive-defining)
14665 // closed-set typed-enum axis to converge on the same
14666 // "pairwise-distinct-by-construction" discipline.
14667 //
14668 // Fail-before-pass-after locally verified by mutating
14669 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
14670 // also read `"SingleNode"` — this pin fires as expected;
14671 // restoring passes.
14672 let all = [
14673 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
14674 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
14675 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
14676 ];
14677 for (i, a) in all.iter().enumerate() {
14678 for (j, b) in all.iter().enumerate() {
14679 if i != j {
14680 assert_ne!(
14681 a, b,
14682 "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
14683 distinct — got duplicate {a:?} at indices {i} and {j}",
14684 );
14685 }
14686 }
14687 }
14688 }
14689
14690 #[test]
14691 fn placement_strategy_display_routes_through_as_str_helper() {
14692 // The fail-before-pass-after pin: pre-lift the sibling
14693 // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
14694 // / [`crate::supervisor::RestartPolicy`] both carried a stable
14695 // [`std::fmt::Display`] surface via their
14696 // `#[discriminant(also_display)]` gen-platform derive, but
14697 // [`PlacementStrategy`] did not — every consumer reaching for
14698 // a strategy byte-string past the wire format had to pick
14699 // between three paths ([`PlacementStrategy::as_str`], the
14700 // `Serialize` derive's serialized string, or `format!("{v:?}")`
14701 // on the `Debug` derive), any two of which a future variant
14702 // rename or `#[serde(rename_all = "kebab-case")]` attribute
14703 // would silently desynchronize. Wiring [`std::fmt::Display`]
14704 // through [`PlacementStrategy::as_str`] closes the third path:
14705 // every `format!("{v}")` call reaches the same lifted
14706 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
14707 // and the [`PlacementStrategy::as_str`] helper already route
14708 // through, so a future variant rename lands at exactly one
14709 // place. Pin the routing here so a future
14710 // `impl std::fmt::Display for PlacementStrategy` reimplementation
14711 // that hand-rolls the arms instead of delegating to
14712 // [`PlacementStrategy::as_str`] fails at caixa-core build time.
14713 for variant in [
14714 PlacementStrategy::SingleNode,
14715 PlacementStrategy::Replicated,
14716 PlacementStrategy::Sharded,
14717 ] {
14718 assert_eq!(
14719 variant.to_string(),
14720 variant.as_str(),
14721 "PlacementStrategy::{variant:?} Display must route through \
14722 PlacementStrategy::as_str (single source of truth: the lifted \
14723 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
14724 );
14725 }
14726 }
14727
14728 #[test]
14729 fn placement_strategy_display_matches_serialized_wire_byte_string() {
14730 // The fail-before-pass-after pin on the second half of the
14731 // three-path convergence: `Display` (user-facing text) agrees
14732 // byte-for-byte with the `Serialize` derive's wire format
14733 // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
14734 // scalar) on every variant. Pre-lift the two paths were
14735 // structurally independent — a future
14736 // `#[serde(rename_all = "kebab-case")]` attribute on the enum
14737 // would silently rebrand the emitted wire scalar
14738 // (`single-node`, `replicated`, `sharded`) while every consumer
14739 // that pretty-prints the strategy (the M3 diagnostic templates,
14740 // the future `feira app graph` per-Aplicacao strategy line,
14741 // the future M4 CR materializer's admission-webhook rejection
14742 // body) would still emit the TitleCase form the `as_str` /
14743 // `Display` route returns, with the mismatch surfacing at
14744 // consumer parse time / operator dispatch time far from the
14745 // source rebrand commit. Pin the two paths byte-for-byte here
14746 // so any future serde-attribute or variant-rename drift is a
14747 // caixa-core-build-time test failure at this call, not a
14748 // silent per-consumer dispatch miss.
14749 for variant in [
14750 PlacementStrategy::SingleNode,
14751 PlacementStrategy::Replicated,
14752 PlacementStrategy::Sharded,
14753 ] {
14754 let wire = serde_json::to_string(&variant).unwrap();
14755 // Strip the outer `"…"` the JSON string form carries — the
14756 // wire scalar the K8s / YAML apiserver consumes is the
14757 // enclosed byte-string, not the quote wrapper.
14758 let unquoted = wire
14759 .strip_prefix('"')
14760 .and_then(|s| s.strip_suffix('"'))
14761 .expect("serialized PlacementStrategy is a JSON string");
14762 assert_eq!(
14763 variant.to_string(),
14764 unquoted,
14765 "PlacementStrategy::{variant:?} Display byte-string must match the \
14766 Serialize derive's wire byte-string (three-path convergence: \
14767 Display + as_str + Serialize all resolve to the same \
14768 M3_PLACEMENT_ESTRATEGIA_* const)"
14769 );
14770 }
14771 }
14772
14773 #[test]
14774 fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
14775 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
14776 // derive on [`PlacementStrategy`]: for each of the three variants
14777 // exactly one of the generated `is_single_node` / `is_replicated`
14778 // / `is_sharded` predicates returns `true` and the other two
14779 // return `false`. Prior to this derive the three per-arm
14780 // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
14781 // (the `placement_strategy_variants_round_trip` fixture, the
14782 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
14783 // fixture, and the
14784 // `validate_placement_reads_through_lifted_estrategia_accessor`
14785 // fixture) each open-coded a per-arm PartialEq compare against
14786 // the enum variant — three sites that expressed no compile-time
14787 // link back to the closed-set typed dispatch a future fourth
14788 // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
14789 // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
14790 // would have to thread through in lockstep or one fixture would
14791 // silently disagree with the others on which arms consume the
14792 // `:shard-key` axis. Peer of the sibling
14793 // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
14794 // / [`crate::supervisor::RestartPolicy`] /
14795 // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
14796 // the sibling closed-set typed-enum discriminator axes — extends
14797 // the same one-typed-dispatch-per-variant discipline onto the
14798 // fifth (and only remaining) closed-set typed-enum discriminator
14799 // on the caixa surface, closing the axis on the M3 mesh-slot
14800 // family.
14801 let rows: [(PlacementStrategy, [bool; 3]); 3] = [
14802 (PlacementStrategy::SingleNode, [true, false, false]),
14803 (PlacementStrategy::Replicated, [false, true, false]),
14804 (PlacementStrategy::Sharded, [false, false, true]),
14805 ];
14806 for (variant, expected) in rows {
14807 let observed = [
14808 variant.is_single_node(),
14809 variant.is_replicated(),
14810 variant.is_sharded(),
14811 ];
14812 assert_eq!(
14813 observed, expected,
14814 "PlacementStrategy::{variant:?} is_* predicates must partition \
14815 the arm set (single_node, replicated, sharded); got {observed:?}"
14816 );
14817 }
14818 }
14819
14820 #[test]
14821 fn placement_strategy_is_variant_predicates_are_const_fn() {
14822 // The [`gen_platform::IsVariant`] derive emits `const fn`
14823 // predicates on the peer [`crate::CaixaKind`] +
14824 // [`crate::upgrade::UpgradeInstruction`] +
14825 // [`crate::supervisor::RestartStrategy`] +
14826 // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
14827 // pin the same posture on [`PlacementStrategy`] so a future
14828 // accidental downgrade to non-`const` (an added runtime helper
14829 // reachable only from a non-`const` context, a manual hand-rolled
14830 // `impl` that shadows the derive-generated method) trips at
14831 // caixa-core build time rather than surfacing as a downstream
14832 // `const`-context regression far from the derive declaration.
14833 const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
14834 const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
14835 const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
14836 assert!(IS_SINGLE_NODE);
14837 assert!(IS_REPLICATED);
14838 assert!(IS_SHARDED);
14839 }
14840
14841 #[test]
14842 fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
14843 // Fail-before-pass-after pin on the substrate-lifted
14844 // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
14845 // per-arm predicate: for each variant in the closed accept-set the
14846 // predicate returns `true` iff the variant consumes the paired
14847 // [`Placement::shard_key`] axis under
14848 // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
14849 // partition. Today the accept-set is the singleton `{Sharded}` —
14850 // `Sharded` is the Akka-style hash-keyed distribution arm
14851 // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
14852 // §II.1) and `Replicated` (active-active) refuse the axis through
14853 // [`AplicacaoError::ShardKeyOnNonSharded`].
14854 //
14855 // Pins the per-arm truth-table so a future arm addition (an
14856 // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
14857 // roadmap names, a `WeightedShard` promotion the future M5
14858 // adaptive-placement engine acknowledges) that landed a variant
14859 // without extending this predicate's arm-set would surface as a
14860 // caixa-core build-time exhaustiveness error at the
14861 // `match self { … }` arm-fan below rather than a silent per-consumer
14862 // mis-classification at renderer emit time. The paired
14863 // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
14864 // predicate stays a distinct question — arm-identity (which the
14865 // sibling
14866 // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
14867 // pin already locks) is not cross-slot-invariant consumption; today
14868 // they trip on the same singleton but the pair migrates through
14869 // one caixa-core edit on any future arm addition.
14870 //
14871 // Peer of the sibling per-arm classifier pins
14872 // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
14873 // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
14874 // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
14875 // derived paired predicate on the post-projection typed-view axis
14876 // — same "per-arm semantic-classification predicate paired with
14877 // the arm-identity predicate the derive already emits" discipline
14878 // extended onto the M3 mesh-slot `:placement :estrategia` ↔
14879 // `:placement :shard-key` cross-slot-invariant axis.
14880 let rows: [(PlacementStrategy, bool); 3] = [
14881 (PlacementStrategy::SingleNode, false),
14882 (PlacementStrategy::Replicated, false),
14883 (PlacementStrategy::Sharded, true),
14884 ];
14885 for (variant, expected) in rows {
14886 assert_eq!(
14887 variant.requires_shard_key(),
14888 expected,
14889 "PlacementStrategy::{variant:?}.requires_shard_key() must \
14890 be {expected} (the substrate-canonical cross-slot invariant \
14891 on the :placement :shard-key axis; today `Sharded` is the \
14892 singleton consuming arm — MESH-COMPOSITION §II.4)",
14893 );
14894 }
14895 }
14896
14897 #[test]
14898 fn placement_strategy_requires_shard_key_is_const_fn() {
14899 // The [`PlacementStrategy::requires_shard_key`] cross-slot-
14900 // invariant per-arm predicate is declared `#[must_use] pub const
14901 // fn` — pin the `const`-eval posture here so a future accidental
14902 // downgrade to non-`const` (an added runtime helper reachable
14903 // only from a non-`const` context, a manual hand-rolled `impl`
14904 // that shadows the current three-arm `match self { … }` dispatch)
14905 // trips at caixa-core build time rather than surfacing as a
14906 // downstream `const`-context regression far from the declaration.
14907 // Same shape as the sibling
14908 // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
14909 // the peer [`gen_platform::IsVariant`]-derived arm-identity
14910 // predicate axis, but here the load-bearing assertions live in
14911 // module-scope `const _: () = assert!(…)` items so a violation
14912 // fails at compile time (const-eval trip) rather than test time —
14913 // strictly stronger than the runtime `assert!(CONST)` pattern the
14914 // sibling pin uses, and side-steps the
14915 // `clippy::assertions_on_constants` lint the runtime pattern
14916 // otherwise accumulates on the module baseline.
14917 //
14918 // The test body simply witnesses that the module-scope items
14919 // compiled and the runtime dispatch agrees with the const-eval
14920 // dispatch on every arm — the runtime read gives the test a
14921 // failure surface (rather than an empty test body clippy would
14922 // flag as a no-op).
14923 const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
14924 const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
14925 const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
14926 assert_eq!(
14927 [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
14928 [
14929 PlacementStrategy::SingleNode.requires_shard_key(),
14930 PlacementStrategy::Replicated.requires_shard_key(),
14931 PlacementStrategy::Sharded.requires_shard_key(),
14932 ],
14933 "runtime and const-eval dispatch on \
14934 PlacementStrategy::requires_shard_key must agree on every arm",
14935 );
14936 }
14937
14938 #[test]
14939 fn placement_estrategia_accessor_is_const_fn() {
14940 // The [`Placement::estrategia`] per-`:placement` distribution-
14941 // strategy `Copy`-return scalar accessor is declared
14942 // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
14943 // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
14944 // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
14945 // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
14946 // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
14947 // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
14948 // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
14949 // [`RateLimit`], every one a `pub const fn`). Pin the
14950 // `const`-eval posture here so a future accidental downgrade to
14951 // non-`const` (an added runtime helper reachable only from a
14952 // non-`const` context, a slot promotion to a non-`Copy` return
14953 // that would silently drop the `const` qualifier, a manual
14954 // hand-rolled shadow) trips at caixa-core build time rather
14955 // than surfacing as a downstream `const`-context regression far
14956 // from the declaration.
14957 //
14958 // Same shape as the sibling
14959 // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
14960 // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
14961 // predicate axis — the load-bearing witness lives in the
14962 // module-scope `const fn` wrapper `estrategia_via_const_fn`
14963 // below: a body that calls [`Placement::estrategia`] under a
14964 // `const fn` signature is well-formed only when the callee is
14965 // itself `const fn`, so any future accidental downgrade of
14966 // [`Placement::estrategia`] to non-`const` fails at caixa-core
14967 // build time (const-eval E0015 / E0658 depending on the arm),
14968 // strictly stronger than a runtime `assert!(CONST)` and
14969 // side-stepping the destructor-in-const restriction that
14970 // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
14971 // items on `Placement`'s `Vec<String>` / `Option<String>`
14972 // carriers.
14973 //
14974 // The runtime body witnesses that the const-eval-shaped
14975 // wrapper agrees with a direct call on every closed-set arm.
14976 const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
14977 p.estrategia()
14978 }
14979 for estrategia in [
14980 PlacementStrategy::SingleNode,
14981 PlacementStrategy::Replicated,
14982 PlacementStrategy::Sharded,
14983 ] {
14984 let placement = Placement {
14985 estrategia,
14986 clusters: Vec::new(),
14987 affinity: None,
14988 shard_key: None,
14989 };
14990 assert_eq!(
14991 estrategia_via_const_fn(&placement),
14992 placement.estrategia(),
14993 "const-fn-wrapped and direct dispatch on \
14994 Placement::estrategia must agree for {estrategia:?}",
14995 );
14996 }
14997 }
14998
14999 #[test]
15000 fn entrada_port_accessor_is_const_fn() {
15001 // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
15002 // scalar accessor is declared `#[must_use] pub const fn` —
15003 // matching the peer M3 mesh-slot `Copy`-return accessor family
15004 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
15005 // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
15006 // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
15007 // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
15008 // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
15009 // [`RateLimit::window`] on the sibling [`RateLimit`], the
15010 // sibling per-`:placement` [`Placement::estrategia`] pinned by
15011 // [`placement_estrategia_accessor_is_const_fn`] above — every
15012 // one a `pub const fn`). Pin the `const`-eval posture here so
15013 // a future accidental downgrade to non-`const` (an added
15014 // runtime helper reachable only from a non-`const` context, an
15015 // `Option<u16>`-shape migration once the substrate grows
15016 // per-`:membros` heterogeneous listener ports that would
15017 // silently drop the `const` qualifier, a manual hand-rolled
15018 // shadow) trips at caixa-core build time rather than surfacing
15019 // as a downstream `const`-context regression far from the
15020 // declaration.
15021 //
15022 // Same shape as the sibling
15023 // [`placement_estrategia_accessor_is_const_fn`] pin above — the
15024 // load-bearing witness lives in the module-scope `const fn`
15025 // wrapper `port_via_const_fn`: a body that calls
15026 // [`Entrada::port`] under a `const fn` signature is well-formed
15027 // only when the callee is itself `const fn`, side-stepping the
15028 // destructor-in-const restriction that would otherwise block a
15029 // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
15030 // `String` / `Vec<String>` carriers.
15031 //
15032 // The runtime body sweeps a representative port set spanning
15033 // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
15034 // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
15035 // ceiling — the const-fn-wrapped call must agree with a direct
15036 // call on every fixture (a violation trips the test) and every
15037 // returned scalar must byte-equal the input `port` (a violation
15038 // means the accessor stopped being a raw field-return copy).
15039 const fn port_via_const_fn(e: &Entrada) -> u16 {
15040 e.port()
15041 }
15042 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
15043 let entrada = Entrada {
15044 host: String::new(),
15045 para: String::new(),
15046 port,
15047 paths: Vec::new(),
15048 };
15049 assert_eq!(
15050 port_via_const_fn(&entrada),
15051 entrada.port(),
15052 "const-fn-wrapped and direct dispatch on Entrada::port \
15053 must agree for port={port}",
15054 );
15055 assert_eq!(
15056 entrada.port(),
15057 port,
15058 "Entrada::port must return the storage-side u16 verbatim \
15059 for port={port}",
15060 );
15061 }
15062 }
15063
15064 #[test]
15065 fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
15066 // Load-bearing cross-slot-partition pin closing the loop between
15067 // the substrate-lifted
15068 // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
15069 // the closed-set typed enum and the actual
15070 // [`AplicacaoSpec::validate_placement`] runtime behavior across
15071 // the paired `:placement :shard-key` axis: every validated
15072 // [`Placement`] past [`AplicacaoSpec::validate_placement`]
15073 // satisfies `placement.shard_key().is_some() ==
15074 // placement.estrategia().requires_shard_key()`. The four-cell
15075 // shape witness sweeps every combination of (variant in the
15076 // closed accept-set, `:shard-key` Some/None) and pins:
15077 //
15078 // * variant.requires_shard_key() && shard_key.is_some() →
15079 // validate() passes; the paired shape is the sole
15080 // `requires_shard_key` arm-family accepted shape.
15081 // * variant.requires_shard_key() && shard_key.is_none() →
15082 // validate() fails with [`AplicacaoError::ShardedWithoutKey`];
15083 // the paired shape is the refused missing-key shape on
15084 // Sharded-family arms.
15085 // * !variant.requires_shard_key() && shard_key.is_some() →
15086 // validate() fails with
15087 // [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
15088 // is the refused declared-but-inert shape on non-Sharded-
15089 // family arms.
15090 // * !variant.requires_shard_key() && shard_key.is_none() →
15091 // validate() passes; the paired shape is the sole
15092 // non-`requires_shard_key` arm-family accepted shape.
15093 //
15094 // The compile-time-exhaustive `match p.estrategia()` dispatch at
15095 // [`AplicacaoSpec::validate_placement`] preserves its structural
15096 // arm-fan (a future arm addition still surfaces a build-time
15097 // exhaustiveness error there); this pin closes the semantic loop
15098 // between the arm-fan's shape-gate cascades and the substrate-
15099 // canonical predicate every downstream consumer of the paired
15100 // shape reads through. Fail-before-pass-after locally verified by
15101 // mutating the predicate's `Sharded => true` arm to `false` — the
15102 // truthy `expects_ok` cell for `Sharded` + `Some` trips the
15103 // `validate() must pass` assertion; restoring passes. Same "close
15104 // the loop between the typed predicate and the runtime behavior"
15105 // discipline as the sibling
15106 // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
15107 // (7b97d26) cross-projection pin on the peer [`WitTarget`]
15108 // per-arm classifier axis.
15109 for variant in [
15110 PlacementStrategy::SingleNode,
15111 PlacementStrategy::Replicated,
15112 PlacementStrategy::Sharded,
15113 ] {
15114 for present in [false, true] {
15115 let mut spec = three_member_spec();
15116 spec.placement.estrategia = variant;
15117 spec.placement.shard_key = present.then(|| "tenantId".into());
15118 let expects_ok = variant.requires_shard_key() == present;
15119 let result = spec.validate();
15120 match (expects_ok, &result) {
15121 (true, Ok(())) => {}
15122 (false, Err(err)) => {
15123 // Cross-check the refusal diagnostic names the
15124 // right cell of the four-cell shape witness — the
15125 // `requires_shard_key && !present` cell must trip
15126 // [`AplicacaoError::ShardedWithoutKey`]; the
15127 // `!requires_shard_key && present` cell must trip
15128 // [`AplicacaoError::ShardKeyOnNonSharded`].
15129 match (variant.requires_shard_key(), present, err) {
15130 (true, false, AplicacaoError::ShardedWithoutKey) => {}
15131 (
15132 false,
15133 true,
15134 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
15135 ) => {
15136 assert_eq!(
15137 *e, variant,
15138 "ShardKeyOnNonSharded.estrategia must byte-equal \
15139 the paired PlacementStrategy",
15140 );
15141 }
15142 _ => panic!(
15143 "unexpected refusal for estrategia={variant:?} \
15144 present={present}: {err:?}"
15145 ),
15146 }
15147 }
15148 (true, Err(err)) => panic!(
15149 "validate() must pass for estrategia={variant:?} \
15150 present={present} (requires_shard_key={} == present={present}), \
15151 got {err:?}",
15152 variant.requires_shard_key(),
15153 ),
15154 (false, Ok(())) => panic!(
15155 "validate() must fail for estrategia={variant:?} \
15156 present={present} (requires_shard_key={} != present={present})",
15157 variant.requires_shard_key(),
15158 ),
15159 }
15160 }
15161 }
15162 }
15163
15164 #[test]
15165 fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
15166 // Pin the M3 diagnostic template routes through the typed
15167 // [`PlacementStrategy`] Display byte-string (rebound from the
15168 // prior `{estrategia:?}` `Debug` route). Pre-lift the two
15169 // routes emitted identical bytes (the `Debug` derive on a
15170 // unit variant emits the variant name verbatim, exactly what
15171 // `as_str` returns), but the two paths were structurally
15172 // independent — a future `#[serde(rename_all = "…")]`
15173 // attribute or variant rename would coordinate the wire /
15174 // `Display` / `as_str` triple through the lifted const but
15175 // leave the `Debug` route on the compiler-derived variant name,
15176 // silently desynchronizing the diagnostic byte-string from the
15177 // wire byte-string. Rebinding the template onto `Display`
15178 // ties the diagnostic to the same lifted
15179 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
15180 // emits — drift becomes structurally impossible. Pin the
15181 // byte-string here so a future edit that reverts the template
15182 // to `{estrategia:?}` is caught at caixa-core test time, not
15183 // at consumer dispatch time.
15184 for (variant, expected_scalar) in [
15185 (
15186 PlacementStrategy::SingleNode,
15187 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15188 ),
15189 (
15190 PlacementStrategy::Replicated,
15191 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15192 ),
15193 (
15194 PlacementStrategy::Sharded,
15195 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15196 ),
15197 ] {
15198 let err = AplicacaoError::PlacementWithoutClusters {
15199 estrategia: variant,
15200 };
15201 let msg = err.to_string();
15202 assert!(
15203 msg.starts_with(&format!(":placement {expected_scalar} requires")),
15204 "PlacementWithoutClusters diagnostic for {variant:?} must open \
15205 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
15206 );
15207 }
15208 }
15209
15210 #[test]
15211 fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
15212 // Peer of
15213 // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
15214 // on the second M3 diagnostic that carries the typed
15215 // [`PlacementStrategy`] in its `#[error(…)]` template. Both
15216 // diagnostics now route the strategy scalar through the same
15217 // [`std::fmt::Display`] surface, tying the diagnostic
15218 // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
15219 // const set the wire format also emits. The two non-Sharded
15220 // arms are exercised here (the diagnostic exists to flag a
15221 // `:shard-key` slot the current strategy will never consume);
15222 // the peer `Sharded` arm never reaches this diagnostic (the
15223 // `Sharded` strategy consumes `:shard-key` — the
15224 // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
15225 // slot instead).
15226 for (variant, expected_scalar) in [
15227 (
15228 PlacementStrategy::SingleNode,
15229 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15230 ),
15231 (
15232 PlacementStrategy::Replicated,
15233 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15234 ),
15235 ] {
15236 let err = AplicacaoError::ShardKeyOnNonSharded {
15237 estrategia: variant,
15238 shard_key: "$tenantId".into(),
15239 };
15240 let msg = err.to_string();
15241 assert!(
15242 msg.starts_with(&format!(":placement {expected_scalar} carries")),
15243 "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
15244 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
15245 );
15246 }
15247 }
15248
15249 #[test]
15250 fn placement_strategy_all_enumerates_every_variant_once() {
15251 // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
15252 // exhaustive-iteration surface: every variant appears exactly
15253 // once, and the slice length matches the arm count of the
15254 // closed set. Every consumer that walks the accepted-strategy
15255 // set (a future `feira app placement --list` CLI-side surfacing,
15256 // a future M4 admission-webhook's rejection body naming the
15257 // accepted-strategy list, the [`PlacementStrategy::from_wire`]
15258 // reverse-projection consumers that iterate the accept-set for
15259 // a "did you mean" hint) reads through this slice, so a future
15260 // variant addition (an `Anycast` mesh-anycast arm the
15261 // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
15262 // grows the enum but forgets to grow [`Self::ALL`] silently
15263 // truncates every downstream consumer's accept-set at the same
15264 // pre-addition boundary — this pin fails at caixa-core build
15265 // time on the pairwise-distinct + arm-count invariants.
15266 //
15267 // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
15268 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
15269 // pins on the peer closed-set typed-enum axes.
15270 let all: &[PlacementStrategy] = PlacementStrategy::ALL;
15271 assert_eq!(
15272 all.len(),
15273 3,
15274 "PlacementStrategy::ALL must enumerate every variant of the \
15275 three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
15276 );
15277 for (i, a) in all.iter().enumerate() {
15278 for (j, b) in all.iter().enumerate() {
15279 if i != j {
15280 assert_ne!(
15281 a, b,
15282 "PlacementStrategy::ALL must carry every variant exactly \
15283 once — got duplicate {a:?} at indices {i} and {j}"
15284 );
15285 }
15286 }
15287 }
15288 for variant in [
15289 PlacementStrategy::SingleNode,
15290 PlacementStrategy::Replicated,
15291 PlacementStrategy::Sharded,
15292 ] {
15293 assert!(
15294 all.contains(&variant),
15295 "PlacementStrategy::ALL must contain {variant:?} — a future variant \
15296 addition that grows the enum but forgets to grow the ALL slice \
15297 silently truncates every downstream consumer's accept-set at the \
15298 pre-addition boundary"
15299 );
15300 }
15301 }
15302
15303 #[test]
15304 fn placement_strategy_from_wire_accepts_every_lifted_constant() {
15305 // Fail-before-pass-after pin on the forward accept-set of the
15306 // [`PlacementStrategy::from_wire`] reverse projection: every
15307 // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
15308 // constant the [`PlacementStrategy::as_str`] emitter walks
15309 // parses back to its paired variant. Any future arm addition
15310 // that grows the emitter's `as_str` match but forgets to grow
15311 // the parser's `from_str` match silently splits the two halves
15312 // of the round-trip — the wire byte-string one non-serde
15313 // consumer parses from the one the emitter wrote — with the
15314 // failure surfacing at parse time far from the rebrand commit.
15315 // Pinning the three-arm accept-set here catches the drift at
15316 // caixa-core build time.
15317 //
15318 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
15319 // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
15320 // closed-set typed-enum `str → Self` axes.
15321 for (wire, expected) in [
15322 (
15323 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15324 PlacementStrategy::SingleNode,
15325 ),
15326 (
15327 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15328 PlacementStrategy::Replicated,
15329 ),
15330 (
15331 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15332 PlacementStrategy::Sharded,
15333 ),
15334 ] {
15335 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
15336 panic!(
15337 "PlacementStrategy::from_wire({wire:?}) must accept every \
15338 M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
15339 lifted canonical byte-string that PlacementStrategy::{expected:?} \
15340 serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
15341 )
15342 });
15343 assert_eq!(
15344 parsed, expected,
15345 "PlacementStrategy::from_wire({wire:?}) must return \
15346 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
15347 );
15348 }
15349 }
15350
15351 #[test]
15352 fn placement_strategy_from_wire_round_trips_through_as_str() {
15353 // Fail-before-pass-after pin on the closed round-trip between
15354 // the forward [`PlacementStrategy::as_str`] emitter and the
15355 // reverse [`PlacementStrategy::from_wire`] parser: for every
15356 // variant in [`PlacementStrategy::ALL`], parsing the emitter's
15357 // output must return exactly the same variant. Any per-arm
15358 // divergence — a future arm added to `as_str` but not
15359 // `from_str`, an accidental copy-paste flip in one but not the
15360 // other — silently splits the emit and parse halves and the
15361 // failure surfaces at consumer parse time far from the drift
15362 // site. The `ALL`-iterating shape means a future variant
15363 // addition picks up the coverage by construction.
15364 //
15365 // Peer of the sibling [`crate::kind::tests`] round-trip pin on
15366 // [`crate::CaixaKind::from_wire`] and the
15367 // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
15368 // sibling round-trip pin on [`RateLimitUnit`].
15369 for &variant in PlacementStrategy::ALL {
15370 let wire = variant.as_str();
15371 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
15372 panic!(
15373 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
15374 must be Some({variant:?}) — the two halves of the round-trip \
15375 dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
15376 got None on wire byte-string {wire:?}"
15377 )
15378 });
15379 assert_eq!(
15380 parsed, variant,
15381 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
15382 must round-trip to the same variant; got {parsed:?}"
15383 );
15384 }
15385 }
15386
15387 #[test]
15388 fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
15389 // Fail-before-pass-after pin on the closed-set refusal
15390 // discipline of [`PlacementStrategy::from_wire`]: every
15391 // byte-string outside the three-arm accept-set returns `None`
15392 // rather than silently collapsing onto the [`Default`]
15393 // (`Replicated`) arm or an arbitrary neighbor. The refusal set
15394 // exercised here sweeps the load-bearing drift shapes: the
15395 // empty string (a stripped serde-attribute drift), an all-
15396 // whitespace string (the canonical text-editor accidental
15397 // padding shape), the lowercased kebab-case forms a future
15398 // `#[serde(rename_all = "kebab-case")]` attribute would emit
15399 // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
15400 // coincidentally match the accepted canonical scalars, so only
15401 // `"single-node"` fires as a refusal, but pinning the case-
15402 // sensitivity of the accepted arms via the peer [`SingleNode`]
15403 // assertion in the round-trip pin makes the discipline
15404 // structurally clear), the lowercased single-word forms
15405 // (`"singlenode"`), the padded canonical scalar
15406 // (`" Sharded "`), the trailing-comma / trailing-newline shapes
15407 // (`"Sharded\n"`), and a pointer-different `&'static str` that
15408 // happens to alias a canonical byte-string by content but not
15409 // by identity (validated implicitly by the emitter's routing
15410 // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
15411 // identity a paired [`crate::assert_str_reexport_identity`] pin
15412 // in caixa-core's per-const declaration surface would catch).
15413 //
15414 // Peer of the sibling
15415 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
15416 // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
15417 for bad in [
15418 "",
15419 " ",
15420 "\n",
15421 "\t",
15422 "single-node",
15423 "singlenode",
15424 "SingleNodes",
15425 "single_node",
15426 "single node",
15427 "SINGLENODE",
15428 "SingleNode ",
15429 " SingleNode",
15430 " Sharded ",
15431 "Sharded\n",
15432 "replicated ",
15433 "sharded",
15434 "REPLICATED",
15435 "Anycast",
15436 "Global",
15437 "?",
15438 ] {
15439 assert!(
15440 PlacementStrategy::from_wire(bad).is_none(),
15441 "PlacementStrategy::from_wire({bad:?}) must return None — the \
15442 parser's accept-set is exactly the three PlacementStrategy::as_str \
15443 outputs (SingleNode, Replicated, Sharded), and this byte-string \
15444 is outside that closed set"
15445 );
15446 }
15447 }
15448
15449 #[test]
15450 fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
15451 // Fail-before-pass-after pin on the third path of the four-path
15452 // convergence: `from_str` (the reverse projection) inverts the
15453 // `Serialize` derive's wire byte-string on every variant.
15454 // Together with the pre-existing three-path convergence
15455 // (`Display` + `as_str` + `Serialize` all resolve to the same
15456 // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
15457 // the peer
15458 // [`placement_strategy_display_matches_serialized_wire_byte_string`])
15459 // this closes the round-trip: the wire byte-string the
15460 // `Serialize` derive emits parses back to the same variant
15461 // through `from_str`, so any future serde-attribute or variant-
15462 // rename drift on the emit half now surfaces as a matched drift
15463 // on the parse half at caixa-core build time — the two halves
15464 // migrate as a unit through the lifted consts on any future
15465 // rename, and the round-trip cannot silently split.
15466 //
15467 // Peer of the sibling
15468 // [`placement_strategy_display_matches_serialized_wire_byte_string`]
15469 // wire-format pin — extends the three-path convergence
15470 // (`Display` + `as_str` + `Serialize`) onto the fourth path
15471 // (`from_str`), closing the `str ↔ Self` round-trip on the
15472 // M3 `:placement :estrategia` closed-set axis.
15473 for &variant in PlacementStrategy::ALL {
15474 let wire = serde_json::to_string(&variant).unwrap();
15475 let unquoted = wire
15476 .strip_prefix('"')
15477 .and_then(|s| s.strip_suffix('"'))
15478 .expect("serialized PlacementStrategy is a JSON string");
15479 let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
15480 panic!(
15481 "PlacementStrategy::from_wire({unquoted:?}) must accept the \
15482 Serialize derive's wire byte-string for \
15483 PlacementStrategy::{variant:?} — the four-path convergence \
15484 (Display + as_str + Serialize + from_str) resolves through \
15485 the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
15486 )
15487 });
15488 assert_eq!(
15489 parsed, variant,
15490 "PlacementStrategy::from_wire of the Serialize derive's wire \
15491 byte-string for PlacementStrategy::{variant:?} must round-trip \
15492 to the same variant; got {parsed:?}"
15493 );
15494 }
15495 }
15496
15497 #[test]
15498 fn rejects_zero_policy_timeout() {
15499 let mut s = three_member_spec();
15500 s.politicas.timeout = Some(Duration::ZERO);
15501 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
15502 }
15503
15504 #[test]
15505 fn rejects_zero_policy_retries() {
15506 let mut s = three_member_spec();
15507 s.politicas.retries = Some(0);
15508 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
15509 }
15510
15511 #[test]
15512 fn rejects_policy_retries_above_cap() {
15513 // The fail-before-pass-after pin: `Some(11)` is structurally
15514 // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
15515 // passed validate on every pre-gate codebase because the
15516 // typed slot's only check was the zero-floor arm. The
15517 // thundering-herd amplification vector only surfaced at the
15518 // runtime substrate (Envoy / Cilium L7 retry overlay)
15519 // far from the source caixa.lisp with no field naming the
15520 // offending policy.
15521 let mut s = three_member_spec();
15522 s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
15523 assert_eq!(
15524 s.validate().unwrap_err(),
15525 AplicacaoError::PolicyRetriesExceedsCap {
15526 retries: POLICY_RETRIES_MAX + 1
15527 }
15528 );
15529 }
15530
15531 #[test]
15532 fn rejects_policy_retries_far_above_cap() {
15533 // The `u32::MAX` worst case — the four-billion-retry policy
15534 // a typo (`(:retries 4294967295)`) or struct-literal
15535 // copy-paste lands in the slot. Pin the cap arm's coverage
15536 // explicitly across the full `u32` overflow so a future
15537 // relaxation that drops the upper bound surfaces here.
15538 let mut s = three_member_spec();
15539 s.politicas.retries = Some(u32::MAX);
15540 assert_eq!(
15541 s.validate().unwrap_err(),
15542 AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
15543 );
15544 }
15545
15546 #[test]
15547 fn accepts_policy_retries_at_cap() {
15548 // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
15549 // must validate. The cap is inclusive on the top edge,
15550 // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
15551 // discipline on the sibling [`crate::LimitsSpec::memory`]
15552 // axis. Pin the boundary explicitly so a future off-by-one
15553 // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
15554 // surfaces here as a test failure rather than a silent
15555 // contract narrowing.
15556 let mut s = three_member_spec();
15557 s.politicas.retries = Some(POLICY_RETRIES_MAX);
15558 s.validate()
15559 .expect("retries == POLICY_RETRIES_MAX must validate");
15560 }
15561
15562 #[test]
15563 fn accepts_policy_retries_typical_values() {
15564 // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
15565 // every value in the validated set must pass. The
15566 // Envoy / Istio production-playbook recommendation band
15567 // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
15568 // (`maxRetries ≤ 10`) both lie within this set.
15569 for r in 1..=POLICY_RETRIES_MAX {
15570 let mut s = three_member_spec();
15571 s.politicas.retries = Some(r);
15572 s.validate()
15573 .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
15574 }
15575 }
15576
15577 #[test]
15578 fn policy_retries_zero_takes_precedence_over_cap() {
15579 // The cross-arm ordering pin: `Some(0)` is structurally
15580 // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
15581 // (cap), but the zero-floor diagnostic is the more
15582 // self-locating one (it directly names the omit-axis
15583 // remediation), so the validate gate must fire on zero
15584 // first. Pin the order so a future refactor that reorders
15585 // the arms surfaces here as a test failure rather than a
15586 // silent diagnostic regression. Same shape every other
15587 // zero-then-shape ordering on this surface uses
15588 // ([`AplicacaoError::PolicyTimeoutZero`] then
15589 // [`AplicacaoError::PolicyTimeoutNotCanonical`];
15590 // [`AplicacaoError::PolicyBreakerZeroWindow`] then
15591 // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
15592 let mut s = three_member_spec();
15593 s.politicas.retries = Some(0);
15594 assert_eq!(
15595 s.validate().unwrap_err(),
15596 AplicacaoError::PolicyRetriesZero,
15597 "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
15598 );
15599 }
15600
15601 #[test]
15602 fn policy_retries_cap_diagnostic_carries_offending_value() {
15603 // The diagnostic-shape pin: the offending `u32` is carried
15604 // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
15605 // variant so the surfaced error message names the value the
15606 // author wrote (`":politicas :retries (47) exceeds the
15607 // mesh-policy ceiling …"`), not just the cap. Same
15608 // self-locating diagnostic shape every other typed-cap arm
15609 // on this surface carries
15610 // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
15611 // offending byte count verbatim).
15612 let mut s = three_member_spec();
15613 s.politicas.retries = Some(47);
15614 let err = s.validate().unwrap_err();
15615 assert!(
15616 matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
15617 "got {err:?}"
15618 );
15619 let msg = err.to_string();
15620 assert!(
15621 msg.contains("47"),
15622 ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
15623 );
15624 }
15625
15626 #[test]
15627 fn policy_retries_cap_is_aws_app_mesh_aligned() {
15628 // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
15629 // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
15630 // schema cap — the only upstream mesh-policy schema that
15631 // documents an explicit hard cap. Pinning the literal value
15632 // here surfaces a future drift (a relaxation to 20, a
15633 // tightening to 5) as a deliberate test edit, not a silent
15634 // contract narrowing.
15635 assert_eq!(POLICY_RETRIES_MAX, 10);
15636 }
15637
15638 #[test]
15639 fn rejects_circuit_breaker_zero_max_failures() {
15640 let mut s = three_member_spec();
15641 s.politicas.circuit_breaker = Some(CircuitBreaker {
15642 max_failures: 0,
15643 window: Duration::from_secs(60),
15644 });
15645 assert_eq!(
15646 s.validate().unwrap_err(),
15647 AplicacaoError::PolicyBreakerZeroFailures
15648 );
15649 }
15650
15651 #[test]
15652 fn rejects_circuit_breaker_max_failures_above_cap() {
15653 // The fail-before-pass-after pin: `1001` is structurally one
15654 // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
15655 // silently passed validate on every pre-gate codebase
15656 // because the typed slot's only check was the zero-floor
15657 // arm. The breaker-no-op vector only surfaced at the runtime
15658 // substrate (Envoy / Cilium L7 outlier-detection overlay)
15659 // far from the source caixa.lisp with no field naming the
15660 // offending policy.
15661 let mut s = three_member_spec();
15662 s.politicas.circuit_breaker = Some(CircuitBreaker {
15663 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15664 window: Duration::from_secs(60),
15665 });
15666 assert_eq!(
15667 s.validate().unwrap_err(),
15668 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15669 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15670 }
15671 );
15672 }
15673
15674 #[test]
15675 fn rejects_circuit_breaker_max_failures_far_above_cap() {
15676 // The `u32::MAX` worst case — the four-billion-failure
15677 // threshold a typo (`(:max-failures 4294967295)`) or a
15678 // struct-literal copy-paste lands in the slot. Pin the cap
15679 // arm's coverage explicitly across the full `u32` overflow
15680 // so a future relaxation that drops the upper bound surfaces
15681 // here.
15682 let mut s = three_member_spec();
15683 s.politicas.circuit_breaker = Some(CircuitBreaker {
15684 max_failures: u32::MAX,
15685 window: Duration::from_secs(60),
15686 });
15687 assert_eq!(
15688 s.validate().unwrap_err(),
15689 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15690 max_failures: u32::MAX,
15691 }
15692 );
15693 }
15694
15695 #[test]
15696 fn accepts_circuit_breaker_max_failures_at_cap() {
15697 // The boundary value — exactly
15698 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
15699 // cap is inclusive on the top edge, matching the
15700 // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
15701 // discipline on the sibling capped axes. Pin the boundary
15702 // explicitly so a future off-by-one tightening
15703 // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
15704 // surfaces here as a test failure rather than a silent
15705 // contract narrowing.
15706 let mut s = three_member_spec();
15707 s.politicas.circuit_breaker = Some(CircuitBreaker {
15708 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
15709 window: Duration::from_secs(60),
15710 });
15711 s.validate()
15712 .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
15713 }
15714
15715 #[test]
15716 fn accepts_circuit_breaker_max_failures_typical_values() {
15717 // The documented production-playbook band positive-control
15718 // sweep — every value Hystrix / Istio / Envoy / Polly /
15719 // Resilience4j recommend (5..=50) must pass, plus a sweep
15720 // through the hyperscale band (100, 500, 1000) the cap
15721 // accepts. Pin the inclusive validated set explicitly so a
15722 // future tightening of the ceiling surfaces here.
15723 for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
15724 let mut s = three_member_spec();
15725 s.politicas.circuit_breaker = Some(CircuitBreaker {
15726 max_failures: n,
15727 window: Duration::from_secs(60),
15728 });
15729 s.validate()
15730 .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
15731 }
15732 }
15733
15734 #[test]
15735 fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
15736 // The cross-arm ordering pin: `0` is structurally outside
15737 // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
15738 // (cap), but the zero-floor diagnostic is the more
15739 // self-locating one (it directly names the omit-axis
15740 // remediation), so the validate gate must fire on zero
15741 // first. Same shape every other zero-then-shape ordering on
15742 // this surface uses
15743 // ([`AplicacaoError::PolicyRetriesZero`] then
15744 // [`AplicacaoError::PolicyRetriesExceedsCap`];
15745 // [`AplicacaoError::PolicyTimeoutZero`] then
15746 // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
15747 let mut s = three_member_spec();
15748 s.politicas.circuit_breaker = Some(CircuitBreaker {
15749 max_failures: 0,
15750 window: Duration::from_secs(60),
15751 });
15752 assert_eq!(
15753 s.validate().unwrap_err(),
15754 AplicacaoError::PolicyBreakerZeroFailures,
15755 "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
15756 );
15757 }
15758
15759 #[test]
15760 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
15761 // The cross-arm ordering pin between the cap and the
15762 // sibling `:window` gates (zero-window, canonical-window).
15763 // A breaker carrying both an over-cap `max_failures` AND a
15764 // structurally invalid window (zero, sub-ms) must surface
15765 // the cap diagnostic first — the cap arm is wired
15766 // immediately after the zero-failure arm and strictly
15767 // before the window arms, so the offending value the
15768 // diagnostic names matches the order the author would
15769 // discover the gates by reading top-to-bottom through
15770 // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
15771 // future refactor that reorders the arms surfaces here as a
15772 // test failure rather than a silent diagnostic regression.
15773 let mut s = three_member_spec();
15774 s.politicas.circuit_breaker = Some(CircuitBreaker {
15775 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15776 window: Duration::ZERO,
15777 });
15778 assert_eq!(
15779 s.validate().unwrap_err(),
15780 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15781 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15782 },
15783 "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
15784 );
15785 }
15786
15787 #[test]
15788 fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
15789 // The diagnostic-shape pin: the offending `u32` is carried
15790 // verbatim into the
15791 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
15792 // variant so the surfaced error message names the value the
15793 // author wrote (`":politicas :circuit-breaker :max-failures
15794 // (50000) exceeds the mesh-policy ceiling …"`), not just
15795 // the cap. Same self-locating diagnostic shape every other
15796 // typed-cap arm on this surface carries
15797 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
15798 // offending retry count verbatim,
15799 // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
15800 // offending byte count verbatim).
15801 let mut s = three_member_spec();
15802 s.politicas.circuit_breaker = Some(CircuitBreaker {
15803 max_failures: 50_000,
15804 window: Duration::from_secs(60),
15805 });
15806 let err = s.validate().unwrap_err();
15807 assert!(
15808 matches!(
15809 err,
15810 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15811 max_failures: 50_000
15812 }
15813 ),
15814 "got {err:?}"
15815 );
15816 let msg = err.to_string();
15817 assert!(
15818 msg.contains("50000"),
15819 ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
15820 );
15821 }
15822
15823 #[test]
15824 fn policy_breaker_max_failures_cap_pins_canonical_value() {
15825 // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
15826 // value at 1000 — an order of magnitude above every
15827 // documented production-playbook recommendation band
15828 // (Hystrix `requestVolumeThreshold` default 20, Istio
15829 // `outlierDetection.consecutive5xxErrors` default 5, Envoy
15830 // `outlier_detection.consecutive_5xx` default 5, Polly /
15831 // Resilience4j typical 5..=50) and below the
15832 // clearly-pathological "effectively no protection" floor
15833 // (10_000, 100_000, u32::MAX). Pinning the literal value
15834 // here surfaces a future drift (a relaxation to 10_000, a
15835 // tightening to 100) as a deliberate test edit, not a
15836 // silent contract narrowing.
15837 assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
15838 }
15839
15840 #[test]
15841 fn rejects_circuit_breaker_zero_window() {
15842 let mut s = three_member_spec();
15843 s.politicas.circuit_breaker = Some(CircuitBreaker {
15844 max_failures: 5,
15845 window: Duration::ZERO,
15846 });
15847 assert_eq!(
15848 s.validate().unwrap_err(),
15849 AplicacaoError::PolicyBreakerZeroWindow
15850 );
15851 }
15852
15853 #[test]
15854 fn rejects_zero_rate_limit() {
15855 let mut s = three_member_spec();
15856 s.politicas.rate_limit = Some(RateLimit {
15857 rate: 0,
15858 window: Duration::from_secs(1),
15859 });
15860 assert_eq!(
15861 s.validate().unwrap_err(),
15862 AplicacaoError::PolicyRateLimitZero
15863 );
15864 }
15865
15866 #[test]
15867 fn rejects_rate_limit_zero_window() {
15868 // `RateLimit { rate: 100, window: Duration::ZERO }` is
15869 // constructible programmatically (the typed `Duration` field
15870 // imposes no nonzero invariant) but renders through
15871 // `rate_limit_codec::render` as `"100/0s"` — a fragment the
15872 // codec's `parse` rejects as `unknown rate-limit window unit
15873 // "0s"`. Until this validate-time gate landed the typed slot
15874 // accepted the value silently and the round-trip break only
15875 // surfaced at deserialize time (potentially in a downstream
15876 // consumer that never re-validates). Pin the rejection at
15877 // `AplicacaoSpec::validate` so the typed slot's valid set
15878 // matches the codec's round-trippable set structurally.
15879 let mut s = three_member_spec();
15880 s.politicas.rate_limit = Some(RateLimit {
15881 rate: 100,
15882 window: Duration::ZERO,
15883 });
15884 assert_eq!(
15885 s.validate().unwrap_err(),
15886 AplicacaoError::PolicyRateLimitWindowNotCanonical {
15887 window: Duration::ZERO
15888 }
15889 );
15890 }
15891
15892 #[test]
15893 fn rejects_rate_limit_arbitrary_seconds_window() {
15894 // 45 seconds is a valid `Duration` but not one of the three
15895 // canonical rate-limit windows the codec round-trips
15896 // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
15897 // refuses on round-trip — same round-trip-break shape the
15898 // zero-window arm above pins, with a non-zero magnitude to
15899 // guard against a future "reject only zero" half-measure.
15900 let mut s = three_member_spec();
15901 let window = Duration::from_secs(45);
15902 s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
15903 assert_eq!(
15904 s.validate().unwrap_err(),
15905 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
15906 );
15907 }
15908
15909 #[test]
15910 fn rejects_rate_limit_two_minute_window() {
15911 // 120 seconds = 2 minutes is a "looks-canonical" but
15912 // not-canonical window: it's a clean integer multiple of the
15913 // minute unit, but the codec only round-trips the
15914 // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
15915 // A `Duration::from_secs(120)` window renders as `"100/120s"`
15916 // which the parser rejects. Pinning this case rules out a
15917 // future "accept any clean multiple of s/m/h" relaxation
15918 // that would silently break the codec contract.
15919 let mut s = three_member_spec();
15920 let window = Duration::from_secs(120);
15921 s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
15922 assert_eq!(
15923 s.validate().unwrap_err(),
15924 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
15925 );
15926 }
15927
15928 #[test]
15929 fn rejects_rate_limit_subsecond_window() {
15930 // A sub-second window (e.g. 500ms) is a valid `Duration` but
15931 // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
15932 // Pin the rejection so a future relaxation can't silently
15933 // admit fractional-second windows that the codec can't
15934 // round-trip.
15935 let mut s = three_member_spec();
15936 let window = Duration::from_millis(500);
15937 s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
15938 assert_eq!(
15939 s.validate().unwrap_err(),
15940 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
15941 );
15942 }
15943
15944 #[test]
15945 fn rejects_policy_rate_limit_above_cap() {
15946 // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
15947 // is structurally one past the cap and silently passed
15948 // validate on every pre-gate codebase because the typed slot's
15949 // only `rate` check was the zero-floor arm. The no-op-limiter
15950 // shape only surfaced at the runtime substrate (Envoy's
15951 // `local_rate_limit.token_bucket.max_tokens`, the future
15952 // Cilium L7 rate-limit overlay) far from the source caixa.lisp
15953 // with no field naming the offending policy.
15954 let mut s = three_member_spec();
15955 s.politicas.rate_limit = Some(RateLimit {
15956 rate: POLICY_RATE_LIMIT_MAX + 1,
15957 window: Duration::from_secs(1),
15958 });
15959 assert_eq!(
15960 s.validate().unwrap_err(),
15961 AplicacaoError::PolicyRateLimitExceedsCap {
15962 rate: POLICY_RATE_LIMIT_MAX + 1
15963 }
15964 );
15965 }
15966
15967 #[test]
15968 fn rejects_policy_rate_limit_far_above_cap() {
15969 // The `u32::MAX` worst case — the four-billion-token rate-limit
15970 // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
15971 // copy-paste lands in the slot. Pin the cap arm's coverage
15972 // explicitly across the full `u32` overflow so a future
15973 // relaxation that drops the upper bound surfaces here. Peer to
15974 // `rejects_policy_retries_far_above_cap` on the sibling
15975 // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
15976 // on the sibling `:max-failures` axis.
15977 let mut s = three_member_spec();
15978 s.politicas.rate_limit = Some(RateLimit {
15979 rate: u32::MAX,
15980 window: Duration::from_secs(1),
15981 });
15982 assert_eq!(
15983 s.validate().unwrap_err(),
15984 AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
15985 );
15986 }
15987
15988 #[test]
15989 fn accepts_policy_rate_limit_at_cap() {
15990 // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
15991 // must validate. The cap is inclusive on the top edge, matching
15992 // every other typed upper bound in this crate
15993 // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
15994 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
15995 // across all three canonical windows so a future off-by-one
15996 // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
15997 // window-conditional cap surfaces here as a test failure rather
15998 // than a silent contract narrowing.
15999 for secs in [1u64, 60, 3600] {
16000 let mut s = three_member_spec();
16001 s.politicas.rate_limit = Some(RateLimit {
16002 rate: POLICY_RATE_LIMIT_MAX,
16003 window: Duration::from_secs(secs),
16004 });
16005 s.validate().unwrap_or_else(|e| {
16006 panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
16007 });
16008 }
16009 }
16010
16011 #[test]
16012 fn accepts_policy_rate_limit_typical_values() {
16013 // The documented production-playbook recommendation band —
16014 // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
16015 // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
16016 // Enterprise ~1M per-hour. Every value in the validated set
16017 // must pass; pin the band explicitly so a future tightening
16018 // surfaces here.
16019 for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
16020 for secs in [1u64, 60, 3600] {
16021 let mut s = three_member_spec();
16022 s.politicas.rate_limit = Some(RateLimit {
16023 rate,
16024 window: Duration::from_secs(secs),
16025 });
16026 s.validate().unwrap_or_else(|e| {
16027 panic!("rate={rate} window={secs}s must validate; got {e:?}")
16028 });
16029 }
16030 }
16031 }
16032
16033 #[test]
16034 fn policy_rate_limit_zero_takes_precedence_over_cap() {
16035 // The cross-arm ordering pin: `rate == 0` is structurally
16036 // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
16037 // (cap), but the zero-floor diagnostic is the more
16038 // self-locating one (it directly names the omit-axis
16039 // remediation). Pin the order so a future refactor that
16040 // reorders the arms surfaces here as a test failure rather
16041 // than a silent diagnostic regression. Same shape every other
16042 // zero-then-cap ordering on this surface uses
16043 // ([`AplicacaoError::PolicyRetriesZero`] then
16044 // [`AplicacaoError::PolicyRetriesExceedsCap`];
16045 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
16046 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
16047 let mut s = three_member_spec();
16048 s.politicas.rate_limit = Some(RateLimit {
16049 rate: 0,
16050 window: Duration::from_secs(1),
16051 });
16052 assert_eq!(
16053 s.validate().unwrap_err(),
16054 AplicacaoError::PolicyRateLimitZero,
16055 "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
16056 );
16057 }
16058
16059 #[test]
16060 fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
16061 // Two-axis-bad pin: rate above cap *and* window non-canonical.
16062 // The validate gate must fire on the rate cap first — the
16063 // amplification-shape (no-op limiter) diagnostic is the more
16064 // fundamental one; the window-canonical diagnostic is the
16065 // narrower codec-round-trip shape. Pin the ordering so a future
16066 // refactor that reorders the rate-then-window check arms
16067 // surfaces here as a test failure rather than a silent
16068 // diagnostic regression.
16069 let mut s = three_member_spec();
16070 s.politicas.rate_limit = Some(RateLimit {
16071 rate: POLICY_RATE_LIMIT_MAX + 1,
16072 window: Duration::from_secs(45),
16073 });
16074 assert_eq!(
16075 s.validate().unwrap_err(),
16076 AplicacaoError::PolicyRateLimitExceedsCap {
16077 rate: POLICY_RATE_LIMIT_MAX + 1
16078 },
16079 "above-cap rate must surface the cap diagnostic, not the window diagnostic"
16080 );
16081 }
16082
16083 #[test]
16084 fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
16085 // The diagnostic-shape pin: the offending `u32` is carried
16086 // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
16087 // variant so the surfaced error message names the value the
16088 // author wrote (`":politicas :rate-limit rate (5000000) exceeds
16089 // the mesh-policy ceiling …"`), not just the cap. Same
16090 // self-locating diagnostic shape every other typed-cap arm on
16091 // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
16092 // carries the offending retries count verbatim,
16093 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
16094 // the offending failure count verbatim).
16095 let mut s = three_member_spec();
16096 s.politicas.rate_limit = Some(RateLimit {
16097 rate: 5_000_000,
16098 window: Duration::from_secs(1),
16099 });
16100 let err = s.validate().unwrap_err();
16101 assert!(
16102 matches!(
16103 err,
16104 AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
16105 ),
16106 "got {err:?}"
16107 );
16108 let msg = err.to_string();
16109 assert!(
16110 msg.contains("5000000"),
16111 ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
16112 );
16113 }
16114
16115 #[test]
16116 fn policy_rate_limit_cap_pins_canonical_value() {
16117 // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
16118 // 1_000_000 — two-to-three orders of magnitude above every
16119 // documented production-playbook recommendation band (Envoy /
16120 // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
16121 // Gateway 10_000..=100_000 per-minute) and below the
16122 // clearly-pathological "paste-from-binary blob" floor
16123 // (100_000_000, u32::MAX). Pinning the literal value here
16124 // surfaces a future drift (a relaxation to 10_000_000, a
16125 // tightening to 100_000) as a deliberate test edit, not a
16126 // silent contract narrowing.
16127 assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
16128 }
16129
16130 #[test]
16131 fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
16132 // Both axes are invalid here: rate == 0 *and* window is
16133 // non-canonical. The validate gate must fire on rate first
16134 // (matching the existing `rejects_zero_rate_limit` ordering),
16135 // so the existing diagnostic continues to lead with the
16136 // simpler "zero rate" framing. Pinning the order of checks
16137 // so a future refactor that reorders the arms surfaces here
16138 // as a test failure rather than a silent diagnostic
16139 // regression.
16140 let mut s = three_member_spec();
16141 s.politicas.rate_limit = Some(RateLimit {
16142 rate: 0,
16143 window: Duration::from_secs(45),
16144 });
16145 assert_eq!(
16146 s.validate().unwrap_err(),
16147 AplicacaoError::PolicyRateLimitZero
16148 );
16149 }
16150
16151 #[test]
16152 fn rate_limit_canonical_windows_validate() {
16153 // The three canonical windows the codec round-trips
16154 // losslessly — 1s / 60s / 3600s — must all pass `validate()`
16155 // unchanged. Pin the full canonical set as a positive case
16156 // (the existing `rate_limit_round_trip_seconds` /
16157 // `rate_limit_round_trip_minutes` tests pin the
16158 // serialize-then-deserialize property at the codec layer; this
16159 // test pins the validate-side complement so a future tightening
16160 // of the canonical set — e.g. dropping `:hour` — surfaces here
16161 // as a test failure rather than a silent contract narrowing).
16162 for secs in [1u64, 60, 3600] {
16163 let mut s = three_member_spec();
16164 s.politicas.rate_limit = Some(RateLimit {
16165 rate: 100,
16166 window: Duration::from_secs(secs),
16167 });
16168 s.validate().expect("canonical window must validate");
16169 }
16170 }
16171
16172 #[test]
16173 fn rate_limit_validated_value_round_trips_through_codec() {
16174 // The structural property the validate gate enforces:
16175 // every `RateLimit` past `AplicacaoSpec::validate` round-trips
16176 // losslessly through the `rate_limit_codec` (serialize → string
16177 // → deserialize → equal value). Pin this end-to-end so a future
16178 // change to either side (the validate gate's accepted window
16179 // set, the codec's parse/render unit set) that breaks the
16180 // alignment surfaces here. The previous-state shape (typed
16181 // slot accepts arbitrary `Duration`, codec only round-trips
16182 // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
16183 // window — the validate gate now forecloses that.
16184 for secs in [1u64, 60, 3600] {
16185 let mut s = three_member_spec();
16186 s.politicas.rate_limit = Some(RateLimit {
16187 rate: 250,
16188 window: Duration::from_secs(secs),
16189 });
16190 s.validate().unwrap();
16191 let json = serde_json::to_string(&s.politicas).unwrap();
16192 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16193 assert_eq!(
16194 back.rate_limit, s.politicas.rate_limit,
16195 "every validated :rate-limit must round-trip losslessly through the codec"
16196 );
16197 }
16198 }
16199
16200 #[test]
16201 fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
16202 // The hour-window canonical form (`"<n>/h"`) was missing from
16203 // the prior `rate_limit_round_trip_seconds` / `_minutes` test
16204 // pair. Now that the validate gate pins 3600s as part of the
16205 // canonical set, pin its serialize-side render shape too so
16206 // the third leg of the s/m/h tripod is explicitly tested.
16207 let policy = MeshPolicy {
16208 rate_limit: Some(RateLimit {
16209 rate: 10000,
16210 window: Duration::from_secs(3600),
16211 }),
16212 ..Default::default()
16213 };
16214 let json = serde_json::to_string(&policy).unwrap();
16215 assert!(
16216 json.contains("\"10000/h\""),
16217 "hour-window canonical form must render with `h` suffix (got: {json})"
16218 );
16219 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16220 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
16221 }
16222
16223 #[test]
16224 fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
16225 // Pin the substrate-primitive [`RateLimit::canonical_unit`]
16226 // typed accessor's accepted-window set against the codec's
16227 // accepted set explicitly. A future addition to the codec
16228 // (e.g. accepting `:day`/`:week` as authoring units) must be
16229 // accompanied by a parallel addition here, and a regression
16230 // that drops one of the three canonical units from either
16231 // side surfaces as a test failure. The accessor is the
16232 // single source of truth for the canonical-window set —
16233 // [`AplicacaoSpec::validate_politicas`]'s canonical-window
16234 // gate and [`rate_limit_codec::render`]'s canonical arm both
16235 // read through it — this test enshrines that its
16236 // `Duration → Option<RateLimitUnit>` projection matches the
16237 // codec's parse / render arms' accepted-window set exactly.
16238 //
16239 // Predecessor: this pin previously read the module-private
16240 // free helper `is_canonical_rate_limit_window` — a delegate
16241 // that composed [`RateLimitUnit::from_window`] with `.is_some()`
16242 // — but the helper had no production consumers left after the
16243 // validate-gate migration onto [`RateLimit::canonical_unit`]
16244 // and was deleted; the closed-set arm-window bijection now
16245 // lives on exactly one typed dispatch on the substrate
16246 // primitive.
16247 let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
16248 RateLimit { rate: 1, window }.canonical_unit()
16249 };
16250 assert!(canonical_unit(Duration::from_secs(1)).is_some());
16251 assert!(canonical_unit(Duration::from_secs(60)).is_some());
16252 assert!(canonical_unit(Duration::from_secs(3600)).is_some());
16253 // Non-canonical windows the accessor rejects.
16254 assert!(canonical_unit(Duration::ZERO).is_none());
16255 assert!(canonical_unit(Duration::from_secs(2)).is_none());
16256 assert!(canonical_unit(Duration::from_secs(30)).is_none());
16257 assert!(canonical_unit(Duration::from_secs(120)).is_none());
16258 assert!(canonical_unit(Duration::from_secs(86400)).is_none());
16259 // Sub-second windows: even `Duration::from_millis(1000)` is
16260 // exactly 1s and accepted; `Duration::from_millis(500)` is
16261 // sub-second and rejected.
16262 assert!(canonical_unit(Duration::from_millis(1000)).is_some());
16263 assert!(canonical_unit(Duration::from_millis(500)).is_none());
16264 assert!(canonical_unit(Duration::from_millis(1500)).is_none());
16265 }
16266
16267 #[test]
16268 fn rate_limit_unit_table_projections_are_mutual_inverses() {
16269 // Bidirection pin against the closed-set typed enum
16270 // [`RateLimitUnit`] arm-table (the canonical
16271 // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
16272 // of the rate-limit unit surface reads from). The two
16273 // projection directions [`RateLimitUnit::from_suffix`] /
16274 // [`RateLimitUnit::window`] (str → Duration, exposed as one
16275 // typed dispatch through [`RateLimitUnit::window_from_suffix`])
16276 // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
16277 // (Duration → str, exposed as one typed dispatch through
16278 // [`RateLimit::canonical_unit`] composed with
16279 // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
16280 // codec's parse arm ([`rate_limit_codec::parse`] via
16281 // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
16282 // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
16283 // and the validate gate ([`AplicacaoSpec::validate_politicas`]
16284 // via [`RateLimit::canonical_unit`]) all key off. A future
16285 // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
16286 // sub-second window) is one variant + one arm per method on the
16287 // closed-set enum; the compiler-enforced exhaustiveness on
16288 // every consumer's `match self` arms picks it up by
16289 // construction. This pin enshrines that both projection
16290 // directions agree on every canonical arm row and neither
16291 // leaks a spurious entry the other doesn't recognize.
16292 //
16293 // Predecessor: this test previously read the two vestigial
16294 // module-private free helpers `rate_limit_window_unit` and
16295 // `rate_limit_window_from_unit` on the `Duration → &str` and
16296 // `&str → Duration` axes; the former was deleted after its
16297 // sole production consumer ([`rate_limit_codec::render`])
16298 // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
16299 // the latter is folded here into the substrate primitive
16300 // [`RateLimitUnit::window_from_suffix`] so both projection
16301 // directions live on the closed-set enum's arm-table.
16302 for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
16303 let window = super::RateLimitUnit::window_from_suffix(unit)
16304 .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
16305 assert_eq!(
16306 window,
16307 Duration::from_secs(secs),
16308 "unit {unit:?} must resolve to {secs}s"
16309 );
16310 let projected_suffix = RateLimit { rate: 1, window }
16311 .canonical_unit()
16312 .map(super::RateLimitUnit::as_suffix);
16313 assert_eq!(
16314 projected_suffix,
16315 Some(unit),
16316 "Duration({secs}s) must render as {unit:?} \
16317 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
16318 );
16319 }
16320 // Non-table units yield None on the `unit → Duration`
16321 // projection — a future `"d"` addition to the table would
16322 // flip this arm; today it pins the current three-row table's
16323 // rejection semantics.
16324 assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
16325 assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
16326 assert!(super::RateLimitUnit::window_from_suffix("").is_none());
16327 // Non-table Durations yield None on the `Duration → unit`
16328 // projection — pins that the two projections agree on the
16329 // "not in the table" semantic too, so a drift where the
16330 // parse-side accepts a value the render-side can't emit is
16331 // a build error at the two-arm pair, not a silent codec
16332 // round-trip break.
16333 let projected_suffix = |window: Duration| -> Option<&'static str> {
16334 RateLimit { rate: 1, window }
16335 .canonical_unit()
16336 .map(super::RateLimitUnit::as_suffix)
16337 };
16338 assert!(projected_suffix(Duration::from_secs(2)).is_none());
16339 assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
16340 assert!(projected_suffix(Duration::from_millis(1500)).is_none());
16341 }
16342
16343 #[test]
16344 fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
16345 // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
16346 // substrate-primitive `&str → Duration` associated method the
16347 // codec's parse arm ([`rate_limit_codec::parse`]) now routes
16348 // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
16349 // to the same [`Duration`] the two-step composition
16350 // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
16351 // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
16352 // `"MIN"`) must project to [`None`] on both paths. A future
16353 // implementation of `window_from_suffix` that took a shortcut
16354 // through a per-suffix `match` table (bypassing the arm-table's
16355 // `Self::from_suffix` scan and the arm-table's `Self::window`
16356 // dispatch) would silently split the accept-set — the parse
16357 // arm would accept a suffix the enum's arm-table doesn't know,
16358 // or reject a suffix the enum's arm-table does; this pin
16359 // surfaces that drift at caixa-core build time rather than at a
16360 // downstream serde round-trip audit on a live `MeshPolicy`.
16361 //
16362 // Same byte-parity discipline the sibling
16363 // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
16364 // pin carries on the peer `Duration → RateLimitUnit` axis via
16365 // [`RateLimit::canonical_unit`], and the peer
16366 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
16367 // carries on the bidirectional arm-table axis — extended here
16368 // onto the fifth (and last unlifted) projection axis on the
16369 // closed-set enum's arm-table.
16370 let composition = |suffix: &str| -> Option<Duration> {
16371 super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
16372 };
16373 for suffix in ["s", "m", "h"] {
16374 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
16375 let via_composition = composition(suffix);
16376 assert_eq!(
16377 via_method, via_composition,
16378 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
16379 from_suffix({suffix:?}).map(window) — the substrate-primitive \
16380 method must delegate to the arm-table's two typed dispatches, \
16381 not shortcut through a per-suffix match table"
16382 );
16383 assert!(
16384 via_method.is_some(),
16385 "canonical suffix {suffix:?} must resolve to Some(Duration) via \
16386 RateLimitUnit::window_from_suffix"
16387 );
16388 }
16389 for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
16390 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
16391 let via_composition = composition(suffix);
16392 assert_eq!(
16393 via_method, via_composition,
16394 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
16395 from_suffix({suffix:?}).map(window) on the non-arm rejection \
16396 axis too"
16397 );
16398 assert!(
16399 via_method.is_none(),
16400 "non-arm suffix {suffix:?} must project to None via \
16401 RateLimitUnit::window_from_suffix — a future extension that \
16402 accepted this suffix without a corresponding arm on the enum \
16403 would split the codec's parse-accepted set from the enum's \
16404 arm-table"
16405 );
16406 }
16407 // And the codec's parse arm now reads through this method: a
16408 // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
16409 // the same `Duration` the method returns for its unit, closing
16410 // the two-consumer drift surface (the codec's parse arm and the
16411 // enum's arm-table) with one typed dispatch on the substrate
16412 // primitive.
16413 for suffix in ["s", "m", "h"] {
16414 let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
16415 let mp: MeshPolicy = serde_json::from_str(&wire)
16416 .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
16417 let parsed = mp.rate_limit().expect("rate_limit payload present");
16418 let via_method = super::RateLimitUnit::window_from_suffix(suffix)
16419 .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
16420 assert_eq!(
16421 parsed.window(),
16422 via_method,
16423 "codec parse arm on {wire:?} must resolve the window through \
16424 RateLimitUnit::window_from_suffix, not a divergent path"
16425 );
16426 }
16427 }
16428
16429 #[test]
16430 fn rate_limit_unit_all_enumerates_every_arm_once() {
16431 // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
16432 // enumerate every arm of the closed-set enum exactly once, in
16433 // the canonical shortest-to-longest window order (Second before
16434 // Minute before Hour) — the same order the sibling
16435 // [`crate::supervisor::RestartStrategy`] /
16436 // [`crate::supervisor::RestartPolicy`] /
16437 // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
16438 // typed enums carry (the arm declared first is the arm listed
16439 // first). A future variant addition that extends the enum
16440 // without appending to [`RateLimitUnit::ALL`] leaves the
16441 // exhaustive iteration surface silently short one arm — the
16442 // codec's parse arm would then reject the new suffix even
16443 // though the enum knows it. This pin closes the drift.
16444 assert_eq!(
16445 super::RateLimitUnit::ALL,
16446 &[
16447 super::RateLimitUnit::Second,
16448 super::RateLimitUnit::Minute,
16449 super::RateLimitUnit::Hour,
16450 ],
16451 "RateLimitUnit::ALL must enumerate every arm exactly once, \
16452 in canonical shortest-to-longest window order"
16453 );
16454 }
16455
16456 #[test]
16457 fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
16458 // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
16459 // every arm's [`RateLimitUnit::as_suffix`] output must parse
16460 // back through [`RateLimitUnit::from_suffix`] to the same
16461 // variant. A future arm addition that lands `as_suffix` but
16462 // forgets `from_suffix` (`from_suffix` iterates
16463 // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
16464 // is the load-bearing carrier of the round-trip; the sibling
16465 // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
16466 // the `ALL` half) trips here at caixa-core build time rather
16467 // than surfacing as a codec round-trip miss (a `render` emit
16468 // that lands a suffix the paired `parse` cannot decode).
16469 for unit in super::RateLimitUnit::ALL {
16470 let suffix = unit.as_suffix();
16471 let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
16472 panic!(
16473 "RateLimitUnit::from_suffix({suffix:?}) must accept every \
16474 RateLimitUnit::as_suffix output — got None for {unit:?}"
16475 )
16476 });
16477 assert_eq!(
16478 parsed, *unit,
16479 "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
16480 must return RateLimitUnit::{unit:?}"
16481 );
16482 }
16483 }
16484
16485 #[test]
16486 fn rate_limit_unit_from_window_and_window_round_trip() {
16487 // Total round-trip pin on the `(from_window, window)` pair:
16488 // every arm's [`RateLimitUnit::window`] output must parse back
16489 // through [`RateLimitUnit::from_window`] to the same variant.
16490 // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
16491 // on the peer `Duration` axis — the two round-trip pins
16492 // together enshrine that both projections of the typed
16493 // canonical-unit bijection are total on the arm-set.
16494 for unit in super::RateLimitUnit::ALL {
16495 let window = unit.window();
16496 let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
16497 panic!(
16498 "RateLimitUnit::from_window({window:?}) must accept every \
16499 RateLimitUnit::window output — got None for {unit:?}"
16500 )
16501 });
16502 assert_eq!(
16503 parsed, *unit,
16504 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
16505 must return RateLimitUnit::{unit:?}"
16506 );
16507 }
16508 }
16509
16510 #[test]
16511 fn rate_limit_unit_from_window_accessor_is_const_fn() {
16512 // Fail-before-pass-after pin: witnesses the
16513 // [`RateLimitUnit::from_window`] `const`-eval posture via a
16514 // `const fn` wrapper `from_window_via_const_fn(window: Duration)
16515 // -> Option<RateLimitUnit>` whose body calls
16516 // `RateLimitUnit::from_window(window)`, well-formed only when
16517 // the callee is itself `const fn` (any future downgrade to
16518 // non-`const` fails at caixa-core build time with E0015 `cannot
16519 // call non-const function`, strictly stronger than a runtime
16520 // `assert!`, side-stepping the destructor-in-const restriction
16521 // that blocks direct `const _: Option<RateLimitUnit> =
16522 // RateLimitUnit::from_window(...)` items on `Duration`'s
16523 // carrier). The runtime body sweeps every closed-set
16524 // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
16525 // rejection sample (`Duration::from_millis(500)` sub-second
16526 // residue) and asserts the wrapped and direct dispatches agree
16527 // — a violation means the wrapper stopped compiling under a
16528 // future `const`-posture downgrade, or the reverse resolver's
16529 // arm-set silently split from the peer `Self::window` emitter's
16530 // arm-set. Peer of the sibling
16531 // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
16532 // (152c868) /
16533 // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
16534 // (152c868) /
16535 // [`entrada_port_accessor_is_const_fn`] (bafa004) /
16536 // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
16537 // `const`-eval-surface pins on the peer M2 / M3 substrate-
16538 // primitive `Copy`-return accessor axes, extended onto the
16539 // reverse `Duration → RateLimitUnit` projection axis on the
16540 // M3 mesh-slot rate-limit closed-set typed enum.
16541 const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
16542 super::RateLimitUnit::from_window(window)
16543 }
16544 for unit in super::RateLimitUnit::ALL {
16545 let window = unit.window();
16546 let via_wrapper = from_window_via_const_fn(window);
16547 let direct = super::RateLimitUnit::from_window(window);
16548 assert_eq!(
16549 via_wrapper, direct,
16550 "RateLimitUnit::from_window({window:?}) via const fn \
16551 wrapper must agree with direct dispatch for {unit:?}"
16552 );
16553 assert_eq!(
16554 via_wrapper,
16555 Some(*unit),
16556 "RateLimitUnit::from_window({window:?}) via const fn \
16557 wrapper must return Some({unit:?}) for the peer \
16558 window() output"
16559 );
16560 }
16561 assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
16562 assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
16563 }
16564
16565 #[test]
16566 fn rate_limit_unit_from_window_composes_through_window_accessor() {
16567 // Composition-witness pin on the routing-through-peer discipline:
16568 // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
16569 // through the peer `pub const fn` [`RateLimitUnit::window`]
16570 // canonical-`Duration` projection rather than a hand-authored
16571 // per-arm second-magnitude literal — a future arm-magnitude edit
16572 // on the sibling `window()` accessor (a `Second → 2s` typo, a
16573 // `Hour → 3599s` off-by-one) must therefore reach this reverse
16574 // resolver by construction. A pin that hard-coded the three
16575 // second-magnitudes here would silently split from the peer
16576 // emitter on any such edit; instead, this pin asserts the
16577 // composition invariant `from_window(u.window()) == Some(u)`
16578 // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
16579 // arm — a violation means either the peer `Self::window`
16580 // accessor drifted (breaking every downstream consumer that
16581 // reads through it), or the reverse resolver stopped routing
16582 // through the peer (introducing a hand-authored literal that
16583 // silently disagrees with the emitter). Either failure is a
16584 // caixa-core-build-time surface, not a downstream renderer
16585 // round-trip regression.
16586 //
16587 // Peer of the sibling
16588 // [`crate::render::assert_str_reexport_identity`] discipline on
16589 // the substrate-primitive `&'static str` re-export axis and the
16590 // [`rate_limit_unit_from_window_and_window_round_trip`]
16591 // round-trip pin on the peer projection direction; extends the
16592 // one-canonical-dispatch-per-projection discipline onto the
16593 // reverse-resolver's per-arm probe axis.
16594 for unit in super::RateLimitUnit::ALL {
16595 let window_via_peer = unit.window();
16596 let resolved = super::RateLimitUnit::from_window(window_via_peer);
16597 assert_eq!(
16598 resolved,
16599 Some(*unit),
16600 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
16601 must return Some({unit:?}) — the reverse resolver's per-arm \
16602 probes must route through the peer `Self::window` accessor \
16603 so any future arm-magnitude edit reaches both projection \
16604 directions by construction"
16605 );
16606 }
16607 }
16608
16609 #[test]
16610 fn rate_limit_canonical_unit_accessor_is_const_fn() {
16611 // Fail-before-pass-after pin: witnesses the
16612 // [`RateLimit::canonical_unit`] `const`-eval posture via a
16613 // `const fn` wrapper
16614 // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
16615 // whose body calls `rl.canonical_unit()`, well-formed only when
16616 // the callee is itself `const fn` (any future downgrade to
16617 // non-`const` fails at caixa-core build time with E0015 `cannot
16618 // call non-const method`). The runtime body sweeps every
16619 // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
16620 // constructs a typed [`RateLimit`] with the peer `Self::window`
16621 // canonical `Duration`, then asserts both the wrapper and the
16622 // direct dispatch agree and both return `Some(unit)`. Composes
16623 // with the sibling
16624 // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
16625 // typed [`RateLimit`] projection layer's `const`-posture is
16626 // load-bearing on the reverse resolver's `const`-posture, and
16627 // both must migrate together (a downgrade of either surface
16628 // splits the paired `const`-eval-surface pass on the M3
16629 // mesh-slot rate-limit `Duration ↔ Self` bijection).
16630 const fn canonical_unit_via_const_fn(
16631 rl: &super::RateLimit,
16632 ) -> Option<super::RateLimitUnit> {
16633 rl.canonical_unit()
16634 }
16635 for unit in super::RateLimitUnit::ALL {
16636 let rl = super::RateLimit {
16637 rate: 1,
16638 window: unit.window(),
16639 };
16640 let via_wrapper = canonical_unit_via_const_fn(&rl);
16641 let direct = rl.canonical_unit();
16642 assert_eq!(
16643 via_wrapper, direct,
16644 "RateLimit::canonical_unit() via const fn wrapper must \
16645 agree with direct dispatch for {unit:?}"
16646 );
16647 assert_eq!(
16648 via_wrapper,
16649 Some(*unit),
16650 "RateLimit::canonical_unit() via const fn wrapper must \
16651 return Some({unit:?}) for a RateLimit whose window is \
16652 the peer RateLimitUnit::{unit:?}.window() output"
16653 );
16654 }
16655 }
16656
16657 #[test]
16658 fn rate_limit_unit_projections_are_pairwise_distinct() {
16659 // Distinctness pin: [`RateLimitUnit::as_suffix`] and
16660 // [`RateLimitUnit::window`] outputs must be pairwise distinct
16661 // across every arm — an accidental copy-paste flip that
16662 // reroutes one arm's suffix or window to also match another
16663 // silently collapses two arms onto one, so
16664 // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
16665 // (both using `find` on `Self::ALL`) would return whichever
16666 // arm the linear scan lands on first — a match-arm-ordering-
16667 // dependent outcome the closed-set typed-enum shape is meant
16668 // to rule out structurally. Peer of the sibling
16669 // `caixa_kind_wire_consts_are_pairwise_distinct` /
16670 // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
16671 // other closed-set typed-enum discriminator axes.
16672 let all = super::RateLimitUnit::ALL;
16673 for (i, a) in all.iter().enumerate() {
16674 for (j, b) in all.iter().enumerate() {
16675 if i != j {
16676 assert_ne!(
16677 a.as_suffix(),
16678 b.as_suffix(),
16679 "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
16680 must be distinct — a collision silently collapses two \
16681 arms onto one under from_suffix's linear scan"
16682 );
16683 assert_ne!(
16684 a.window(),
16685 b.window(),
16686 "RateLimitUnit::{a:?}.window() and {b:?}.window() \
16687 must be distinct — a collision silently collapses two \
16688 arms onto one under from_window's linear scan"
16689 );
16690 }
16691 }
16692 }
16693 }
16694
16695 #[test]
16696 fn rate_limit_unit_display_routes_through_as_suffix() {
16697 // Route pin: [`std::fmt::Display`] must byte-equal
16698 // [`RateLimitUnit::as_suffix`] on every arm — the single
16699 // source of truth for the canonical suffix. A future
16700 // reimplementation that hand-rolls the arms instead of
16701 // delegating to [`RateLimitUnit::as_suffix`] would silently
16702 // desynchronize `format!("{u}")` from the codec's parse arm
16703 // (which uses `as_suffix` to compare suffixes). Peer of the
16704 // sibling `caixa_kind_display_routes_through_as_str_helper` /
16705 // `placement_strategy_display_routes_through_as_str_helper`
16706 // pins on the peer closed-set typed-enum Display axes.
16707 for unit in super::RateLimitUnit::ALL {
16708 assert_eq!(
16709 unit.to_string(),
16710 unit.as_suffix(),
16711 "RateLimitUnit::{unit:?} Display must route through \
16712 as_suffix (single source of truth: the canonical suffix \
16713 the codec parses and renders)"
16714 );
16715 }
16716 }
16717
16718 #[test]
16719 fn rate_limit_unit_from_window_rejects_non_canonical() {
16720 // Rejection pin on the parser's accept-set: any Duration
16721 // outside the three-arm [`RateLimitUnit::window`] output set
16722 // (sub-second residue, or a second-magnitude outside `{1, 60,
16723 // 3600}`) must return `None`. A future accidental widening of
16724 // the accept-set (rounding down sub-second residue to the
16725 // nearest arm, admitting `Duration::from_secs(30)` as a
16726 // half-minute unit) would silently drift the parser's accept-
16727 // set from the emitter's — a validated slot with a
16728 // non-canonical window would then round-trip through the
16729 // codec to a canonical form the author never wrote.
16730 assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
16731 assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
16732 assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
16733 assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
16734 assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
16735 assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
16736 assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
16737 }
16738
16739 #[test]
16740 fn rate_limit_unit_from_suffix_rejects_unknown() {
16741 // Rejection pin on the suffix parser's accept-set: any string
16742 // outside the three-arm [`RateLimitUnit::as_suffix`] output
16743 // set must return `None`. Peer of the sibling
16744 // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
16745 // the [`crate::CaixaKind`] `from_wire` accept-set.
16746 for bad in [
16747 "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
16748 " s",
16749 ] {
16750 assert!(
16751 super::RateLimitUnit::from_suffix(bad).is_none(),
16752 "RateLimitUnit::from_suffix({bad:?}) must return None — the \
16753 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
16754 outputs"
16755 );
16756 }
16757 }
16758
16759 #[test]
16760 fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
16761 // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
16762 // every canonical `:window` magnitude the validate gate
16763 // accepts must map to the paired [`RateLimitUnit`] arm through
16764 // this accessor. A future validate-gate rebrand that widened
16765 // the accepted-window set without extending [`RateLimitUnit`]
16766 // would silently split the accessor's `Some`-return set from
16767 // the validate gate's accept-set — a slot that satisfies
16768 // validate would land at the accessor with `None`, so a
16769 // consumer past validate that pattern-matches on the returned
16770 // `Some` would silently miss the newly-accepted magnitude.
16771 for (window_secs, expected) in [
16772 (1u64, super::RateLimitUnit::Second),
16773 (60, super::RateLimitUnit::Minute),
16774 (3600, super::RateLimitUnit::Hour),
16775 ] {
16776 let rl = RateLimit {
16777 rate: 100,
16778 window: Duration::from_secs(window_secs),
16779 };
16780 assert_eq!(
16781 rl.canonical_unit(),
16782 Some(expected),
16783 "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
16784 must return Some({expected:?})"
16785 );
16786 }
16787 // Non-canonical windows the validate gate rejects also return
16788 // None here — the accessor is the typed-enum projection of
16789 // the sibling `is_canonical_rate_limit_window` predicate.
16790 let bad = RateLimit {
16791 rate: 100,
16792 window: Duration::from_secs(30),
16793 };
16794 assert!(
16795 bad.canonical_unit().is_none(),
16796 "RateLimit with a non-canonical window must return None from \
16797 canonical_unit — the validate gate rejects the same set"
16798 );
16799 }
16800
16801 #[test]
16802 fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
16803 // Fail-before-pass-after byte-parity pin: for every canonical
16804 // window the [`rate_limit_codec::render`] arm's emitted string
16805 // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
16806 // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
16807 // the vestigial free helper [`rate_limit_window_unit`] (a
16808 // `find_map`-walked `Duration → &'static str` delegate) onto the
16809 // substrate primitive [`RateLimit::canonical_unit`] typed method
16810 // (a closed-set `match self.window` arm on
16811 // [`RateLimitUnit::from_window`], projected through
16812 // [`RateLimitUnit::as_suffix`] via the enum's
16813 // [`std::fmt::Display`] impl). A future re-routing of the render
16814 // arm through a differently-computed unit projection would break
16815 // this pin at build time rather than as a silent per-consumer
16816 // codec round-trip drift far from the substrate primitive edit.
16817 //
16818 // Sibling to the peer
16819 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
16820 // on the free-helper axis: that pin locks the two projections
16821 // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
16822 // on the closed-set arm table; this pin locks the codec's render
16823 // arm reads through the typed accessor rather than the free
16824 // helper. Two production consumers of the canonical-unit axis
16825 // now key off one typed dispatch on the substrate primitive.
16826 for (window_secs, unit) in [
16827 (1u64, super::RateLimitUnit::Second),
16828 (60, super::RateLimitUnit::Minute),
16829 (3600, super::RateLimitUnit::Hour),
16830 ] {
16831 let rl = RateLimit {
16832 rate: 42,
16833 window: Duration::from_secs(window_secs),
16834 };
16835 let policy = MeshPolicy {
16836 rate_limit: Some(rl),
16837 ..Default::default()
16838 };
16839 let json = serde_json::to_string(&policy).unwrap();
16840 let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
16841 assert!(
16842 json.contains(&expected),
16843 "rate_limit_codec::render must emit {expected} (via \
16844 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
16845 for a {window_secs}s window; serialized MeshPolicy was: {json}"
16846 );
16847 // And the accessor route resolves to the same typed unit
16848 // the render arm's Display formatting is asked to produce —
16849 // so a future edit that split the two paths (one through
16850 // the accessor, one through a re-introduced free helper)
16851 // trips this pin.
16852 assert_eq!(
16853 rl.canonical_unit(),
16854 Some(unit),
16855 "RateLimit::canonical_unit must return Some({unit:?}) for a \
16856 {window_secs}s window; the codec render arm reads the same \
16857 typed unit through this accessor"
16858 );
16859 }
16860 }
16861
16862 #[test]
16863 fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
16864 // Fail-before-pass-after byte-parity pin on the validate gate's
16865 // canonical-window shape probe: every non-canonical `:window`
16866 // the free-helper predicate [`is_canonical_rate_limit_window`]
16867 // rejects is also rejected by the substrate primitive
16868 // [`RateLimit::canonical_unit`] `.is_none()` route the validate
16869 // gate now reads through, and vice versa on the accepted set
16870 // (the three canonical windows). Locks the migration from the
16871 // free helper onto the substrate primitive: a future re-routing
16872 // of one of the two paths through a differently-computed unit
16873 // projection would silently split the codec's accepted set from
16874 // the validate gate's accepted set — a two-consumer drift the
16875 // codec-round-trip pin
16876 // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
16877 // above closes on the render arm and this pin closes on the
16878 // validate arm.
16879 for canonical_window_secs in [1u64, 60, 3600] {
16880 let mut s = three_member_spec();
16881 let rl = RateLimit {
16882 rate: 100,
16883 window: Duration::from_secs(canonical_window_secs),
16884 };
16885 s.politicas.rate_limit = Some(rl);
16886 assert!(
16887 s.validate().is_ok(),
16888 "canonical {canonical_window_secs}s window must pass \
16889 validate_politicas — the validate gate now reads \
16890 RateLimit::canonical_unit().is_none() and the accessor \
16891 returns Some on every canonical arm"
16892 );
16893 assert!(
16894 rl.canonical_unit().is_some(),
16895 "canonical {canonical_window_secs}s window must resolve to \
16896 Some on RateLimit::canonical_unit — the validate gate reads \
16897 this accessor directly"
16898 );
16899 }
16900 for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
16901 let mut s = three_member_spec();
16902 let rl = RateLimit {
16903 rate: 100,
16904 window: Duration::from_secs(non_canonical_window_secs),
16905 };
16906 s.politicas.rate_limit = Some(rl);
16907 assert_eq!(
16908 s.validate().unwrap_err(),
16909 AplicacaoError::PolicyRateLimitWindowNotCanonical {
16910 window: rl.window(),
16911 },
16912 "non-canonical {non_canonical_window_secs}s window must be \
16913 rejected by validate_politicas — the validate gate now \
16914 keys off RateLimit::canonical_unit().is_none()"
16915 );
16916 assert!(
16917 rl.canonical_unit().is_none(),
16918 "non-canonical {non_canonical_window_secs}s window must \
16919 resolve to None on RateLimit::canonical_unit — the two \
16920 paths (the free helper the validate gate previously read \
16921 and the substrate primitive the validate gate now reads) \
16922 must agree on the same rejected set"
16923 );
16924 }
16925 // And the substrate-primitive [`RateLimit::canonical_unit`]
16926 // accessor's accepted-window set matches the codec's parse arm's
16927 // accepted-suffix set on every canonical / non-canonical shape,
16928 // so a future silent drift between the codec's accepted set and
16929 // the validate gate's accepted set is a build error at test time
16930 // (both consumers key off the same closed-set enum's `match self`
16931 // arms). The predecessor free helper `is_canonical_rate_limit_window`
16932 // — a delegate that composed [`RateLimitUnit::from_window`] with
16933 // `.is_some()` — was deleted after this migration; the
16934 // canonical-window set now lives on exactly one typed dispatch
16935 // on the substrate primitive.
16936 for (secs, expected) in [
16937 (1u64, true),
16938 (60, true),
16939 (3600, true),
16940 (2, false),
16941 (30, false),
16942 (86_400, false),
16943 ] {
16944 let window = Duration::from_secs(secs);
16945 let rl = RateLimit { rate: 1, window };
16946 assert_eq!(
16947 rl.canonical_unit().is_some(),
16948 expected,
16949 "RateLimit::canonical_unit().is_some() must agree with the \
16950 codec-accepted canonical-window set on {secs}s"
16951 );
16952 let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
16953 1 => "s",
16954 60 => "m",
16955 3600 => "h",
16956 _ => return,
16957 })
16958 .is_some_and(|d| d == window);
16959 if expected {
16960 assert!(
16961 suffix_from_axis,
16962 "the codec's `&str → Duration` axis \
16963 ({secs}s) must round-trip to the same Duration the \
16964 substrate primitive's accessor returns Some on"
16965 );
16966 }
16967 }
16968 }
16969
16970 #[test]
16971 fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
16972 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
16973 // derive: for each of the three variants, exactly one of the
16974 // generated `is_second` / `is_minute` / `is_hour` predicates
16975 // returns `true` and the other two return `false`. Peer of
16976 // the sibling
16977 // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
16978 // sibling `IsVariant`-derived closed-set typed-enum pins.
16979 let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
16980 (super::RateLimitUnit::Second, [true, false, false]),
16981 (super::RateLimitUnit::Minute, [false, true, false]),
16982 (super::RateLimitUnit::Hour, [false, false, true]),
16983 ];
16984 for (variant, expected) in rows {
16985 let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
16986 assert_eq!(
16987 observed, expected,
16988 "RateLimitUnit::{variant:?} is_* predicates must partition \
16989 the arm set (second, minute, hour); got {observed:?}"
16990 );
16991 }
16992 }
16993
16994 #[test]
16995 fn rejects_policy_timeout_sub_millisecond() {
16996 // A purely sub-millisecond `Duration` (`from_micros(500)` =
16997 // 500_000 ns) is not the zero `Duration` — the `is_zero()`
16998 // arm passes — but `as_millis() == 0`, so the shared codec's
16999 // `render` arm returns the literal `"0s"`, which the
17000 // codec's `parse` arm then deserializes as `Duration::ZERO`
17001 // and the `PolicyTimeoutZero` zero-floor gate would reject
17002 // on re-validate. Pin the rejection at the typed slot's
17003 // canonical-floor gate so the round-trip break surfaces at
17004 // validate time, naming the offending `Duration`, rather
17005 // than at the next serialize → deserialize round-trip far
17006 // from the source `caixa.lisp`.
17007 let mut s = three_member_spec();
17008 let timeout = Duration::from_micros(500);
17009 s.politicas.timeout = Some(timeout);
17010 assert_eq!(
17011 s.validate().unwrap_err(),
17012 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
17013 );
17014 }
17015
17016 #[test]
17017 fn rejects_policy_timeout_non_integer_millisecond() {
17018 // A `Duration` with non-integer-millisecond residue
17019 // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
17020 // through the shared codec's `render` arm as `"1ms"` (the
17021 // `as_millis()` floor truncates), which the codec's `parse`
17022 // arm then deserializes as `Duration::from_millis(1)` =
17023 // 1_000_000 ns — silently *different* from the original.
17024 // Pin the rejection so this round-trip break surfaces at
17025 // validate time, where the offending `Duration` is named,
17026 // rather than as a silent value-laundered round-trip on the
17027 // next codec round-trip.
17028 let mut s = three_member_spec();
17029 let timeout = Duration::from_micros(1500);
17030 s.politicas.timeout = Some(timeout);
17031 assert_eq!(
17032 s.validate().unwrap_err(),
17033 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
17034 );
17035 }
17036
17037 #[test]
17038 fn accepts_policy_timeout_integer_millisecond_forms() {
17039 // The codec's accepted set — integer multiples of 1ms — is
17040 // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
17041 // `1h` all pass the canonical gate. Pin the canonical-forms
17042 // sweep so a future tightening of the codec's grammar (e.g.
17043 // dropping `:ms`) surfaces here as a test failure rather
17044 // than a silent contract narrowing on the typed slot.
17045 for timeout in [
17046 Duration::from_millis(1),
17047 Duration::from_millis(500),
17048 Duration::from_millis(1500),
17049 Duration::from_secs(30),
17050 Duration::from_secs(120),
17051 Duration::from_secs(3600),
17052 ] {
17053 let mut s = three_member_spec();
17054 s.politicas.timeout = Some(timeout);
17055 s.validate()
17056 .expect("integer-millisecond :timeout must validate");
17057 }
17058 }
17059
17060 #[test]
17061 fn policy_timeout_zero_takes_precedence_over_canonical() {
17062 // `Duration::ZERO` carries `subsec_nanos() == 0` and would
17063 // pass the canonical-millisecond gate; the more self-locating
17064 // `PolicyTimeoutZero` arm (which names the omit-axis
17065 // remediation directly) must fire first. Pin the ordering so
17066 // a future refactor that reorders the arms surfaces here as a
17067 // test failure rather than a silent diagnostic regression.
17068 let mut s = three_member_spec();
17069 s.politicas.timeout = Some(Duration::ZERO);
17070 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
17071 }
17072
17073 #[test]
17074 fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
17075 // The diagnostic envelope carries the offending `Duration`
17076 // verbatim so the author can grep their `caixa.lisp` for
17077 // `:timeout "<value>"` and fix it in one edit. Same
17078 // diagnostic shape every other typed-slot canonical-form
17079 // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
17080 // peer `:rate-limit :window` axis.
17081 let mut s = three_member_spec();
17082 let timeout = Duration::from_nanos(1_000_001);
17083 s.politicas.timeout = Some(timeout);
17084 match s.validate().unwrap_err() {
17085 AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
17086 assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
17087 }
17088 other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
17089 }
17090 }
17091
17092 #[test]
17093 fn rejects_policy_timeout_above_cap() {
17094 // The fail-before-pass-after pin: 3601s = 1h + 1s is
17095 // structurally one canonical-tick past the
17096 // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
17097 // integer-millisecond magnitude the canonical-form arm above
17098 // accepts cleanly, that the codec round-trips losslessly as
17099 // `"3601s"`, and that silently passed validate on every
17100 // pre-gate codebase because the typed slot's only checks were
17101 // the zero-floor and canonical-form arms. The mesh-level
17102 // deadline degenerates only at the runtime substrate (Envoy
17103 // / Cilium L7 timeout overlay) far from the source
17104 // `caixa.lisp` with no field naming the offending policy.
17105 let mut s = three_member_spec();
17106 let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
17107 s.politicas.timeout = Some(timeout);
17108 assert_eq!(
17109 s.validate().unwrap_err(),
17110 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17111 );
17112 }
17113
17114 #[test]
17115 fn rejects_policy_timeout_one_millisecond_above_cap() {
17116 // Boundary case: exactly 1ms past the cap (the granularity
17117 // the canonical-form gate enforces). Catches a future
17118 // "strictly less than" half-measure and pins the diagnostic
17119 // to name the offending `Duration` verbatim. Peer of
17120 // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
17121 // boundary pin on the sibling `:limits :memory` top edge.
17122 let mut s = three_member_spec();
17123 let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
17124 s.politicas.timeout = Some(timeout);
17125 assert_eq!(
17126 s.validate().unwrap_err(),
17127 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17128 );
17129 }
17130
17131 #[test]
17132 fn rejects_policy_timeout_far_above_cap() {
17133 // The "obvious authoring footgun" case: a `(:timeout "24h")`
17134 // or `(:timeout "86400s")` — values the canonical-form arm
17135 // accepts as integer-millisecond magnitudes, the codec
17136 // round-trips losslessly through serde, but the mesh-level
17137 // policy cannot honor (a 24-hour synchronous-`:contratos`
17138 // deadline is operationally indistinguishable from
17139 // omit-the-axis). Until this gate landed validate accepted
17140 // it. Pin both common above-cap values (24h, 7d) so a future
17141 // relaxation that drops the upper bound surfaces here.
17142 for timeout in [
17143 Duration::from_secs(86_400), // 24h
17144 Duration::from_secs(604_800), // 7d
17145 Duration::from_secs(1_000_000), // ~11.5 days
17146 ] {
17147 let mut s = three_member_spec();
17148 s.politicas.timeout = Some(timeout);
17149 assert_eq!(
17150 s.validate().unwrap_err(),
17151 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17152 );
17153 }
17154 }
17155
17156 #[test]
17157 fn accepts_policy_timeout_at_cap() {
17158 // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
17159 // must validate. The cap is inclusive on the top edge,
17160 // matching the [`POLICY_RETRIES_MAX`] /
17161 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
17162 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
17163 // sibling capped axes. Pin the boundary explicitly so a
17164 // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
17165 // instead of `>`) surfaces here as a test failure rather
17166 // than a silent contract narrowing.
17167 let mut s = three_member_spec();
17168 s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
17169 s.validate()
17170 .expect("timeout == POLICY_TIMEOUT_MAX must validate");
17171 }
17172
17173 #[test]
17174 fn accepts_policy_timeout_typical_values() {
17175 // The documented production-playbook band positive-control
17176 // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
17177 // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
17178 // plus a sweep through the long-running-workflow band
17179 // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
17180 // validated set explicitly so a future tightening of the
17181 // ceiling surfaces here as a deliberate test edit, not a
17182 // silent contract narrowing.
17183 for timeout in [
17184 Duration::from_millis(1),
17185 Duration::from_millis(500),
17186 Duration::from_secs(1),
17187 Duration::from_secs(10),
17188 Duration::from_secs(15), // Envoy default
17189 Duration::from_secs(30),
17190 Duration::from_secs(60), // AWS App Mesh typical
17191 Duration::from_secs(300),
17192 Duration::from_secs(900),
17193 Duration::from_secs(1800),
17194 Duration::from_secs(3600), // exactly 1h, the cap
17195 ] {
17196 let mut s = three_member_spec();
17197 s.politicas.timeout = Some(timeout);
17198 s.validate()
17199 .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
17200 }
17201 }
17202
17203 #[test]
17204 fn policy_timeout_zero_takes_precedence_over_cap() {
17205 // The cross-arm ordering pin: `Duration::ZERO` is
17206 // structurally outside both `>= 1ms` (zero-floor) and
17207 // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
17208 // diagnostic is the more self-locating one (it directly
17209 // names the omit-axis remediation), so the validate gate
17210 // must fire on zero first. Same shape every other
17211 // zero-then-shape ordering on this surface uses
17212 // ([`AplicacaoError::PolicyRetriesZero`] then
17213 // [`AplicacaoError::PolicyRetriesExceedsCap`];
17214 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17215 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17216 let mut s = three_member_spec();
17217 s.politicas.timeout = Some(Duration::ZERO);
17218 assert_eq!(
17219 s.validate().unwrap_err(),
17220 AplicacaoError::PolicyTimeoutZero,
17221 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
17222 );
17223 }
17224
17225 #[test]
17226 fn policy_timeout_canonical_takes_precedence_over_cap() {
17227 // The cross-arm ordering pin: a `Duration` that is *both*
17228 // sub-millisecond (non-canonical-form) and structurally
17229 // above the cap surfaces the canonical-form diagnostic
17230 // first, because the round-trip-shape break is the more
17231 // fundamental issue (the value can't even round-trip
17232 // through the codec, so the cap diagnostic naming
17233 // `1ms..=1h` would be misleading — there's no integer-ms
17234 // form of the offending value). Pin the order so a future
17235 // refactor that reorders the arms surfaces here as a test
17236 // failure rather than a silent diagnostic regression.
17237 let mut s = three_member_spec();
17238 // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
17239 // *and* total magnitude above the 1h cap.
17240 let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
17241 s.politicas.timeout = Some(timeout);
17242 assert_eq!(
17243 s.validate().unwrap_err(),
17244 AplicacaoError::PolicyTimeoutNotCanonical { timeout },
17245 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
17246 );
17247 }
17248
17249 #[test]
17250 fn policy_timeout_cap_diagnostic_carries_offending_value() {
17251 // The diagnostic-shape pin: the offending `Duration` is
17252 // carried verbatim into the
17253 // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
17254 // surfaced error message names the value the author wrote
17255 // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
17256 // exceeds the mesh-policy ceiling …"`), not just the cap.
17257 // Same self-locating diagnostic shape every other typed-cap
17258 // arm on this surface carries
17259 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
17260 // offending retry count verbatim).
17261 let mut s = three_member_spec();
17262 let timeout = Duration::from_secs(7200); // 2h
17263 s.politicas.timeout = Some(timeout);
17264 let err = s.validate().unwrap_err();
17265 assert!(
17266 matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
17267 "got {err:?}"
17268 );
17269 let msg = err.to_string();
17270 assert!(
17271 msg.contains("7200"),
17272 ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
17273 );
17274 }
17275
17276 #[test]
17277 fn policy_timeout_cap_pins_canonical_value() {
17278 // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
17279 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
17280 // the shared duration codec emits as a clean canonical
17281 // string (`"<n>h"`). Pinning the literal value here surfaces
17282 // a future drift (a relaxation to 24h, a tightening to 5m)
17283 // as a deliberate test edit, not a silent contract
17284 // narrowing. Same shape every other typed-cap value pin on
17285 // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
17286 assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
17287 assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
17288 }
17289
17290 #[test]
17291 fn policy_timeout_cap_value_round_trips_through_codec() {
17292 // The codec round-trip property the cap arm preserves: the
17293 // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
17294 // the shared duration codec — every value at the cap renders
17295 // to a clean canonical string (`"1h"`) and parses back to
17296 // the same `Duration`. Pin this so a future drift between
17297 // the cap constant and the codec's largest emitted unit
17298 // surfaces here. Same shape every other typed boundary pin
17299 // on this surface uses
17300 // (`wasm32_memory_cap_matches_parsed_4_gib`).
17301 let policy = MeshPolicy {
17302 timeout: Some(POLICY_TIMEOUT_MAX),
17303 ..Default::default()
17304 };
17305 let json = serde_json::to_string(&policy).unwrap();
17306 // The codec emits `"1h"` for the canonical 1-hour magnitude.
17307 assert!(
17308 json.contains("\"1h\""),
17309 "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
17310 );
17311 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17312 assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
17313 }
17314
17315 #[test]
17316 fn rejects_circuit_breaker_window_sub_millisecond() {
17317 // Peer of the `:timeout` sub-millisecond arm on the second
17318 // typed-`Duration` `:politicas` axis: a purely sub-ms
17319 // `Duration` (`from_micros(500)`) renders through the shared
17320 // codec as `"0s"`, which the codec parses back to
17321 // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
17322 // zero-floor gate then rejects on re-validate.
17323 let mut s = three_member_spec();
17324 let window = Duration::from_micros(500);
17325 s.politicas.circuit_breaker = Some(CircuitBreaker {
17326 max_failures: 5,
17327 window,
17328 });
17329 assert_eq!(
17330 s.validate().unwrap_err(),
17331 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
17332 );
17333 }
17334
17335 #[test]
17336 fn rejects_circuit_breaker_window_non_integer_millisecond() {
17337 // Peer of the `:timeout` non-integer-ms arm: a `Duration`
17338 // with non-integer-millisecond residue renders through the
17339 // shared codec as the truncated `"<n>ms"` form, parsing back
17340 // to a *different* `Duration` on the next round-trip.
17341 let mut s = three_member_spec();
17342 let window = Duration::from_micros(1500);
17343 s.politicas.circuit_breaker = Some(CircuitBreaker {
17344 max_failures: 5,
17345 window,
17346 });
17347 assert_eq!(
17348 s.validate().unwrap_err(),
17349 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
17350 );
17351 }
17352
17353 #[test]
17354 fn accepts_circuit_breaker_window_integer_millisecond_forms() {
17355 // The canonical-forms sweep on the breaker axis: every
17356 // integer-ms multiple the codec round-trips losslessly
17357 // passes the canonical gate.
17358 for window in [
17359 Duration::from_millis(1),
17360 Duration::from_millis(500),
17361 Duration::from_millis(1500),
17362 Duration::from_secs(30),
17363 Duration::from_secs(60),
17364 Duration::from_secs(3600),
17365 ] {
17366 let mut s = three_member_spec();
17367 s.politicas.circuit_breaker = Some(CircuitBreaker {
17368 max_failures: 5,
17369 window,
17370 });
17371 s.validate()
17372 .expect("integer-millisecond :circuit-breaker :window must validate");
17373 }
17374 }
17375
17376 #[test]
17377 fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
17378 // `Duration::ZERO` would pass the canonical-ms gate (the
17379 // sub-ns residue is zero) but must surface the narrower
17380 // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
17381 // remediation.
17382 let mut s = three_member_spec();
17383 s.politicas.circuit_breaker = Some(CircuitBreaker {
17384 max_failures: 5,
17385 window: Duration::ZERO,
17386 });
17387 assert_eq!(
17388 s.validate().unwrap_err(),
17389 AplicacaoError::PolicyBreakerZeroWindow
17390 );
17391 }
17392
17393 #[test]
17394 fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
17395 // Both axes invalid: max_failures == 0 *and* window is
17396 // sub-ms. The validate gate must fire on max_failures first
17397 // (matching the existing ordering pin
17398 // `rejects_circuit_breaker_zero_max_failures` enshrines), so
17399 // the existing diagnostic continues to lead with the simpler
17400 // "zero threshold" framing.
17401 let mut s = three_member_spec();
17402 s.politicas.circuit_breaker = Some(CircuitBreaker {
17403 max_failures: 0,
17404 window: Duration::from_micros(500),
17405 });
17406 assert_eq!(
17407 s.validate().unwrap_err(),
17408 AplicacaoError::PolicyBreakerZeroFailures
17409 );
17410 }
17411
17412 #[test]
17413 fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
17414 let mut s = three_member_spec();
17415 let window = Duration::from_nanos(60_000_000_001);
17416 s.politicas.circuit_breaker = Some(CircuitBreaker {
17417 max_failures: 5,
17418 window,
17419 });
17420 match s.validate().unwrap_err() {
17421 AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
17422 assert_eq!(w, window, "diagnostic must carry the offending Duration");
17423 }
17424 other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
17425 }
17426 }
17427
17428 #[test]
17429 fn rejects_circuit_breaker_window_above_cap() {
17430 // The fail-before-pass-after pin: 3601s = 1h + 1s is
17431 // structurally one canonical-tick past the
17432 // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
17433 // integer-millisecond magnitude the canonical-form arm above
17434 // accepts cleanly, that the codec round-trips losslessly as
17435 // `"3601s"`, and that silently passed validate on every
17436 // pre-gate codebase because the typed slot's only checks were
17437 // the zero-floor and canonical-form arms. The
17438 // rolling-window-to-lifetime-counter degeneration surfaces
17439 // only at the runtime substrate (Envoy's outlier_detection
17440 // interval, the future CiliumClusterwideEnvoyConfig overlay)
17441 // far from the source `caixa.lisp` with no field naming the
17442 // offending policy.
17443 let mut s = three_member_spec();
17444 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
17445 s.politicas.circuit_breaker = Some(CircuitBreaker {
17446 max_failures: 5,
17447 window,
17448 });
17449 assert_eq!(
17450 s.validate().unwrap_err(),
17451 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17452 );
17453 }
17454
17455 #[test]
17456 fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
17457 // Boundary case: exactly 1ms past the cap (the granularity the
17458 // canonical-form gate enforces). Catches a future "strictly
17459 // less than" half-measure and pins the diagnostic to name the
17460 // offending `Duration` verbatim. Peer of
17461 // `rejects_policy_timeout_one_millisecond_above_cap` on the
17462 // sibling duration-typed `:politicas :timeout` top edge.
17463 let mut s = three_member_spec();
17464 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
17465 s.politicas.circuit_breaker = Some(CircuitBreaker {
17466 max_failures: 5,
17467 window,
17468 });
17469 assert_eq!(
17470 s.validate().unwrap_err(),
17471 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17472 );
17473 }
17474
17475 #[test]
17476 fn rejects_circuit_breaker_window_far_above_cap() {
17477 // The "obvious authoring footgun" case: a `(:window "24h")` or
17478 // `(:window "86400s")` — values the canonical-form arm
17479 // accepts as integer-millisecond magnitudes, the codec
17480 // round-trips losslessly through serde, but the
17481 // rolling-window breaker contract cannot honor (a 24-hour
17482 // rolling failure window is operationally a lifetime counter).
17483 // Until this gate landed validate accepted it. Pin both common
17484 // above-cap values (24h, 7d) so a future relaxation that
17485 // drops the upper bound surfaces here.
17486 for window in [
17487 Duration::from_secs(86_400), // 24h
17488 Duration::from_secs(604_800), // 7d
17489 Duration::from_secs(1_000_000), // ~11.5 days
17490 ] {
17491 let mut s = three_member_spec();
17492 s.politicas.circuit_breaker = Some(CircuitBreaker {
17493 max_failures: 5,
17494 window,
17495 });
17496 assert_eq!(
17497 s.validate().unwrap_err(),
17498 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17499 );
17500 }
17501 }
17502
17503 #[test]
17504 fn accepts_circuit_breaker_window_at_cap() {
17505 // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
17506 // (1h) — must validate. The cap is inclusive on the top edge,
17507 // matching the [`POLICY_TIMEOUT_MAX`] /
17508 // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
17509 // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
17510 // sibling capped axes. Pin the boundary explicitly so a
17511 // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
17512 // instead of `>`) surfaces here as a test failure rather than
17513 // a silent contract narrowing.
17514 let mut s = three_member_spec();
17515 s.politicas.circuit_breaker = Some(CircuitBreaker {
17516 max_failures: 5,
17517 window: POLICY_BREAKER_WINDOW_MAX,
17518 });
17519 s.validate()
17520 .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
17521 }
17522
17523 #[test]
17524 fn accepts_circuit_breaker_window_typical_values() {
17525 // The documented production-playbook band positive-control
17526 // sweep — every value Hystrix / resilience4j / Istio / Envoy
17527 // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
17528 // through the long-tail failure-detection band (15m, 30m, 1h)
17529 // the cap accepts. Pin the inclusive validated set explicitly
17530 // so a future tightening of the ceiling surfaces here as a
17531 // deliberate test edit, not a silent contract narrowing.
17532 for window in [
17533 Duration::from_millis(1),
17534 Duration::from_millis(500),
17535 Duration::from_secs(1),
17536 Duration::from_secs(10), // Hystrix / Istio / Envoy default
17537 Duration::from_secs(30),
17538 Duration::from_secs(60), // resilience4j typical
17539 Duration::from_secs(300), // AWS App Mesh typical
17540 Duration::from_secs(900),
17541 Duration::from_secs(1800),
17542 Duration::from_secs(3600), // exactly 1h, the cap
17543 ] {
17544 let mut s = three_member_spec();
17545 s.politicas.circuit_breaker = Some(CircuitBreaker {
17546 max_failures: 5,
17547 window,
17548 });
17549 s.validate()
17550 .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
17551 }
17552 }
17553
17554 #[test]
17555 fn circuit_breaker_zero_window_takes_precedence_over_cap() {
17556 // The cross-arm ordering pin: `Duration::ZERO` is structurally
17557 // outside both `>= 1ms` (zero-floor) and
17558 // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
17559 // diagnostic is the more self-locating one (it directly names
17560 // the omit-axis remediation), so the validate gate must fire
17561 // on zero first. Same shape every other zero-then-cap
17562 // ordering on this surface uses
17563 // ([`AplicacaoError::PolicyTimeoutZero`] then
17564 // [`AplicacaoError::PolicyTimeoutExceedsCap`];
17565 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17566 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17567 let mut s = three_member_spec();
17568 s.politicas.circuit_breaker = Some(CircuitBreaker {
17569 max_failures: 5,
17570 window: Duration::ZERO,
17571 });
17572 assert_eq!(
17573 s.validate().unwrap_err(),
17574 AplicacaoError::PolicyBreakerZeroWindow,
17575 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
17576 );
17577 }
17578
17579 #[test]
17580 fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
17581 // The cross-arm ordering pin: a `Duration` that is *both*
17582 // sub-millisecond (non-canonical-form) and structurally above
17583 // the cap surfaces the canonical-form diagnostic first,
17584 // because the round-trip-shape break is the more fundamental
17585 // issue (the value can't even round-trip through the codec, so
17586 // the cap diagnostic naming `1ms..=1h` would be misleading —
17587 // there's no integer-ms form of the offending value). Pin the
17588 // order so a future refactor that reorders the arms surfaces
17589 // here as a test failure rather than a silent diagnostic
17590 // regression. Peer of
17591 // `policy_timeout_canonical_takes_precedence_over_cap` on the
17592 // sibling duration-typed `:politicas :timeout` axis.
17593 let mut s = three_member_spec();
17594 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
17595 s.politicas.circuit_breaker = Some(CircuitBreaker {
17596 max_failures: 5,
17597 window,
17598 });
17599 assert_eq!(
17600 s.validate().unwrap_err(),
17601 AplicacaoError::PolicyBreakerWindowNotCanonical { window },
17602 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
17603 );
17604 }
17605
17606 #[test]
17607 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
17608 // The cross-arm ordering pin between the two breaker axes: a
17609 // `CircuitBreaker` whose *both* `max_failures` is above its
17610 // cap *and* `window` is above its cap surfaces the
17611 // max-failures cap diagnostic first, because the validate
17612 // gate visits the failures arm before the window arm. Pin the
17613 // order so a future refactor that reorders the breaker arms
17614 // surfaces here.
17615 let mut s = three_member_spec();
17616 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
17617 s.politicas.circuit_breaker = Some(CircuitBreaker {
17618 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17619 window,
17620 });
17621 assert_eq!(
17622 s.validate().unwrap_err(),
17623 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17624 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
17625 },
17626 "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
17627 );
17628 }
17629
17630 #[test]
17631 fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
17632 // The diagnostic-shape pin: the offending `Duration` is
17633 // carried verbatim into the
17634 // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
17635 // the surfaced error message names the value the author wrote
17636 // (`":politicas :circuit-breaker :window (Duration { secs:
17637 // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
17638 // just the cap. Same self-locating diagnostic shape every
17639 // other typed-cap arm on this surface carries
17640 // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
17641 // offending `Duration` verbatim).
17642 let mut s = three_member_spec();
17643 let window = Duration::from_secs(7200); // 2h
17644 s.politicas.circuit_breaker = Some(CircuitBreaker {
17645 max_failures: 5,
17646 window,
17647 });
17648 let err = s.validate().unwrap_err();
17649 assert!(
17650 matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
17651 "got {err:?}"
17652 );
17653 let msg = err.to_string();
17654 assert!(
17655 msg.contains("7200"),
17656 ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
17657 );
17658 }
17659
17660 #[test]
17661 fn circuit_breaker_window_cap_pins_canonical_value() {
17662 // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
17663 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
17664 // shared duration codec emits as a clean canonical string
17665 // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
17666 // the sibling duration-typed `:politicas :timeout` axis (the
17667 // two duration-typed `:politicas` axes share a uniform top
17668 // edge). Pinning the literal value here surfaces a future
17669 // drift (a relaxation to 24h, a tightening to 5m) as a
17670 // deliberate test edit, not a silent contract narrowing. Same
17671 // shape every other typed-cap value pin on this surface uses
17672 // (`policy_timeout_cap_pins_canonical_value`).
17673 assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
17674 assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
17675 assert_eq!(
17676 POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
17677 "the two duration-typed `:politicas` caps share the same top edge"
17678 );
17679 }
17680
17681 #[test]
17682 fn circuit_breaker_window_cap_value_round_trips_through_codec() {
17683 // The codec round-trip property the cap arm preserves: the
17684 // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
17685 // through the shared duration codec — every value at the cap
17686 // renders to a clean canonical string (`"1h"`) and parses back
17687 // to the same `Duration`. Pin this so a future drift between
17688 // the cap constant and the codec's largest emitted unit
17689 // surfaces here. Same shape every other typed boundary pin on
17690 // this surface uses
17691 // (`policy_timeout_cap_value_round_trips_through_codec`).
17692 let policy = MeshPolicy {
17693 circuit_breaker: Some(CircuitBreaker {
17694 max_failures: 5,
17695 window: POLICY_BREAKER_WINDOW_MAX,
17696 }),
17697 ..Default::default()
17698 };
17699 let json = serde_json::to_string(&policy).unwrap();
17700 // The codec emits `"1h"` for the canonical 1-hour magnitude.
17701 assert!(
17702 json.contains("\"1h\""),
17703 "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
17704 );
17705 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17706 assert_eq!(
17707 back.circuit_breaker.unwrap().window,
17708 POLICY_BREAKER_WINDOW_MAX
17709 );
17710 }
17711
17712 #[test]
17713 fn is_integer_millisecond_duration_predicate_tracks_codec() {
17714 // Pin the predicate's accepted set against the codec's
17715 // accepted set explicitly. The codec parses
17716 // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
17717 // accepted value is an integer-millisecond multiple — so the
17718 // predicate must accept exactly that set. Same shape every
17719 // other predicate-on-the-typed-slot helper carries
17720 // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
17721 // Read directly from the codec-owned predicate — the crate's
17722 // single source of truth every typed-`Duration` axis now routes
17723 // through via
17724 // [`crate::render::require_positive_canonical_bounded_duration`].
17725 use super::supervisor::duration_codec::is_integer_millisecond_duration;
17726 assert!(is_integer_millisecond_duration(Duration::ZERO));
17727 assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
17728 assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
17729 assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
17730 assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
17731 assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
17732 // Non-integer-millisecond residue: rejected.
17733 assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
17734 assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
17735 assert!(!is_integer_millisecond_duration(Duration::from_micros(
17736 1500
17737 )));
17738 assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
17739 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
17740 999_999
17741 )));
17742 // The 1-ns-past-1ms boundary: rejected (no longer a clean
17743 // integer-millisecond multiple).
17744 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
17745 1_000_001
17746 )));
17747 }
17748
17749 #[test]
17750 fn policy_timeout_validated_value_round_trips_through_codec() {
17751 // The structural property the canonical-ms gate enforces:
17752 // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
17753 // round-trips losslessly through the shared `duration_codec`
17754 // (serialize → string → deserialize → equal value). Pin this
17755 // end-to-end so a future change to either side (the validate
17756 // gate's accepted granularity, the codec's parse/render unit
17757 // set) that breaks the alignment surfaces here. The
17758 // previous-state shape (typed slot accepts arbitrary
17759 // `Duration`, codec only round-trips integer-ms) would fail
17760 // this test for any `Duration::from_micros(1500)` timeout —
17761 // the validate gate now forecloses that.
17762 for timeout in [
17763 Duration::from_millis(1),
17764 Duration::from_millis(1500),
17765 Duration::from_secs(30),
17766 Duration::from_secs(3600),
17767 ] {
17768 let mut s = three_member_spec();
17769 s.politicas.timeout = Some(timeout);
17770 s.validate().unwrap();
17771 let json = serde_json::to_string(&s.politicas).unwrap();
17772 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17773 assert_eq!(
17774 back.timeout, s.politicas.timeout,
17775 "every validated :timeout must round-trip losslessly through the codec"
17776 );
17777 }
17778 }
17779
17780 #[test]
17781 fn circuit_breaker_window_validated_value_round_trips_through_codec() {
17782 // Peer of the `:timeout` round-trip property on the breaker
17783 // axis.
17784 for window in [
17785 Duration::from_millis(1),
17786 Duration::from_millis(1500),
17787 Duration::from_secs(30),
17788 Duration::from_secs(3600),
17789 ] {
17790 let mut s = three_member_spec();
17791 s.politicas.circuit_breaker = Some(CircuitBreaker {
17792 max_failures: 5,
17793 window,
17794 });
17795 s.validate().unwrap();
17796 let json = serde_json::to_string(&s.politicas).unwrap();
17797 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17798 assert_eq!(
17799 back.circuit_breaker.unwrap().window,
17800 window,
17801 "every validated :circuit-breaker :window must round-trip losslessly"
17802 );
17803 }
17804 }
17805
17806 #[test]
17807 fn empty_politicas_validates() {
17808 // Omitting every policy axis is fine — defaults express "no
17809 // policy on this axis", not "policy = 0". The fixture's typical
17810 // values continue to validate; this test pins that
17811 // MeshPolicy::default() is a clean pass through validate().
17812 let mut s = three_member_spec();
17813 s.politicas = MeshPolicy::default();
17814 s.validate().unwrap();
17815 }
17816
17817 #[test]
17818 fn typical_politicas_validates_with_every_axis_set() {
17819 // The full §III.1 example block (timeout + retries + breaker +
17820 // mtls + rate-limit) — every axis nonzero — must remain a
17821 // clean pass.
17822 let mut s = three_member_spec();
17823 s.politicas = MeshPolicy {
17824 timeout: Some(Duration::from_secs(30)),
17825 retries: Some(3),
17826 circuit_breaker: Some(CircuitBreaker {
17827 max_failures: 5,
17828 window: Duration::from_secs(60),
17829 }),
17830 mtls_required: Some(true),
17831 rate_limit: Some(RateLimit {
17832 rate: 100,
17833 window: Duration::from_secs(1),
17834 }),
17835 };
17836 s.validate().unwrap();
17837 }
17838
17839 #[test]
17840 fn rejects_empty_cluster_name() {
17841 let mut s = three_member_spec();
17842 s.placement.clusters = vec!["rio".into(), "".into()];
17843 assert_eq!(
17844 s.validate().unwrap_err(),
17845 AplicacaoError::PlacementClusterEmpty
17846 );
17847 }
17848
17849 #[test]
17850 fn rejects_duplicate_cluster_names() {
17851 let mut s = three_member_spec();
17852 s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
17853 let err = s.validate().unwrap_err();
17854 assert!(
17855 matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
17856 "got {err:?}"
17857 );
17858 }
17859
17860 #[test]
17861 fn rejects_placement_cluster_with_uppercase() {
17862 // The canonical "I copied the cluster's display name verbatim"
17863 // typo — K8s context names are lowercase per DNS-1123 label
17864 // rule, but org docs often round-trip a TitleCase identifier
17865 // (`Rio`, `Mar-East`) from an ADR. Mirrors the
17866 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
17867 // on the peer name axis.
17868 let mut s = three_member_spec();
17869 s.placement.clusters = vec!["Rio".into(), "mar".into()];
17870 let err = s.validate().unwrap_err();
17871 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
17872 panic!("expected PlacementClusterInvalid, got other variant");
17873 };
17874 assert_eq!(cluster, "Rio");
17875 assert!(
17876 reason.contains("uppercase"),
17877 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
17878 );
17879 assert!(
17880 reason.contains("\"rio\""),
17881 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
17882 );
17883 }
17884
17885 #[test]
17886 fn rejects_placement_cluster_with_underscore() {
17887 // The canonical "I'm thinking of an env var / hostname slug"
17888 // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
17889 // schema. K8s context filtering on `my_cluster` silently misses
17890 // the cluster the author intended; the gate moves it to caixa-
17891 // build time. Same shape as `rejects_membro_caixa_with_underscore`
17892 // (3f9d7a0).
17893 let mut s = three_member_spec();
17894 s.placement.clusters = vec!["my_cluster".into()];
17895 let err = s.validate().unwrap_err();
17896 assert!(
17897 matches!(
17898 err,
17899 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
17900 if cluster == "my_cluster" && reason.contains('_')
17901 ),
17902 "got {err:?}"
17903 );
17904 }
17905
17906 #[test]
17907 fn rejects_placement_cluster_with_dot() {
17908 // A `:placement :clusters` entry is a single DNS-1123 *label*,
17909 // not a subdomain — even though K8s context names sometimes
17910 // carry a dotted form via kubeconfig conventions, the strictest
17911 // floor among the use sites (DNS-1035 cluster.x-k8s.io
17912 // `metadata.name`, Cilium identity label values) wins. The "I
17913 // want to namespace my cluster names with `.`" intent is
17914 // expressed via `-` (`mar-east`).
17915 let mut s = three_member_spec();
17916 s.placement.clusters = vec!["team.rio".into()];
17917 let err = s.validate().unwrap_err();
17918 assert!(
17919 matches!(
17920 err,
17921 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
17922 if cluster == "team.rio" && reason.contains('.')
17923 ),
17924 "got {err:?}"
17925 );
17926 }
17927
17928 #[test]
17929 fn rejects_placement_cluster_with_leading_hyphen() {
17930 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
17931 // with an alphanumeric. The K8s apiserver rejects `-rio`
17932 // outright; the rendered fan-out would emit a `metadata.name:
17933 // "-rio"` that fails admission far from the source caixa.lisp.
17934 let mut s = three_member_spec();
17935 s.placement.clusters = vec!["-rio".into()];
17936 let err = s.validate().unwrap_err();
17937 assert!(
17938 matches!(
17939 err,
17940 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
17941 if cluster == "-rio" && reason.contains("start and end")
17942 ),
17943 "got {err:?}"
17944 );
17945 }
17946
17947 #[test]
17948 fn rejects_placement_cluster_with_trailing_hyphen() {
17949 // The symmetric arm of the boundary rule. Pin separately so
17950 // both ends are covered against a future relaxation that only
17951 // checks one boundary (parallel to
17952 // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
17953 let mut s = three_member_spec();
17954 s.placement.clusters = vec!["rio-".into()];
17955 let err = s.validate().unwrap_err();
17956 assert!(
17957 matches!(
17958 err,
17959 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
17960 if cluster == "rio-"
17961 ),
17962 "got {err:?}"
17963 );
17964 }
17965
17966 #[test]
17967 fn rejects_placement_cluster_with_unicode() {
17968 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
17969 // before it reaches K8s. The byte-by-byte ASCII validity check
17970 // rejects multi-byte UTF-8 sequences by the first byte that
17971 // fails `[a-z0-9-]`.
17972 let mut s = three_member_spec();
17973 s.placement.clusters = vec!["rió".into()];
17974 let err = s.validate().unwrap_err();
17975 assert!(
17976 matches!(
17977 err,
17978 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
17979 if cluster == "rió"
17980 ),
17981 "got {err:?}"
17982 );
17983 }
17984
17985 #[test]
17986 fn rejects_placement_cluster_with_whitespace() {
17987 // Whitespace is the canonical "I pasted from a sketch / doc"
17988 // footgun. The apiserver rejects every cluster `metadata.name`
17989 // value carrying whitespace.
17990 let mut s = three_member_spec();
17991 s.placement.clusters = vec!["rio cluster".into()];
17992 let err = s.validate().unwrap_err();
17993 assert!(
17994 matches!(
17995 err,
17996 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
17997 if cluster == "rio cluster"
17998 ),
17999 "got {err:?}"
18000 );
18001 }
18002
18003 #[test]
18004 fn rejects_placement_cluster_too_long() {
18005 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
18006 // pin. The diagnostic names both the cap (63) and the actual
18007 // length so the author can shorten in one edit. Mirrors
18008 // `rejects_membro_caixa_too_long` (3f9d7a0).
18009 let mut s = three_member_spec();
18010 let too_long = "a".repeat(64);
18011 s.placement.clusters = vec![too_long.clone()];
18012 let err = s.validate().unwrap_err();
18013 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18014 panic!("expected PlacementClusterInvalid");
18015 };
18016 assert_eq!(cluster, too_long);
18017 assert!(
18018 reason.contains("63") && reason.contains("64"),
18019 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18020 );
18021 }
18022
18023 #[test]
18024 fn placement_cluster_max_length_validates() {
18025 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
18026 // future tightening (e.g. dropping to 62) surfaces here as a
18027 // regression, mirroring `membro_caixa_max_length_validates`
18028 // (3f9d7a0).
18029 let mut s = three_member_spec();
18030 s.placement.clusters = vec!["a".repeat(63)];
18031 s.validate().unwrap();
18032 }
18033
18034 #[test]
18035 fn accepts_canonical_placement_cluster_forms() {
18036 // The DNS-1123 label shapes a caixa author is realistically
18037 // going to write for cluster names: single-word lowercase
18038 // (`rio`), regional hyphen-joined (`mar-east`), single
18039 // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
18040 // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
18041 // Pin every leg so a future tightening that bans (e.g.) digit-
18042 // start identifiers surfaces here.
18043 for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
18044 let mut s = three_member_spec();
18045 s.placement.clusters = vec![form.into()];
18046 s.validate().unwrap_or_else(|e| {
18047 panic!("canonical cluster form {form:?} must validate, got {e:?}")
18048 });
18049 }
18050 }
18051
18052 #[test]
18053 fn placement_cluster_empty_takes_precedence_over_invalid() {
18054 // Order pin: the existing `PlacementClusterEmpty` diagnostic
18055 // (which doesn't try to parse) fires before the new
18056 // `PlacementClusterInvalid` parse-side diagnostic, so an empty
18057 // `:clusters` entry keeps its narrower error message — the new
18058 // gate would also reject `""`, but the empty-string arm is the
18059 // more self-locating diagnostic. Mirrors the
18060 // `membro_caixa_empty_takes_precedence_over_invalid` pin
18061 // (3f9d7a0).
18062 let mut s = three_member_spec();
18063 s.placement.clusters = vec!["rio".into(), "".into()];
18064 let err = s.validate().unwrap_err();
18065 assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
18066 }
18067
18068 #[test]
18069 fn placement_cluster_invalid_fires_before_duplicate_check() {
18070 // Order pin: a malformed-shape `:clusters` entry surfaces *its
18071 // own* diagnostic, even when a later entry would otherwise
18072 // collapse onto a duplicate name. The per-entry shape gate runs
18073 // inline before the duplicate-key insert, parallel to
18074 // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
18075 let mut s = three_member_spec();
18076 s.placement.clusters = vec!["Rio".into(), "rio".into()];
18077 let err = s.validate().unwrap_err();
18078 assert!(
18079 matches!(
18080 err,
18081 AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
18082 ),
18083 "got {err:?}"
18084 );
18085 }
18086
18087 #[test]
18088 fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
18089 // The diagnostic-shape pin: the error names the offending
18090 // `:clusters` value verbatim so the author can grep their
18091 // caixa.lisp without re-running the build, and carries a
18092 // non-empty `reason` naming the specific violation. Same shape
18093 // every typed-shape gate enshrines
18094 // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
18095 // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
18096 let mut s = three_member_spec();
18097 s.placement.clusters = vec!["BAD_CLUSTER".into()];
18098 let err = s.validate().unwrap_err();
18099 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18100 panic!("expected PlacementClusterInvalid");
18101 };
18102 assert_eq!(cluster, "BAD_CLUSTER");
18103 assert!(
18104 !reason.is_empty(),
18105 "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
18106 );
18107 }
18108
18109 #[test]
18110 fn rejects_sharded_with_empty_clusters() {
18111 // §III.1: Sharded uses :clusters as the shard pool. An empty
18112 // pool means "shard across no clusters" — meaningless, same as
18113 // Replicated with no hosts.
18114 let mut s = three_member_spec();
18115 s.placement.estrategia = PlacementStrategy::Sharded;
18116 s.placement.shard_key = Some("$tenantId".into());
18117 s.placement.clusters = vec![];
18118 assert!(matches!(
18119 s.validate().unwrap_err(),
18120 AplicacaoError::PlacementWithoutClusters {
18121 estrategia: PlacementStrategy::Sharded
18122 }
18123 ));
18124 }
18125
18126 #[test]
18127 fn rejects_sharded_with_empty_shard_key() {
18128 let mut s = three_member_spec();
18129 s.placement.estrategia = PlacementStrategy::Sharded;
18130 s.placement.shard_key = Some("".into());
18131 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
18132 }
18133
18134 #[test]
18135 fn rejects_shard_key_under_replicated_strategy() {
18136 // The fail-before-pass-after pin: a `:placement (:estrategia
18137 // Replicated :shard-key "tenantId")` manifest carries the
18138 // hash-keyed-distribution slot on a strategy that never consumes
18139 // it. Before the gate the typed slot's value silently vanished
18140 // at the renderer layer (caixa-mesh emits `placement.shardKey`
18141 // verbatim regardless of strategy; the Akka-style cluster-
18142 // sharding reconciler keys off `estrategia == Sharded` and
18143 // ignores the slot otherwise), with no diagnostic. Lifting the
18144 // rejection to a build-time gate makes the
18145 // `shard_key.is_some() == matches!(estrategia, Sharded)`
18146 // partition a structural property of every validated
18147 // [`Placement`].
18148 let mut s = three_member_spec();
18149 // The fixture already uses Replicated; just add a shard-key.
18150 s.placement.shard_key = Some("$tenantId".into());
18151 let err = s.validate().unwrap_err();
18152 let AplicacaoError::ShardKeyOnNonSharded {
18153 estrategia,
18154 shard_key,
18155 } = err
18156 else {
18157 panic!("expected ShardKeyOnNonSharded, got {err:?}");
18158 };
18159 assert_eq!(estrategia, PlacementStrategy::Replicated);
18160 assert_eq!(shard_key, "$tenantId");
18161 }
18162
18163 #[test]
18164 fn rejects_shard_key_under_singlenode_strategy() {
18165 // Peer of the Replicated case above on the SingleNode arm: OTP
18166 // distributed-app takeover (one cluster runs at a time) has no
18167 // hash-keyed routing axis to consume `:shard-key` either, so
18168 // the rejection fires on both non-Sharded arms uniformly.
18169 let mut s = three_member_spec();
18170 s.placement.estrategia = PlacementStrategy::SingleNode;
18171 s.placement.shard_key = Some("$tenantId".into());
18172 let err = s.validate().unwrap_err();
18173 let AplicacaoError::ShardKeyOnNonSharded {
18174 estrategia,
18175 shard_key,
18176 } = err
18177 else {
18178 panic!("expected ShardKeyOnNonSharded, got {err:?}");
18179 };
18180 assert_eq!(estrategia, PlacementStrategy::SingleNode);
18181 assert_eq!(shard_key, "$tenantId");
18182 }
18183
18184 #[test]
18185 fn rejects_empty_shard_key_under_replicated_strategy() {
18186 // The `Some("")` case under non-Sharded is rejected by
18187 // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
18188 // fires before the empty-value gate), not
18189 // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
18190 // the `Sharded` arm). Pin the partition so a future reorder of
18191 // the validate_placement match arms doesn't silently swap which
18192 // diagnostic the author sees — both are author errors, but
18193 // ShardKeyOnNonSharded names which strategy is the actual fix
18194 // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
18195 // only says "pick a non-empty key".
18196 let mut s = three_member_spec();
18197 s.placement.shard_key = Some(String::new());
18198 let err = s.validate().unwrap_err();
18199 assert!(
18200 matches!(
18201 err,
18202 AplicacaoError::ShardKeyOnNonSharded {
18203 estrategia: PlacementStrategy::Replicated,
18204 ref shard_key,
18205 } if shard_key.is_empty()
18206 ),
18207 "got {err:?}"
18208 );
18209 }
18210
18211 #[test]
18212 fn replicated_without_shard_key_validates() {
18213 // The complement of the rejection: `:placement :estrategia
18214 // Replicated` with `:shard-key None` is the canonical happy
18215 // path on every existing fixture. Pin the no-shard-key case so
18216 // the new gate doesn't accidentally fire on `None`.
18217 let mut s = three_member_spec();
18218 assert!(matches!(
18219 s.placement.estrategia,
18220 PlacementStrategy::Replicated
18221 ));
18222 s.placement.shard_key = None;
18223 s.validate().unwrap();
18224 }
18225
18226 #[test]
18227 fn singlenode_without_shard_key_validates() {
18228 // Peer of the Replicated no-shard-key case on the SingleNode
18229 // arm — both non-Sharded strategies must validate cleanly when
18230 // the slot is omitted.
18231 let mut s = three_member_spec();
18232 s.placement.estrategia = PlacementStrategy::SingleNode;
18233 s.placement.shard_key = None;
18234 s.validate().unwrap();
18235 }
18236
18237 fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
18238 // Fixture builder for the `:placement :shard-key` shape gate
18239 // tests: a three-member Aplicacao on the `Sharded` strategy
18240 // with the supplied `:shard-key` slot. Co-locates the
18241 // arm-construction so every test below carries one line of
18242 // setup (the offending `:shard-key` value) and the assertion.
18243 let mut s = three_member_spec();
18244 s.placement.estrategia = PlacementStrategy::Sharded;
18245 s.placement.shard_key = Some(key.into());
18246 s
18247 }
18248
18249 #[test]
18250 fn rejects_shard_key_with_embedded_space() {
18251 // The canonical paste-from-aligned-doc footgun:
18252 // `:shard-key "$tenant Id"` — the Akka-style entity-id
18253 // extractor reads the slot as a single-token reference, and an
18254 // embedded space breaks the token boundary at the runtime
18255 // hash-extractor pass with no diagnostic naming the offending
18256 // entry.
18257 let s = sharded_spec_with_key("$tenant Id");
18258 let err = s.validate().unwrap_err();
18259 assert!(
18260 matches!(
18261 err,
18262 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18263 if shard_key == "$tenant Id" && reason.contains("space")
18264 ),
18265 "got {err:?}"
18266 );
18267 }
18268
18269 #[test]
18270 fn rejects_shard_key_with_leading_space() {
18271 // Leading-space arm of the embedded-whitespace footgun — the
18272 // paste-from-aligned-doc / paste-from-CSV-cell variant where
18273 // the leading column-padding leaked into the slot.
18274 let s = sharded_spec_with_key(" $tenantId");
18275 let err = s.validate().unwrap_err();
18276 assert!(
18277 matches!(
18278 err,
18279 AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
18280 if shard_key == " $tenantId"
18281 ),
18282 "got {err:?}"
18283 );
18284 }
18285
18286 #[test]
18287 fn rejects_shard_key_with_trailing_newline() {
18288 // The canonical paste-from-shell-heredoc footgun — every
18289 // `<<EOF` heredoc terminator paste leaves a trailing newline
18290 // the YAML emitter then folds away inconsistently across
18291 // emitter implementations.
18292 let s = sharded_spec_with_key("$tenantId\n");
18293 let err = s.validate().unwrap_err();
18294 assert!(
18295 matches!(
18296 err,
18297 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18298 if shard_key == "$tenantId\n" && reason.contains("0x0a")
18299 ),
18300 "got {err:?}"
18301 );
18302 }
18303
18304 #[test]
18305 fn rejects_shard_key_with_embedded_tab() {
18306 // The paste-from-aligned-doc tab-stop variant — tabs land
18307 // alongside spaces in copy-paste from formatted columns.
18308 let s = sharded_spec_with_key("$tenant\tId");
18309 let err = s.validate().unwrap_err();
18310 assert!(
18311 matches!(
18312 err,
18313 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18314 if shard_key == "$tenant\tId" && reason.contains("tab")
18315 ),
18316 "got {err:?}"
18317 );
18318 }
18319
18320 #[test]
18321 fn rejects_shard_key_with_control_character() {
18322 // The paste-from-binary / paste-from-screen-cleared-terminal
18323 // footgun — an embedded `\x01` (SOH) byte that some YAML
18324 // emitters silently strip and others escape as ``,
18325 // breaking round-trip across emitter implementations.
18326 let s = sharded_spec_with_key("$tenant\u{0001}Id");
18327 let err = s.validate().unwrap_err();
18328 assert!(
18329 matches!(
18330 err,
18331 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18332 if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
18333 ),
18334 "got {err:?}"
18335 );
18336 }
18337
18338 #[test]
18339 fn rejects_shard_key_with_non_ascii() {
18340 // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
18341 // footgun — non-ASCII bytes normalize differently between the
18342 // caixa-mesh-side YAML emitter and the in-cluster reconciler's
18343 // YAML parser, the same entity ID can silently map to two
18344 // distinct shards on a re-render.
18345 let s = sharded_spec_with_key("$tenàntId");
18346 let err = s.validate().unwrap_err();
18347 assert!(
18348 matches!(
18349 err,
18350 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
18351 if shard_key == "$tenàntId" && reason.contains("non-ASCII")
18352 ),
18353 "got {err:?}"
18354 );
18355 }
18356
18357 #[test]
18358 fn rejects_shard_key_too_long() {
18359 // Length cap pin: 64 bytes — one byte over the
18360 // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
18361 // here is a paste-from-doc multi-line blob landing in
18362 // `:shard-key` instead of a single-token extractor expression.
18363 let too_long = "a".repeat(64);
18364 let s = sharded_spec_with_key(&too_long);
18365 let err = s.validate().unwrap_err();
18366 let AplicacaoError::ShardKeyInvalid {
18367 ref shard_key,
18368 ref reason,
18369 } = err
18370 else {
18371 panic!("expected ShardKeyInvalid, got {err:?}");
18372 };
18373 assert_eq!(shard_key, &too_long);
18374 assert!(
18375 reason.contains("63") && reason.contains("64"),
18376 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18377 );
18378 }
18379
18380 #[test]
18381 fn shard_key_max_length_validates() {
18382 // Boundary pin: 63 bytes exactly — the
18383 // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
18384 // dropping to 62) surfaces here as a regression, mirroring
18385 // `placement_cluster_max_length_validates` /
18386 // `placement_affinity_max_length_validates` on the peer
18387 // identifier-shaped slots.
18388 let s = sharded_spec_with_key(&"a".repeat(63));
18389 s.validate().unwrap();
18390 }
18391
18392 #[test]
18393 fn accepts_canonical_shard_key_forms() {
18394 // The Akka-style entity-id extractor shapes a caixa author is
18395 // realistically going to write — pin every leg so a future
18396 // tightening that bans (e.g.) the `${...}` interpolation
18397 // variant or the `metadata.<field>` JSONPath form surfaces
18398 // here as a regression. The canonical forms span:
18399 //
18400 // - bare property name (`tenantId`, `customerId`)
18401 // - Akka `ExtractEntityId` placeholder (`$tenantId`)
18402 // - JSONPath-style nested reference (`metadata.tenantId`,
18403 // `$.user.id`)
18404 // - interpolation-style template (`${tenant}`)
18405 // - snake_case property name (`customer_id`)
18406 // - kebab-case property name (`customer-id` — accepted
18407 // because the slot is a printable-ASCII single-token
18408 // reference, not a DNS-1123 label like
18409 // `:placement :affinity` / `:clusters`)
18410 // - single character (`a`, `$` — boundary)
18411 for form in [
18412 "tenantId",
18413 "customerId",
18414 "$tenantId",
18415 "metadata.tenantId",
18416 "$.user.id",
18417 "${tenant}",
18418 "customer_id",
18419 "customer-id",
18420 "a",
18421 "$",
18422 ] {
18423 let s = sharded_spec_with_key(form);
18424 s.validate().unwrap_or_else(|e| {
18425 panic!("canonical shard-key form {form:?} must validate, got {e:?}")
18426 });
18427 }
18428 }
18429
18430 #[test]
18431 fn shard_key_empty_takes_precedence_over_invalid() {
18432 // Order pin: the existing `ShardedKeyEmpty` diagnostic
18433 // (reserved for the `Sharded` `Some("")` arm) fires before the
18434 // new `ShardKeyInvalid` parse-side diagnostic, so an empty
18435 // `:shard-key` keeps its narrower error message — the new gate
18436 // would also reject `""` defensively, but the empty-string arm
18437 // is the more self-locating diagnostic. Mirrors the
18438 // `placement_cluster_empty_takes_precedence_over_invalid` pin
18439 // on the peer identifier-shaped slot.
18440 let s = sharded_spec_with_key("");
18441 let err = s.validate().unwrap_err();
18442 assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
18443 }
18444
18445 #[test]
18446 fn shard_key_invalid_diagnostic_carries_offending_value() {
18447 // The diagnostic-shape pin: the error names the offending
18448 // `:shard-key` value verbatim so the author can grep their
18449 // caixa.lisp without re-running the build, and carries a
18450 // parser-shaped `reason:` naming the specific violation —
18451 // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
18452 // on the peer identifier-shaped slot.
18453 let s = sharded_spec_with_key("$tenant Id");
18454 let err = s.validate().unwrap_err();
18455 let AplicacaoError::ShardKeyInvalid {
18456 ref shard_key,
18457 ref reason,
18458 } = err
18459 else {
18460 panic!("expected ShardKeyInvalid, got {err:?}");
18461 };
18462 assert_eq!(shard_key, "$tenant Id");
18463 assert!(
18464 !reason.is_empty(),
18465 "reason must name the specific violation, got empty string"
18466 );
18467 }
18468
18469 #[test]
18470 fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
18471 // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
18472 // `:shard-key` carried on non-Sharded strategies) fires before
18473 // the shape gate, so a malformed `:shard-key` carried on (e.g.)
18474 // a `Replicated` strategy surfaces the more self-locating
18475 // strategy-mismatch diagnostic (naming the actual fix — drop
18476 // the slot, or switch to Sharded) rather than the shape
18477 // diagnostic. The strategy-mismatch arm is the more actionable
18478 // diagnostic: a malformed shard-key on Replicated is "you
18479 // shouldn't have a :shard-key here at all", not "your
18480 // :shard-key value is malformed".
18481 let mut s = three_member_spec();
18482 // Replicated is the default fixture strategy.
18483 s.placement.shard_key = Some("$tenant Id".into());
18484 let err = s.validate().unwrap_err();
18485 assert!(
18486 matches!(
18487 err,
18488 AplicacaoError::ShardKeyOnNonSharded {
18489 estrategia: PlacementStrategy::Replicated,
18490 ..
18491 }
18492 ),
18493 "got {err:?}"
18494 );
18495 }
18496
18497 #[test]
18498 fn rejects_empty_affinity_hint() {
18499 let mut s = three_member_spec();
18500 s.placement.affinity = Some("".into());
18501 assert_eq!(
18502 s.validate().unwrap_err(),
18503 AplicacaoError::PlacementAffinityEmpty
18504 );
18505 }
18506
18507 #[test]
18508 fn placement_without_affinity_validates() {
18509 // Omitting :affinity is fine — the placement engine falls back
18510 // to the default heuristic. Pin the no-hint case so the
18511 // affinity-empty rejection doesn't accidentally fire on `None`.
18512 let mut s = three_member_spec();
18513 s.placement.affinity = None;
18514 s.validate().unwrap();
18515 }
18516
18517 #[test]
18518 fn rejects_placement_affinity_with_uppercase() {
18519 // The canonical "I copied the ADR's display name verbatim" typo
18520 // — placement hints land verbatim in K8s label-selector
18521 // territory, where the apiserver enforces the DNS-1123 label
18522 // rule (lowercase-only) on every identity-keyed admission axis.
18523 // Mirrors `rejects_placement_cluster_with_uppercase` on the
18524 // sibling slot.
18525 let mut s = three_member_spec();
18526 s.placement.affinity = Some("DataLocality".into());
18527 let err = s.validate().unwrap_err();
18528 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18529 panic!("expected PlacementAffinityInvalid, got other variant");
18530 };
18531 assert_eq!(affinity, "DataLocality");
18532 assert!(
18533 reason.contains("uppercase"),
18534 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
18535 );
18536 assert!(
18537 reason.contains("\"datalocality\""),
18538 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
18539 );
18540 }
18541
18542 #[test]
18543 fn rejects_placement_affinity_with_underscore() {
18544 // The canonical "I'm thinking of an env var / Python identifier"
18545 // leak — `_` is forbidden by every DNS-1123 label schema. Same
18546 // shape as `rejects_placement_cluster_with_underscore` on the
18547 // sibling slot.
18548 let mut s = three_member_spec();
18549 s.placement.affinity = Some("data_locality".into());
18550 let err = s.validate().unwrap_err();
18551 assert!(
18552 matches!(
18553 err,
18554 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18555 if affinity == "data_locality" && reason.contains('_')
18556 ),
18557 "got {err:?}"
18558 );
18559 }
18560
18561 #[test]
18562 fn rejects_placement_affinity_with_dot() {
18563 // A `:placement :affinity` value is a single DNS-1123 *label*
18564 // (it lands as a K8s label value selector key), not a subdomain.
18565 // The "I want to namespace my hint with `.`" intent is expressed
18566 // via `-` (`data-locality-east`).
18567 let mut s = three_member_spec();
18568 s.placement.affinity = Some("data.locality".into());
18569 let err = s.validate().unwrap_err();
18570 assert!(
18571 matches!(
18572 err,
18573 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18574 if affinity == "data.locality" && reason.contains('.')
18575 ),
18576 "got {err:?}"
18577 );
18578 }
18579
18580 #[test]
18581 fn rejects_placement_affinity_with_unicode() {
18582 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
18583 // before it reaches K8s. The byte-by-byte ASCII validity check
18584 // rejects multi-byte UTF-8 sequences by the first byte that
18585 // fails `[a-z0-9-]`.
18586 let mut s = three_member_spec();
18587 s.placement.affinity = Some("data-localité".into());
18588 let err = s.validate().unwrap_err();
18589 assert!(
18590 matches!(
18591 err,
18592 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
18593 if affinity == "data-localité"
18594 ),
18595 "got {err:?}"
18596 );
18597 }
18598
18599 #[test]
18600 fn rejects_placement_affinity_with_leading_hyphen() {
18601 // DNS-1123 boundary rule: labels must start with an
18602 // alphanumeric. Pin separately from the trailing-hyphen arm so
18603 // a future relaxation that only checks one boundary surfaces
18604 // here as a regression (parallel to
18605 // `rejects_placement_cluster_with_leading_hyphen`).
18606 let mut s = three_member_spec();
18607 s.placement.affinity = Some("-data-locality".into());
18608 let err = s.validate().unwrap_err();
18609 assert!(
18610 matches!(
18611 err,
18612 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18613 if affinity == "-data-locality" && reason.contains("start and end")
18614 ),
18615 "got {err:?}"
18616 );
18617 }
18618
18619 #[test]
18620 fn rejects_placement_affinity_with_trailing_hyphen() {
18621 // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
18622 // ends are covered against a future relaxation.
18623 let mut s = three_member_spec();
18624 s.placement.affinity = Some("data-locality-".into());
18625 let err = s.validate().unwrap_err();
18626 assert!(
18627 matches!(
18628 err,
18629 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
18630 if affinity == "data-locality-"
18631 ),
18632 "got {err:?}"
18633 );
18634 }
18635
18636 #[test]
18637 fn rejects_placement_affinity_with_whitespace() {
18638 // Whitespace is the canonical "I pasted from a sketch / doc"
18639 // footgun. The apiserver rejects every label-selector value
18640 // carrying whitespace.
18641 let mut s = three_member_spec();
18642 s.placement.affinity = Some("data locality".into());
18643 let err = s.validate().unwrap_err();
18644 assert!(
18645 matches!(
18646 err,
18647 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
18648 if affinity == "data locality"
18649 ),
18650 "got {err:?}"
18651 );
18652 }
18653
18654 #[test]
18655 fn rejects_placement_affinity_too_long() {
18656 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
18657 // pin. The diagnostic names both the cap (63) and the actual
18658 // length so the author can shorten in one edit. Mirrors
18659 // `rejects_placement_cluster_too_long`.
18660 let mut s = three_member_spec();
18661 let too_long = "a".repeat(64);
18662 s.placement.affinity = Some(too_long.clone());
18663 let err = s.validate().unwrap_err();
18664 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18665 panic!("expected PlacementAffinityInvalid");
18666 };
18667 assert_eq!(affinity, too_long);
18668 assert!(
18669 reason.contains("63") && reason.contains("64"),
18670 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18671 );
18672 }
18673
18674 #[test]
18675 fn placement_affinity_max_length_validates() {
18676 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
18677 // future tightening (e.g. dropping to 62) surfaces here as a
18678 // regression, mirroring `placement_cluster_max_length_validates`.
18679 let mut s = three_member_spec();
18680 s.placement.affinity = Some("a".repeat(63));
18681 s.validate().unwrap();
18682 }
18683
18684 #[test]
18685 fn accepts_canonical_placement_affinity_forms() {
18686 // The DNS-1123 label shapes a caixa author is realistically
18687 // going to write for placement hints: the M3 canonical examples
18688 // (`data-locality`, `low-latency`, `anti-affinity`), the
18689 // single-token form (`affinity`), the single-character boundary
18690 // (`a`), the digit-start (DNS-1123 allows this, unlike
18691 // DNS-1035), and a regional-suffixed form. Pin every leg so a
18692 // future tightening that bans (e.g.) digit-start identifiers
18693 // surfaces here.
18694 for form in [
18695 "data-locality",
18696 "low-latency",
18697 "anti-affinity",
18698 "affinity",
18699 "a",
18700 "3-tier",
18701 "locality-east",
18702 ] {
18703 let mut s = three_member_spec();
18704 s.placement.affinity = Some(form.into());
18705 s.validate().unwrap_or_else(|e| {
18706 panic!("canonical affinity form {form:?} must validate, got {e:?}")
18707 });
18708 }
18709 }
18710
18711 #[test]
18712 fn placement_affinity_empty_takes_precedence_over_invalid() {
18713 // Order pin: the existing `PlacementAffinityEmpty` diagnostic
18714 // (which doesn't try to parse) fires before the new
18715 // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
18716 // `:affinity` keeps its narrower error message — the new gate
18717 // would also reject `""`, but the empty-string arm is the more
18718 // self-locating diagnostic. Mirrors the
18719 // `placement_cluster_empty_takes_precedence_over_invalid` pin.
18720 let mut s = three_member_spec();
18721 s.placement.affinity = Some(String::new());
18722 let err = s.validate().unwrap_err();
18723 assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
18724 }
18725
18726 #[test]
18727 fn placement_affinity_invalid_diagnostic_carries_offending_value() {
18728 // The diagnostic shape pin: every rejection carries the offending
18729 // `affinity:` verbatim plus a parser-shaped `reason:` so the
18730 // author can grep their caixa.lisp for `:affinity "<hint>"` and
18731 // fix it in one edit. Mirrors the
18732 // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
18733 // pin on the sibling slot.
18734 let mut s = three_member_spec();
18735 s.placement.affinity = Some("Data_Locality".into());
18736 let err = s.validate().unwrap_err();
18737 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18738 panic!("expected PlacementAffinityInvalid");
18739 };
18740 assert_eq!(affinity, "Data_Locality");
18741 assert!(
18742 !reason.is_empty(),
18743 "diagnostic reason must not be empty (got: {reason:?})"
18744 );
18745 }
18746
18747 #[test]
18748 fn singlenode_with_takeover_candidates_validates() {
18749 // OTP distributed-application convention (MESH-COMPOSITION
18750 // §II.1): SingleNode runs on one cluster at a time but the
18751 // :clusters list enumerates the takeover candidates. Multiple
18752 // entries are not a contradiction — they are the failover pool.
18753 let mut s = three_member_spec();
18754 s.placement.estrategia = PlacementStrategy::SingleNode;
18755 s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
18756 s.validate().unwrap();
18757 }
18758
18759 // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
18760
18761 #[test]
18762 fn mesh_policy_default_is_empty() {
18763 // The Default impl carries None on every axis — the typed
18764 // analog of an unset `:politicas (())` slot. Renderers that
18765 // overlay the policy onto a cluster artifact key off this
18766 // predicate to skip the slot entirely; pinning so a future
18767 // axis added to MeshPolicy can't silently break the contract
18768 // (a new field whose Default is non-None would flip is_empty
18769 // to false on every existing caixa, surfacing here).
18770 assert!(MeshPolicy::default().is_empty());
18771 }
18772
18773 #[test]
18774 fn mesh_policy_with_only_timeout_is_not_empty() {
18775 let p = MeshPolicy {
18776 timeout: Some(Duration::from_secs(30)),
18777 ..Default::default()
18778 };
18779 assert!(!p.is_empty());
18780 }
18781
18782 #[test]
18783 fn mesh_policy_with_only_retries_is_not_empty() {
18784 let p = MeshPolicy {
18785 retries: Some(3),
18786 ..Default::default()
18787 };
18788 assert!(!p.is_empty());
18789 }
18790
18791 #[test]
18792 fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
18793 let p = MeshPolicy {
18794 circuit_breaker: Some(CircuitBreaker {
18795 max_failures: 5,
18796 window: Duration::from_secs(60),
18797 }),
18798 ..Default::default()
18799 };
18800 assert!(!p.is_empty());
18801 }
18802
18803 #[test]
18804 fn mesh_policy_with_only_mtls_required_is_not_empty() {
18805 // Even `mtls_required: Some(false)` (an explicit opt-out) is
18806 // not empty — the author *named* the axis, the renderer needs
18807 // to honor that vs. fall back to the cluster default.
18808 let p = MeshPolicy {
18809 mtls_required: Some(false),
18810 ..Default::default()
18811 };
18812 assert!(!p.is_empty());
18813 }
18814
18815 #[test]
18816 fn mesh_policy_with_only_rate_limit_is_not_empty() {
18817 let p = MeshPolicy {
18818 rate_limit: Some(RateLimit {
18819 rate: 100,
18820 window: Duration::from_secs(1),
18821 }),
18822 ..Default::default()
18823 };
18824 assert!(!p.is_empty());
18825 }
18826
18827 #[test]
18828 fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
18829 // The three-member happy-path fixture sets timeout + retries +
18830 // mtls_required — every populated axis must read non-empty.
18831 // Pin the round-trip so the M3.x per-:politicas emitter (the
18832 // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
18833 // on is_empty() to decide whether to emit at all without
18834 // re-deriving the contract from inline field probes.
18835 assert!(!three_member_spec().politicas.is_empty());
18836 }
18837
18838 // ── shared duration codec: cross-slot integer-magnitude gate ──
18839 //
18840 // The integer-magnitude discipline applied to
18841 // `supervisor::duration_codec::parse` lifts onto every typed slot
18842 // that routes through the shared codec — `MeshPolicy::timeout`
18843 // (`:politicas :timeout`) and `CircuitBreaker::window`
18844 // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
18845 // These cross-slot tests pin that the gate fires at the serde
18846 // layer for both typed slots, not just for the supervisor side.
18847
18848 #[test]
18849 fn policy_timeout_serde_rejects_fractional_seconds() {
18850 // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
18851 // so the shared codec's integer-magnitude gate applies on
18852 // deserialize. `"1.5s"` previously parsed to 1500ms and round-
18853 // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
18854 // deserialize with the canonical-form diagnostic naming the
18855 // offending `"1.5"` and the remediation `"1500ms"`.
18856 let payload = r#"{"timeout":"1.5s"}"#;
18857 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18858 let msg = err.to_string();
18859 assert!(
18860 msg.contains("not a non-negative integer"),
18861 "expected integer-magnitude diagnostic in {msg:?}"
18862 );
18863 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
18864 assert!(
18865 msg.contains("\"1500ms\""),
18866 "missing canonical-form remediation in {msg:?}"
18867 );
18868 }
18869
18870 #[test]
18871 fn policy_timeout_serde_rejects_leading_plus_sign() {
18872 // Pin the leading-`+` arm cross-slot — the prior f64 parser
18873 // accepted `"+30s"` silently and round-tripped to `"30s"`.
18874 let payload = r#"{"timeout":"+30s"}"#;
18875 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18876 let msg = err.to_string();
18877 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
18878 }
18879
18880 #[test]
18881 fn circuit_breaker_window_serde_rejects_fractional_minutes() {
18882 // `CircuitBreaker::window` uses `with =
18883 // "supervisor::duration_codec_required"` (the required-Duration
18884 // variant that delegates to the same shared parser). `"0.5m"`
18885 // parsed to 30s and round-tripped to `"30s"` on next emit —
18886 // DRIFT closed.
18887 let payload = format!(
18888 r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
18889 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
18890 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
18891 );
18892 let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
18893 let msg = err.to_string();
18894 assert!(
18895 msg.contains("not a non-negative integer"),
18896 "expected integer-magnitude diagnostic in {msg:?}"
18897 );
18898 assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
18899 assert!(
18900 msg.contains("\"30s\""),
18901 "missing canonical-form remediation in {msg:?}"
18902 );
18903 }
18904
18905 #[test]
18906 fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
18907 // Pin the happy-path on the cross-slot side: every canonical
18908 // author shape `render` ever emits parses cleanly through the
18909 // shared codec on the `CircuitBreaker` slot. The
18910 // codec's accepted set (post-gate) is exactly its emitted set
18911 // for the integer-magnitude class.
18912 for window_lit in ["30s", "500ms", "2m", "1h"] {
18913 let payload = format!(
18914 r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
18915 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
18916 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
18917 );
18918 let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
18919 panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
18920 });
18921 assert_eq!(cb.max_failures, 5);
18922 }
18923 }
18924
18925 // ── rate_limit_codec: integer-magnitude gate ──
18926 //
18927 // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
18928 // / 737a676 / d53c922 trajectory landed on every typed-duration /
18929 // typed-byte-size codec in caixa-core lifts onto the fifth typed
18930 // codec — `rate_limit_codec` — through the digit-only magnitude
18931 // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
18932 // These tests pin the gate at the serde layer for `:politicas
18933 // :rate-limit` (the only typed slot the codec backs), and at the
18934 // codec-internal `parse` layer for the canonical positive cases.
18935
18936 #[test]
18937 fn rate_limit_serde_rejects_fractional_rate() {
18938 // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
18939 // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
18940 // wording, which didn't name the canonical-form remediation or
18941 // the round-trip drift the next emit would produce. Now refused
18942 // at deserialize with the canonical-form diagnostic naming the
18943 // offending `"1.5"` magnitude and the round-trip drift wording.
18944 let payload = r#"{"rateLimit":"1.5/s"}"#;
18945 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18946 let msg = err.to_string();
18947 assert!(
18948 msg.contains("not a non-negative integer"),
18949 "expected integer-magnitude diagnostic in {msg:?}"
18950 );
18951 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
18952 assert!(
18953 msg.contains("THEORY.md"),
18954 "missing render-determinism contract citation in {msg:?}"
18955 );
18956 }
18957
18958 #[test]
18959 fn rate_limit_serde_rejects_leading_plus_sign() {
18960 // `u32::from_str("+100")` returns `Ok(100)` (Rust's
18961 // permissive-`+` parse), so `"+100/s"` silently parsed to
18962 // `RateLimit { 100, 1s }` and round-tripped through `render` to
18963 // `"100/s"` — a *different* canonical string on the next emit,
18964 // breaking the THEORY.md Part V render-determinism contract
18965 // exactly the way the peer duration codecs' `"+30s"` case did.
18966 // This is the load-bearing class the digit-only gate closes
18967 // beyond what `u32::from_str`'s strictness covers on its own.
18968 let payload = r#"{"rateLimit":"+100/s"}"#;
18969 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18970 let msg = err.to_string();
18971 assert!(
18972 msg.contains("not a non-negative integer"),
18973 "expected integer-magnitude diagnostic in {msg:?}"
18974 );
18975 assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
18976 }
18977
18978 #[test]
18979 fn rate_limit_serde_rejects_leading_minus_sign() {
18980 // The signed-negative arm: `"-1/s"` lands on the
18981 // non-canonical-but-numeric branch via the `i64` fallback (the
18982 // `f64` parse also succeeds), surfacing the canonical-form
18983 // diagnostic. Replaces the prior value-laundered "not a u32"
18984 // wording with the unified diagnostic across signs.
18985 let payload = r#"{"rateLimit":"-1/s"}"#;
18986 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18987 let msg = err.to_string();
18988 assert!(
18989 msg.contains("not a non-negative integer"),
18990 "expected integer-magnitude diagnostic in {msg:?}"
18991 );
18992 assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
18993 }
18994
18995 #[test]
18996 fn rate_limit_serde_rejects_decimal_shaped_integer() {
18997 // `"100.0/s"` is integer-valued numerically but not in the
18998 // codec's accepted set — `render` emits `"100/s"`, so the
18999 // round-trip would drift. Lifted to the canonical-form
19000 // diagnostic peer with the duration codec's `"1.0s"` case
19001 // (1c55a2a).
19002 let payload = r#"{"rateLimit":"100.0/s"}"#;
19003 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19004 let msg = err.to_string();
19005 assert!(
19006 msg.contains("not a non-negative integer"),
19007 "expected integer-magnitude diagnostic in {msg:?}"
19008 );
19009 assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
19010 }
19011
19012 #[test]
19013 fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
19014 // Non-numeric, non-digit-only input lands on the existing
19015 // narrower `"not a u32"` arm (preserved for diagnostic-shape
19016 // stability on the parser-shape footgun case). Pin this so a
19017 // future relaxation of the numeric-fallback predicate doesn't
19018 // silently collapse garbage onto the canonical-form arm — same
19019 // partition the peer duration codecs draw between
19020 // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
19021 let payload = r#"{"rateLimit":"abc/s"}"#;
19022 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19023 let msg = err.to_string();
19024 assert!(
19025 msg.contains("not a u32"),
19026 "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
19027 );
19028 assert!(
19029 !msg.contains("not a non-negative integer"),
19030 "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
19031 );
19032 }
19033
19034 #[test]
19035 fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
19036 // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
19037 // u32's range. The digit-only gate passes; `u32::from_str`
19038 // fails on overflow. Surface that with the overflow-shaped
19039 // diagnostic naming the offending magnitude verbatim, peer
19040 // with `supervisor::duration_codec`'s overflow arm. Pinning
19041 // the wording so a future refactor doesn't silently collapse
19042 // overflow onto the canonical-form arm.
19043 let payload = r#"{"rateLimit":"4294967296/s"}"#;
19044 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19045 let msg = err.to_string();
19046 assert!(
19047 msg.contains("overflows u32"),
19048 "expected overflow diagnostic in {msg:?}"
19049 );
19050 assert!(
19051 msg.contains("\"4294967296\""),
19052 "missing offending magnitude in {msg:?}"
19053 );
19054 }
19055
19056 #[test]
19057 fn rate_limit_serde_rejects_leading_zero_magnitude() {
19058 // `"0100/s"` is digit-only, so the existing
19059 // non-digit-only / sign / fractional arm doesn't catch it —
19060 // `u32::from_str("0100")` returns `Ok(100)`, so before this
19061 // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
19062 // round-tripped through `render` to `"100/s"` — a *different*
19063 // canonical string on the next emit, breaking the THEORY.md
19064 // Part V render-determinism contract exactly the way the
19065 // peer `"+100/s"` case did before the leading-`+` arm landed.
19066 // This is the load-bearing class the leading-zero gate closes
19067 // beyond what the existing digit-only / sign / fractional
19068 // gates cover, and the peer arm to the leading-`+` test
19069 // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
19070 // canonical-form-drift axis.
19071 let payload = r#"{"rateLimit":"0100/s"}"#;
19072 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19073 let msg = err.to_string();
19074 assert!(
19075 msg.contains("non-canonical leading zero"),
19076 "expected leading-zero diagnostic in {msg:?}"
19077 );
19078 assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
19079 assert!(
19080 msg.contains("THEORY.md"),
19081 "missing render-determinism contract citation in {msg:?}"
19082 );
19083 }
19084
19085 #[test]
19086 fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
19087 // `"00/s"` is the degenerate leading-zero case — every byte
19088 // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
19089 // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
19090 // a *different* canonical string, same render-determinism
19091 // violation. The single-byte `"0/s"` itself is in the
19092 // accepted set (round-trips losslessly through `render`,
19093 // refused downstream by `PolicyRateLimitZero`); the
19094 // multi-byte `"00/s"` is not. Pins the boundary between the
19095 // accepted single-`0` and the rejected leading-zero class.
19096 let payload = r#"{"rateLimit":"00/s"}"#;
19097 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19098 let msg = err.to_string();
19099 assert!(
19100 msg.contains("non-canonical leading zero"),
19101 "expected leading-zero diagnostic in {msg:?}"
19102 );
19103 assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
19104 }
19105
19106 #[test]
19107 fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
19108 // Cross-window pin — the gate is window-agnostic; the
19109 // leading-zero class is a property of the magnitude, not the
19110 // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
19111 // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
19112 // single-window coverage extended across the three canonical
19113 // windows the codec accepts.
19114 let payload = r#"{"rateLimit":"007/h"}"#;
19115 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19116 let msg = err.to_string();
19117 assert!(
19118 msg.contains("non-canonical leading zero"),
19119 "expected leading-zero diagnostic in {msg:?}"
19120 );
19121 assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
19122 }
19123
19124 #[test]
19125 fn rate_limit_serde_rejects_leading_whitespace() {
19126 // `" 100/s"` — the canonical paste-from-aligned-doc /
19127 // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
19128 // the top-level `s.trim()` silently ate the leading space and
19129 // parsed the value to `RateLimit { 100, 1s }`, which then
19130 // round-tripped through `render` to `"100/s"` (a *different*
19131 // canonical string on the next emit) — the exact
19132 // canonical-form-drift class the leading-`+` / leading-zero
19133 // arms already close, extended to the whitespace byte class.
19134 let payload = r#"{"rateLimit":" 100/s"}"#;
19135 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19136 let msg = err.to_string();
19137 assert!(
19138 msg.contains("contains whitespace byte"),
19139 "expected whitespace diagnostic in {msg:?}"
19140 );
19141 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19142 assert!(
19143 msg.contains("THEORY.md"),
19144 "missing render-determinism contract citation in {msg:?}"
19145 );
19146 }
19147
19148 #[test]
19149 fn rate_limit_serde_rejects_trailing_whitespace() {
19150 // `"100/s "` — the canonical shell-history / trailing-space
19151 // paste footgun. Before this gate the top-level `s.trim()`
19152 // silently ate the trailing space and parsed to
19153 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
19154 // next emit — same canonical-form drift as the leading-space
19155 // sibling, closed on the same whitespace-byte arm.
19156 let payload = r#"{"rateLimit":"100/s "}"#;
19157 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19158 let msg = err.to_string();
19159 assert!(
19160 msg.contains("contains whitespace byte"),
19161 "expected whitespace diagnostic in {msg:?}"
19162 );
19163 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19164 }
19165
19166 #[test]
19167 fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
19168 // `"100 / s"` — the canonical typographically-spaced author
19169 // shape (the same idiom every prose reference to a rate limit
19170 // renders as, mistakenly retained when the value is pasted
19171 // into a codec-shaped slot). Before this gate the per-part
19172 // `rate_str.trim()` / `unit.trim()` calls silently ate both
19173 // spaces on either side of `/` and parsed to
19174 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
19175 // codec's *internal* whitespace-tolerance vector, orthogonal
19176 // to the leading / trailing surface but the same canonical-
19177 // form-drift class. Pins the arm as strictly stronger than the
19178 // pre-existing top-level `s.trim()` behavior: it fires on
19179 // whitespace anywhere in the value, not just at the string
19180 // boundary.
19181 let payload = r#"{"rateLimit":"100 / s"}"#;
19182 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19183 let msg = err.to_string();
19184 assert!(
19185 msg.contains("contains whitespace byte"),
19186 "expected whitespace diagnostic in {msg:?}"
19187 );
19188 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19189 }
19190
19191 #[test]
19192 fn rate_limit_serde_rejects_tab_byte() {
19193 // `"\t100/s"` — the canonical paste-from-indented-doc /
19194 // paste-from-YAML-block-scalar footgun where a tab byte leads
19195 // the magnitude. Pins that the gate covers tab (`0x09`) as
19196 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
19197 // members and both would be silently swallowed by `s.trim()`
19198 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
19199 // space alone to the full ASCII-whitespace set (space `0x20`,
19200 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
19201 // the tab arm as a representative of the non-space members.
19202 let payload = r#"{"rateLimit":"\t100/s"}"#;
19203 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19204 let msg = err.to_string();
19205 assert!(
19206 msg.contains("contains whitespace byte"),
19207 "expected whitespace diagnostic in {msg:?}"
19208 );
19209 assert!(
19210 msg.contains("0x09"),
19211 "missing offending tab byte in {msg:?}"
19212 );
19213 }
19214
19215 // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
19216 //
19217 // Successor to the ASCII-whitespace arm (1ad7755) on
19218 // `rate_limit_codec` — closes the strictly-complementary class the
19219 // byte-scan cannot see, through the lifted
19220 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
19221
19222 #[test]
19223 fn rate_limit_serde_rejects_leading_nbsp() {
19224 // NBSP prefix — paste-from-typography footgun. Byte-scan
19225 // misses, `str::trim` silently strips it, value drifts to
19226 // `"100/s"` on next serialize.
19227 let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
19228 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19229 let msg = err.to_string();
19230 assert!(
19231 msg.contains("non-ASCII Unicode whitespace character"),
19232 "expected non-ASCII whitespace diagnostic in {msg:?}"
19233 );
19234 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
19235 }
19236
19237 #[test]
19238 fn rate_limit_serde_rejects_internal_em_space() {
19239 // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
19240 // paste-from-typography footgun on the `<integer>/<unit>`
19241 // shape.
19242 let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
19243 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19244 let msg = err.to_string();
19245 assert!(
19246 msg.contains("non-ASCII Unicode whitespace character"),
19247 "expected non-ASCII whitespace diagnostic in {msg:?}"
19248 );
19249 assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
19250 }
19251
19252 #[test]
19253 fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
19254 // Positive-control pin: every ASCII-only canonical form the
19255 // renderer emits stays accepted through the new arm.
19256 for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
19257 let payload = format!(r#"{{"rateLimit":{lit}}}"#);
19258 let p: MeshPolicy = serde_json::from_str(&payload)
19259 .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
19260 assert!(p.rate_limit.is_some());
19261 }
19262 }
19263
19264 #[test]
19265 fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
19266 // The boundary case — `"0/s"` is the canonical form
19267 // `render(RateLimit { 0, 1s })` emits, so the codec accepts
19268 // it at the parse layer; the downstream
19269 // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
19270 // `rate == 0` at the typed-validate layer above. Pins the
19271 // partition: the leading-zero gate at the codec layer does
19272 // not poach the rate-zero semantic-validation arm at the
19273 // typed-validate layer above (a future stricter codec must
19274 // not reject `"0/s"` here, or it'd collapse the diagnostic
19275 // partitioning that lets `PolicyRateLimitZero` name the
19276 // offending typed slot).
19277 let payload = r#"{"rateLimit":"0/s"}"#;
19278 let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
19279 panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
19280 });
19281 let rl = policy.rate_limit.expect("rate_limit must be Some");
19282 assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
19283 assert_eq!(
19284 rl.window,
19285 Duration::from_secs(1),
19286 "single-`0` magnitude with `s` unit must parse to window=1s"
19287 );
19288 }
19289
19290 #[test]
19291 fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
19292 // The complementary boundary pin — every magnitude
19293 // `render` emits starts with `[1-9]` (or is the single byte
19294 // `"0"`), so the canonical-form predicate is `(len == 1) ||
19295 // (first byte != '0')`. Pinning the `len > 1 && first byte ==
19296 // '1'` case explicitly so a future tightening of the gate
19297 // (e.g. an over-eager "no leading digit < 5" rule, or a
19298 // mistakenly anchored start-of-magnitude byte check) lands
19299 // here before the canonical-forms-iterating test would catch
19300 // it.
19301 let payload = r#"{"rateLimit":"100/s"}"#;
19302 let policy: MeshPolicy = serde_json::from_str(payload)
19303 .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
19304 let rl = policy.rate_limit.expect("rate_limit must be Some");
19305 assert_eq!(
19306 rl.rate, 100,
19307 "canonical-100 magnitude must parse to rate=100"
19308 );
19309 }
19310
19311 #[test]
19312 fn rate_limit_serde_accepts_integer_canonical_forms() {
19313 // Pin the happy-path: every canonical author shape `render`
19314 // ever emits parses cleanly through the codec post-gate. The
19315 // codec's accepted set (post-gate) is exactly its emitted set
19316 // for the integer-magnitude class — same property
19317 // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
19318 // gates guarantee on the peer codecs. Iterating across rate
19319 // magnitudes (including `"0"`, which the codec accepts even
19320 // though `validate_politicas` rejects `rate == 0` at the typed
19321 // layer above) closes the codec contract at the parse layer
19322 // independently of the validate layer.
19323 for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
19324 for unit_lit in ["s", "m", "h"] {
19325 let lit = format!("{rate_lit}/{unit_lit}");
19326 let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
19327 let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
19328 panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
19329 });
19330 let rl = policy.rate_limit.expect("rate_limit must be Some");
19331 assert_eq!(
19332 rl.rate,
19333 rate_lit.parse::<u32>().unwrap(),
19334 "rate mismatch for {lit:?}"
19335 );
19336 }
19337 }
19338 }
19339
19340 #[test]
19341 fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
19342 // The structural property the gate enforces: serialize ∘
19343 // deserialize is the identity on every canonical author shape.
19344 // Peer of `parse_byte_size`'s and `parse_duration`'s
19345 // `_round_trips_through_render_for_every_canonical_form` tests
19346 // on the rate-limit axis. Before the gate, `"+100/s"` violated
19347 // this (`parse` → `RateLimit { 100, 1s }` → `render` →
19348 // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
19349 for rate in [1u32, 100, 5000, 1_000_000] {
19350 for (window, unit) in [
19351 (Duration::from_secs(1), "s"),
19352 (Duration::from_secs(60), "m"),
19353 (Duration::from_secs(3600), "h"),
19354 ] {
19355 let policy = MeshPolicy {
19356 rate_limit: Some(RateLimit { rate, window }),
19357 ..Default::default()
19358 };
19359 let json = serde_json::to_string(&policy).unwrap();
19360 let expected = format!("\"{rate}/{unit}\"");
19361 assert!(
19362 json.contains(&expected),
19363 "expected {expected:?} in {json:?}"
19364 );
19365 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19366 assert_eq!(
19367 back.rate_limit, policy.rate_limit,
19368 "round-trip for {json:?}"
19369 );
19370 }
19371 }
19372 }
19373
19374 // ── self-membership cross-slot gate ──────────────────────────────
19375
19376 #[test]
19377 fn validate_no_self_membership_rejects_self_named_membro() {
19378 // An Aplicacao whose `:membros` lists its own `:nome` is a
19379 // one-node lacre-closure recursion — rejected, naming the parent.
19380 let membros = vec![
19381 membro("catalog", "^0.1"),
19382 membro("checkout", "^0.1"),
19383 membro("cart", "^0.1"),
19384 ];
19385 let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
19386 assert!(
19387 matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
19388 "got {err:?}"
19389 );
19390 }
19391
19392 #[test]
19393 fn validate_no_self_membership_accepts_distinct_membros() {
19394 // Positive control: distinct member names (including a member
19395 // that is itself an Aplicacao — recursive composition is valid,
19396 // MESH-COMPOSITION §V) pass the gate.
19397 let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
19398 validate_no_self_membership(&membros, "checkout").unwrap();
19399 }
19400
19401 #[test]
19402 fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
19403 // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
19404 // `NoMembros` arm (the more-fundamental "graph must have nodes"
19405 // gate), not by this cross-slot self-edge gate. Keeping the
19406 // self-membership predicate vacuously-ok on the empty input
19407 // matches its supervisor-axis peer
19408 // (`validate_no_self_supervision_empty_children_is_ok`) and
19409 // makes the gate composable from any future call site (an M4
19410 // CR materializer's per-membros validator) without re-checking
19411 // emptiness.
19412 validate_no_self_membership(&[], "checkout").unwrap();
19413 }
19414
19415 #[test]
19416 fn validate_no_self_membership_diagnostic_names_offending_caixa() {
19417 // Pinning the Display: the self-membership diagnostic must name
19418 // the offending caixa verbatim + the "lists itself" framing the
19419 // author can grep for, so the cluster-far failure surfaces at
19420 // build time with one-line remediation. Same diagnostic shape
19421 // as the supervisor-axis `ChildSupervisesSelf` peer.
19422 let membros = vec![membro("orquestra", "^0.1")];
19423 let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
19424 let msg = err.to_string();
19425 assert!(
19426 msg.contains("orquestra"),
19427 "diagnostic must name the offending caixa nome (got: {msg:?})"
19428 );
19429 assert!(
19430 msg.contains("lists itself"),
19431 "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
19432 );
19433 }
19434
19435 #[test]
19436 fn default_servico_port_constant_pins_canonical_8080_literal() {
19437 // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
19438 // at the verbatim `8080` literal both consumers (the
19439 // `Entrada::port` serde default via [`default_port`] and the
19440 // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
19441 // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
19442 // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
19443 // discipline (a085b26) on the per-renderer canonical-K8s-axis
19444 // string-constant axis: a future refactor that drifts the
19445 // constant out from under either consumer surfaces here ahead
19446 // of every per-renderer's first emission. The literal value
19447 // matches the well-known HTTP-alt port the `pleme-computeunit`
19448 // library chart already emits as its `trigger.service.port`
19449 // default — by construction the same value the substrate
19450 // assumes about every Servico's in-cluster L4 listener.
19451 assert_eq!(
19452 DEFAULT_SERVICO_PORT, 8080,
19453 "canonical Servico port literal must remain `8080` verbatim — \
19454 this is the value both the `Entrada::port` serde default and the \
19455 caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
19456 );
19457 }
19458
19459 #[test]
19460 fn default_port_helper_returns_canonical_servico_port_constant() {
19461 // The bridge-arm — pins that the [`default_port`] helper
19462 // [`Entrada::port`]'s `#[serde(default = "default_port")]`
19463 // attribute hooks routes through the lifted
19464 // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
19465 // literal. A future refactor that re-introduces the `8080`
19466 // literal at the helper's return site (silently re-opening
19467 // the drift footgun this lift closed) surfaces here ahead of
19468 // every author-side `(:entrada (:host … :para …))` slot
19469 // without an explicit `:port`. Peer with the
19470 // `default_namespace_re_export_points_at_caixa_core_canonical`
19471 // pin on the caixa-mesh-side re-export axis.
19472 assert_eq!(
19473 default_port(),
19474 DEFAULT_SERVICO_PORT,
19475 "the serde-default helper must route through the lifted constant"
19476 );
19477 }
19478
19479 #[test]
19480 fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
19481 // The end-to-end pin — an author-surface `(:entrada (:host …
19482 // :para …))` without an explicit `:port` slot deserializes to
19483 // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
19484 // verbatim. Routes the canonical lifted constant through both
19485 // the serde-default machinery (the `#[serde(default =
19486 // "default_port")]` attribute) and the typed-value-shape
19487 // contract (the resulting [`Entrada::port`] value). A future
19488 // refactor that drifts either axis — replacing the serde
19489 // hook's helper, changing the typed slot's wire shape — would
19490 // surface here before any per-renderer's CNP / Gateway /
19491 // HTTPRoute emission consumed the drifted default.
19492 let entrada: Entrada =
19493 serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
19494 assert_eq!(
19495 entrada.port, DEFAULT_SERVICO_PORT,
19496 "the serde default must materialize as the lifted canonical Servico port"
19497 );
19498 }
19499
19500 #[test]
19501 fn servico_port_min_pins_canonical_accept_set_floor() {
19502 // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
19503 // verbatim `1` literal every typed `:entrada :port` acceptance
19504 // gate keys off. Peer with the
19505 // [`default_servico_port_constant_pins_canonical_8080_literal`]
19506 // discipline on the canonical-Servico-port-constant axis: a
19507 // future refactor that drifts the accept-set floor out from
19508 // under the sole consumer at [`AplicacaoSpec::validate`]'s
19509 // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
19510 // every per-`:entrada` `EntradaPortZero` diagnostic. The
19511 // literal value matches the IANA-registered TCP/UDP port
19512 // space floor (`1..=65535` — port `0` is the "any ephemeral"
19513 // sentinel, not a well-defined destination the substrate's
19514 // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
19515 // axis can honor).
19516 assert_eq!(
19517 SERVICO_PORT_MIN, 1,
19518 "canonical Servico port accept-set floor must remain `1` verbatim — \
19519 this is the value the `AplicacaoSpec::validate` gate at \
19520 `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
19521 );
19522 }
19523
19524 #[test]
19525 fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
19526 // The cross-const invariant pin — the substrate's canonical
19527 // default port must satisfy its own accept-set floor by
19528 // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
19529 // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
19530 // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
19531 // override the operator pins through a future
19532 // `:placement :default-port` slot that lands out-of-range, a
19533 // per-edition Servico-port migration that lifted the floor
19534 // above the previous default without coordinating the pair —
19535 // would silently invalidate the serde-default emission at
19536 // every author-side `(:entrada (:host … :para …))` slot
19537 // without an explicit `:port`: the default port would fall
19538 // below the accept-set floor, the `AplicacaoSpec::validate`
19539 // gate would reject every default-carrying Aplicacao as
19540 // `EntradaPortZero`, and the substrate's typed
19541 // `(defcaixa … :kind Aplicacao)` surface would fail validate
19542 // on every Aplicacao whose author omitted `:entrada :port`
19543 // for the substrate's chosen default — a class of authoring-
19544 // surface footguns the compile-time pin structurally closes.
19545 // Peer with the
19546 // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
19547 // (27f9b34) cross-const invariant pin discipline on the peer
19548 // canonical-Helm-per-values-block child-chart-enablement-toggle
19549 // axis pair.
19550 assert!(
19551 SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
19552 "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
19553 satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
19554 every default-carrying `(:entrada (:host … :para …))` slot without an \
19555 explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
19556 hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
19557 );
19558 }
19559
19560 #[test]
19561 fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
19562 // The gate-site pin — asserts the `AplicacaoSpec::validate`
19563 // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
19564 // `EntradaPortZero` diagnostic on the below-floor input
19565 // `port: 0` (the only below-floor value the `u16` field can
19566 // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
19567 // is the singleton `{0}`). A future refactor that drifts the
19568 // gate off the lifted const (silently re-introducing an
19569 // inline `if e.port == 0` byte-check) surfaces here — the
19570 // pin cannot distinguish `< 1` from `== 0` on the current
19571 // floor, but it *does* pin that the diagnostic fires on `0`
19572 // through whichever gate is wired, so any future accept-set
19573 // floor migration (a hypothetical unprivileged-only
19574 // migration lifting `SERVICO_PORT_MIN` to `1024`) must
19575 // update this test alongside the const declaration —
19576 // structurally guaranteeing the gate + accept-set + pin
19577 // trio move together. Peer with the
19578 // [`rejects_zero_entrada_port`] behavioral pin on the same
19579 // per-`:entrada :port` axis — that pin asserts the pre-lift
19580 // behavioral contract (`port: 0` → `EntradaPortZero`); this
19581 // pin adds the structural link to the lifted floor const.
19582 assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
19583 let mut s = three_member_spec();
19584 s.entrada.as_mut().unwrap().port = 0;
19585 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
19586 }
19587
19588 // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
19589
19590 #[test]
19591 fn membro_serde_keys_match_lifted_membro_key_consts() {
19592 // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
19593 // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
19594 // name the exact camelCase JSON keys the
19595 // `#[serde(rename_all = "camelCase")]` attribute on
19596 // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
19597 // that each canonical byte-sequence appears verbatim in the
19598 // JSON — a future accidental `rename_all = "snake_case"` /
19599 // `"kebab-case"` / verbatim-field-name flip at the derive
19600 // attribute (any of which would silently break every downstream
19601 // JSON consumer that reaches for one of the two consts via
19602 // `Value::get(...)`) surfaces here as a build-time test failure
19603 // at `aplicacao.rs`, not as an apply-time
19604 // `.get(<stale-canonical-const>)` returning `None` far from the
19605 // derive-attr drift's commit. Peer with the sibling
19606 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
19607 // (40cc4e5) pin on the M2 supervision-tree top-level axis —
19608 // same discipline the SupervisorSpec top-level lift established,
19609 // extended here to the M3 [`Membro`] per-`:membros` axis.
19610 let m = Membro {
19611 caixa: "catalog".into(),
19612 versao: "^0.1".into(),
19613 };
19614 let json = serde_json::to_string(&m).unwrap();
19615 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
19616 let quoted = format!("\"{key}\"");
19617 assert!(
19618 json.contains("ed),
19619 "serialized Membro must carry the lifted MEMBRO_KEY_* \
19620 byte-sequence {quoted} verbatim in the JSON emission \
19621 (got: {json})",
19622 );
19623 }
19624 }
19625
19626 #[test]
19627 fn membro_key_consts_are_pairwise_distinct() {
19628 // Cross-axis drift-detection pin: a future collapse of the two
19629 // canonical [`Membro`] per-entry byte-strings onto the same
19630 // value (e.g. an accidental copy-paste flip of
19631 // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
19632 // silently reroute every downstream probe on one axis onto the
19633 // sibling axis's overlay entry and pass every propagation-probe
19634 // test that expected only the stale axis's value. Peer of the
19635 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
19636 // (40cc4e5).
19637 let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
19638 for (i, a) in all.iter().enumerate() {
19639 for b in all.iter().skip(i + 1) {
19640 assert_ne!(
19641 a, b,
19642 "MEMBRO_KEY_* consts must be pairwise-distinct \
19643 canonical byte-sequences — got `{a}` == `{b}`",
19644 );
19645 }
19646 }
19647 }
19648
19649 // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
19650 // URL-path fallback resolver every HTTPRoute-aware renderer
19651 // reaching for a per-rule path-list resolution routes through.
19652 // The four pin tests below fix the four-way accept-set the
19653 // resolver must always honor: (:paths-non-empty-verbatim,
19654 // :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
19655 // :paths-preserves-order-across-multiple-entries) — drift on any
19656 // arm surfaces at caixa-core build time rather than at cluster-
19657 // apply time. Peer discipline with `MeshPolicy::is_empty` on the
19658 // sibling `:politicas` typed-primitive dispatch axis.
19659
19660 fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
19661 Entrada {
19662 host: "example.com".into(),
19663 para: "cart".into(),
19664 paths: paths.into_iter().map(String::from).collect(),
19665 port: DEFAULT_SERVICO_PORT,
19666 }
19667 }
19668
19669 #[test]
19670 fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
19671 // The typed `:entrada :paths` slot carries an author-declared
19672 // list — the resolver returns each entry verbatim, no
19673 // catch-all substitution. The canonical "author declared
19674 // paths, honor them verbatim" arm of the path-list dispatch.
19675 let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
19676 assert_eq!(
19677 e.resolved_paths(),
19678 vec!["/api/cart", "/api/products"],
19679 "resolved_paths must return each `:entrada :paths` entry \
19680 verbatim when the typed slot is non-empty (got {:?})",
19681 e.resolved_paths(),
19682 );
19683 }
19684
19685 #[test]
19686 fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
19687 // Empty `:entrada :paths` slot — the resolver substitutes the
19688 // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
19689 // catch-all fallback verbatim. Pins the empty-arm of the
19690 // resolver's four-way accept-set against a future silent
19691 // detour that returned an empty Vec (which would emit an
19692 // HTTPRoute with zero rules — silently dropping every
19693 // external `:entrada` flow at admission time), routed to a
19694 // different fallback shape, or dropped the catch-all
19695 // altogether.
19696 let e = entrada_with_paths(vec![]);
19697 assert_eq!(
19698 e.resolved_paths(),
19699 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
19700 "resolved_paths on empty `:entrada :paths` must fall back \
19701 to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
19702 all — got {:?}",
19703 e.resolved_paths(),
19704 );
19705 }
19706
19707 #[test]
19708 fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
19709 // Single-entry `:entrada :paths` — the resolver returns the
19710 // single declared path verbatim, NOT the catch-all fallback
19711 // (author declared a path, honor it — the empty-arm and the
19712 // len-1 arm are semantically distinct axes of the resolver's
19713 // accept-set). Pins that the resolver treats "author declared
19714 // one path" as authored input, not as the empty case.
19715 let e = entrada_with_paths(vec!["/api/only"]);
19716 assert_eq!(
19717 e.resolved_paths(),
19718 vec!["/api/only"],
19719 "resolved_paths on single-entry `:entrada :paths` must \
19720 return the declared path verbatim, NOT the catch-all \
19721 fallback (got {:?})",
19722 e.resolved_paths(),
19723 );
19724 }
19725
19726 #[test]
19727 fn resolved_paths_preserves_author_declared_order() {
19728 // The `:entrada :paths` list is author-ordered — the resolver
19729 // preserves the author's declaration order verbatim, since
19730 // per-rule dispatch order at the K8s Gateway API HTTPRoute
19731 // consumer is significant (first-match-wins under the
19732 // path-prefix matcher). Pins against a future silent
19733 // re-sort / dedup / normalize detour that reordered author
19734 // input.
19735 let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
19736 assert_eq!(
19737 e.resolved_paths(),
19738 vec!["/z/last", "/a/first", "/m/mid"],
19739 "resolved_paths must preserve author-declared `:entrada \
19740 :paths` order verbatim — got {:?}",
19741 e.resolved_paths(),
19742 );
19743 }
19744
19745 // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
19746 // slot `&[String]` slice accessor every per-`:entrada` consumer
19747 // that must see the author's declaration verbatim (not the
19748 // fallback-applied projection the sibling `resolved_paths`
19749 // returns) routes through. The three pin tests below fix the
19750 // accept-set the accessor must honor: (:non-empty-byte-equal,
19751 // :empty-projects-empty-slice, :preserves-author-declared-order)
19752 // — drift on any arm surfaces at caixa-core build time rather
19753 // than at cluster-apply time. Peer discipline with the sibling
19754 // [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
19755 // peer M3 mesh-slot `Vec<String>`-carry axis.
19756
19757 #[test]
19758 fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
19759 // Byte-equal pin: [`Entrada::paths`] must project the raw
19760 // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
19761 // slice borrowed from the typed slot's own [`Vec<String>`]
19762 // storage — no re-ordering, no dedup, no per-entry normalization,
19763 // no fallback substitution (the fallback-applying projection is
19764 // the sibling [`Entrada::resolved_paths`] resolver). Pins against
19765 // a future silent detour that re-normalized the list, dropped
19766 // duplicates the [`AplicacaoSpec::validate`]
19767 // `EntradaPathDuplicate` refusal already rejects at build time,
19768 // or (most severe) accidentally routed through the fallback-
19769 // applying sibling and returned the substrate catch-all when
19770 // the author declared an empty list — collapsing the raw-slot
19771 // and fallback-applied axes into one and breaking the
19772 // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
19773 //
19774 // Peer of the sibling
19775 // [`Placement::clusters`]-shape byte-equal pin
19776 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
19777 // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
19778 let fixtures: Vec<Vec<String>> = vec![
19779 Vec::new(),
19780 vec!["/api/cart".into()],
19781 vec!["/api/cart".into(), "/api/products".into()],
19782 vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
19783 ];
19784 for paths in fixtures {
19785 let e = Entrada {
19786 host: "example.com".into(),
19787 para: "cart".into(),
19788 paths: paths.clone(),
19789 port: DEFAULT_SERVICO_PORT,
19790 };
19791 assert_eq!(
19792 e.paths(),
19793 paths.as_slice(),
19794 "Entrada::paths must return :entrada :paths verbatim \
19795 (got {:?}, expected {:?})",
19796 e.paths(),
19797 paths.as_slice(),
19798 );
19799 assert_eq!(
19800 e.paths(),
19801 e.paths.as_slice(),
19802 "Entrada::paths accessor and .paths.as_slice() field \
19803 access must byte-equal — the accessor is the substrate-\
19804 primitive typed dispatch every downstream per-`:entrada` \
19805 raw-slot path-list consumer must route through",
19806 );
19807 assert_eq!(
19808 e.paths().len(),
19809 e.paths.len(),
19810 "Entrada::paths().len() must byte-equal self.paths.len() \
19811 — a length drift would silently split the paired \
19812 pre-flight cascade-head `.is_empty()` probe input in \
19813 the sibling [`Entrada::resolved_paths`] resolver from \
19814 the per-entry validate loop's traversal input in \
19815 [`AplicacaoSpec::validate`]",
19816 );
19817 }
19818 }
19819
19820 #[test]
19821 fn resolved_paths_reads_through_lifted_paths_accessor() {
19822 // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
19823 // pre-flight `.paths().is_empty()` cascade-head probe (which
19824 // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
19825 // catch-all fallback arm when the accessor projects the empty
19826 // slice) and the per-entry `.paths().iter().map(String::as_str)`
19827 // projection (which must reach every entry in the same order
19828 // the accessor projects, so the sibling
19829 // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
19830 // per-entry projection stay in lockstep by construction) must
19831 // both key off the lifted accessor. Pins the two-site coherence
19832 // by exercising each production consumer end-to-end: (1) the
19833 // catch-all-fallback arm under the empty slice, (2) the
19834 // author-declared-verbatim arm under a two-entry cohort whose
19835 // per-entry projection must byte-equal the input's per-entry
19836 // author-declared paths in the author's declared order.
19837 //
19838 // Peer of the sibling M3
19839 // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
19840 // `validate_placement_reads_through_lifted_clusters_accessor`
19841 // on the sibling `Placement::clusters` reader-site convergence.
19842 let empty = entrada_with_paths(vec![]);
19843 assert_eq!(
19844 empty.resolved_paths(),
19845 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
19846 "resolved_paths on empty :entrada :paths must trip the \
19847 lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
19848 catch-all fallback — routing through the lifted paths() \
19849 accessor must not silently drop the fallback arm",
19850 );
19851
19852 let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
19853 assert_eq!(
19854 declared.resolved_paths(),
19855 vec!["/api/cart", "/api/products"],
19856 "resolved_paths on non-empty :entrada :paths must return each \
19857 entry verbatim in the author's declared order — routing \
19858 through the lifted paths() accessor must not silently \
19859 reorder or drop entries",
19860 );
19861 // Byte-equal pin against the raw-slot accessor to keep the
19862 // fallback-applying resolver's per-entry projection input in
19863 // lockstep with the raw-slot accessor's projection.
19864 let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
19865 assert_eq!(
19866 declared.resolved_paths(),
19867 raw_projected,
19868 "resolved_paths non-empty projection must byte-equal the \
19869 lifted paths() accessor's per-entry String::as_str projection \
19870 — the two projections share the same input slice by \
19871 construction, so any drift here would surface a silent \
19872 re-ordering / dedup / normalization detour in the resolver",
19873 );
19874 }
19875
19876 #[test]
19877 fn validate_reads_through_lifted_entrada_paths_accessor() {
19878 // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
19879 // per-entry value-shape gate's `for p in e.paths()` traversal
19880 // (which must reach every entry in the same order the accessor
19881 // projects, so both the per-entry `EntradaPathEmpty` /
19882 // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
19883 // the duplicate-detection HashSet insert that trips
19884 // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
19885 // projection) must route through the lifted accessor. Pins the
19886 // coherence by exercising each production consumer end-to-end:
19887 // (1) the `EntradaPathEmpty` refusal fires on the second entry
19888 // of a two-entry cohort whose head is valid but tail is empty
19889 // (which requires the loop to reach the second entry through
19890 // the accessor), and (2) the `EntradaPathDuplicate` refusal
19891 // fires on the second entry of a two-entry cohort that shares
19892 // a path (which requires the loop to reach both entries — a
19893 // first-entry-only projection would silently pass since the
19894 // dedup HashSet has room for the first insert).
19895 //
19896 // Peer of the sibling
19897 // `validate_placement_reads_through_lifted_clusters_accessor`
19898 // on the sibling `Placement::clusters` reader-site convergence.
19899 let base = crate::AplicacaoSpec {
19900 membros: vec![crate::Membro {
19901 caixa: "cart".into(),
19902 versao: "^0.1".into(),
19903 }],
19904 contratos: Vec::new(),
19905 politicas: crate::MeshPolicy::default(),
19906 placement: crate::Placement {
19907 estrategia: crate::PlacementStrategy::SingleNode,
19908 clusters: vec!["rio".into()],
19909 shard_key: None,
19910 affinity: None,
19911 },
19912 entrada: Some(Entrada {
19913 host: "example.com".into(),
19914 para: "cart".into(),
19915 paths: vec!["/api/cart".into(), String::new()],
19916 port: DEFAULT_SERVICO_PORT,
19917 }),
19918 };
19919 assert_eq!(
19920 base.validate(),
19921 Err(crate::AplicacaoError::EntradaPathEmpty),
19922 "validate must trip EntradaPathEmpty on the second entry of \
19923 a two-entry cohort — routing through the lifted paths() \
19924 accessor must not silently short-circuit the loop at the \
19925 valid head entry",
19926 );
19927
19928 let mut dup = base;
19929 dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
19930 assert_eq!(
19931 dup.validate(),
19932 Err(crate::AplicacaoError::EntradaPathDuplicate {
19933 path: "/api/cart".into(),
19934 }),
19935 "validate must trip EntradaPathDuplicate on the second entry \
19936 of a two-entry cohort that shares a path — routing through \
19937 the lifted paths() accessor must not silently short-circuit \
19938 the dedup HashSet insert at the first entry",
19939 );
19940 }
19941
19942 // ── Entrada::hostname / Entrada::hostnames — the substrate-
19943 // canonical per-`:entrada` DNS-hostname resolver pair every
19944 // Gateway-API-aware renderer reaching for a per-listener
19945 // singular `hostname:` filter (Gateway) or a per-route plural
19946 // `spec.hostnames[]` filter list (HTTPRoute) routes through.
19947 // The three pin tests below fix the two-way accept-set the pair
19948 // must always honor: (:singular-byte-equal-to-host,
19949 // :plural-is-singleton-of-singular, :plural-len-is-one) — drift
19950 // on any arm surfaces at caixa-core build time rather than at
19951 // cluster-apply time when the API server refuses the HTTPRoute
19952 // for non-intersecting hostname filters. Peer discipline with
19953 // the sibling `resolved_paths` accept-set pin block above on the
19954 // per-`:entrada` path-list resolver axis.
19955
19956 fn entrada_with_host(host: &str) -> Entrada {
19957 Entrada {
19958 host: host.into(),
19959 para: "cart".into(),
19960 paths: Vec::new(),
19961 port: DEFAULT_SERVICO_PORT,
19962 }
19963 }
19964
19965 #[test]
19966 fn hostname_returns_entrada_host_byte_equal() {
19967 // The canonical singular-axis pin: [`Entrada::hostname`] must
19968 // return the `:entrada :host` field byte-for-byte, borrowed
19969 // from the typed slot's own [`String`] storage. Pins against a
19970 // future silent detour that re-normalized the host (an
19971 // accidental `.to_lowercase()` — validate_entrada_host already
19972 // enforces lowercase, so any re-normalization is redundant + a
19973 // drift surface between the validator and the accessor), a
19974 // trailing-`.` fully-qualified DNS shape substitution, or a
19975 // Punycode round-trip that lowered a Unicode host through IDNA.
19976 let e = entrada_with_host("checkout.quero.cloud");
19977 assert_eq!(
19978 e.hostname(),
19979 "checkout.quero.cloud",
19980 "Entrada::hostname must return :entrada :host verbatim \
19981 (got {:?})",
19982 e.hostname(),
19983 );
19984 assert_eq!(
19985 e.hostname(),
19986 e.host.as_str(),
19987 "Entrada::hostname must byte-equal the .host field access",
19988 );
19989 }
19990
19991 #[test]
19992 fn hostnames_returns_singleton_of_hostname_accessor() {
19993 // The pair-invariant pin: [`Entrada::hostnames`] must always
19994 // return exactly `vec![hostname()]` — the singleton list whose
19995 // sole entry is the substrate's canonical per-`:entrada`
19996 // singular hostname. Pins the two-consumer coherence axis: the
19997 // Gateway listener's singular `hostname:` filter and the
19998 // HTTPRoute's plural `spec.hostnames[]` filter list must
19999 // agree, else the Gateway API v1.x conformance layer rejects
20000 // the HTTPRoute at attach time with
20001 // `Accepted:False/NoMatchingParent` (the parent Gateway's
20002 // listener hostname doesn't intersect the route's hostname
20003 // filter list) — a divergence whose apply-time symptom is far
20004 // from any single-site commit and never surfaces in the
20005 // emitted YAML. Pinning the pair-invariant here makes any
20006 // future accidental split (an accidental `.to_string() + "."`
20007 // trailing-`.` on the plural side that didn't land on the
20008 // singular side, an accidental prefix stripping on one axis,
20009 // an accidental wildcard prepend the SNI fan-out overlay
20010 // authors on the plural side without a paired singular
20011 // migration) trip at caixa-core build time.
20012 let e = entrada_with_host("checkout.quero.cloud");
20013 assert_eq!(
20014 e.hostnames(),
20015 vec![e.hostname()],
20016 "Entrada::hostnames must return `vec![hostname()]` under \
20017 the pair-invariant — got {:?} vs. singleton {:?}",
20018 e.hostnames(),
20019 vec![e.hostname()],
20020 );
20021 }
20022
20023 #[test]
20024 fn hostnames_is_singleton_under_single_host_author_surface() {
20025 // The singleton-shape pin: under today's single-hostname-per-
20026 // `:entrada` author surface (the `:host` slot is a single
20027 // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
20028 // must always return a list of length exactly one. Pins
20029 // against a future silent detour that returned an empty list
20030 // (which would emit an HTTPRoute with `spec.hostnames: []` —
20031 // matching every incoming Host header regardless of the
20032 // Aplicacao's declared ingress apex, silently over-matching
20033 // every foreign VirtualHost the parent Gateway also fronts) or
20034 // a duplicated entry (which the Gateway API v1.x parser
20035 // accepts as a `[]-length-2 list of equal hostnames]` but
20036 // whose semantics differ from the intended singleton). The
20037 // author-surface extension point ("a future `:entrada
20038 // :alt-hosts` list overlay" the docstring names) is the sole
20039 // future axis that flips this pin — that migration will re-
20040 // author this test to pin the new plural cardinality.
20041 let e = entrada_with_host("checkout.quero.cloud");
20042 assert_eq!(
20043 e.hostnames().len(),
20044 1,
20045 "Entrada::hostnames must be a singleton under today's \
20046 single-hostname-per-`:entrada` author surface — got \
20047 length {}: {:?}",
20048 e.hostnames().len(),
20049 e.hostnames(),
20050 );
20051 }
20052
20053 // ── Entrada::destination — the substrate-canonical per-`:entrada`
20054 // destination-Servico scalar accessor every Gateway-API
20055 // HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
20056 // discriminator arg (HTTPRoute name composer) or a per-rule
20057 // `backendRefs[0].name` axis routes through. The two pin tests
20058 // below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
20059 // either arm surfaces at caixa-core build time rather than at
20060 // cluster-apply time when an HTTPRoute's `metadata.name` and
20061 // `backendRefs[]` silently disagree on which destination Servico
20062 // the ingress fronts. Peer discipline with the sibling
20063 // `resolved_paths` + `hostname` + `hostnames` accept-set pin
20064 // blocks above on the per-`:entrada` path-list / DNS-hostname
20065 // resolver axes.
20066
20067 #[test]
20068 fn destination_returns_entrada_para_byte_equal() {
20069 // The canonical destination-scalar pin: [`Entrada::destination`]
20070 // must return the `:entrada :para` field byte-for-byte, borrowed
20071 // from the typed slot's own [`String`] storage. Pins against a
20072 // future silent detour that re-normalized the destination (an
20073 // accidental `.to_lowercase()` — the destination Servico is
20074 // already validated as a DNS-1123 label upstream, so any
20075 // re-normalization is redundant + a drift surface between the
20076 // validator and the accessor), a namespace-prefix rewrite (an
20077 // accidental `format!("{namespace}/{para}")` per-CR fully-
20078 // qualified rewrite that didn't land on the peer axis), or a
20079 // per-cluster suffix stamp the operator authors on one
20080 // consumer without the other.
20081 for para in ["cart", "checkout", "catalog", "orders-v2"] {
20082 let e = Entrada {
20083 host: "checkout.quero.cloud".into(),
20084 para: para.into(),
20085 paths: Vec::new(),
20086 port: DEFAULT_SERVICO_PORT,
20087 };
20088 assert_eq!(
20089 e.destination(),
20090 para,
20091 "Entrada::destination must return :entrada :para verbatim \
20092 (got {:?}, expected {para:?})",
20093 e.destination(),
20094 );
20095 assert_eq!(
20096 e.destination(),
20097 e.para.as_str(),
20098 "Entrada::destination must byte-equal the .para field access",
20099 );
20100 }
20101 }
20102
20103 #[test]
20104 fn destination_borrows_from_entrada_para_storage() {
20105 // The borrow-not-copy pin: [`Entrada::destination`] must
20106 // return a `&str` slice that borrows from the typed slot's
20107 // own [`String`] storage — same-address invariant with
20108 // `entrada.para.as_str()`. Pins against a future silent detour
20109 // that allocated a fresh `String` (`self.para.clone()` in the
20110 // body would type-check but silently drop the borrow, and
20111 // every downstream consumer that assumed the returned slice
20112 // outlives `&self` would break on a stale-reference use-after-
20113 // free). Peer with the sibling `hostname_returns_entrada_
20114 // host_byte_equal` on the singular-DNS-hostname axis.
20115 let e = entrada_with_host("checkout.quero.cloud");
20116 let dest = e.destination();
20117 let para_slice = e.para.as_str();
20118 assert_eq!(
20119 dest.as_ptr(),
20120 para_slice.as_ptr(),
20121 "Entrada::destination must borrow from the .para String's \
20122 backing storage — a fresh allocation here means the \
20123 accessor no longer names the substrate-primitive typed \
20124 dispatch and every downstream consumer would silently \
20125 carry a detached copy",
20126 );
20127 assert_eq!(
20128 dest.len(),
20129 para_slice.len(),
20130 "Entrada::destination and .para.as_str() must byte-equal in \
20131 length as well as in address",
20132 );
20133 }
20134
20135 #[test]
20136 fn port_returns_entrada_port_verbatim_across_permutations() {
20137 // The canonical L4-port-scalar pin: [`Entrada::port`] must
20138 // return the `:entrada :port` field verbatim as a `u16` across
20139 // every author-declared value in the validated accept-set
20140 // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
20141 // silent detour that clamped the port (an accidental
20142 // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
20143 // land on the peer [`AplicacaoSpec::port_for_destination`]
20144 // resolver), rewrote it through a per-cluster port-remap table
20145 // the operator authors on one consumer without the other, or
20146 // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
20147 // serde-default value (which would silently collapse the
20148 // distinction between "author explicitly declared `:port 8080`"
20149 // and "author omitted the slot and inherited the default" the
20150 // future per-cluster override slot depends on). Peer with the
20151 // sibling `destination_returns_entrada_para_byte_equal` +
20152 // `hostname_returns_entrada_host_byte_equal` pins on the
20153 // per-`:entrada` `&str` scalar axes.
20154 for port in [
20155 SERVICO_PORT_MIN,
20156 DEFAULT_SERVICO_PORT,
20157 8443u16,
20158 9090u16,
20159 u16::MAX,
20160 ] {
20161 let e = Entrada {
20162 host: "checkout.quero.cloud".into(),
20163 para: "cart".into(),
20164 paths: Vec::new(),
20165 port,
20166 };
20167 assert_eq!(
20168 e.port(),
20169 port,
20170 "Entrada::port must return :entrada :port verbatim \
20171 (got {}, expected {port})",
20172 e.port(),
20173 );
20174 assert_eq!(
20175 e.port(),
20176 e.port,
20177 "Entrada::port accessor and .port field access must \
20178 byte-equal — the accessor is the substrate-primitive \
20179 typed dispatch every downstream L4-port consumer must \
20180 route through",
20181 );
20182 }
20183 }
20184
20185 #[test]
20186 fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
20187 // Two-consumer coherence pin: the
20188 // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
20189 // (which reads through [`Entrada::port`] to compare against
20190 // [`SERVICO_PORT_MIN`]) and the
20191 // [`AplicacaoSpec::port_for_destination`] resolver (which reads
20192 // through [`Entrada::port`] to emit the per-destination
20193 // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
20194 // lifted accessor, so any future rebrand on the typed slot's
20195 // reader shape lands at exactly one place. Pins the two-site
20196 // coherence by exercising a below-floor port through validate
20197 // (which must reject) and a validated in-accept-set port through
20198 // port_for_destination (which must emit the same value the
20199 // accessor returns).
20200 let mut spec = three_member_spec();
20201 if let Some(e) = spec.entrada.as_mut() {
20202 e.port = 0;
20203 }
20204 assert_eq!(
20205 spec.validate().unwrap_err(),
20206 AplicacaoError::EntradaPortZero,
20207 "validate must reject `:entrada :port 0` through the lifted \
20208 Entrada::port accessor — port zero lies below \
20209 SERVICO_PORT_MIN and the validator routes through port() \
20210 to name the floor",
20211 );
20212
20213 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
20214 let mut spec = three_member_spec();
20215 if let Some(e) = spec.entrada.as_mut() {
20216 e.port = port;
20217 }
20218 spec.validate().expect(
20219 "entrada with in-accept-set :port must validate — the \
20220 structural-floor gate reads through Entrada::port",
20221 );
20222 let entrada_ref = spec.entrada().expect(":entrada present");
20223 assert_eq!(
20224 spec.port_for_destination(entrada_ref.destination()),
20225 entrada_ref.port(),
20226 "port_for_destination(entrada.destination()) must equal \
20227 entrada.port() — the two consumers of the per-:entrada \
20228 L4-port axis (validator, per-destination resolver) both \
20229 route through Entrada::port",
20230 );
20231 }
20232 }
20233
20234 #[test]
20235 fn wit_contract_source_returns_de_byte_equal_across_permutations() {
20236 // The canonical caller-Servico-scalar pin: [`WitContract::source`]
20237 // must return the `:contratos :de` field byte-for-byte, borrowed
20238 // from the typed slot's own [`String`] storage. Peer of the
20239 // sibling `destination_returns_entrada_para_byte_equal` pin on
20240 // the per-`:entrada` axis — same "the substrate-primitive
20241 // accessor must byte-equal the raw field access verbatim across
20242 // every author-declared value" discipline extended to the
20243 // per-`:contratos` caller arm. Pins against a future silent
20244 // detour that re-normalized the caller (an accidental
20245 // `.to_lowercase()` — every `:contratos :de` is validated as a
20246 // DNS-1123 label upstream via `validate_contrato_caixa`, so any
20247 // re-normalization is redundant + a drift surface between the
20248 // validator and the accessor), a namespace-prefix rewrite (an
20249 // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
20250 // rewrite that didn't land on the peer axis), or a per-cluster
20251 // suffix stamp the operator authors on one consumer without the
20252 // other.
20253 for de in ["cart", "checkout", "catalog", "orders-v2"] {
20254 let c = WitContract {
20255 de: de.into(),
20256 para: "downstream".into(),
20257 wit: "wasi:http/proxy".into(),
20258 endpoint: Some("/lookup".into()),
20259 subject: None,
20260 slot: None,
20261 };
20262 assert_eq!(
20263 c.source(),
20264 de,
20265 "WitContract::source must return :contratos :de verbatim \
20266 (got {:?}, expected {de:?})",
20267 c.source(),
20268 );
20269 assert_eq!(
20270 c.source(),
20271 c.de.as_str(),
20272 "WitContract::source must byte-equal the .de field access",
20273 );
20274 }
20275 }
20276
20277 #[test]
20278 fn wit_contract_source_borrows_from_de_storage() {
20279 // The borrow-not-copy pin: [`WitContract::source`] must return a
20280 // `&str` slice that borrows from the typed slot's own [`String`]
20281 // storage — same-address invariant with `c.de.as_str()`. Pins
20282 // against a future silent detour that allocated a fresh `String`
20283 // (`self.de.clone()` in the body would type-check but silently
20284 // drop the borrow, and every downstream consumer that assumed
20285 // the returned slice outlives `&self` would break on a stale-
20286 // reference use-after-free). Peer of the sibling
20287 // `destination_borrows_from_entrada_para_storage` on the
20288 // per-`:entrada` axis.
20289 let c = WitContract {
20290 de: "cart".into(),
20291 para: "catalog".into(),
20292 wit: "wasi:http/proxy".into(),
20293 endpoint: Some("/lookup".into()),
20294 subject: None,
20295 slot: None,
20296 };
20297 let src = c.source();
20298 let de_slice = c.de.as_str();
20299 assert_eq!(
20300 src.as_ptr(),
20301 de_slice.as_ptr(),
20302 "WitContract::source must borrow from the .de String's \
20303 backing storage — a fresh allocation here means the \
20304 accessor no longer names the substrate-primitive typed \
20305 dispatch and every downstream consumer would silently \
20306 carry a detached copy",
20307 );
20308 assert_eq!(
20309 src.len(),
20310 de_slice.len(),
20311 "WitContract::source and .de.as_str() must byte-equal in \
20312 length as well as in address",
20313 );
20314 }
20315
20316 #[test]
20317 fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
20318 // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
20319 // must return the `:contratos :para` field byte-for-byte,
20320 // borrowed from the typed slot's own [`String`] storage. Peer of
20321 // the sibling `destination_returns_entrada_para_byte_equal` on
20322 // the per-`:entrada` axis — both accessors name "the destination-
20323 // Servico byte-string" concept on their respective mesh-slot
20324 // atoms (per-ingress apex vs. per-typed-edge callee) and both
20325 // must project the underlying `.para` field verbatim so every
20326 // downstream renderer that composes them with peer accessors
20327 // (e.g. `spec.port_for_destination(c.destination())` at the CNP
20328 // per-edge L4 port emit site) reads the same byte-string the
20329 // author declared.
20330 for para in ["catalog", "payment", "orders", "inventory-v3"] {
20331 let c = WitContract {
20332 de: "cart".into(),
20333 para: para.into(),
20334 wit: "wasi:http/proxy".into(),
20335 endpoint: Some("/lookup".into()),
20336 subject: None,
20337 slot: None,
20338 };
20339 assert_eq!(
20340 c.destination(),
20341 para,
20342 "WitContract::destination must return :contratos :para \
20343 verbatim (got {:?}, expected {para:?})",
20344 c.destination(),
20345 );
20346 assert_eq!(
20347 c.destination(),
20348 c.para.as_str(),
20349 "WitContract::destination must byte-equal the .para \
20350 field access",
20351 );
20352 }
20353 }
20354
20355 #[test]
20356 fn wit_contract_destination_borrows_from_para_storage() {
20357 // The borrow-not-copy pin: [`WitContract::destination`] must
20358 // return a `&str` slice that borrows from the typed slot's own
20359 // [`String`] storage — same-address invariant with
20360 // `c.para.as_str()`. Peer of the sibling
20361 // `destination_borrows_from_entrada_para_storage` on the
20362 // per-`:entrada` axis.
20363 let c = WitContract {
20364 de: "cart".into(),
20365 para: "catalog".into(),
20366 wit: "wasi:http/proxy".into(),
20367 endpoint: Some("/lookup".into()),
20368 subject: None,
20369 slot: None,
20370 };
20371 let dest = c.destination();
20372 let para_slice = c.para.as_str();
20373 assert_eq!(
20374 dest.as_ptr(),
20375 para_slice.as_ptr(),
20376 "WitContract::destination must borrow from the .para \
20377 String's backing storage — a fresh allocation here means \
20378 the accessor no longer names the substrate-primitive typed \
20379 dispatch and every downstream consumer would silently \
20380 carry a detached copy",
20381 );
20382 assert_eq!(
20383 dest.len(),
20384 para_slice.len(),
20385 "WitContract::destination and .para.as_str() must byte-equal \
20386 in length as well as in address",
20387 );
20388 }
20389
20390 #[test]
20391 fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
20392 // The canonical per-`:contratos` WIT-world-reference scalar pin:
20393 // [`WitContract::world_ref`] must return the `:contratos :wit`
20394 // field byte-for-byte, borrowed from the typed slot's own
20395 // [`String`] storage. Sibling of the peer per-`:contratos`
20396 // [`WitContract::source`] / [`WitContract::destination`]
20397 // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
20398 // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
20399 // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
20400 // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
20401 // "the substrate-primitive accessor must byte-equal the raw
20402 // field access verbatim across every author-declared value"
20403 // discipline extended to the per-`:contratos` WIT-world arm.
20404 // Pins against a future silent detour that re-canonicalized the
20405 // WIT world reference (an accidental `.to_lowercase()` pass that
20406 // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
20407 // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
20408 // gate is already lowercase-prefixed so any re-normalization is
20409 // redundant + a drift surface between the validator and the
20410 // accessor), an M4-promotion-shape rewrite that formatted a
20411 // typed WIT-world enum through [`Display`] and silently drifted
20412 // the printer output from the source `caixa.lisp`, or a per-
20413 // cluster WIT-alias rewrite that didn't land on the peer field-
20414 // access sites. Five values sweep the shape-dispatch accept-set
20415 // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
20416 // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
20417 // `wasi:keyvalue/`).
20418 for (wit, endpoint, subject, slot) in [
20419 ("wasi:http/proxy", Some("/lookup"), None, None),
20420 ("http:proxy", Some("/health"), None, None),
20421 ("nats:pub-sub", None, Some("orders.paid"), None),
20422 ("kafka:events", None, Some("checkout-events"), None),
20423 ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
20424 ] {
20425 let c = WitContract {
20426 de: "cart".into(),
20427 para: "downstream".into(),
20428 wit: wit.into(),
20429 endpoint: endpoint.map(str::to_string),
20430 subject: subject.map(str::to_string),
20431 slot: slot.map(str::to_string),
20432 };
20433 assert_eq!(
20434 c.world_ref(),
20435 wit,
20436 "WitContract::world_ref must return :contratos :wit \
20437 verbatim (got {:?}, expected {wit:?})",
20438 c.world_ref(),
20439 );
20440 assert_eq!(
20441 c.world_ref(),
20442 c.wit.as_str(),
20443 "WitContract::world_ref must byte-equal the .wit field \
20444 access",
20445 );
20446 }
20447 }
20448
20449 #[test]
20450 fn wit_contract_world_ref_borrows_from_wit_storage() {
20451 // The borrow-not-copy pin: [`WitContract::world_ref`] must
20452 // return a `&str` slice that borrows from the typed slot's own
20453 // [`String`] storage — same-address invariant with
20454 // `c.wit.as_str()`. Pins against a future silent detour that
20455 // allocated a fresh `String` (`self.wit.clone()` in the body
20456 // would type-check but silently drop the borrow, and every
20457 // downstream consumer that assumed the returned slice outlives
20458 // `&self` would break on a stale-reference use-after-free — the
20459 // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
20460 // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
20461 // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
20462 // / [`is_pubsub`][WitContract::is_pubsub] /
20463 // [`is_store`][WitContract::is_store] methods route through —
20464 // each borrow from the WitContract's own storage and each would
20465 // silently misbehave if this accessor produced a detached copy).
20466 // Peer of the sibling per-`:contratos` [`WitContract::source`] /
20467 // [`WitContract::destination`] and per-`:entrada`
20468 // [`Entrada::destination`] / [`Entrada::hostname`] and
20469 // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
20470 // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
20471 let c = WitContract {
20472 de: "cart".into(),
20473 para: "catalog".into(),
20474 wit: "wasi:http/proxy".into(),
20475 endpoint: Some("/lookup".into()),
20476 subject: None,
20477 slot: None,
20478 };
20479 let world = c.world_ref();
20480 let wit_slice = c.wit.as_str();
20481 assert_eq!(
20482 world.as_ptr(),
20483 wit_slice.as_ptr(),
20484 "WitContract::world_ref must borrow from the .wit String's \
20485 backing storage — a fresh allocation here means the \
20486 accessor no longer names the substrate-primitive typed \
20487 dispatch and every downstream consumer would silently carry \
20488 a detached copy",
20489 );
20490 assert_eq!(
20491 world.len(),
20492 wit_slice.len(),
20493 "WitContract::world_ref and .wit.as_str() must byte-equal in \
20494 length as well as in address",
20495 );
20496 }
20497
20498 #[test]
20499 fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
20500 // Sibling-triple invariant pin composing all three per-`:contratos`
20501 // substrate-primitive typed dispatches — [`WitContract::source`]
20502 // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
20503 // [`WitContract::world_ref`] — at the joint
20504 // `(source(), destination(), world_ref())` call shape every
20505 // renderer that fans on per-edge caller-callee-shape identity
20506 // keys off. The invariant, evaluated per-contract:
20507 //
20508 // (c.source(), c.destination(), c.world_ref())
20509 // == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
20510 //
20511 // Closes the last unlifted per-`:contratos` scalar axis — every
20512 // downstream consumer that reads the triple now routes through
20513 // exactly three typed dispatches on the substrate primitive,
20514 // not two typed + one open-coded field access. A future refactor
20515 // that silently split any one accessor's projection (an
20516 // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
20517 // canonicalization that didn't reach the peer `source`/
20518 // `destination` arms, an accidental `source()` per-cluster
20519 // caller-alias rewrite that didn't land on the `world_ref` peer)
20520 // surfaces at caixa-core build time. Peer of the sibling per-
20521 // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
20522 // per-`:entrada` `(hostname(), destination())` (6db982c /
20523 // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
20524 // axes, extended to the per-`:contratos` triple.
20525 for (de, para, wit, endpoint, subject, slot) in [
20526 (
20527 "cart",
20528 "catalog",
20529 "wasi:http/proxy",
20530 Some("/lookup"),
20531 None,
20532 None,
20533 ),
20534 (
20535 "checkout",
20536 "orders",
20537 "nats:pub-sub",
20538 None,
20539 Some("orders.paid"),
20540 None,
20541 ),
20542 (
20543 "cart",
20544 "kv",
20545 "wasi:keyvalue/store",
20546 None,
20547 None,
20548 Some("carts/{cart_id}"),
20549 ),
20550 (
20551 "orders-v2",
20552 "inventory-v3",
20553 "http:proxy",
20554 Some("/reserve"),
20555 None,
20556 None,
20557 ),
20558 ] {
20559 let c = WitContract {
20560 de: de.into(),
20561 para: para.into(),
20562 wit: wit.into(),
20563 endpoint: endpoint.map(str::to_string),
20564 subject: subject.map(str::to_string),
20565 slot: slot.map(str::to_string),
20566 };
20567 assert_eq!(
20568 (c.source(), c.destination(), c.world_ref()),
20569 (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
20570 "(WitContract::source, ::destination, ::world_ref) must \
20571 project (.de, .para, .wit) verbatim across every author-\
20572 declared triple (got ({:?}, {:?}, {:?}), expected \
20573 ({de:?}, {para:?}, {wit:?}))",
20574 c.source(),
20575 c.destination(),
20576 c.world_ref(),
20577 );
20578 }
20579 }
20580
20581 #[test]
20582 fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
20583 // The canonical per-`:contratos` owned-form caller-callee-pair
20584 // pin: [`WitContract::edge_pair`] must return the
20585 // `(source(), destination())` tuple in owned form byte-for-byte,
20586 // projected through the lifted [`WitContract::source`] /
20587 // [`WitContract::destination`] scalar accessors. Pins the
20588 // composite-projection invariant on the per-`:contratos`
20589 // mesh-slot atom — every author-declared `(de, para)` pair must
20590 // round-trip verbatim through the substrate primitive's typed
20591 // dispatch, so the nine [`AplicacaoError`] diagnostic-
20592 // construction sites the accessor now feeds
20593 // ([`AplicacaoError::EmptyWit`],
20594 // [`AplicacaoError::ContratoEndpointEmpty`],
20595 // [`AplicacaoError::ContratoEndpointNotAbsolute`],
20596 // [`AplicacaoError::ContratoEndpointInvalid`],
20597 // [`AplicacaoError::ContratoSubjectEmpty`],
20598 // [`AplicacaoError::ContratoSubjectInvalid`],
20599 // [`AplicacaoError::ContratoSlotEmpty`],
20600 // [`AplicacaoError::ContratoSlotInvalid`],
20601 // [`AplicacaoError::ContratoDuplicate`]) all read the same
20602 // `(de, para)` label pair every author sees at the source
20603 // `caixa.lisp`. Pins against a future silent detour that swapped
20604 // the `.0` / `.1` arms (an accidental `(destination(),
20605 // source())` re-order in the body would silently invert every
20606 // downstream diagnostic's `de:` / `para:` label pair, silently
20607 // reversing the direction of every operator-facing typed error
20608 // arrow), a fresh-allocation shape drift (an accidental
20609 // `.to_string()` on one arm but not the other would leave the
20610 // owned/borrowed pair mismatched vs. the sibling `source()` /
20611 // `destination()` returns), or an M4 per-cluster caller/callee-
20612 // alias rewrite that landed on `source()` without reaching
20613 // `destination()` (or vice versa). Peer of the sibling per-
20614 // `:contratos` `(source, destination, world_ref)` triple
20615 // pin above on the mesh-slot-atom scalar-value axes, extended
20616 // to the owned-form pair-projection axis.
20617 for (de, para, wit, endpoint, subject, slot) in [
20618 (
20619 "cart",
20620 "catalog",
20621 "wasi:http/proxy",
20622 Some("/lookup"),
20623 None,
20624 None,
20625 ),
20626 (
20627 "checkout",
20628 "orders",
20629 "nats:pub-sub",
20630 None,
20631 Some("orders.paid"),
20632 None,
20633 ),
20634 (
20635 "cart",
20636 "kv",
20637 "wasi:keyvalue/store",
20638 None,
20639 None,
20640 Some("carts/{cart_id}"),
20641 ),
20642 (
20643 "orders-v2",
20644 "inventory-v3",
20645 "http:proxy",
20646 Some("/reserve"),
20647 None,
20648 None,
20649 ),
20650 ] {
20651 let c = WitContract {
20652 de: de.into(),
20653 para: para.into(),
20654 wit: wit.into(),
20655 endpoint: endpoint.map(str::to_string),
20656 subject: subject.map(str::to_string),
20657 slot: slot.map(str::to_string),
20658 };
20659 assert_eq!(
20660 c.edge_pair(),
20661 (de.to_string(), para.to_string()),
20662 "WitContract::edge_pair must return (:contratos :de, \
20663 :contratos :para) as an owned tuple verbatim (got {:?}, \
20664 expected ({de:?}, {para:?}))",
20665 c.edge_pair(),
20666 );
20667 }
20668 }
20669
20670 #[test]
20671 fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
20672 // The composition pin: [`WitContract::edge_pair`] must return
20673 // exactly `(source().to_string(), destination().to_string())` —
20674 // the owned form of the sibling accessor pair — so any future
20675 // refactor that silently re-authored the caller-arm / callee-arm
20676 // projection to bypass the lifted scalar accessors (an accidental
20677 // `(self.de.clone(), self.para.clone())` regression back to the
20678 // raw field-access shape, an M4-typed-caller-enum `Display`
20679 // re-canonicalization on `source()` that didn't reach
20680 // `edge_pair()`, a per-cluster alias rewrite the operator lands
20681 // on `destination()` without reaching this composite projection)
20682 // trips at caixa-core build time. Pins the "typed dispatch
20683 // composes with typed dispatch, not with raw field access"
20684 // discipline every downstream diagnostic-construction site now
20685 // routes through — a `de:` / `para:` label pair whose
20686 // projection silently drifted off the substrate primitive's
20687 // scalar accessors would silently split the diagnostic's self-
20688 // locating signal from the source `caixa.lisp` author's view.
20689 // Peer of the sibling per-`:politicas` `is_empty` /
20690 // `validate_politicas` accessor-routing-pin family on the M3
20691 // mesh-slot family (18575, 18739, 18918, 19140, 19371).
20692 let c = WitContract {
20693 de: "cart".into(),
20694 para: "catalog".into(),
20695 wit: "wasi:http/proxy".into(),
20696 endpoint: Some("/lookup".into()),
20697 subject: None,
20698 slot: None,
20699 };
20700 assert_eq!(
20701 c.edge_pair(),
20702 (c.source().to_string(), c.destination().to_string()),
20703 "WitContract::edge_pair must compose exactly \
20704 (source().to_string(), destination().to_string()) — a \
20705 bypass of either sibling accessor here would silently \
20706 decouple the composite-projection axis from the \
20707 substrate-primitive scalar accessors every downstream \
20708 consumer routes through",
20709 );
20710 }
20711
20712 #[test]
20713 fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
20714 {
20715 // The canonical per-`:contratos` owned-form
20716 // caller-callee-world-ref-triple pin:
20717 // [`WitContract::edge_triple`] must return the
20718 // `(source(), destination(), world_ref())` tuple in owned form
20719 // byte-for-byte, projected through the lifted
20720 // [`WitContract::source`] / [`WitContract::destination`] /
20721 // [`WitContract::world_ref`] scalar accessors. Pins the
20722 // composite-projection invariant on the per-`:contratos`
20723 // mesh-slot atom — every author-declared `(de, para, wit)`
20724 // triple must round-trip verbatim through the substrate
20725 // primitive's typed dispatch, so the nine
20726 // [`AplicacaoError`] diagnostic-construction sites the
20727 // accessor now feeds (the [`WitTarget`]-dispatch's eight
20728 // wrong-target / missing-target / invalid-wit / capability-
20729 // with-payload arms in [`WitContract::target`], plus the
20730 // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
20731 // diagnostic constructor in [`AplicacaoSpec::validate`]) all
20732 // read the same `(de, para, wit)` triple every author sees at
20733 // the source `caixa.lisp`. Pins against a future silent
20734 // detour that swapped any two arms (an accidental `(destination(),
20735 // source(), world_ref())` re-order in the body would silently
20736 // invert every downstream diagnostic's `de:` / `para:` label
20737 // pair, silently reversing the direction of every operator-
20738 // facing typed error arrow), a fresh-allocation shape drift
20739 // (an accidental `.to_string()` skipped on one arm would leave
20740 // the owned/borrowed triple mismatched vs. the sibling
20741 // `source()` / `destination()` / `world_ref()` returns), or an
20742 // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
20743 // canonicalization pass that landed on one accessor without
20744 // reaching the peers. Peer of the sibling per-`:contratos`
20745 // caller-callee-pair
20746 // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
20747 // pin on the mesh-slot-atom composite-projection axis,
20748 // extended to the triple-projection axis.
20749 for (de, para, wit, endpoint, subject, slot) in [
20750 (
20751 "cart",
20752 "catalog",
20753 "wasi:http/proxy",
20754 Some("/lookup"),
20755 None,
20756 None,
20757 ),
20758 (
20759 "checkout",
20760 "orders",
20761 "nats:pub-sub",
20762 None,
20763 Some("orders.paid"),
20764 None,
20765 ),
20766 (
20767 "cart",
20768 "kv",
20769 "wasi:keyvalue/store",
20770 None,
20771 None,
20772 Some("carts/{cart_id}"),
20773 ),
20774 (
20775 "orders-v2",
20776 "inventory-v3",
20777 "http:proxy",
20778 Some("/reserve"),
20779 None,
20780 None,
20781 ),
20782 ] {
20783 let c = WitContract {
20784 de: de.into(),
20785 para: para.into(),
20786 wit: wit.into(),
20787 endpoint: endpoint.map(str::to_string),
20788 subject: subject.map(str::to_string),
20789 slot: slot.map(str::to_string),
20790 };
20791 assert_eq!(
20792 c.edge_triple(),
20793 (de.to_string(), para.to_string(), wit.to_string()),
20794 "WitContract::edge_triple must return (:contratos :de, \
20795 :contratos :para, :contratos :wit) as an owned triple \
20796 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
20797 c.edge_triple(),
20798 );
20799 }
20800 }
20801
20802 #[test]
20803 fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
20804 // The composition pin: [`WitContract::edge_triple`] must return
20805 // exactly `(source().to_string(), destination().to_string(),
20806 // world_ref().to_string())` — the owned form of the sibling
20807 // scalar-accessor triple — so any future refactor that silently
20808 // re-authored one arm's projection to bypass the lifted scalar
20809 // accessors (an accidental `(self.de.clone(), self.para.clone(),
20810 // self.wit.clone())` regression back to the raw field-access
20811 // shape the internal `edge` closure and the ContratoDuplicate
20812 // diagnostic both carried before this lift landed, an
20813 // M4-typed-caller-enum `Display` re-canonicalization on
20814 // `source()` that didn't reach `edge_triple()`, a per-cluster
20815 // alias rewrite the operator lands on `destination()` /
20816 // `world_ref()` without reaching this composite projection)
20817 // trips at caixa-core build time. Pins the "typed dispatch
20818 // composes with typed dispatch, not with raw field access"
20819 // discipline every downstream diagnostic-construction site now
20820 // routes through — a `de:` / `para:` / `wit:` triple whose
20821 // projection silently drifted off the substrate primitive's
20822 // scalar accessors would silently split the diagnostic's self-
20823 // locating signal from the source `caixa.lisp` author's view.
20824 // Peer of the sibling per-`:contratos` edge_pair composition-
20825 // pin above on the mesh-slot-atom composite-projection axis.
20826 let c = WitContract {
20827 de: "cart".into(),
20828 para: "catalog".into(),
20829 wit: "wasi:http/proxy".into(),
20830 endpoint: Some("/lookup".into()),
20831 subject: None,
20832 slot: None,
20833 };
20834 assert_eq!(
20835 c.edge_triple(),
20836 (
20837 c.source().to_string(),
20838 c.destination().to_string(),
20839 c.world_ref().to_string(),
20840 ),
20841 "WitContract::edge_triple must compose exactly \
20842 (source().to_string(), destination().to_string(), \
20843 world_ref().to_string()) — a bypass of any sibling accessor \
20844 here would silently decouple the composite-projection axis \
20845 from the substrate-primitive scalar accessors every \
20846 downstream consumer routes through",
20847 );
20848 }
20849
20850 #[test]
20851 fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
20852 // The canonical semantics-pin: [`WitContract::edge_triple`] must
20853 // project the full `(de, para, wit)` identity of a `:contratos`
20854 // edge — the sub-triple every triple-carrying
20855 // [`AplicacaoError::Contrato*`] diagnostic weaves into its
20856 // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
20857 // missing-target, capability-with-payload, invalid-wit, and the
20858 // duplicate-gate). Rejects a drift in shape (an accidental
20859 // silent detour that returned a `(de, para)` pair or added an
20860 // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
20861 // would trip here because the return type would no longer
20862 // pattern-match the eight `let (de, para, wit) = edge();`
20863 // destructures the [`WitContract::target`] dispatch feeds off
20864 // + the paired duplicate-gate `let (de, para, wit) =
20865 // c.edge_triple();` destructure in
20866 // [`AplicacaoSpec::validate`]). Peer of the sibling per-
20867 // `:contratos` caller-callee-pair pin above extended to the
20868 // triple projection surface: closes the "one composite
20869 // accessor per typed diagnostic-construction sub-tuple"
20870 // discipline on the per-`:contratos` mesh-slot-atom axis.
20871 let c = WitContract {
20872 de: "checkout".into(),
20873 para: "orders".into(),
20874 wit: "nats:pub-sub".into(),
20875 endpoint: None,
20876 subject: Some("orders.paid".into()),
20877 slot: None,
20878 };
20879 let (de, para, wit) = c.edge_triple();
20880 assert_eq!(de, "checkout");
20881 assert_eq!(para, "orders");
20882 assert_eq!(wit, "nats:pub-sub");
20883 }
20884
20885 #[test]
20886 fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
20887 {
20888 // The composition pin: [`WitContract::identity`] must return
20889 // exactly `(source(), destination(), world_ref(), endpoint(),
20890 // subject(), slot())` — the borrowed form of the six-scalar-
20891 // accessor identity axis. Any future refactor that silently
20892 // re-authored one arm's projection to bypass a scalar accessor
20893 // (a `self.de.as_str()` regression back to raw field access on
20894 // any of the three required arms, a `self.endpoint.as_deref()`
20895 // regression on any of the three optional arms, an M4 per-
20896 // cluster caller/callee-alias rewrite the operator lands on
20897 // `source()` / `destination()` without reaching this composite
20898 // projection) trips at caixa-core build time. Sweeps four
20899 // permutations of the WIT-shape × payload lattice — HTTP with
20900 // endpoint, pub-sub with subject, store with slot, payload-less
20901 // capability — so every payload arm is exercised. Peer of the
20902 // sibling per-`:contratos`
20903 // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
20904 // composition pin on the mesh-slot-atom composite-projection
20905 // axis; extends the discipline from the (de, para, wit) prefix
20906 // onto the full-identity axis carrying the three payload arms.
20907 for (de, para, wit, endpoint, subject, slot) in [
20908 (
20909 "cart",
20910 "catalog",
20911 "wasi:http/proxy",
20912 Some("/lookup"),
20913 None,
20914 None,
20915 ),
20916 (
20917 "checkout",
20918 "orders",
20919 "nats:pub-sub",
20920 None,
20921 Some("orders.paid"),
20922 None,
20923 ),
20924 (
20925 "cart",
20926 "kv",
20927 "wasi:keyvalue/store",
20928 None,
20929 None,
20930 Some("carts/{cart_id}"),
20931 ),
20932 ("audit", "sink", "wasi:logging", None, None, None),
20933 ] {
20934 let c = WitContract {
20935 de: de.into(),
20936 para: para.into(),
20937 wit: wit.into(),
20938 endpoint: endpoint.map(str::to_owned),
20939 subject: subject.map(str::to_owned),
20940 slot: slot.map(str::to_owned),
20941 };
20942 assert_eq!(
20943 c.identity(),
20944 (
20945 c.source(),
20946 c.destination(),
20947 c.world_ref(),
20948 c.endpoint(),
20949 c.subject(),
20950 c.slot(),
20951 ),
20952 "WitContract::identity must compose exactly \
20953 (source(), destination(), world_ref(), endpoint(), \
20954 subject(), slot()) — a bypass of any sibling accessor \
20955 here would silently decouple the identity-projection \
20956 axis from the substrate-primitive scalar accessors \
20957 every dedup-key consumer routes through",
20958 );
20959 }
20960 }
20961
20962 #[test]
20963 fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
20964 // The canonical semantics-pin: [`WitContract::identity`] must
20965 // project the six-axis (de, para, wit, endpoint, subject, slot)
20966 // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
20967 // gate keys off — two `WitContract`s that agree on all six axes
20968 // are the same typed edge declared twice, the graph-edge
20969 // analogue of duplicate `:membros` / `:placement :clusters` /
20970 // `:entrada :paths` entries. Rejects a shape drift (an
20971 // accidental silent detour that returned a prefix tuple or
20972 // added an extra field) by pattern-matching the six-arm shape.
20973 // Peer of the sibling per-`:contratos`
20974 // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
20975 // pin extended from the (de, para, wit) prefix onto the full
20976 // six-axis identity that the dedup key rides.
20977 let c = WitContract {
20978 de: "cart".into(),
20979 para: "catalog".into(),
20980 wit: "wasi:http/proxy".into(),
20981 endpoint: Some("/products/:id".into()),
20982 subject: None,
20983 slot: None,
20984 };
20985 let (de, para, wit, endpoint, subject, slot) = c.identity();
20986 assert_eq!(de, "cart");
20987 assert_eq!(para, "catalog");
20988 assert_eq!(wit, "wasi:http/proxy");
20989 assert_eq!(endpoint, Some("/products/:id"));
20990 assert_eq!(subject, None);
20991 assert_eq!(slot, None);
20992
20993 // Two byte-identical contracts must produce equal identities —
20994 // the dedup key's foundational invariant.
20995 let c2 = c.clone();
20996 assert_eq!(c.identity(), c2.identity());
20997
20998 // Any change on any of the six axes must break the identity —
20999 // sweeps by mutating one axis at a time.
21000 let mut mutated = c.clone();
21001 mutated.de = "search".into();
21002 assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
21003 let mut mutated = c.clone();
21004 mutated.para = "warehouse".into();
21005 assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
21006 let mut mutated = c.clone();
21007 mutated.wit = "http:legacy".into();
21008 assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
21009 let mut mutated = c.clone();
21010 mutated.endpoint = Some("/search".into());
21011 assert_ne!(
21012 c.identity(),
21013 mutated.identity(),
21014 "endpoint axis must partition"
21015 );
21016 let mut mutated = c.clone();
21017 mutated.subject = Some("orders.paid".into());
21018 assert_ne!(
21019 c.identity(),
21020 mutated.identity(),
21021 "subject axis must partition"
21022 );
21023 let mut mutated = c;
21024 mutated.slot = Some("carts/{id}".into());
21025 assert_ne!(mutated.identity().5, None, "slot axis must partition");
21026 }
21027
21028 #[test]
21029 fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
21030 // The canonical per-`:contratos` structural-self-edge pin:
21031 // [`WitContract::is_self_loop`] must return `true` when the
21032 // `:de` and `:para` fields agree byte-for-byte, across every
21033 // WIT-shape variant the per-edge shape family carries. Pins
21034 // the shape-agnostic identity-space partition the
21035 // [`AplicacaoSpec::validate`] self-edge gate at
21036 // caixa-core/src/aplicacao.rs:5559 fires against — all four
21037 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
21038 // under the same one predicate. Four permutations sweep the
21039 // accept-set: HTTP with endpoint, pub-sub with subject, KV
21040 // store with slot, and payload-less capability.
21041 for (nome, wit, endpoint, subject, slot) in [
21042 ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
21043 ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
21044 (
21045 "kv",
21046 "wasi:keyvalue/store",
21047 None,
21048 None,
21049 Some("carts/{cart_id}"),
21050 ),
21051 ("audit", "wasi:logging", None, None, None),
21052 ] {
21053 let c = WitContract {
21054 de: nome.into(),
21055 para: nome.into(),
21056 wit: wit.into(),
21057 endpoint: endpoint.map(str::to_string),
21058 subject: subject.map(str::to_string),
21059 slot: slot.map(str::to_string),
21060 };
21061 assert!(
21062 c.is_self_loop(),
21063 "WitContract::is_self_loop must return true when \
21064 :contratos :de == :contratos :para (got false on \
21065 {nome:?} under {wit:?})",
21066 );
21067 }
21068 }
21069
21070 #[test]
21071 fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
21072 // The complement pin: [`WitContract::is_self_loop`] must return
21073 // `false` on every well-shaped inter-Servico contract (the
21074 // author-intended `:contratos` shape MESH-COMPOSITION §III.1
21075 // names — "Servico A calls Servico B" between two distinct
21076 // graph nodes). Pins against a future silent detour that
21077 // inverted the predicate (an accidental `!= ` swap for `==`
21078 // would silently reject every legitimate inter-Servico edge
21079 // and admit every self-edge — the exact inversion of the
21080 // author-intended shape). Four permutations sweep the same
21081 // WIT-shape accept-set the sibling positive-arm test carries.
21082 for (de, para, wit, endpoint, subject, slot) in [
21083 (
21084 "cart",
21085 "catalog",
21086 "wasi:http/proxy",
21087 Some("/lookup"),
21088 None,
21089 None,
21090 ),
21091 (
21092 "checkout",
21093 "orders",
21094 "nats:pub-sub",
21095 None,
21096 Some("orders.paid"),
21097 None,
21098 ),
21099 (
21100 "cart",
21101 "kv",
21102 "wasi:keyvalue/store",
21103 None,
21104 None,
21105 Some("carts/{cart_id}"),
21106 ),
21107 ("audit", "sink", "wasi:logging", None, None, None),
21108 ] {
21109 let c = WitContract {
21110 de: de.into(),
21111 para: para.into(),
21112 wit: wit.into(),
21113 endpoint: endpoint.map(str::to_string),
21114 subject: subject.map(str::to_string),
21115 slot: slot.map(str::to_string),
21116 };
21117 assert!(
21118 !c.is_self_loop(),
21119 "WitContract::is_self_loop must return false when \
21120 :contratos :de differs from :contratos :para (got true \
21121 on {de:?} → {para:?} under {wit:?})",
21122 );
21123 }
21124 }
21125
21126 #[test]
21127 fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
21128 // The composition pin: [`WitContract::is_self_loop`] must
21129 // resolve to exactly `self.source() == self.destination()` —
21130 // the equality probe of the sibling scalar-accessor pair — so
21131 // any future refactor that silently re-authored the predicate
21132 // to bypass the lifted scalar accessors (an accidental
21133 // `self.de == self.para` regression back to the raw field-
21134 // access shape, an M4-typed-caller-enum identity-comparison
21135 // rule that landed on `source()` without reaching
21136 // `destination()`, a per-cluster alias rewrite the operator
21137 // pins on `destination()` without reaching this predicate)
21138 // trips at caixa-core build time. Pins the "typed dispatch
21139 // composes with typed dispatch, not with raw field access"
21140 // discipline the sibling [`WitContract::edge_pair`] /
21141 // [`WitContract::edge_triple`] composite-projection accessors
21142 // already carry, extended onto the per-edge endpoint-equality
21143 // predicate axis. Positive and complement arms both fire.
21144 let self_edge = WitContract {
21145 de: "cart".into(),
21146 para: "cart".into(),
21147 wit: "wasi:http/proxy".into(),
21148 endpoint: Some("/lookup".into()),
21149 subject: None,
21150 slot: None,
21151 };
21152 assert_eq!(
21153 self_edge.is_self_loop(),
21154 self_edge.source() == self_edge.destination(),
21155 "WitContract::is_self_loop must compose exactly \
21156 `source() == destination()` — a bypass of either sibling \
21157 accessor here would silently decouple the endpoint-\
21158 equality predicate from the substrate-primitive scalar \
21159 accessors every downstream consumer routes through",
21160 );
21161 let inter_edge = WitContract {
21162 de: "cart".into(),
21163 para: "catalog".into(),
21164 wit: "wasi:http/proxy".into(),
21165 endpoint: Some("/lookup".into()),
21166 subject: None,
21167 slot: None,
21168 };
21169 assert_eq!(
21170 inter_edge.is_self_loop(),
21171 inter_edge.source() == inter_edge.destination(),
21172 "WitContract::is_self_loop must compose exactly \
21173 `source() == destination()` on the complement arm too",
21174 );
21175 }
21176
21177 #[test]
21178 fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
21179 // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
21180 // pin: [`WitContract::endpoint`] must return the `:contratos
21181 // :endpoint` field byte-for-byte, borrowed from the typed slot's
21182 // own `Option<String>` storage. Peer of the sibling
21183 // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
21184 // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
21185 // mesh-slot `Option<String>` optional-scalar axes — same "the
21186 // substrate-primitive accessor must byte-equal the raw field
21187 // access verbatim across every author-declared value" discipline
21188 // extended to the per-`:contratos` HTTP-payload-carrier arm.
21189 // Pins against a future silent detour that re-canonicalized the
21190 // endpoint (an accidental percent-encoding pass that didn't
21191 // reach the peer field-access site at the dedup key, a per-CR
21192 // fully-qualified prefix rewrite the operator authors on one
21193 // consumer without the other, or an M4 typed-path-template
21194 // `Display` re-canonicalization that silently drifted the
21195 // printer output from the source `caixa.lisp`). Four values
21196 // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
21197 // gate upstream admits (short root-path, dashed, param-shaped,
21198 // deep-hierarchy).
21199 for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
21200 let c = WitContract {
21201 de: "cart".into(),
21202 para: "catalog".into(),
21203 wit: "wasi:http/proxy".into(),
21204 endpoint: Some(endpoint.into()),
21205 subject: None,
21206 slot: None,
21207 };
21208 assert_eq!(
21209 c.endpoint(),
21210 Some(endpoint),
21211 "WitContract::endpoint must return :contratos :endpoint \
21212 verbatim (got {:?}, expected Some({endpoint:?}))",
21213 c.endpoint(),
21214 );
21215 assert_eq!(
21216 c.endpoint(),
21217 c.endpoint.as_deref(),
21218 "WitContract::endpoint must byte-equal the .endpoint \
21219 field's `.as_deref()` projection",
21220 );
21221 }
21222 }
21223
21224 #[test]
21225 fn wit_contract_endpoint_none_when_field_is_none() {
21226 // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
21227 // payload-carrier accessor pin: when the typed slot is absent —
21228 // the canonical shape under a non-HTTP `:wit` world per the
21229 // [`WitContract::target`]-enforced shape ↔ target partition
21230 // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
21231 // carries `:slot`, [`WitTarget::Capability`] carries none) —
21232 // [`WitContract::endpoint`] must return `None`. Pins against a
21233 // future silent detour that projected the absent slot to a
21234 // `Some("")` empty-string default (the canonical `Option<String>`
21235 // → `String` collapse footgun the sibling M2
21236 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21237 // emptiness predicates already guard on the peer M2 typed-slot
21238 // surfaces), a `Some("None")` stringified-None round-trip, or a
21239 // `Some` arm whose contents were derived from a sibling slot (an
21240 // accidental fallback to the `:subject` / `:slot` payload that
21241 // read the pub-sub / store payload into the endpoint axis).
21242 // Three contracts sweep the accept-set every non-HTTP `:wit`
21243 // world lands on — pub-sub NATS, key/value, and payload-less
21244 // capability.
21245 for (wit, subject, slot) in [
21246 ("nats:pub-sub", Some("orders.paid"), None),
21247 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
21248 ("wasi:cli/environment", None, None),
21249 ] {
21250 let c = WitContract {
21251 de: "cart".into(),
21252 para: "downstream".into(),
21253 wit: wit.into(),
21254 endpoint: None,
21255 subject: subject.map(str::to_string),
21256 slot: slot.map(str::to_string),
21257 };
21258 assert!(
21259 c.endpoint().is_none(),
21260 "WitContract::endpoint must return None when the typed \
21261 slot is absent under :wit {wit:?} (got {:?})",
21262 c.endpoint(),
21263 );
21264 assert_eq!(
21265 c.endpoint(),
21266 c.endpoint.as_deref(),
21267 "WitContract::endpoint must byte-equal the .endpoint \
21268 field's `.as_deref()` projection in the absent arm",
21269 );
21270 }
21271 }
21272
21273 #[test]
21274 fn wit_contract_endpoint_borrows_from_endpoint_storage() {
21275 // The borrow-not-copy pin: [`WitContract::endpoint`] must return
21276 // an `Option<&str>` whose `Some` arm borrows from the typed
21277 // slot's own [`String`] storage — same-address invariant with
21278 // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
21279 // detour that allocated a fresh `String`
21280 // (`self.endpoint.clone().map(...)` in the body would type-check
21281 // but silently drop the borrow, and every downstream consumer
21282 // that assumed the returned slice outlives `&self` would break
21283 // on a stale-reference use-after-free — the [`WitContract::target`]
21284 // Http-arm payload extraction rebinds the returned `Option<&str>`
21285 // through `.ok_or_else(...)` and threads the `&str` payload into
21286 // [`WitTarget::Http { endpoint: &'a str }`], the
21287 // [`AplicacaoSpec::validate`] duplicate-`:contratos`
21288 // [`ContratoIdentity`] dedup key threads the returned
21289 // `Option<&str>` into the six-tuple's HTTP arm — each borrow
21290 // from the WitContract's own storage and each would silently
21291 // misbehave if this accessor produced a detached copy). Peer of
21292 // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
21293 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
21294 // shaped optional-scalar axes — first extension of the
21295 // `Option<&str>` borrow-not-copy discipline onto the
21296 // per-`:contratos` HTTP-shaped payload-carrier axis.
21297 let c = WitContract {
21298 de: "cart".into(),
21299 para: "catalog".into(),
21300 wit: "wasi:http/proxy".into(),
21301 endpoint: Some("/lookup".into()),
21302 subject: None,
21303 slot: None,
21304 };
21305 let ep = c.endpoint().expect("Some arm");
21306 let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
21307 assert_eq!(
21308 ep.as_ptr(),
21309 storage_slice.as_ptr(),
21310 "WitContract::endpoint must borrow from the .endpoint \
21311 String's backing storage — a fresh allocation here means \
21312 the accessor no longer names the substrate-primitive typed \
21313 dispatch and every downstream consumer would silently \
21314 carry a detached copy",
21315 );
21316 assert_eq!(
21317 ep.len(),
21318 storage_slice.len(),
21319 "WitContract::endpoint and .endpoint.as_deref() must byte-\
21320 equal in length as well as in address",
21321 );
21322 }
21323
21324 #[test]
21325 fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
21326 // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
21327 // pin: [`WitContract::subject`] must return the `:contratos
21328 // :subject` field byte-for-byte, borrowed from the typed slot's
21329 // own `Option<String>` storage. Peer of the sibling per-`:contratos`
21330 // [`WitContract::endpoint`] (7020470) accessor pin on the M3
21331 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
21332 // optional-scalar axis — same "the substrate-primitive accessor
21333 // must byte-equal the raw field access verbatim across every
21334 // author-declared value" discipline extended to the pub-sub arm.
21335 // Pins against a future silent detour that re-canonicalized the
21336 // subject (an accidental `.to_lowercase()` normalization that
21337 // didn't reach the peer field-access site at the dedup key, a
21338 // per-CR fully-qualified prefix rewrite the operator authors on
21339 // one consumer without the other, or an M4 typed-subject-template
21340 // `Display` re-canonicalization that silently drifted the printer
21341 // output from the source `caixa.lisp`). Four values sweep the
21342 // NATS accept-set every pub-sub author-declared subject lands on
21343 // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
21344 for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
21345 let c = WitContract {
21346 de: "cart".into(),
21347 para: "notifier".into(),
21348 wit: "nats:pub-sub".into(),
21349 endpoint: None,
21350 subject: Some(subject.into()),
21351 slot: None,
21352 };
21353 assert_eq!(
21354 c.subject(),
21355 Some(subject),
21356 "WitContract::subject must return :contratos :subject \
21357 verbatim (got {:?}, expected Some({subject:?}))",
21358 c.subject(),
21359 );
21360 assert_eq!(
21361 c.subject(),
21362 c.subject.as_deref(),
21363 "WitContract::subject must byte-equal the .subject \
21364 field's `.as_deref()` projection",
21365 );
21366 }
21367 }
21368
21369 #[test]
21370 fn wit_contract_subject_none_when_field_is_none() {
21371 // The absent-`:subject` arm of the per-`:contratos` pub-sub-
21372 // shaped payload-carrier accessor pin: when the typed slot is
21373 // absent — the canonical shape under a non-pub-sub `:wit` world
21374 // per the [`WitContract::target`]-enforced shape ↔ target
21375 // partition ([`WitTarget::Http`] carries `:endpoint`,
21376 // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
21377 // carries none) — [`WitContract::subject`] must return `None`.
21378 // Pins against a future silent detour that projected the absent
21379 // slot to a `Some("")` empty-string default (the canonical
21380 // `Option<String>` → `String` collapse footgun the sibling M2
21381 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21382 // emptiness predicates already guard on the peer M2 typed-slot
21383 // surfaces), a `Some("None")` stringified-None round-trip, or a
21384 // `Some` arm whose contents were derived from a sibling slot (an
21385 // accidental fallback to the `:endpoint` / `:slot` payload that
21386 // read the HTTP / store payload into the subject axis). Three
21387 // contracts sweep the accept-set every non-pub-sub `:wit` world
21388 // lands on — HTTP proxy, key/value store, and payload-less
21389 // capability.
21390 for (wit, endpoint, slot) in [
21391 ("wasi:http/proxy", Some("/lookup"), None),
21392 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
21393 ("wasi:cli/environment", None, None),
21394 ] {
21395 let c = WitContract {
21396 de: "cart".into(),
21397 para: "downstream".into(),
21398 wit: wit.into(),
21399 endpoint: endpoint.map(str::to_string),
21400 subject: None,
21401 slot: slot.map(str::to_string),
21402 };
21403 assert!(
21404 c.subject().is_none(),
21405 "WitContract::subject must return None when the typed \
21406 slot is absent under :wit {wit:?} (got {:?})",
21407 c.subject(),
21408 );
21409 assert_eq!(
21410 c.subject(),
21411 c.subject.as_deref(),
21412 "WitContract::subject must byte-equal the .subject \
21413 field's `.as_deref()` projection in the absent arm",
21414 );
21415 }
21416 }
21417
21418 #[test]
21419 fn wit_contract_subject_borrows_from_subject_storage() {
21420 // The borrow-not-copy pin: [`WitContract::subject`] must return
21421 // an `Option<&str>` whose `Some` arm borrows from the typed
21422 // slot's own [`String`] storage — same-address invariant with
21423 // `c.subject.as_deref().unwrap()`. Pins against a future silent
21424 // detour that allocated a fresh `String`
21425 // (`self.subject.clone().map(...)` in the body would type-check
21426 // but silently drop the borrow, and every downstream consumer
21427 // that assumed the returned slice outlives `&self` would break
21428 // on a stale-reference use-after-free — the [`WitContract::target`]
21429 // PubSub-arm payload extraction rebinds the returned
21430 // `Option<&str>` through `.ok_or_else(...)` and threads the
21431 // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
21432 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21433 // [`ContratoIdentity`] dedup key threads the returned
21434 // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
21435 // from the WitContract's own storage and each would silently
21436 // misbehave if this accessor produced a detached copy). Peer of
21437 // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
21438 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
21439 // shaped optional-scalar axis — second extension of the
21440 // `Option<&str>` borrow-not-copy discipline onto the
21441 // per-`:contratos` payload-carrier family, this time on the
21442 // pub-sub arm.
21443 let c = WitContract {
21444 de: "cart".into(),
21445 para: "notifier".into(),
21446 wit: "nats:pub-sub".into(),
21447 endpoint: None,
21448 subject: Some("orders.paid".into()),
21449 slot: None,
21450 };
21451 let sub = c.subject().expect("Some arm");
21452 let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
21453 assert_eq!(
21454 sub.as_ptr(),
21455 storage_slice.as_ptr(),
21456 "WitContract::subject must borrow from the .subject \
21457 String's backing storage — a fresh allocation here means \
21458 the accessor no longer names the substrate-primitive typed \
21459 dispatch and every downstream consumer would silently \
21460 carry a detached copy",
21461 );
21462 assert_eq!(
21463 sub.len(),
21464 storage_slice.len(),
21465 "WitContract::subject and .subject.as_deref() must byte-\
21466 equal in length as well as in address",
21467 );
21468 }
21469
21470 #[test]
21471 fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
21472 // The canonical per-`:contratos` key/value-store-shaped
21473 // `:slot`-scalar pin: [`WitContract::slot`] must return the
21474 // `:contratos :slot` field byte-for-byte, borrowed from the
21475 // typed slot's own `Option<String>` storage. Peer of the
21476 // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
21477 // [`WitContract::subject`] (90de675) accessor pins on the M3
21478 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
21479 // optional-scalar axis — same "the substrate-primitive
21480 // accessor must byte-equal the raw field access verbatim
21481 // across every author-declared value" discipline extended to
21482 // the store arm. Pins against a future silent detour that
21483 // re-canonicalized the slot template (an accidental
21484 // `.to_lowercase()` bucket-prefix normalization that didn't
21485 // reach the peer field-access site at the dedup key, a per-CR
21486 // fully-qualified prefix rewrite the operator authors on one
21487 // consumer without the other, or an M4 typed-key-template
21488 // `Display` re-canonicalization that silently drifted the
21489 // printer output from the source `caixa.lisp`). Four values
21490 // sweep the wasi:keyvalue accept-set every store-shaped
21491 // author-declared slot lands on (flat bucket, single-param
21492 // template, multi-param template, nested-hierarchy template).
21493 for slot in [
21494 "sessions",
21495 "carts/{cart_id}",
21496 "orders/{tenant}/{order_id}",
21497 "cache/tenant-a/orders/{id}",
21498 ] {
21499 let c = WitContract {
21500 de: "cart".into(),
21501 para: "kv".into(),
21502 wit: "wasi:keyvalue/store".into(),
21503 endpoint: None,
21504 subject: None,
21505 slot: Some(slot.into()),
21506 };
21507 assert_eq!(
21508 c.slot(),
21509 Some(slot),
21510 "WitContract::slot must return :contratos :slot \
21511 verbatim (got {:?}, expected Some({slot:?}))",
21512 c.slot(),
21513 );
21514 assert_eq!(
21515 c.slot(),
21516 c.slot.as_deref(),
21517 "WitContract::slot must byte-equal the .slot field's \
21518 `.as_deref()` projection",
21519 );
21520 }
21521 }
21522
21523 #[test]
21524 fn wit_contract_slot_none_when_field_is_none() {
21525 // The absent-`:slot` arm of the per-`:contratos` store-shaped
21526 // payload-carrier accessor pin: when the typed slot is absent —
21527 // the canonical shape under a non-store `:wit` world per the
21528 // [`WitContract::target`]-enforced shape ↔ target partition
21529 // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
21530 // carries `:subject`, [`WitTarget::Capability`] carries none) —
21531 // [`WitContract::slot`] must return `None`. Pins against a
21532 // future silent detour that projected the absent slot to a
21533 // `Some("")` empty-string default (the canonical
21534 // `Option<String>` → `String` collapse footgun the sibling M2
21535 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21536 // emptiness predicates already guard on the peer M2 typed-slot
21537 // surfaces), a `Some("None")` stringified-None round-trip, or
21538 // a `Some` arm whose contents were derived from a sibling
21539 // slot (an accidental fallback to the `:endpoint` / `:subject`
21540 // payload that read the HTTP / pub-sub payload into the store
21541 // axis). Three contracts sweep the accept-set every non-store
21542 // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
21543 // payload-less capability.
21544 for (wit, endpoint, subject) in [
21545 ("wasi:http/proxy", Some("/lookup"), None),
21546 ("nats:pub-sub", None, Some("orders.paid")),
21547 ("wasi:cli/environment", None, None),
21548 ] {
21549 let c = WitContract {
21550 de: "cart".into(),
21551 para: "downstream".into(),
21552 wit: wit.into(),
21553 endpoint: endpoint.map(str::to_string),
21554 subject: subject.map(str::to_string),
21555 slot: None,
21556 };
21557 assert!(
21558 c.slot().is_none(),
21559 "WitContract::slot must return None when the typed \
21560 slot is absent under :wit {wit:?} (got {:?})",
21561 c.slot(),
21562 );
21563 assert_eq!(
21564 c.slot(),
21565 c.slot.as_deref(),
21566 "WitContract::slot must byte-equal the .slot field's \
21567 `.as_deref()` projection in the absent arm",
21568 );
21569 }
21570 }
21571
21572 #[test]
21573 fn wit_contract_slot_borrows_from_slot_storage() {
21574 // The borrow-not-copy pin: [`WitContract::slot`] must return
21575 // an `Option<&str>` whose `Some` arm borrows from the typed
21576 // slot's own [`String`] storage — same-address invariant with
21577 // `c.slot.as_deref().unwrap()`. Pins against a future silent
21578 // detour that allocated a fresh `String`
21579 // (`self.slot.clone().map(...)` in the body would type-check
21580 // but silently drop the borrow, and every downstream consumer
21581 // that assumed the returned slice outlives `&self` would
21582 // break on a stale-reference use-after-free — the
21583 // [`WitContract::target`] Store-arm payload extraction rebinds
21584 // the returned `Option<&str>` through `.ok_or_else(...)` and
21585 // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
21586 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21587 // [`ContratoIdentity`] dedup key threads the returned
21588 // `Option<&str>` into the six-tuple's store arm — each borrow
21589 // from the WitContract's own storage and each would silently
21590 // misbehave if this accessor produced a detached copy). Peer
21591 // of the sibling per-`:contratos` [`WitContract::endpoint`]
21592 // (7020470) / [`WitContract::subject`] (90de675)
21593 // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
21594 // shaped optional-scalar axis — third and final extension of
21595 // the `Option<&str>` borrow-not-copy discipline onto the
21596 // per-`:contratos` payload-carrier family, this time on the
21597 // store arm.
21598 let c = WitContract {
21599 de: "cart".into(),
21600 para: "kv".into(),
21601 wit: "wasi:keyvalue/store".into(),
21602 endpoint: None,
21603 subject: None,
21604 slot: Some("carts/{cart_id}".into()),
21605 };
21606 let slot = c.slot().expect("Some arm");
21607 let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
21608 assert_eq!(
21609 slot.as_ptr(),
21610 storage_slice.as_ptr(),
21611 "WitContract::slot must borrow from the .slot String's \
21612 backing storage — a fresh allocation here means the \
21613 accessor no longer names the substrate-primitive typed \
21614 dispatch and every downstream consumer would silently \
21615 carry a detached copy",
21616 );
21617 assert_eq!(
21618 slot.len(),
21619 storage_slice.len(),
21620 "WitContract::slot and .slot.as_deref() must byte-equal \
21621 in length as well as in address",
21622 );
21623 }
21624
21625 #[test]
21626 fn membro_nome_returns_caixa_byte_equal_across_permutations() {
21627 // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
21628 // [`Membro::nome`] must return the `:membros :caixa` field
21629 // byte-for-byte, borrowed from the typed slot's own [`String`]
21630 // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
21631 // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
21632 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
21633 // slot-atom scalar-value axes — same "the substrate-primitive
21634 // accessor must byte-equal the raw field access verbatim across
21635 // every author-declared value" discipline extended to the
21636 // per-`:membros` member-identity arm. Pins against a future
21637 // silent detour that re-normalized the member identity (an
21638 // accidental `.to_lowercase()` — every `:membros :caixa` is
21639 // validated as a DNS-1123 label upstream via
21640 // [`validate_membro_caixa`], so any re-normalization is
21641 // redundant + a drift surface between the validator and the
21642 // accessor), a namespace-prefix rewrite (an accidental
21643 // `format!("{namespace}/{caixa}")` per-CR fully-qualified
21644 // rewrite that didn't land on the peer axes), or a per-cluster
21645 // alias stamp the operator authors on one consumer without the
21646 // other. Four values sweep the accept-set the DNS-1123 gate
21647 // upstream admits (short single-word / dashed / v-suffixed
21648 // member names).
21649 for name in ["cart", "checkout", "catalog", "orders-v2"] {
21650 let m = Membro {
21651 caixa: name.into(),
21652 versao: "^0.1".into(),
21653 };
21654 assert_eq!(
21655 m.nome(),
21656 name,
21657 "Membro::nome must return :membros :caixa verbatim \
21658 (got {:?}, expected {name:?})",
21659 m.nome(),
21660 );
21661 assert_eq!(
21662 m.nome(),
21663 m.caixa.as_str(),
21664 "Membro::nome must byte-equal the .caixa field access",
21665 );
21666 }
21667 }
21668
21669 #[test]
21670 fn membro_nome_borrows_from_caixa_storage() {
21671 // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
21672 // slice that borrows from the typed slot's own [`String`]
21673 // storage — same-address invariant with `m.caixa.as_str()`. Pins
21674 // against a future silent detour that allocated a fresh `String`
21675 // (`self.caixa.clone()` in the body would type-check but
21676 // silently drop the borrow, and every downstream consumer that
21677 // assumed the returned slice outlives `&self` would break on a
21678 // stale-reference use-after-free — the `HashSet<&str>` collector
21679 // at [`AplicacaoSpec::validate`]'s `names` seed, the
21680 // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
21681 // [`AplicacaoSpec::detect_sync_cycles`], the
21682 // [`crate::render::insert_first_seen`] dedup key at
21683 // [`AplicacaoSpec::validate_membros`] — each borrow from the
21684 // Membro's own storage and each would silently misbehave if
21685 // this accessor produced a detached copy). Peer of the sibling
21686 // per-`:contratos` [`WitContract::source`] /
21687 // [`WitContract::destination`] and per-`:entrada`
21688 // [`Entrada::destination`] borrow-invariant pins on the mesh-
21689 // slot-atom scalar-value axes.
21690 let m = Membro {
21691 caixa: "checkout".into(),
21692 versao: "^0.1".into(),
21693 };
21694 let name = m.nome();
21695 let caixa_slice = m.caixa.as_str();
21696 assert_eq!(
21697 name.as_ptr(),
21698 caixa_slice.as_ptr(),
21699 "Membro::nome must borrow from the .caixa String's backing \
21700 storage — a fresh allocation here means the accessor no \
21701 longer names the substrate-primitive typed dispatch and \
21702 every downstream consumer would silently carry a detached \
21703 copy",
21704 );
21705 assert_eq!(
21706 name.len(),
21707 caixa_slice.len(),
21708 "Membro::nome and .caixa.as_str() must byte-equal in length \
21709 as well as in address",
21710 );
21711 }
21712
21713 #[test]
21714 fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
21715 // The canonical per-`:membros` member-`:versao`-scalar pin:
21716 // [`Membro::versao_requirement`] must return the
21717 // `:membros :versao` field byte-for-byte, borrowed from the typed
21718 // slot's own [`String`] storage. Sibling of the peer
21719 // `membro_nome_returns_caixa_byte_equal_across_permutations`
21720 // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
21721 // — same "the substrate-primitive accessor must byte-equal the
21722 // raw field access verbatim across every author-declared value"
21723 // discipline extended to the per-`:membros` member-`:versao`
21724 // requirement-string arm. Pins against a future silent detour
21725 // that re-canonicalized the requirement (an accidental
21726 // `.to_string()` via [`parse_requirement`] → [`Display`] round-
21727 // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
21728 // drifted the printer output away from the source `caixa.lisp`,
21729 // an accidental whitespace trim on `"^ 0.1"` that no consumer
21730 // ever produced from the field-access side, an accidental
21731 // per-cluster lacre-projected concrete-version rewrite that
21732 // didn't land on the peer field-access sites). Five values sweep
21733 // the accept-set the shared
21734 // [`crate::render::require_valid_versao_requirement`] gate
21735 // admits (caret / tilde / exact / wildcard / bare-major).
21736 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
21737 let m = Membro {
21738 caixa: "cart".into(),
21739 versao: req.into(),
21740 };
21741 assert_eq!(
21742 m.versao_requirement(),
21743 req,
21744 "Membro::versao_requirement must return :membros :versao \
21745 verbatim (got {:?}, expected {req:?})",
21746 m.versao_requirement(),
21747 );
21748 assert_eq!(
21749 m.versao_requirement(),
21750 m.versao.as_str(),
21751 "Membro::versao_requirement must byte-equal the .versao \
21752 field access",
21753 );
21754 }
21755 }
21756
21757 #[test]
21758 fn membro_versao_requirement_borrows_from_versao_storage() {
21759 // The borrow-not-copy pin: [`Membro::versao_requirement`] must
21760 // return a `&str` slice that borrows from the typed slot's own
21761 // [`String`] storage — same-address invariant with
21762 // `m.versao.as_str()`. Pins against a future silent detour that
21763 // allocated a fresh `String` (`self.versao.clone()` in the body
21764 // would type-check but silently drop the borrow, and every
21765 // downstream consumer that assumed the returned slice outlives
21766 // `&self` would break on a stale-reference use-after-free). Peer
21767 // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
21768 // per-`:contratos` [`WitContract::source`] /
21769 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
21770 // [`Entrada::destination`] (6db982c) borrow-invariant pins on
21771 // the mesh-slot-atom scalar-value axes.
21772 let m = Membro {
21773 caixa: "checkout".into(),
21774 versao: "^0.1".into(),
21775 };
21776 let req = m.versao_requirement();
21777 let versao_slice = m.versao.as_str();
21778 assert_eq!(
21779 req.as_ptr(),
21780 versao_slice.as_ptr(),
21781 "Membro::versao_requirement must borrow from the .versao \
21782 String's backing storage — a fresh allocation here means \
21783 the accessor no longer names the substrate-primitive typed \
21784 dispatch and every downstream consumer would silently carry \
21785 a detached copy",
21786 );
21787 assert_eq!(
21788 req.len(),
21789 versao_slice.len(),
21790 "Membro::versao_requirement and .versao.as_str() must byte-\
21791 equal in length as well as in address",
21792 );
21793 }
21794
21795 #[test]
21796 fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
21797 // Sibling-pair invariant pin composing both per-`:membros`
21798 // substrate-primitive typed dispatches — [`Membro::nome`]
21799 // (4a32abf) and [`Membro::versao_requirement`] — at the joint
21800 // `(nome(), versao_requirement())` call shape every renderer
21801 // that fans on per-member identity + version pin keys off. The
21802 // invariant, evaluated per-member:
21803 //
21804 // (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
21805 //
21806 // Closes the last unlifted per-`:membros` scalar axis — every
21807 // downstream consumer that reads the pair now routes through
21808 // exactly two typed dispatches on the substrate primitive, not
21809 // one typed + one open-coded field access. A future refactor
21810 // that silently split either accessor's projection (an
21811 // accidental `nome()` namespace-prefix rewrite that didn't
21812 // reach the peer, an accidental `versao_requirement()` lacre-
21813 // projected concrete-version rewrite that didn't land on the
21814 // `nome()` peer) surfaces at caixa-core build time. Peer of the
21815 // sibling per-`:entrada` `(hostname(), destination())` and
21816 // per-`:contratos` `(source(), destination())` pair invariants
21817 // on the mesh-slot-atom scalar-value axes.
21818 for (caixa, versao) in [
21819 ("cart", "^0.1"),
21820 ("checkout", "~0.1.2"),
21821 ("catalog", "0.1.0"),
21822 ("orders-v2", "*"),
21823 ] {
21824 let m = Membro {
21825 caixa: caixa.into(),
21826 versao: versao.into(),
21827 };
21828 assert_eq!(
21829 (m.nome(), m.versao_requirement()),
21830 (m.caixa.as_str(), m.versao.as_str()),
21831 "(Membro::nome, Membro::versao_requirement) must project \
21832 (.caixa, .versao) verbatim across every author-declared \
21833 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
21834 m.nome(),
21835 m.versao_requirement(),
21836 );
21837 }
21838 }
21839
21840 #[test]
21841 fn validate_membros_empty_gate_routes_through_nome_accessor() {
21842 // Composition pin: [`AplicacaoSpec::validate_membros`]'s
21843 // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
21844 // not the raw `.caixa` field access. Structurally: setting
21845 // ONLY the `.caixa` field to `""` on an otherwise-well-formed
21846 // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
21847 // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
21848 // (i.e. the empty string) — so the emptiness predicate the
21849 // refusal arm reaches under is the accessor-projected value,
21850 // not a peer field that would silently drift under a future
21851 // accessor-side rewrite.
21852 //
21853 // Pins against a future silent detour that (a) re-derived the
21854 // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
21855 // instead of `self.nome().is_empty()`, silently disagreeing with
21856 // every peer consumer (the `validate_membro_caixa(m.nome())`
21857 // call one line below, the dedup-key `insert_first_seen(&mut
21858 // seen, m.nome(), …)` two lines below, the emit-side per-
21859 // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
21860 // (b) accessor-side introduced a per-tenant alias arm the
21861 // caller was unaware of, silently rewriting an author-declared
21862 // `:caixa "checkout"` to `""` — the raw-field-access gate
21863 // would fail-open while the accessor-routed peer consumers
21864 // would fail-closed, splitting the diagnostic from the actual
21865 // failure surface.
21866 //
21867 // Peer of the sibling
21868 // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
21869 // (c0110f1) composition pin — same "the shape-gate predicate
21870 // must route through the substrate-primitive typed dispatch"
21871 // discipline extended onto the per-`:membros` empty-`:caixa`
21872 // refusal-arm axis. Closes the last unlifted `.caixa` production-
21873 // code read site on `Membro` — after this converge every
21874 // caixa-core `.caixa` field access outside the accessor's own
21875 // body is either a test-side field-setter (in-module tests
21876 // constructing invalid-shape inputs) or a doc-comment reference.
21877 let mut s = three_member_spec();
21878 s.membros[1].caixa = String::new();
21879 assert!(
21880 s.membros[1].nome().is_empty(),
21881 "Membro::nome must byte-equal the .caixa field access — an \
21882 accessor-side detour that no longer projects the raw field \
21883 would silently split this drift-detection test from the \
21884 validate() refusal arm",
21885 );
21886 assert_eq!(
21887 s.membros[1].nome(),
21888 s.membros[1].caixa.as_str(),
21889 "Membro::nome and .caixa.as_str() must byte-equal on an \
21890 empty-`:caixa` entry — the emptiness gate keys off the \
21891 accessor by construction",
21892 );
21893 assert_eq!(
21894 s.validate().unwrap_err(),
21895 AplicacaoError::MembroCaixaEmpty,
21896 "validate_membros' emptiness gate must fire MembroCaixaEmpty \
21897 on an entry whose accessor-projected `nome()` is empty",
21898 );
21899 }
21900
21901 #[test]
21902 fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
21903 // The canonical per-`:placement` Akka-cluster-sharding
21904 // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
21905 // the `:placement :shard-key` field byte-for-byte, borrowed
21906 // from the typed slot's own `Option<String>` storage. Peer of
21907 // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
21908 // per-`:contratos` [`WitContract::source`] /
21909 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
21910 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
21911 // slot-atom scalar-value axes — same "the substrate-primitive
21912 // accessor must byte-equal the raw field access verbatim across
21913 // every author-declared value" discipline extended to the
21914 // per-`:placement` Akka-cluster-sharding key extractor arm.
21915 // Pins against a future silent detour that re-normalized the
21916 // key (an accidental `.to_lowercase()` — every non-empty
21917 // `:shard-key` is validated as a printable-ASCII single-token
21918 // reference upstream via [`validate_placement_shard_key`], so
21919 // any re-normalization is redundant + a drift surface between
21920 // the validator and the accessor), a per-cluster alias rewrite
21921 // the operator authors on one consumer without the other, or an
21922 // accidental variable-prefix strip (`$tenantId` → `tenantId`)
21923 // that didn't land on the peer field-access sites. Four values
21924 // sweep the accept-set the shape gate admits — bare identifier,
21925 // `$`-prefixed variable, dotted path, `${}`-quoted variable —
21926 // the four canonical Akka-style entity-id extractor shapes the
21927 // future M4 cluster-sharding reconciler hashes.
21928 for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
21929 let p = Placement {
21930 estrategia: PlacementStrategy::Sharded,
21931 clusters: vec!["rio".into()],
21932 affinity: None,
21933 shard_key: Some(key.into()),
21934 };
21935 assert_eq!(
21936 p.shard_key(),
21937 Some(key),
21938 "Placement::shard_key must return :placement :shard-key \
21939 verbatim (got {:?}, expected Some({key:?}))",
21940 p.shard_key(),
21941 );
21942 assert_eq!(
21943 p.shard_key(),
21944 p.shard_key.as_deref(),
21945 "Placement::shard_key must byte-equal the .shard_key \
21946 field's `.as_deref()` projection",
21947 );
21948 }
21949 }
21950
21951 #[test]
21952 fn placement_shard_key_none_when_field_is_none() {
21953 // The absent-`:shard-key` arm of the per-`:placement`
21954 // Akka-cluster-sharding accessor pin: when the typed slot is
21955 // absent — the canonical shape under `:estrategia Replicated` /
21956 // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
21957 // enforced `shard_key.is_some() == matches!(estrategia,
21958 // Sharded)` partition — [`Placement::shard_key`] must return
21959 // `None`. Pins against a future silent detour that projected
21960 // the absent slot to a `Some("")` empty-string default (the
21961 // canonical `Option<String>` → `String` collapse footgun the
21962 // sibling M2 [`crate::LimitsSpec::is_empty`] /
21963 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
21964 // already guard on the peer M2 typed-slot surfaces), a
21965 // `Some("None")` stringified-None round-trip, or a `Some` arm
21966 // whose contents were derived from a sibling slot (an
21967 // accidental fallback to `estrategia.as_str()` that read the
21968 // strategy discriminator into the key axis). Two placements
21969 // sweep the accept-set every `validate`-passing non-`Sharded`
21970 // shape lands on — `Replicated` (Erlang/OTP distributed-app
21971 // takeover) and `SingleNode` (single-node hosting).
21972 for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
21973 let p = Placement {
21974 estrategia,
21975 clusters: vec!["rio".into()],
21976 affinity: None,
21977 shard_key: None,
21978 };
21979 assert!(
21980 p.shard_key().is_none(),
21981 "Placement::shard_key must return None when the typed \
21982 slot is absent under :estrategia {estrategia:?} (got {:?})",
21983 p.shard_key(),
21984 );
21985 assert_eq!(
21986 p.shard_key(),
21987 p.shard_key.as_deref(),
21988 "Placement::shard_key must byte-equal the .shard_key \
21989 field's `.as_deref()` projection in the absent arm",
21990 );
21991 }
21992 }
21993
21994 #[test]
21995 fn placement_shard_key_borrows_from_shard_key_storage() {
21996 // The borrow-not-copy pin: [`Placement::shard_key`] must return
21997 // an `Option<&str>` whose `Some` arm borrows from the typed
21998 // slot's own [`String`] storage — same-address invariant with
21999 // `p.shard_key.as_deref().unwrap()`. Pins against a future
22000 // silent detour that allocated a fresh `String`
22001 // (`self.shard_key.clone().map(...)` in the body would type-
22002 // check but silently drop the borrow, and every downstream
22003 // consumer that assumed the returned slice outlives `&self`
22004 // would break on a stale-reference use-after-free — the
22005 // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
22006 // gate's `Some(k)`-bound match arm reads `k: &str` under the
22007 // accessor's return type and would silently misbehave if this
22008 // accessor produced a detached copy). Peer of the sibling
22009 // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
22010 // [`WitContract::source`] / [`WitContract::destination`]
22011 // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
22012 // (6db982c) borrow-invariant pins on the mesh-slot-atom
22013 // scalar-value axes — first extension of the discipline onto
22014 // an `Option<String>`-shaped optional-scalar axis.
22015 let p = Placement {
22016 estrategia: PlacementStrategy::Sharded,
22017 clusters: vec!["rio".into()],
22018 affinity: None,
22019 shard_key: Some("tenantId".into()),
22020 };
22021 let key = p.shard_key().expect("Some arm");
22022 let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
22023 assert_eq!(
22024 key.as_ptr(),
22025 storage_slice.as_ptr(),
22026 "Placement::shard_key must borrow from the .shard_key \
22027 String's backing storage — a fresh allocation here means \
22028 the accessor no longer names the substrate-primitive typed \
22029 dispatch and every downstream consumer would silently \
22030 carry a detached copy",
22031 );
22032 assert_eq!(
22033 key.len(),
22034 storage_slice.len(),
22035 "Placement::shard_key and .shard_key.as_deref() must byte-\
22036 equal in length as well as in address",
22037 );
22038 }
22039
22040 #[test]
22041 fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
22042 // The canonical per-`:placement` M3-Adaptive-compression-hint
22043 // scalar pin: [`Placement::affinity`] must return the
22044 // `:placement :affinity` field byte-for-byte, borrowed from the
22045 // typed slot's own `Option<String>` storage. Peer of the sibling
22046 // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
22047 // pin on the sibling `Option<&str>` optional-scalar axis — same
22048 // "the substrate-primitive accessor must byte-equal the raw
22049 // field access verbatim across every author-declared value"
22050 // discipline extended to the peer per-`:placement` M3-Adaptive-
22051 // compression-hint arm. Pins against a future silent detour
22052 // that re-normalized the hint (an accidental `.to_lowercase()`
22053 // — every `:affinity` is already validated as a DNS-1123 label
22054 // upstream via [`validate_placement_affinity`], so any re-
22055 // normalization is redundant + a drift surface between the
22056 // validator and the accessor), a per-cluster alias rewrite the
22057 // operator authors on one consumer without the other, or an
22058 // accidental hint-family collapse (`low-latency` → `latency`
22059 // that dropped the qualifier prefix). Four values sweep the
22060 // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
22061 // canonical adaptive-compression-weight biases the future M4
22062 // placement engine reads.
22063 for hint in [
22064 "data-locality",
22065 "low-latency",
22066 "high-throughput",
22067 "cost-optimized",
22068 ] {
22069 let p = Placement {
22070 estrategia: PlacementStrategy::Replicated,
22071 clusters: vec!["rio".into()],
22072 affinity: Some(hint.into()),
22073 shard_key: None,
22074 };
22075 assert_eq!(
22076 p.affinity(),
22077 Some(hint),
22078 "Placement::affinity must return :placement :affinity \
22079 verbatim (got {:?}, expected Some({hint:?}))",
22080 p.affinity(),
22081 );
22082 assert_eq!(
22083 p.affinity(),
22084 p.affinity.as_deref(),
22085 "Placement::affinity must byte-equal the .affinity \
22086 field's `.as_deref()` projection",
22087 );
22088 }
22089 }
22090
22091 #[test]
22092 fn placement_affinity_none_when_field_is_none() {
22093 // The absent-`:affinity` arm of the per-`:placement`
22094 // M3-Adaptive-compression-hint accessor pin: when the typed
22095 // slot is absent — the canonical shape of an Aplicacao that
22096 // leaves the compression weighting up to the placement engine's
22097 // cluster-default arm — [`Placement::affinity`] must return
22098 // `None`. Pins against a future silent detour that projected
22099 // the absent slot to a `Some("")` empty-string default (the
22100 // canonical `Option<String>` → `String` collapse footgun the
22101 // sibling M2 [`crate::LimitsSpec::is_empty`] /
22102 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
22103 // already guard on the peer M2 typed-slot surfaces), a
22104 // `Some("None")` stringified-None round-trip, a `Some` arm
22105 // whose contents were derived from a sibling slot (an
22106 // accidental fallback to `estrategia.as_str()` that read the
22107 // strategy discriminator into the hint axis), or a
22108 // `Some("default")` implicit-default that would silently biases
22109 // the routing without the author having written one. Three
22110 // placements sweep the accept-set every `validate`-passing
22111 // `:affinity None` shape lands on — one per PlacementStrategy
22112 // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
22113 // with a shard-key), since `:affinity` is orthogonal to
22114 // `:estrategia` in the typed grammar.
22115 for (estrategia, shard_key) in [
22116 (PlacementStrategy::SingleNode, None),
22117 (PlacementStrategy::Replicated, None),
22118 (PlacementStrategy::Sharded, Some("tenantId".to_string())),
22119 ] {
22120 let p = Placement {
22121 estrategia,
22122 clusters: vec!["rio".into()],
22123 affinity: None,
22124 shard_key,
22125 };
22126 assert!(
22127 p.affinity().is_none(),
22128 "Placement::affinity must return None when the typed \
22129 slot is absent under :estrategia {estrategia:?} (got {:?})",
22130 p.affinity(),
22131 );
22132 assert_eq!(
22133 p.affinity(),
22134 p.affinity.as_deref(),
22135 "Placement::affinity must byte-equal the .affinity \
22136 field's `.as_deref()` projection in the absent arm",
22137 );
22138 }
22139 }
22140
22141 #[test]
22142 fn placement_affinity_borrows_from_affinity_storage() {
22143 // The borrow-not-copy pin: [`Placement::affinity`] must return
22144 // an `Option<&str>` whose `Some` arm borrows from the typed
22145 // slot's own [`String`] storage — same-address invariant with
22146 // `p.affinity.as_deref().unwrap()`. Pins against a future
22147 // silent detour that allocated a fresh `String`
22148 // (`self.affinity.clone().map(...)` in the body would type-
22149 // check but silently drop the borrow, and every downstream
22150 // consumer that assumed the returned slice outlives `&self`
22151 // would break on a stale-reference use-after-free — the
22152 // [`AplicacaoSpec::validate_placement`] per-hint value-shape
22153 // gate reads the accessor's `&str` return through the
22154 // [`validate_placement_affinity`] `&str` parameter and would
22155 // silently misbehave if this accessor produced a detached
22156 // copy). Peer of the sibling per-`:placement`
22157 // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
22158 // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
22159 // extends the discipline onto the sibling per-`:placement`
22160 // M3-Adaptive-compression-hint arm.
22161 let p = Placement {
22162 estrategia: PlacementStrategy::Replicated,
22163 clusters: vec!["rio".into()],
22164 affinity: Some("data-locality".into()),
22165 shard_key: None,
22166 };
22167 let hint = p.affinity().expect("Some arm");
22168 let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
22169 assert_eq!(
22170 hint.as_ptr(),
22171 storage_slice.as_ptr(),
22172 "Placement::affinity must borrow from the .affinity \
22173 String's backing storage — a fresh allocation here means \
22174 the accessor no longer names the substrate-primitive typed \
22175 dispatch and every downstream consumer would silently \
22176 carry a detached copy",
22177 );
22178 assert_eq!(
22179 hint.len(),
22180 storage_slice.len(),
22181 "Placement::affinity and .affinity.as_deref() must byte-\
22182 equal in length as well as in address",
22183 );
22184 }
22185
22186 #[test]
22187 fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
22188 // The canonical per-`:placement` distribution-strategy-scalar
22189 // pin: [`Placement::estrategia`] must return the `:placement
22190 // :estrategia` field verbatim as a [`PlacementStrategy`],
22191 // `Copy`-projected from the typed slot's own `PlacementStrategy`
22192 // storage across every variant in the closed accept-set
22193 // (`SingleNode` — Erlang/OTP distributed-app takeover;
22194 // `Replicated` — active-active across every named cluster;
22195 // `Sharded` — Akka-style hash-keyed entity distribution). Pins
22196 // against a future silent detour that re-derived the strategy
22197 // from a peer axis (an accidental fallback to
22198 // `if shard_key.is_some() { Sharded } else { Replicated }`
22199 // collapse that read the shard-key axis into the strategy
22200 // discriminator), a variant remap the operator authors on one
22201 // consumer without the other, or a stale-derive detour that
22202 // substituted [`PlacementStrategy::default`] when the field
22203 // held any explicit variant (which would silently collapse the
22204 // distinction between "author explicitly declared `:estrategia
22205 // Replicated`" and "author omitted the slot and inherited the
22206 // default" the future per-cluster override slot depends on).
22207 // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
22208 // pin on the `Copy`-return `u16` scalar axis — same "the
22209 // substrate-primitive accessor must byte-equal the raw field
22210 // access verbatim across every author-declared value" discipline
22211 // extended onto the per-`:placement` distribution-strategy
22212 // `Copy`-composite-enum scalar axis.
22213 for estrategia in [
22214 PlacementStrategy::SingleNode,
22215 PlacementStrategy::Replicated,
22216 PlacementStrategy::Sharded,
22217 ] {
22218 // Route the paired `:shard-key` fixture-builder through the
22219 // typed cross-slot invariant predicate
22220 // [`PlacementStrategy::requires_shard_key`] rather than the
22221 // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
22222 // arm-identity predicate — same discipline the sibling
22223 // `placement_strategy_variants_round_trip` fixture builder now
22224 // reads through.
22225 let shard_key = estrategia
22226 .requires_shard_key()
22227 .then(|| "tenantId".to_string());
22228 let p = Placement {
22229 estrategia,
22230 clusters: vec!["rio".into()],
22231 affinity: None,
22232 shard_key,
22233 };
22234 assert_eq!(
22235 p.estrategia(),
22236 estrategia,
22237 "Placement::estrategia must return :placement :estrategia \
22238 verbatim (got {:?}, expected {estrategia:?})",
22239 p.estrategia(),
22240 );
22241 assert_eq!(
22242 p.estrategia(),
22243 p.estrategia,
22244 "Placement::estrategia accessor and .estrategia field \
22245 access must byte-equal — the accessor is the substrate-\
22246 primitive typed dispatch every downstream distribution-\
22247 strategy consumer must route through",
22248 );
22249 }
22250 }
22251
22252 #[test]
22253 fn validate_placement_reads_through_lifted_estrategia_accessor() {
22254 // Three-consumer coherence pin: the
22255 // [`AplicacaoSpec::validate_placement`]
22256 // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
22257 // `estrategia:` field (which reads through
22258 // [`Placement::estrategia`] to name the strategy the empty
22259 // `:clusters` list was declared against), the same method's
22260 // `Sharded ↔ non-Sharded` `match` partition dispatch (which
22261 // reads through [`Placement::estrategia`] to fan across the
22262 // shape-gate cascades), and the non-`Sharded`-arm
22263 // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
22264 // `estrategia:` field (which reads through
22265 // [`Placement::estrategia`] to name the strategy the declared-
22266 // but-inert `:shard-key` was authored under) must all key off
22267 // the lifted accessor, so any future rebrand on the typed
22268 // slot's reader shape lands at exactly one place. Pins the
22269 // three-site coherence by exercising each error surface end-
22270 // to-end and asserting the surfaced `estrategia:` field byte-
22271 // equals the accessor's return. Peer of the sibling per-
22272 // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
22273 // pin on the M3 mesh-slot `Copy`-return scalar axis.
22274
22275 // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
22276 // whose `estrategia:` field must byte-equal the accessor's return
22277 // for every variant in the closed accept-set.
22278 for estrategia in [
22279 PlacementStrategy::SingleNode,
22280 PlacementStrategy::Replicated,
22281 PlacementStrategy::Sharded,
22282 ] {
22283 let mut spec = three_member_spec();
22284 spec.placement.estrategia = estrategia;
22285 spec.placement.clusters = Vec::new();
22286 // Route the paired `:shard-key` spec-mutator through the typed
22287 // cross-slot invariant predicate
22288 // [`PlacementStrategy::requires_shard_key`] rather than the
22289 // [`gen_platform::IsVariant`]-derived
22290 // [`PlacementStrategy::is_sharded`] arm-identity predicate —
22291 // same discipline the sibling
22292 // `placement_strategy_variants_round_trip` and
22293 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
22294 // fixture builders now read through.
22295 spec.placement.shard_key = estrategia
22296 .requires_shard_key()
22297 .then(|| "tenantId".to_string());
22298 let err = spec.validate().unwrap_err();
22299 match err {
22300 AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
22301 assert_eq!(
22302 e,
22303 spec.placement.estrategia(),
22304 "PlacementWithoutClusters.estrategia must byte-equal \
22305 Placement::estrategia() — the error carrier reads \
22306 through the lifted accessor",
22307 );
22308 }
22309 other => panic!(
22310 "expected PlacementWithoutClusters, got {other:?} for \
22311 estrategia={estrategia:?}"
22312 ),
22313 }
22314 }
22315
22316 // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
22317 // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
22318 // must byte-equal the accessor's return for both non-`Sharded`
22319 // strategies.
22320 for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
22321 let mut spec = three_member_spec();
22322 spec.placement.estrategia = estrategia;
22323 spec.placement.shard_key = Some("tenantId".into());
22324 let err = spec.validate().unwrap_err();
22325 match err {
22326 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
22327 assert_eq!(
22328 e,
22329 spec.placement.estrategia(),
22330 "ShardKeyOnNonSharded.estrategia must byte-equal \
22331 Placement::estrategia() — the non-Sharded-arm \
22332 refusal reads through the lifted accessor",
22333 );
22334 }
22335 other => panic!(
22336 "expected ShardKeyOnNonSharded, got {other:?} for \
22337 estrategia={estrategia:?}"
22338 ),
22339 }
22340 }
22341 }
22342
22343 // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
22344 //
22345 // The [`Placement::clusters`] accessor lift is the second slice-return
22346 // (`&[T]`) accessor on any typed slot — sibling to the seed M2
22347 // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
22348 // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
22349 // below cover (1) the accessor's byte-equal projection against the raw
22350 // field access across the empty / singleton / cohort fixtures the
22351 // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
22352 // and the per-cluster validate loop fan between, and (2) the two-
22353 // consumer coherence of the paired pre-flight refusal probe and the
22354 // per-cluster validate loop routing through the accessor on both arms.
22355
22356 #[test]
22357 fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
22358 // The canonical per-`:placement` cluster-pool-scalar-shape pin:
22359 // [`Placement::clusters`] must return the `:placement :clusters`
22360 // typed `Vec<String>` verbatim as a `&[String]` slice-view over
22361 // the same backing buffer the raw `self.clusters.as_slice()`
22362 // field access borrows from, byte-equal across every
22363 // representative fixture in the accept-set — the empty slice
22364 // (the pre-validation sentinel every
22365 // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
22366 // the singleton slice (the minimal `SingleNode`-shape cohort),
22367 // and multi-entry cohorts (the peer `Replicated` / `Sharded`
22368 // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
22369 //
22370 // Pins against a future silent detour that returned
22371 // `&Vec<String>` (which would type-check but leak the storage-
22372 // side `Vec`'s grow/push/reserve surface no consumer of the
22373 // typed view reaches for), a fresh-allocated `Vec<String>` copy
22374 // (which would type-check via a coercion but silently break
22375 // every downstream caller that relied on the slice sharing the
22376 // backing buffer's identity), or an out-of-order or length-
22377 // drifted projection (which would silently split the paired
22378 // pre-flight `.is_empty()` refusal probe's input from the per-
22379 // cluster validate loop's traversal input).
22380 //
22381 // Peer of the sibling M2
22382 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22383 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22384 // `:supervisor` static-child-list axis, extended onto the M3
22385 // per-`:placement` distribution-target-list `Vec`-carry axis.
22386 let fixtures: Vec<Vec<String>> = vec![
22387 Vec::new(),
22388 vec!["rio".into()],
22389 vec!["rio".into(), "mar".into()],
22390 vec!["rio".into(), "mar".into(), "plo".into()],
22391 ];
22392 for clusters in fixtures {
22393 let p = Placement {
22394 clusters: clusters.clone(),
22395 ..Placement::default()
22396 };
22397 assert_eq!(
22398 p.clusters(),
22399 clusters.as_slice(),
22400 "Placement::clusters must return :placement :clusters \
22401 verbatim (got {:?}, expected {:?})",
22402 p.clusters(),
22403 clusters.as_slice(),
22404 );
22405 assert_eq!(
22406 p.clusters(),
22407 p.clusters.as_slice(),
22408 "Placement::clusters accessor and .clusters.as_slice() \
22409 field access must byte-equal — the accessor is the \
22410 substrate-primitive typed dispatch every downstream \
22411 cluster-pool consumer must route through",
22412 );
22413 assert_eq!(
22414 p.clusters().len(),
22415 p.clusters.len(),
22416 "Placement::clusters().len() must byte-equal \
22417 self.clusters.len() — a length-drift would silently \
22418 split the paired pre-flight `.is_empty()` refusal \
22419 probe input from the per-cluster validate loop's \
22420 traversal input",
22421 );
22422 }
22423 }
22424
22425 #[test]
22426 fn validate_placement_reads_through_lifted_clusters_accessor() {
22427 // Two-consumer coherence pin: the
22428 // [`AplicacaoSpec::validate_placement`] pre-flight
22429 // `self.placement.clusters().is_empty()` refusal probe (which
22430 // must trip [`AplicacaoError::PlacementWithoutClusters`] when
22431 // the accessor projects the empty slice) and the per-cluster
22432 // validate loop's `for c in self.placement.clusters()`
22433 // traversal (which must reach every entry in the same order
22434 // the accessor projects, so both the per-entry value-shape
22435 // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
22436 // and the duplicate-detection HashSet insert that trips
22437 // [`AplicacaoError::PlacementClusterDuplicate`] key off the
22438 // accessor's projection) must both key off the lifted
22439 // accessor, so any future rebrand on the typed slot's reader
22440 // shape lands at exactly one place. Pins the two-site
22441 // coherence by exercising each production consumer end-to-end:
22442 // (1) the `PlacementWithoutClusters` refusal under the empty
22443 // slice, (2) the `PlacementClusterInvalid` refusal fires on
22444 // the second entry of a two-cluster cohort whose head is
22445 // valid but tail is not (which requires the loop to reach the
22446 // second entry through the accessor), and (3) the
22447 // `PlacementClusterDuplicate` refusal fires on the second
22448 // entry of a two-cluster cohort that shares a name (which
22449 // requires the loop to reach both entries — a first-entry-only
22450 // projection would silently pass since the dedup HashSet has
22451 // room for the first insert).
22452 //
22453 // Peer of the sibling M2
22454 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
22455 // (bc92bce) coherence pin on the per-`:supervisor` static-
22456 // child-list axis, extended onto the M3 per-`:placement`
22457 // distribution-target-list `Vec`-carry axis.
22458
22459 // (1) Pre-flight `.is_empty()` probe: the empty slice must
22460 // trip `PlacementWithoutClusters`.
22461 let mut spec = three_member_spec();
22462 spec.placement.clusters = Vec::new();
22463 match spec.validate().unwrap_err() {
22464 AplicacaoError::PlacementWithoutClusters { .. } => {}
22465 other => panic!("expected PlacementWithoutClusters, got {other:?}"),
22466 }
22467 assert!(
22468 spec.placement.clusters().is_empty(),
22469 "the pre-flight refusal input must be the empty slice per \
22470 the accessor's projection",
22471 );
22472
22473 // (2) Per-cluster validate loop: a two-cluster cohort with an
22474 // invalid tail entry must trip `PlacementClusterInvalid` on
22475 // the tail — the loop must reach the second entry through
22476 // the accessor.
22477 let mut spec = three_member_spec();
22478 spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
22479 match spec.validate().unwrap_err() {
22480 AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
22481 assert_eq!(
22482 cluster, "BAD_CLUSTER",
22483 "PlacementClusterInvalid.cluster must carry the \
22484 tail entry the loop reached through the accessor",
22485 );
22486 }
22487 other => panic!("expected PlacementClusterInvalid, got {other:?}"),
22488 }
22489 assert_eq!(
22490 spec.placement.clusters().len(),
22491 2,
22492 "the per-cluster validate loop's traversal input must be \
22493 a two-element slice per the accessor's projection",
22494 );
22495
22496 // (3) Per-cluster validate loop: a two-cluster cohort that
22497 // shares a name must trip `PlacementClusterDuplicate` on the
22498 // second entry — the loop must reach both entries through the
22499 // accessor for the dedup HashSet's second insert to collide.
22500 let mut spec = three_member_spec();
22501 spec.placement.clusters = vec!["rio".into(), "rio".into()];
22502 match spec.validate().unwrap_err() {
22503 AplicacaoError::PlacementClusterDuplicate { cluster } => {
22504 assert_eq!(
22505 cluster, "rio",
22506 "PlacementClusterDuplicate.cluster must carry the \
22507 shared cluster name verbatim",
22508 );
22509 }
22510 other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
22511 }
22512 assert_eq!(
22513 spec.placement.clusters().len(),
22514 2,
22515 "the per-cluster validate loop's traversal input must be \
22516 a two-element slice per the accessor's projection",
22517 );
22518 }
22519
22520 #[test]
22521 fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
22522 // The canonical per-`:membros` member-list-slice-shape pin:
22523 // [`AplicacaoSpec::membros`] must return the `:membros` typed
22524 // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
22525 // same backing buffer the raw `self.membros.as_slice()` field
22526 // access borrows from, byte-equal across every representative
22527 // fixture in the accept-set — the empty slice (the pre-
22528 // validation sentinel every [`AplicacaoError::NoMembros`]
22529 // refusal keys off), the singleton slice (the minimal one-
22530 // Servico Aplicacao shape), and multi-entry cohorts (the peer
22531 // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
22532 // load-bearing identity of the application graph).
22533 //
22534 // Pins against a future silent detour that returned
22535 // `&Vec<Membro>` (which would type-check but leak the storage-
22536 // side `Vec`'s grow/push/reserve surface no consumer of the
22537 // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
22538 // (which would type-check via a coercion but silently break
22539 // every downstream caller that relied on the slice sharing the
22540 // backing buffer's identity), or an out-of-order or length-
22541 // drifted projection (which would silently split the paired
22542 // `HashSet<&str>` name-set seed's collect input from the
22543 // pre-flight `.is_empty()` refusal probe's input from the per-
22544 // member validate loop's traversal input from the
22545 // programs.yaml emitter's per-entry fan-out loop's input from
22546 // the `feira app graph` per-member print traversal's input).
22547 //
22548 // Peer of the sibling M2
22549 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22550 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22551 // `:supervisor` static-child-list axis and the sibling M3
22552 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
22553 // (a6e18d7) `&[String]` byte-equal pin on the per-
22554 // `:placement` distribution-target-list axis — extends the
22555 // slice-return-accessor byte-equal-projection discipline onto
22556 // the outermost M3 mesh-slot type's per-Aplicacao member-list
22557 // `Vec`-carry axis.
22558 let fixtures: Vec<Vec<Membro>> = vec![
22559 Vec::new(),
22560 vec![membro("catalog", "^0.1")],
22561 vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
22562 vec![
22563 membro("catalog", "^0.1"),
22564 membro("cart", "^0.1"),
22565 membro("payment", "^0.2"),
22566 ],
22567 ];
22568 for membros in fixtures {
22569 let s = AplicacaoSpec {
22570 membros: membros.clone(),
22571 contratos: Vec::new(),
22572 politicas: MeshPolicy::default(),
22573 placement: Placement::default(),
22574 entrada: None,
22575 };
22576 assert_eq!(
22577 s.membros(),
22578 membros.as_slice(),
22579 "AplicacaoSpec::membros must return :membros verbatim \
22580 (got {:?}, expected {:?})",
22581 s.membros(),
22582 membros.as_slice(),
22583 );
22584 assert_eq!(
22585 s.membros(),
22586 s.membros.as_slice(),
22587 "AplicacaoSpec::membros accessor and .membros.as_slice() \
22588 field access must byte-equal — the accessor is the \
22589 substrate-primitive typed dispatch every downstream \
22590 member-list consumer must route through",
22591 );
22592 assert_eq!(
22593 s.membros().len(),
22594 s.membros.len(),
22595 "AplicacaoSpec::membros().len() must byte-equal \
22596 self.membros.len() — a length-drift would silently \
22597 split the paired `HashSet<&str>` name-set seed's \
22598 collect input from the pre-flight `.is_empty()` \
22599 refusal probe input from the per-member validate \
22600 loop's traversal input",
22601 );
22602 }
22603 }
22604
22605 #[test]
22606 fn validate_reads_through_lifted_membros_accessor() {
22607 // Three-consumer coherence pin: the
22608 // [`AplicacaoSpec::validate_membros`] pre-flight
22609 // `self.membros().is_empty()` refusal probe (which must trip
22610 // [`AplicacaoError::NoMembros`] when the accessor projects the
22611 // empty slice), the same method's per-member validate loop's
22612 // `for m in self.membros()` traversal (which must reach every
22613 // entry in the same order the accessor projects, so both the
22614 // per-entry empty-`:caixa` gate that trips
22615 // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
22616 // detection `insert_first_seen` that trips
22617 // [`AplicacaoError::MembroDuplicate`] key off the accessor's
22618 // projection), and the peer [`AplicacaoSpec::validate`]'s
22619 // `HashSet<&str>` name-set seed's
22620 // `self.membros().iter().map(Membro::nome).collect()` collect
22621 // input (which every `:contratos` `:de` / `:para` membership
22622 // lookup rejects an unknown name against) must all three key
22623 // off the lifted accessor, so any future rebrand on the typed
22624 // slot's reader shape lands at exactly one place. Pins the
22625 // three-site coherence by exercising each production consumer
22626 // end-to-end: (1) the `NoMembros` refusal under the empty
22627 // slice, (2) the `MembroCaixaEmpty` refusal fires on the
22628 // second entry of a two-member cohort whose head is valid but
22629 // tail has an empty `:caixa` (which requires the loop to
22630 // reach the second entry through the accessor), and (3) the
22631 // `MembroDuplicate` refusal fires on the second entry of a
22632 // two-member cohort that shares a `:caixa` name (which
22633 // requires the loop to reach both entries through the
22634 // accessor for the dedup HashSet's second insert to collide).
22635 //
22636 // Peer of the sibling M2
22637 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
22638 // (bc92bce) coherence pin on the per-`:supervisor` static-
22639 // child-list axis and the sibling M3
22640 // `validate_placement_reads_through_lifted_clusters_accessor`
22641 // (a6e18d7) coherence pin on the per-`:placement` distribution-
22642 // target-list axis — extends the slice-return-accessor
22643 // multi-consumer coherence discipline onto the outermost M3
22644 // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
22645
22646 // (1) Pre-flight `.is_empty()` probe: the empty slice must
22647 // trip `NoMembros`.
22648 let mut spec = three_member_spec();
22649 spec.membros = Vec::new();
22650 assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
22651 assert!(
22652 spec.membros().is_empty(),
22653 "the pre-flight refusal input must be the empty slice per \
22654 the accessor's projection",
22655 );
22656
22657 // (2) Per-member validate loop: a two-member cohort with an
22658 // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
22659 // the tail — the loop must reach the second entry through
22660 // the accessor.
22661 let mut spec = three_member_spec();
22662 spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
22663 assert_eq!(
22664 spec.validate().unwrap_err(),
22665 AplicacaoError::MembroCaixaEmpty,
22666 );
22667 assert_eq!(
22668 spec.membros().len(),
22669 2,
22670 "the per-member validate loop's traversal input must be \
22671 a two-element slice per the accessor's projection",
22672 );
22673
22674 // (3) Per-member validate loop: a two-member cohort that
22675 // shares a `:caixa` name must trip `MembroDuplicate` on the
22676 // second entry — the loop must reach both entries through the
22677 // accessor for the dedup HashSet's second insert to collide.
22678 let mut spec = three_member_spec();
22679 spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
22680 match spec.validate().unwrap_err() {
22681 AplicacaoError::MembroDuplicate { caixa } => {
22682 assert_eq!(
22683 caixa, "catalog",
22684 "MembroDuplicate.caixa must carry the shared \
22685 member name verbatim",
22686 );
22687 }
22688 other => panic!("expected MembroDuplicate, got {other:?}"),
22689 }
22690 assert_eq!(
22691 spec.membros().len(),
22692 2,
22693 "the per-member validate loop's traversal input must be \
22694 a two-element slice per the accessor's projection",
22695 );
22696 }
22697
22698 #[test]
22699 fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
22700 // The canonical per-`:contratos` contract-list-slice-shape pin:
22701 // [`AplicacaoSpec::contratos`] must return the `:contratos`
22702 // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
22703 // slice-view over the same backing buffer the raw
22704 // `self.contratos.as_slice()` field access borrows from, byte-
22705 // equal across every representative fixture in the accept-set —
22706 // the empty slice (the pre-validation "internal-only mesh" shape
22707 // an Aplicacao whose members exchange no typed edges renders
22708 // through), the singleton slice (the minimal one-edge Aplicacao
22709 // shape), and multi-entry cohorts (the peer multi-edge shapes
22710 // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
22711 // of the application graph).
22712 //
22713 // Pins against a future silent detour that returned
22714 // `&Vec<WitContract>` (which would type-check but leak the
22715 // storage-side `Vec`'s grow/push/reserve surface no consumer of
22716 // the typed view reaches for), a fresh-allocated
22717 // `Vec<WitContract>` copy (which would type-check via a coercion
22718 // but silently break every downstream caller that relied on the
22719 // slice sharing the backing buffer's identity), or an out-of-
22720 // order or length-drifted projection (which would silently split
22721 // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
22722 // seed's traversal input from the `detect_sync_cycles` per-edge
22723 // adjacency-list seed's traversal input from the
22724 // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
22725 // BTreeMap grouping loop's traversal input from the
22726 // `feira app graph` per-contract print traversal's input).
22727 //
22728 // Peer of the immediately-adjacent sibling M3
22729 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
22730 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
22731 // node-list axis, the sibling M3
22732 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
22733 // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
22734 // distribution-target-list axis, and the sibling M2
22735 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22736 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22737 // `:supervisor` static-child-list axis — extends the slice-
22738 // return-accessor byte-equal-projection discipline onto the
22739 // outermost M3 mesh-slot type's per-Aplicacao contract-list
22740 // `Vec`-carry axis, closing the last unlifted per-
22741 // `AplicacaoSpec` `Vec`-carry axis.
22742 let fixtures: Vec<Vec<WitContract>> = vec![
22743 Vec::new(),
22744 vec![contract_http("cart", "catalog", "/products/:id")],
22745 vec![
22746 contract_http("cart", "catalog", "/products/:id"),
22747 contract_http("cart", "payment", "/charge"),
22748 ],
22749 vec![
22750 contract_http("cart", "catalog", "/products/:id"),
22751 contract_http("cart", "payment", "/charge"),
22752 contract_http("payment", "catalog", "/audit"),
22753 ],
22754 ];
22755 for contratos in fixtures {
22756 let s = AplicacaoSpec {
22757 membros: vec![
22758 membro("catalog", "^0.1"),
22759 membro("cart", "^0.1"),
22760 membro("payment", "^0.2"),
22761 ],
22762 contratos: contratos.clone(),
22763 politicas: MeshPolicy::default(),
22764 placement: Placement::default(),
22765 entrada: None,
22766 };
22767 assert_eq!(
22768 s.contratos(),
22769 contratos.as_slice(),
22770 "AplicacaoSpec::contratos must return :contratos verbatim \
22771 (got {:?}, expected {:?})",
22772 s.contratos(),
22773 contratos.as_slice(),
22774 );
22775 assert_eq!(
22776 s.contratos(),
22777 s.contratos.as_slice(),
22778 "AplicacaoSpec::contratos accessor and \
22779 .contratos.as_slice() field access must byte-equal — \
22780 the accessor is the substrate-primitive typed dispatch \
22781 every downstream contract-list consumer must route \
22782 through",
22783 );
22784 assert_eq!(
22785 s.contratos().len(),
22786 s.contratos.len(),
22787 "AplicacaoSpec::contratos().len() must byte-equal \
22788 self.contratos.len() — a length-drift would silently \
22789 split the paired per-edge validate-loop's traversal \
22790 input from the sync-cycle adjacency-list seed's \
22791 traversal input from the cilium_network_policies \
22792 per-`(:de, :para)` BTreeMap grouping loop's traversal \
22793 input from the `feira app graph` per-contract print \
22794 traversal's input",
22795 );
22796 }
22797 }
22798
22799 #[test]
22800 fn validate_reads_through_lifted_contratos_accessor() {
22801 // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
22802 // per-`:contratos` validate-loop's `for c in self.contratos()`
22803 // traversal (which must reach every entry in the same order the
22804 // accessor projects, so both the per-entry
22805 // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
22806 // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
22807 // dedup `HashSet` insert key off the accessor's projection),
22808 // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
22809 // `for c in self.contratos()` adjacency-list seed (which drives
22810 // the sync-subgraph deadlock-detection gate via
22811 // [`AplicacaoError::SyncCycle`]), and the peer
22812 // [`caixa_mesh::cilium_network_policies`]'s
22813 // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
22814 // grouping loop (which drives the per-CNP fan-out) must all
22815 // three key off the lifted accessor, so any future rebrand on
22816 // the typed slot's reader shape lands at exactly one place. Pins
22817 // the three-site coherence by exercising the two caixa-core
22818 // production consumers end-to-end: (1) the empty-`:contratos`
22819 // slice must validate without a per-edge diagnostic (the
22820 // per-edge loop is a no-op under the empty projection), (2) the
22821 // `ContratoMemberMissing` refusal fires on the second entry of a
22822 // two-edge cohort whose head references a valid member but tail
22823 // references a phantom name (which requires the loop to reach
22824 // the second entry through the accessor), and (3) the
22825 // `SyncCycle` refusal fires on a self-referential two-edge
22826 // cohort through the sync-cycle detector's peer projection
22827 // (which requires the detector to iterate the accessor's
22828 // projection to add the back-edge to its adjacency list).
22829 //
22830 // Peer of the sibling M3
22831 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
22832 // three-consumer coherence pin on the per-`:membros` node-list
22833 // axis and the sibling M3
22834 // `validate_placement_reads_through_lifted_clusters_accessor`
22835 // (a6e18d7) coherence pin on the per-`:placement` distribution-
22836 // target-list axis — extends the slice-return-accessor multi-
22837 // consumer coherence discipline onto the outermost M3 mesh-slot
22838 // type's per-Aplicacao contract-list `Vec`-carry axis.
22839
22840 // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
22841 // and no per-edge diagnostic surfaces. Validate succeeds on
22842 // the well-formed `:membros` head.
22843 let mut spec = three_member_spec();
22844 spec.contratos = Vec::new();
22845 assert!(
22846 spec.validate().is_ok(),
22847 "empty :contratos must validate — the per-edge loop is a \
22848 no-op under the accessor's empty projection",
22849 );
22850 assert!(
22851 spec.contratos().is_empty(),
22852 "the per-edge validate loop's traversal input must be the \
22853 empty slice per the accessor's projection",
22854 );
22855
22856 // (2) Per-edge validate loop: a two-edge cohort whose tail
22857 // references a phantom `:para` member must trip
22858 // `ContratoMemberMissing` on the tail — the loop must reach
22859 // the second entry through the accessor for the membership
22860 // lookup to fail on the phantom name.
22861 let mut spec = three_member_spec();
22862 spec.contratos = vec![
22863 contract_http("cart", "catalog", "/products/:id"),
22864 contract_http("cart", "phantom", "/x"),
22865 ];
22866 let err = spec.validate().unwrap_err();
22867 assert!(
22868 matches!(
22869 err,
22870 AplicacaoError::ContratoMemberMissing { ref caixa }
22871 if caixa == "phantom"
22872 ),
22873 "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
22874 );
22875 assert_eq!(
22876 spec.contratos().len(),
22877 2,
22878 "the per-edge validate loop's traversal input must be \
22879 a two-element slice per the accessor's projection",
22880 );
22881
22882 // (3) Sync-cycle detector: a two-edge synchronous cohort
22883 // whose second edge closes the sync-subgraph back onto the
22884 // first must trip [`AplicacaoError::ContratoCycle`] — the
22885 // detector must iterate the accessor's projection to add
22886 // both edges to its adjacency list, so a length-drift on
22887 // the accessor's projection would silently disagree with
22888 // the sync-cycle detector on which edge closes the loop.
22889 // Peer projection to the `validate` per-edge loop above:
22890 // the sync-cycle detector routes through the same lifted
22891 // accessor, so a rebrand of the reader shape lands at one
22892 // place. Uses a two-edge cohort (cart → catalog → cart)
22893 // because the per-edge `ContratoSelfLoop` gate fires before
22894 // the sync-cycle detector on a single self-referential edge
22895 // (`cart → cart`) — the cycle-detector's input must be a
22896 // multi-edge cohort for its per-edge traversal input to be
22897 // observably wider than the per-edge validate loop's input.
22898 let mut spec = three_member_spec();
22899 spec.contratos = vec![
22900 contract_http("cart", "catalog", "/products/:id"),
22901 contract_http("catalog", "cart", "/callback"),
22902 ];
22903 let err = spec.validate().unwrap_err();
22904 assert!(
22905 matches!(err, AplicacaoError::ContratoCycle { .. }),
22906 "expected ContratoCycle from the sync-cycle detector on a \
22907 two-edge back-edge cohort, got {err:?}",
22908 );
22909 assert_eq!(
22910 spec.contratos().len(),
22911 2,
22912 "the sync-cycle detector's traversal input must be a \
22913 two-element slice per the accessor's projection",
22914 );
22915 }
22916
22917 #[test]
22918 fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
22919 // The canonical per-`:politicas` outer-composite-reference-shape
22920 // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
22921 // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
22922 // the same backing storage the raw `&self.politicas` field
22923 // access borrows from, byte-equal across every representative
22924 // fixture in the accept-set — the default `MeshPolicy` (the
22925 // author-empty "no policy on any axis" shape whose
22926 // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
22927 // shapes carrying one axis at a time
22928 // (`{mtls_required, timeout, retries, circuit_breaker,
22929 // rate_limit}` — the minimal five-axis fan-out over the
22930 // per-axis lifted accessor family every downstream mesh-artifact
22931 // emitter dispatches on), and the multi-axis composite (the
22932 // canonical `three_member_spec` fixture's `{timeout, retries,
22933 // mtls_required}` triple — the load-bearing shape every
22934 // Aplicacao-scoped fixture in this suite constructs).
22935 //
22936 // Pins against a future silent detour that returned a fresh-
22937 // cloned `MeshPolicy` copy (which would type-check via a `Clone`
22938 // impl but silently break every downstream caller that relied
22939 // on the reference sharing the composite's backing identity), a
22940 // reference to an operator-resolved overlay (the future
22941 // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
22942 // acknowledges — its resolution must land at exactly this
22943 // accessor body, not silently divert the raw slot away from a
22944 // second consumer), or an axis-shuffled projection (a future
22945 // detour that swapped `timeout` and `retries` through the
22946 // accessor would silently split the paired `validate_politicas`
22947 // per-axis bracket-dispatch's traversal input from the peer
22948 // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
22949 // emitter's fan-out input from the peer
22950 // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
22951 // overlay emitter's fan-out input).
22952 //
22953 // Peer of the sibling M3
22954 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
22955 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
22956 // node-list `Vec`-carry axis and the sibling M3
22957 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
22958 // (0dcc926) `&[WitContract]` byte-equal pin on the per-
22959 // `:contratos` edge-list `Vec`-carry axis — extends the outer-
22960 // accessor byte-equal-projection discipline onto the outermost
22961 // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
22962 // reference axis, the first `&Composite`-return accessor on the
22963 // outer [`AplicacaoSpec`] type.
22964 let fixtures: Vec<MeshPolicy> = vec![
22965 MeshPolicy::default(),
22966 MeshPolicy {
22967 mtls_required: Some(true),
22968 ..MeshPolicy::default()
22969 },
22970 MeshPolicy {
22971 mtls_required: Some(false),
22972 ..MeshPolicy::default()
22973 },
22974 MeshPolicy {
22975 timeout: Some(Duration::from_secs(30)),
22976 ..MeshPolicy::default()
22977 },
22978 MeshPolicy {
22979 retries: Some(3),
22980 ..MeshPolicy::default()
22981 },
22982 MeshPolicy {
22983 circuit_breaker: Some(CircuitBreaker {
22984 max_failures: 5,
22985 window: Duration::from_secs(30),
22986 }),
22987 ..MeshPolicy::default()
22988 },
22989 MeshPolicy {
22990 rate_limit: Some(RateLimit {
22991 rate: 100,
22992 window: Duration::from_secs(1),
22993 }),
22994 ..MeshPolicy::default()
22995 },
22996 MeshPolicy {
22997 timeout: Some(Duration::from_secs(30)),
22998 retries: Some(3),
22999 mtls_required: Some(true),
23000 ..MeshPolicy::default()
23001 },
23002 ];
23003 for politicas in fixtures {
23004 let s = AplicacaoSpec {
23005 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23006 contratos: Vec::new(),
23007 politicas: politicas.clone(),
23008 placement: Placement::default(),
23009 entrada: None,
23010 };
23011 assert_eq!(
23012 *s.politicas(),
23013 politicas,
23014 "AplicacaoSpec::politicas must return :politicas verbatim \
23015 (got {:?}, expected {:?})",
23016 s.politicas(),
23017 politicas,
23018 );
23019 assert!(
23020 std::ptr::eq(s.politicas(), &s.politicas),
23021 "AplicacaoSpec::politicas accessor and &self.politicas \
23022 field access must borrow the same backing storage — \
23023 the accessor is the substrate-primitive typed dispatch \
23024 every downstream mesh-policy composite consumer must \
23025 route through, and a reference-identity split would \
23026 silently break every consumer that relied on the \
23027 borrow sharing the composite's storage",
23028 );
23029 assert_eq!(
23030 s.politicas().is_empty(),
23031 s.politicas.is_empty(),
23032 "AplicacaoSpec::politicas().is_empty() must byte-equal \
23033 self.politicas.is_empty() — an emptiness-drift would \
23034 silently split the paired `validate_politicas` \
23035 per-axis bracket-dispatch's seed from the peer \
23036 caixa-mesh CNP mTLS-overlay emitter's key from the \
23037 peer caixa-mesh HTTPRoute timeout+retry overlay \
23038 emitter's key",
23039 );
23040 }
23041 }
23042
23043 #[test]
23044 fn validate_politicas_reads_through_lifted_politicas_accessor() {
23045 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
23046 // per-axis bracket-dispatch seed (`let p = self.politicas();`,
23047 // followed by the per-axis fan-out `p.timeout()` /
23048 // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
23049 // the lifted axis-level accessor family) must key off the
23050 // lifted outer accessor, so any future rebrand on the typed
23051 // slot's outer-composite reader shape lands at exactly one
23052 // place. Pins the multi-axis coherence by exercising each
23053 // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
23054 // a `Some(Duration::ZERO)` timeout under the outer accessor's
23055 // reference projection, (2) `PolicyRetriesZero` fires on a
23056 // `Some(0)` retries under the same projection, and (3) an
23057 // empty [`MeshPolicy::default`] passes `validate_politicas` —
23058 // the outer accessor's reference-projection reaches every
23059 // per-axis branch without silently short-circuiting any.
23060 //
23061 // Peer of the sibling M3
23062 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23063 // three-consumer coherence pin on the per-`:membros` node-list
23064 // axis and the sibling M3
23065 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
23066 // three-consumer coherence pin on the per-`:contratos`
23067 // edge-list axis — extends the multi-consumer coherence
23068 // discipline onto the outermost M3 mesh-slot type's per-
23069 // Aplicacao mesh-policy composite-reference axis, the first
23070 // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
23071 // type.
23072
23073 // (1) `PolicyTimeoutZero` refusal under the outer accessor's
23074 // reference projection: a `Some(Duration::ZERO)` timeout must
23075 // trip the zero-floor gate. The bracket-dispatch's first arm
23076 // reads `p.timeout()` on the reference returned by the outer
23077 // accessor.
23078 let mut spec = three_member_spec();
23079 spec.politicas.timeout = Some(Duration::ZERO);
23080 spec.politicas.retries = None;
23081 spec.politicas.circuit_breaker = None;
23082 spec.politicas.rate_limit = None;
23083 assert_eq!(
23084 spec.validate().unwrap_err(),
23085 AplicacaoError::PolicyTimeoutZero,
23086 );
23087 assert!(
23088 std::ptr::eq(spec.politicas(), &spec.politicas),
23089 "the `validate_politicas` per-axis bracket-dispatch's \
23090 traversal input must be the same backing composite the \
23091 accessor's reference projection borrows from",
23092 );
23093
23094 // (2) `PolicyRetriesZero` refusal under the outer accessor's
23095 // reference projection: a `Some(0)` retries must trip the
23096 // zero-floor gate. The bracket-dispatch's second arm reads
23097 // `p.retries()` on the reference returned by the outer accessor.
23098 let mut spec = three_member_spec();
23099 spec.politicas.timeout = None;
23100 spec.politicas.retries = Some(0);
23101 spec.politicas.circuit_breaker = None;
23102 spec.politicas.rate_limit = None;
23103 assert_eq!(
23104 spec.validate().unwrap_err(),
23105 AplicacaoError::PolicyRetriesZero,
23106 );
23107
23108 // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
23109 // — every per-axis arm short-circuits on `None`, so the outer
23110 // accessor's reference projection reaches the fall-through
23111 // `Ok(())` without any per-axis refusal firing.
23112 let mut spec = three_member_spec();
23113 spec.politicas = MeshPolicy::default();
23114 assert!(
23115 spec.validate().is_ok(),
23116 "an empty `MeshPolicy` must pass `validate_politicas` — \
23117 every per-axis arm short-circuits on `None` under the \
23118 outer accessor's reference projection",
23119 );
23120 assert!(
23121 spec.politicas().is_empty(),
23122 "the outer accessor's reference projection must be the \
23123 empty composite per the `MeshPolicy::default()` fixture",
23124 );
23125 }
23126
23127 #[test]
23128 #[allow(clippy::too_many_lines)]
23129 fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
23130 // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
23131 // per-axis bracket-dispatch's `:timeout` and `:retries` arms
23132 // must both key off the lifted axis-level accessors
23133 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
23134 // the peer `:circuit-breaker` / `:rate-limit` arms already
23135 // routing through [`MeshPolicy::circuit_breaker`] /
23136 // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
23137 // per axis on the substrate primitive" shape at the fan-out
23138 // (four axes, four accessors, no raw-field-access site
23139 // anywhere on the bracket-dispatch). Pins the per-axis
23140 // coherence at the accept-set boundaries the bracket carves:
23141 // 1. accessor byte-equal to raw field on every representative
23142 // accept-set value (`None`, sub-cap, at-cap, past-cap
23143 // sentinel) — a future accessor drift that no longer
23144 // shipped the raw slot verbatim would surface here,
23145 // 2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
23146 // routed through the accessor's projection, proving the
23147 // first arm reads through the accessor rather than a
23148 // silent-detour peer-axis field access,
23149 // 3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
23150 // through the accessor's projection, proving the second
23151 // arm reads through the accessor,
23152 // 4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
23153 // passes validate under the accessor projection (paired
23154 // with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
23155 // sibling axis), pinning the upper-boundary accept-arm
23156 // also routes through the accessor.
23157 //
23158 // Peer of the sibling M3
23159 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23160 // outer-composite-reference coherence pin (which asserts the
23161 // `let p = self.politicas()` seed); extends the discipline onto
23162 // the per-axis fan-out layer that consumes the seed's
23163 // reference. Same shape as
23164 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
23165 // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23166 // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
23167 // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
23168
23169 // (1) Accessor byte-equal to raw field on the `:timeout` axis
23170 // across the accept-set boundaries the bracket dispatch's
23171 // three-arm gate carves out
23172 // ([`crate::render::require_positive_canonical_bounded_duration`]
23173 // — zero-floor + canonical-form + upper-cap).
23174 for timeout in [
23175 None,
23176 Some(Duration::ZERO),
23177 Some(Duration::from_millis(1)),
23178 Some(POLICY_TIMEOUT_MAX),
23179 ] {
23180 let p = MeshPolicy {
23181 timeout,
23182 ..MeshPolicy::default()
23183 };
23184 assert_eq!(
23185 p.timeout(),
23186 p.timeout,
23187 "MeshPolicy::timeout accessor must byte-equal the raw \
23188 .timeout field across every accept-set boundary the \
23189 validate_politicas :timeout arm carves out — a drift \
23190 here would silently split the validate bracket's arm \
23191 from the peer caixa-mesh HTTPRoute timeout-overlay \
23192 emitter's read",
23193 );
23194 }
23195
23196 // (2) Accessor byte-equal to raw field on the `:retries` axis
23197 // across the accept-set boundaries the bracket dispatch's
23198 // two-arm gate carves out
23199 // ([`crate::render::require_positive_bounded_u32`] — zero-floor
23200 // + upper-cap).
23201 for retries in [
23202 None,
23203 Some(0u32),
23204 Some(1u32),
23205 Some(POLICY_RETRIES_MAX),
23206 Some(POLICY_RETRIES_MAX + 1),
23207 Some(u32::MAX),
23208 ] {
23209 let p = MeshPolicy {
23210 retries,
23211 ..MeshPolicy::default()
23212 };
23213 assert_eq!(
23214 p.retries(),
23215 p.retries,
23216 "MeshPolicy::retries accessor must byte-equal the raw \
23217 .retries field across every accept-set boundary the \
23218 validate_politicas :retries arm carves out — a drift \
23219 here would silently split the validate bracket's arm \
23220 from the peer caixa-mesh HTTPRoute retry-overlay \
23221 emitter's read",
23222 );
23223 }
23224
23225 // (3) `PolicyTimeoutZero` fires on the accessor-projected
23226 // zero-floor boundary. A silent detour that no longer read
23227 // through `p.timeout()` (a peer-axis field read, an accidental
23228 // Option::and-then chain that collapsed the None arm to Some,
23229 // an accessor rebrand that clamped the return through the
23230 // upper cap) would fail to refuse here.
23231 let mut spec = three_member_spec();
23232 spec.politicas.timeout = Some(Duration::ZERO);
23233 spec.politicas.retries = None;
23234 spec.politicas.circuit_breaker = None;
23235 spec.politicas.rate_limit = None;
23236 assert_eq!(
23237 spec.politicas().timeout(),
23238 Some(Duration::ZERO),
23239 "the accessor projection must reflect the fixture's \
23240 `Some(Duration::ZERO)` :timeout verbatim",
23241 );
23242 assert_eq!(
23243 spec.validate().unwrap_err(),
23244 AplicacaoError::PolicyTimeoutZero,
23245 "the validate_politicas :timeout zero-floor arm must fire \
23246 through the lifted accessor's projection — a silent \
23247 detour to a peer-axis field would fail to refuse",
23248 );
23249
23250 // (4) `PolicyRetriesZero` fires on the accessor-projected
23251 // zero-floor boundary on the sibling `:retries` axis.
23252 let mut spec = three_member_spec();
23253 spec.politicas.timeout = None;
23254 spec.politicas.retries = Some(0);
23255 spec.politicas.circuit_breaker = None;
23256 spec.politicas.rate_limit = None;
23257 assert_eq!(
23258 spec.politicas().retries(),
23259 Some(0),
23260 "the accessor projection must reflect the fixture's \
23261 `Some(0)` :retries verbatim",
23262 );
23263 assert_eq!(
23264 spec.validate().unwrap_err(),
23265 AplicacaoError::PolicyRetriesZero,
23266 "the validate_politicas :retries zero-floor arm must fire \
23267 through the lifted accessor's projection — a silent \
23268 detour to a peer-axis field would fail to refuse",
23269 );
23270
23271 // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
23272 // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
23273 // must pass validate under the accessor projection — pins the
23274 // upper-boundary accept-arm also routes through the lifted
23275 // accessor (a drift that clamped or short-circuited at the
23276 // upper boundary would fail the whole-spec validate here).
23277 let mut spec = three_member_spec();
23278 spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
23279 spec.politicas.retries = Some(POLICY_RETRIES_MAX);
23280 spec.politicas.circuit_breaker = None;
23281 spec.politicas.rate_limit = None;
23282 assert_eq!(
23283 spec.politicas().timeout(),
23284 Some(POLICY_TIMEOUT_MAX),
23285 "the accessor projection must reflect the fixture's \
23286 at-cap :timeout verbatim",
23287 );
23288 assert_eq!(
23289 spec.politicas().retries(),
23290 Some(POLICY_RETRIES_MAX),
23291 "the accessor projection must reflect the fixture's \
23292 at-cap :retries verbatim",
23293 );
23294 assert!(
23295 spec.validate().is_ok(),
23296 "at-cap :timeout + :retries must pass validate under the \
23297 accessor projection — the upper-boundary accept-arm on \
23298 both axes routes through the lifted accessor",
23299 );
23300 }
23301
23302 #[test]
23303 fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
23304 // The canonical per-`:placement` outer-composite-reference-shape
23305 // pin: [`AplicacaoSpec::placement`] must return the `:placement`
23306 // typed `Placement` verbatim as a `&Placement` reference over the
23307 // same backing storage the raw `&self.placement` field access
23308 // borrows from, byte-equal across every representative fixture in
23309 // the accept-set — the default `Placement` (the substrate seed
23310 // shape whose [`PlacementStrategy::default`] evaluates to
23311 // `SingleNode` with an empty `:clusters` pool and both
23312 // optional-scalar axes `None`), and every canonical strategy /
23313 // cluster-pool / optional-scalar combination the
23314 // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
23315 // three [`PlacementStrategy`] variants — `SingleNode`,
23316 // `Replicated`, `Sharded` — cross-projected with a non-empty
23317 // `:clusters` pool and, on the `Sharded` arm, a non-empty
23318 // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
23319 // canonical `three_member_spec` `Replicated` fixture's
23320 // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
23321 //
23322 // Pins against a future silent detour that returned a fresh-
23323 // cloned `Placement` copy (which would type-check via a `Clone`
23324 // impl but silently break every downstream caller that relied on
23325 // the reference sharing the composite's backing identity), a
23326 // reference to an operator-resolved overlay (the future per-
23327 // cluster `:placement-overrides` slot MESH-COMPOSITION §V
23328 // acknowledges — its resolution must land at exactly this
23329 // accessor body, not silently divert the raw slot away from a
23330 // second consumer), or an axis-shuffled projection (a future
23331 // detour that swapped `clusters` and `affinity` through the
23332 // accessor would silently split the paired `validate_placement`
23333 // per-axis bracket-dispatch's traversal input from the peer
23334 // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
23335 // programs.yaml distribution-annotation emitter's fan-out input
23336 // from the peer `feira app graph` per-Aplicacao print line's
23337 // input).
23338 //
23339 // Peer of the sibling M3
23340 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
23341 // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
23342 // outer mesh-policy composite-reference axis, and of the sibling
23343 // slice-return `aplicacao_spec_membros_returns_membros_slice_
23344 // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
23345 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
23346 // across_permutations` (0dcc926) `&[WitContract]` pins — extends
23347 // the outer-accessor byte-equal-projection discipline onto the
23348 // outermost M3 mesh-slot type's per-Aplicacao distribution
23349 // composite-reference axis, the second `&Composite`-return
23350 // accessor on the outer [`AplicacaoSpec`] type.
23351 let fixtures: Vec<Placement> = vec![
23352 Placement::default(),
23353 Placement {
23354 estrategia: PlacementStrategy::SingleNode,
23355 clusters: vec!["rio".into()],
23356 affinity: None,
23357 shard_key: None,
23358 },
23359 Placement {
23360 estrategia: PlacementStrategy::Replicated,
23361 clusters: vec!["rio".into(), "mar".into()],
23362 affinity: None,
23363 shard_key: None,
23364 },
23365 Placement {
23366 estrategia: PlacementStrategy::Replicated,
23367 clusters: vec!["rio".into(), "mar".into()],
23368 affinity: Some("data-locality".into()),
23369 shard_key: None,
23370 },
23371 Placement {
23372 estrategia: PlacementStrategy::Sharded,
23373 clusters: vec!["rio".into(), "mar".into()],
23374 affinity: None,
23375 shard_key: Some("tenantId".into()),
23376 },
23377 Placement {
23378 estrategia: PlacementStrategy::Sharded,
23379 clusters: vec!["rio".into(), "mar".into(), "sol".into()],
23380 affinity: Some("low-latency".into()),
23381 shard_key: Some("metadata.tenantId".into()),
23382 },
23383 ];
23384 for placement in fixtures {
23385 let s = AplicacaoSpec {
23386 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23387 contratos: Vec::new(),
23388 politicas: MeshPolicy::default(),
23389 placement: placement.clone(),
23390 entrada: None,
23391 };
23392 assert_eq!(
23393 *s.placement(),
23394 placement,
23395 "AplicacaoSpec::placement must return :placement verbatim \
23396 (got {:?}, expected {:?})",
23397 s.placement(),
23398 placement,
23399 );
23400 assert!(
23401 std::ptr::eq(s.placement(), &s.placement),
23402 "AplicacaoSpec::placement accessor and &self.placement \
23403 field access must borrow the same backing storage — the \
23404 accessor is the substrate-primitive typed dispatch every \
23405 downstream distribution-composite consumer must route \
23406 through, and a reference-identity split would silently \
23407 break every consumer that relied on the borrow sharing \
23408 the composite's storage",
23409 );
23410 assert_eq!(
23411 s.placement().estrategia(),
23412 s.placement.estrategia,
23413 "AplicacaoSpec::placement().estrategia() must byte-equal \
23414 self.placement.estrategia — a strategy-drift would \
23415 silently split the paired `validate_placement` \
23416 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
23417 peer caixa-mesh programs.yaml `placement.estrategia` \
23418 emitter's key from the peer `feira app graph` printer's \
23419 strategy label",
23420 );
23421 assert_eq!(
23422 s.placement().clusters(),
23423 s.placement.clusters.as_slice(),
23424 "AplicacaoSpec::placement().clusters() must byte-equal \
23425 self.placement.clusters — a cluster-pool drift would \
23426 silently split the paired `validate_placement` \
23427 pre-flight `.is_empty()` refusal probe's traversal from \
23428 the peer caixa-mesh programs.yaml `placement.clusters` \
23429 emitter's fan-out from the peer `feira app graph` \
23430 printer's cluster list",
23431 );
23432 }
23433 }
23434
23435 #[test]
23436 fn validate_placement_reads_through_lifted_placement_accessor() {
23437 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
23438 // per-axis bracket-dispatch seed (`let p = self.placement();`,
23439 // followed by the per-axis fan-out `p.clusters()` /
23440 // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
23441 // lifted axis-level accessor family) must key off the lifted
23442 // outer accessor, so any future rebrand on the typed slot's
23443 // outer-composite reader shape lands at exactly one place. Pins
23444 // the multi-axis coherence by exercising each per-axis refusal
23445 // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
23446 // `:clusters` pool under the outer accessor's reference
23447 // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
23448 // strategy with a `None` `:shard-key` under the same projection,
23449 // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
23450 // with a `Some` `:shard-key` under the same projection, and
23451 // (4) the canonical `three_member_spec` `Replicated` fixture
23452 // passes `validate_placement` under the outer accessor's
23453 // reference projection — the accessor's reference-projection
23454 // reaches every per-axis branch (cluster-pool refusal, `Sharded`
23455 // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
23456 // without silently short-circuiting any.
23457 //
23458 // Peer of the sibling M3
23459 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23460 // (534dc21) multi-axis coherence pin on the per-`:politicas`
23461 // outer mesh-policy composite-reference axis — extends the
23462 // multi-consumer coherence discipline onto the outermost M3
23463 // mesh-slot type's per-Aplicacao distribution composite-
23464 // reference axis, the second `&Composite`-return accessor on
23465 // the outer [`AplicacaoSpec`] type.
23466
23467 // (1) `PlacementWithoutClusters` refusal under the outer
23468 // accessor's reference projection: an empty `:clusters` pool
23469 // must trip the pre-flight refusal probe. The bracket-dispatch's
23470 // first arm reads `p.clusters()` on the reference returned by
23471 // the outer accessor.
23472 let mut spec = three_member_spec();
23473 spec.placement.clusters = Vec::new();
23474 assert_eq!(
23475 spec.validate().unwrap_err(),
23476 AplicacaoError::PlacementWithoutClusters {
23477 estrategia: PlacementStrategy::Replicated,
23478 },
23479 );
23480 assert!(
23481 std::ptr::eq(spec.placement(), &spec.placement),
23482 "the `validate_placement` per-axis bracket-dispatch's \
23483 traversal input must be the same backing composite the \
23484 accessor's reference projection borrows from",
23485 );
23486
23487 // (2) `ShardedWithoutKey` refusal under the outer accessor's
23488 // reference projection: a `Sharded` strategy with a `None`
23489 // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
23490 // The bracket-dispatch's third arm reads `p.estrategia()` for
23491 // the match scrutinee then `p.shard_key()` for the cascade
23492 // scrutinee, both on the reference returned by the outer
23493 // accessor.
23494 let mut spec = three_member_spec();
23495 spec.placement.estrategia = PlacementStrategy::Sharded;
23496 spec.placement.shard_key = None;
23497 assert_eq!(
23498 spec.validate().unwrap_err(),
23499 AplicacaoError::ShardedWithoutKey,
23500 );
23501
23502 // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
23503 // reference projection: a non-`Sharded` strategy with a `Some`
23504 // `:shard-key` must trip the declared-but-inert refusal. The
23505 // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
23506 // + `p.estrategia()` for the diagnostic on the reference
23507 // returned by the outer accessor.
23508 let mut spec = three_member_spec();
23509 spec.placement.estrategia = PlacementStrategy::Replicated;
23510 spec.placement.shard_key = Some("tenantId".into());
23511 assert_eq!(
23512 spec.validate().unwrap_err(),
23513 AplicacaoError::ShardKeyOnNonSharded {
23514 estrategia: PlacementStrategy::Replicated,
23515 shard_key: "tenantId".into(),
23516 },
23517 );
23518
23519 // (4) Canonical `three_member_spec` `Replicated` fixture passes
23520 // `validate_placement` — every per-axis arm reaches the fall-
23521 // through `Ok(())` without any per-axis refusal firing under the
23522 // outer accessor's reference projection.
23523 let spec = three_member_spec();
23524 assert!(
23525 spec.validate().is_ok(),
23526 "the canonical Replicated placement fixture must pass \
23527 `validate_placement` — every per-axis arm short-circuits on \
23528 valid input under the outer accessor's reference projection",
23529 );
23530 assert_eq!(
23531 spec.placement().estrategia(),
23532 PlacementStrategy::Replicated,
23533 "the outer accessor's reference projection must be the \
23534 canonical Replicated fixture's strategy",
23535 );
23536 assert_eq!(
23537 spec.placement().clusters(),
23538 &["rio", "mar"],
23539 "the outer accessor's reference projection must be the \
23540 canonical Replicated fixture's cluster pool",
23541 );
23542 }
23543
23544 #[test]
23545 fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
23546 // The canonical per-`:entrada` outer-composite-optional-
23547 // reference-shape pin: [`AplicacaoSpec::entrada`] must return
23548 // the `:entrada` typed `Option<Entrada>` verbatim as an
23549 // `Option<&Entrada>` reference over the same backing storage
23550 // the raw `self.entrada.as_ref()` field access borrows from,
23551 // byte-equal across every representative fixture in the
23552 // accept-set — the author-omitted `None` shape (the
23553 // "internal-only mesh" partition every downstream external-
23554 // gateway emitter treats as "emit nothing"), the minimal
23555 // singleton `:entrada` composite (host + destination + empty
23556 // paths + default port), the paths-carrying composite (the
23557 // canonical `three_member_spec` fixture's ["/api" "/health"]
23558 // path-list shape every HTTPRoute per-rule fan-out emitter
23559 // reads), and the non-default port composite (the canonical
23560 // custom-port shape the port-fallback resolver reads).
23561 //
23562 // Pins against a future silent detour that returned a fresh-
23563 // cloned `Entrada` copy (which would type-check via a `Clone`
23564 // impl but silently break every downstream caller that
23565 // relied on the reference sharing the composite's backing
23566 // identity), a reference to an operator-resolved overlay
23567 // (the future per-cluster `:entrada-overrides` slot the
23568 // MESH-COMPOSITION §V federation roadmap acknowledges — its
23569 // resolution must land at exactly this accessor body, not
23570 // silently divert the raw slot away from a second consumer),
23571 // a `None` → `Some(Entrada::default)` cluster-default
23572 // projection (which would collapse the load-bearing
23573 // "author-omitted `:entrada` ⇒ internal-only mesh" partition
23574 // the peer `gateway_routes` early-return + `feira app graph`
23575 // internal-only-mesh partition both read), or an axis-
23576 // shuffled projection (a future detour that swapped
23577 // `host` and `para` through the accessor would silently
23578 // split the paired `validate` per-`:entrada` shape-and-
23579 // membership gate's traversal input from the peer
23580 // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
23581 // fan-out input from the peer `feira app graph` external-
23582 // gateway summary line).
23583 //
23584 // Peer of the sibling M3
23585 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
23586 // (534dc21) `&MeshPolicy` byte-equal pin on the per-
23587 // `:politicas` outer mesh-policy composite-reference axis
23588 // and of the sibling M3
23589 // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
23590 // (9abb8f0) `&Placement` byte-equal pin on the per-
23591 // `:placement` outer distribution-composite composite-
23592 // reference axis — extends the outer-accessor byte-equal-
23593 // projection discipline onto the last unlifted outermost M3
23594 // mesh-slot type's per-Aplicacao external-gateway composite-
23595 // reference axis, the third and final `&Composite`-return
23596 // accessor on the outer [`AplicacaoSpec`] type.
23597 let fixtures: Vec<Option<Entrada>> = vec![
23598 None,
23599 Some(Entrada {
23600 host: "checkout.quero.cloud".into(),
23601 para: "cart".into(),
23602 paths: Vec::new(),
23603 port: DEFAULT_SERVICO_PORT,
23604 }),
23605 Some(Entrada {
23606 host: "checkout.quero.cloud".into(),
23607 para: "cart".into(),
23608 paths: vec!["/api".into(), "/health".into()],
23609 port: DEFAULT_SERVICO_PORT,
23610 }),
23611 Some(Entrada {
23612 host: "checkout.quero.cloud".into(),
23613 para: "cart".into(),
23614 paths: vec!["/api".into()],
23615 port: 9443,
23616 }),
23617 ];
23618 for entrada in fixtures {
23619 let s = AplicacaoSpec {
23620 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23621 contratos: Vec::new(),
23622 politicas: MeshPolicy::default(),
23623 placement: Placement::default(),
23624 entrada: entrada.clone(),
23625 };
23626 assert_eq!(
23627 s.entrada(),
23628 entrada.as_ref(),
23629 "AplicacaoSpec::entrada must return :entrada verbatim \
23630 (got {:?}, expected {:?})",
23631 s.entrada(),
23632 entrada.as_ref(),
23633 );
23634 match (s.entrada(), s.entrada.as_ref()) {
23635 (Some(a), Some(b)) => assert!(
23636 std::ptr::eq(a, b),
23637 "AplicacaoSpec::entrada accessor and \
23638 self.entrada.as_ref() field access must borrow \
23639 the same backing storage — the accessor is the \
23640 substrate-primitive typed dispatch every \
23641 downstream external-gateway composite consumer \
23642 must route through, and a reference-identity \
23643 split would silently break every consumer that \
23644 relied on the borrow sharing the composite's \
23645 storage",
23646 ),
23647 (None, None) => {}
23648 _ => panic!(
23649 "AplicacaoSpec::entrada presence bit must byte-\
23650 equal self.entrada.is_some() — a presence-bit \
23651 drift would silently split the paired `validate` \
23652 per-`:entrada` shape-and-membership gate's \
23653 traversal head from the peer \
23654 caixa-mesh gateway_routes early-return partition \
23655 from the peer `feira app graph` internal-only-\
23656 mesh partition",
23657 ),
23658 }
23659 assert_eq!(
23660 s.entrada().is_some(),
23661 s.entrada.is_some(),
23662 "AplicacaoSpec::entrada().is_some() must byte-equal \
23663 self.entrada.is_some() — a presence-bit drift would \
23664 silently split every downstream `Option<&Entrada>` \
23665 consumer's partition on the internal-only-mesh arm",
23666 );
23667 }
23668 }
23669
23670 #[test]
23671 fn validate_reads_through_lifted_entrada_accessor() {
23672 // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
23673 // per-`:entrada` shape-and-membership gate (`if let Some(e) =
23674 // self.entrada() { … }`, followed by the per-axis fan-out
23675 // `validate_entrada_para(&e.para)` /
23676 // `EntradaMemberMissing` membership lookup /
23677 // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
23678 // per-`e.paths` `validate_entrada_path` traversal) must key
23679 // off the lifted outer accessor, so any future rebrand on
23680 // the typed slot's outer-composite reader shape lands at
23681 // exactly one place. Pins the multi-axis coherence by
23682 // exercising each per-axis refusal end-to-end: (1) the
23683 // author-omitted `None` shape short-circuits past every
23684 // per-`:entrada` refusal (the internal-only mesh partition
23685 // the accessor's `None` arm names), (2) `EntradaMemberMissing`
23686 // fires on a well-shaped but phantom `:para` under the outer
23687 // accessor's reference projection, and (3) the canonical
23688 // `three_member_spec` `:entrada` fixture passes `validate`
23689 // under the outer accessor's reference projection.
23690 //
23691 // Peer of the sibling M3
23692 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23693 // (534dc21) multi-axis coherence pin on the per-`:politicas`
23694 // outer mesh-policy composite-reference axis and the sibling
23695 // M3
23696 // [`validate_placement_reads_through_lifted_placement_accessor`]
23697 // (9abb8f0) multi-axis coherence pin on the per-`:placement`
23698 // outer distribution-composite composite-reference axis —
23699 // extends the multi-consumer coherence discipline onto the
23700 // last unlifted outermost M3 mesh-slot type's per-Aplicacao
23701 // external-gateway composite-reference axis, the third and
23702 // final `&Composite`-return accessor on the outer
23703 // [`AplicacaoSpec`] type.
23704
23705 // (1) `None` :entrada — the internal-only-mesh partition
23706 // short-circuits past every per-`:entrada` refusal. The outer
23707 // accessor's reference projection reaches the fall-through
23708 // `Ok(())` on the `None` arm without any per-axis refusal
23709 // firing.
23710 let mut spec = three_member_spec();
23711 spec.entrada = None;
23712 assert!(
23713 spec.validate().is_ok(),
23714 "an author-omitted `:entrada` must pass `validate` — the \
23715 internal-only-mesh partition short-circuits past every \
23716 per-`:entrada` refusal under the outer accessor's \
23717 reference projection",
23718 );
23719 assert!(
23720 spec.entrada().is_none(),
23721 "the outer accessor's reference projection must name the \
23722 internal-only-mesh partition per the `None` fixture",
23723 );
23724
23725 // (2) `EntradaMemberMissing` refusal under the outer accessor's
23726 // reference projection: a well-shaped but phantom `:para` must
23727 // trip the membership-lookup refusal. The gate's second arm
23728 // reads `e.para` on the reference returned by the outer
23729 // accessor.
23730 let mut spec = three_member_spec();
23731 if let Some(e) = spec.entrada.as_mut() {
23732 e.para = "phantom".into();
23733 }
23734 assert_eq!(
23735 spec.validate().unwrap_err(),
23736 AplicacaoError::EntradaMemberMissing {
23737 para: "phantom".into(),
23738 },
23739 );
23740 match (spec.entrada(), spec.entrada.as_ref()) {
23741 (Some(a), Some(b)) => assert!(
23742 std::ptr::eq(a, b),
23743 "the `validate` per-`:entrada` gate's traversal head \
23744 must be the same backing composite the accessor's \
23745 reference projection borrows from",
23746 ),
23747 _ => panic!("fixture must carry Some(:entrada)"),
23748 }
23749
23750 // (3) Canonical `three_member_spec` `:entrada` fixture passes
23751 // `validate` — every per-axis arm reaches the fall-through
23752 // `Ok(())` without any per-axis refusal firing under the
23753 // outer accessor's reference projection.
23754 let spec = three_member_spec();
23755 assert!(
23756 spec.validate().is_ok(),
23757 "the canonical `:entrada` fixture must pass `validate` — \
23758 every per-axis arm short-circuits on valid input under \
23759 the outer accessor's reference projection",
23760 );
23761 assert!(
23762 spec.entrada().is_some(),
23763 "the outer accessor's reference projection must be the \
23764 canonical `:entrada` fixture's composite",
23765 );
23766 }
23767
23768 #[test]
23769 fn port_for_destination_reads_through_lifted_entrada_accessor() {
23770 // Peer coherence pin: the
23771 // [`AplicacaoSpec::port_for_destination`] per-destination
23772 // L4-port fallback resolver's composite-projection seed
23773 // (`self.entrada().filter(…).map_or(…)`) must key off the
23774 // lifted outer accessor. Pins the coherence by exercising
23775 // the resolver end-to-end: (1) the `None` `:entrada` shape
23776 // falls through to `DEFAULT_SERVICO_PORT` under the outer
23777 // accessor's reference projection, (2) a non-matching
23778 // destination falls through to `DEFAULT_SERVICO_PORT` under
23779 // the outer accessor's reference projection, and (3) the
23780 // matching destination resolves to the `:entrada :port`
23781 // value under the outer accessor's reference projection.
23782 //
23783 // Peer of the sibling
23784 // [`validate_reads_through_lifted_entrada_accessor`] multi-
23785 // consumer coherence pin on the same per-`:entrada` outer-
23786 // composite axis — extends the multi-consumer coherence
23787 // discipline onto the second per-`:entrada` production
23788 // consumer, the L4-port fallback resolver.
23789
23790 // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
23791 // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
23792 // arm under the outer accessor's reference projection.
23793 let mut spec = three_member_spec();
23794 spec.entrada = None;
23795 assert_eq!(
23796 spec.port_for_destination("cart"),
23797 DEFAULT_SERVICO_PORT,
23798 "the port-fallback resolver must fall through to \
23799 DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
23800 under the outer accessor's reference projection",
23801 );
23802
23803 // (2) Non-matching destination — the resolver's `filter(…)`
23804 // arm rejects a mismatched destination and falls through
23805 // to `DEFAULT_SERVICO_PORT` under the outer accessor's
23806 // reference projection.
23807 let mut spec = three_member_spec();
23808 if let Some(e) = spec.entrada.as_mut() {
23809 e.para = "cart".into();
23810 e.port = 9443;
23811 }
23812 assert_eq!(
23813 spec.port_for_destination("catalog"),
23814 DEFAULT_SERVICO_PORT,
23815 "the port-fallback resolver must fall through to \
23816 DEFAULT_SERVICO_PORT on a non-matching destination \
23817 under the outer accessor's reference projection",
23818 );
23819
23820 // (3) Matching destination — the resolver's `map_or(…)` arm
23821 // returns the `:entrada :port` value under the outer
23822 // accessor's reference projection.
23823 let mut spec = three_member_spec();
23824 if let Some(e) = spec.entrada.as_mut() {
23825 e.para = "cart".into();
23826 e.port = 9443;
23827 }
23828 assert_eq!(
23829 spec.port_for_destination("cart"),
23830 9443,
23831 "the port-fallback resolver must return the \
23832 `:entrada :port` value on a matching destination \
23833 under the outer accessor's reference projection",
23834 );
23835 }
23836
23837 #[test]
23838 fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
23839 // The canonical per-`:politicas` `:mtls-required` mTLS-
23840 // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
23841 // must return the `:politicas :mtls-required` typed bool
23842 // verbatim as an `Option<bool>`, byte-equal to the raw field
23843 // access across every value in the three-way accept-set —
23844 // `None` (cluster default applies), `Some(true)` (mTLS
23845 // handshake enforced — the sandboxing-by-default arm the
23846 // MeshPolicy's docstring names), `Some(false)` (handshake
23847 // skipped — the explicit debug-edge opt-out).
23848 //
23849 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
23850 // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
23851 // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
23852 // shape — first `Option<Copy-T>`-return accessor on the M3
23853 // mesh-slot family. Pins against a future silent detour that
23854 // re-derived the toggle from a peer axis (an accidental
23855 // `.circuit_breaker.is_some()` collapse that assumed mTLS on
23856 // whenever a breaker is set), a `None` → `Some(false)` cluster-
23857 // default projection (the canonical `Option<bool>` → `bool`
23858 // collapse footgun the surrounding `is_empty()` predicate
23859 // guards on the peer emptiness axis), or a `Some(true)` /
23860 // `Some(false)` variant swap that landed on one consumer
23861 // without the other.
23862 for required in [None, Some(true), Some(false)] {
23863 let p = MeshPolicy {
23864 mtls_required: required,
23865 ..MeshPolicy::default()
23866 };
23867 assert_eq!(
23868 p.mtls_required(),
23869 required,
23870 "MeshPolicy::mtls_required must return :politicas \
23871 :mtls-required verbatim (got {:?}, expected {required:?})",
23872 p.mtls_required(),
23873 );
23874 assert_eq!(
23875 p.mtls_required(),
23876 p.mtls_required,
23877 "MeshPolicy::mtls_required must byte-equal the raw \
23878 .mtls_required field access across every value in the \
23879 three-way accept-set",
23880 );
23881 }
23882 }
23883
23884 #[test]
23885 fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
23886 // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
23887 // arm must key off [`MeshPolicy::mtls_required`], not the raw
23888 // `.mtls_required` field access. Structurally: toggling ONLY
23889 // the `mtls_required` slot on an otherwise-default MeshPolicy
23890 // must flip `is_empty()` from `true` (all-`None`) to `false`
23891 // (one axis carries a value); the flip must be observed for
23892 // both `Some(true)` and `Some(false)` since the emptiness
23893 // semantic reads "any axis carries a value" — not "any axis
23894 // carries a truthy value" — the same non-collapsing shape the
23895 // sibling M2 [`crate::LimitsSpec::is_empty`] /
23896 // [`crate::BehaviorSpec::is_empty`] predicates carry on their
23897 // peer `Option<T>`-typed slot surfaces.
23898 //
23899 // Pins against a future silent detour that re-derived the
23900 // emptiness predicate off a peer axis (an accidental
23901 // `.rate_limit.is_none()`-only chain that dropped the
23902 // `mtls_required` arm entirely), a `mtls_required == Some(_)`
23903 // collapse to a truthy-only check (which would silently
23904 // classify `Some(false)` as empty), or an accessor-side
23905 // detour that no longer names the substrate-primitive typed
23906 // dispatch (an accidental `self.mtls_required.unwrap_or(false)
23907 // == false` fallback in the accessor that would silently
23908 // classify both `None` and `Some(false)` as the same value).
23909 //
23910 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
23911 // (7cd2a28) accessor-composition pin on the sibling optional-
23912 // scalar axis — same "the emptiness / shape-gate predicate
23913 // must route through the substrate-primitive typed dispatch"
23914 // discipline extended onto the peer per-`:politicas` emptiness
23915 // predicate.
23916 let empty = MeshPolicy::default();
23917 assert!(
23918 empty.is_empty(),
23919 "MeshPolicy::default() must be is_empty() — every axis \
23920 defaults to None",
23921 );
23922 for required in [Some(true), Some(false)] {
23923 let p = MeshPolicy {
23924 mtls_required: required,
23925 ..MeshPolicy::default()
23926 };
23927 assert!(
23928 !p.is_empty(),
23929 "MeshPolicy::is_empty must return false when \
23930 :mtls-required is {required:?} — the emptiness \
23931 predicate reads \"any axis carries a value\", not \
23932 \"any axis carries a truthy value\"",
23933 );
23934 assert_eq!(
23935 p.mtls_required().is_none(),
23936 p.is_empty(),
23937 "when :mtls-required is the only set axis, \
23938 is_empty() must equal mtls_required().is_none() — \
23939 the accessor and the emptiness predicate must \
23940 route through the same substrate-primitive typed \
23941 dispatch on the :mtls-required arm",
23942 );
23943 }
23944 }
23945
23946 #[test]
23947 fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
23948 // The by-copy pin: [`MeshPolicy::mtls_required`] returns
23949 // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
23950 // accessor must return by value, not by reference. Peer of the
23951 // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
23952 // borrow-invariant pin on the sibling `Option<String>` slot,
23953 // but extended onto the peer `Option<bool>` copy-invariant
23954 // shape — the accessor's returned `Option<bool>` must outlive
23955 // `&self` (multiple calls must return equal values from a
23956 // dropped-`&self` copy, since the returned Option carries no
23957 // borrow), and calling the accessor twice on the same
23958 // MeshPolicy must yield the same `Option<bool>` verbatim
23959 // (idempotent, no side effects on `&self`).
23960 //
23961 // Pins against a future silent detour that returned
23962 // `Option<&bool>` (which would type-check but silently break
23963 // every downstream caller — [`single_field_overlay`]'s first
23964 // parameter is `Option<T: Clone>`, and `&bool` would fold to a
23965 // detached copy at the call site), an accidental
23966 // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
23967 // would also type-check but return `Option<&bool>`), or a
23968 // one-arm-only accessor that reads `Some(*b)` in the Some arm
23969 // but reads a fresh Default::default() in the None arm.
23970 for required in [None, Some(true), Some(false)] {
23971 let p = MeshPolicy {
23972 mtls_required: required,
23973 ..MeshPolicy::default()
23974 };
23975 let first = p.mtls_required();
23976 let second = p.mtls_required();
23977 assert_eq!(
23978 first, second,
23979 "MeshPolicy::mtls_required must be idempotent — two \
23980 successive calls on the same &self must return the \
23981 same Option<bool>",
23982 );
23983 assert_eq!(
23984 first, required,
23985 "MeshPolicy::mtls_required must return :politicas \
23986 :mtls-required verbatim by copy — got {first:?}, \
23987 expected {required:?}",
23988 );
23989 }
23990 }
23991
23992 #[test]
23993 fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
23994 // The canonical per-`:politicas` `:retries` transient-failure-
23995 // retry-budget scalar pin: [`MeshPolicy::retries`] must return
23996 // the `:politicas :retries` typed `u32` verbatim as an
23997 // `Option<u32>`, byte-equal to the raw field access across every
23998 // representative value in the accept-set — `None` (cluster
23999 // default applies — typically "no retries beyond a single
24000 // dispatch attempt" the caixa-mesh `retry_overlay` builder
24001 // documents), `Some(1)` (the lower boundary of the
24002 // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
24003 // `AplicacaoSpec::validate_politicas` gate carves out on the
24004 // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
24005 // (the upper boundary the same gate carves out on the sibling
24006 // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
24007 // past-the-guard sentinel that pins the accessor doesn't perform
24008 // a silent bounds-collapse at the return path).
24009 //
24010 // Sibling of the peer per-`:politicas`
24011 // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
24012 // sibling `Option<Copy-T>` optional-scalar axis, extended to the
24013 // peer per-`:politicas` `Option<u32>` shape — second
24014 // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
24015 // Pins against a future silent detour that re-derived the retry
24016 // cap from a peer axis (an accidental `.circuit_breaker
24017 // .as_ref().map(|b| b.max_failures)` collapse that read the
24018 // breaker's max-failure count as a retry budget), a
24019 // `None → Some(0)` cluster-default projection (which would
24020 // silently re-introduce the `PolicyRetriesZero` refusal case at
24021 // the emit boundary), or a bounds-collapsing accessor that
24022 // clamped the return through `POLICY_RETRIES_MAX` (the
24023 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
24024 // must ship the raw slot verbatim so a validate-time gate
24025 // regression surfaces at the emit boundary rather than being
24026 // silently absorbed).
24027 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
24028 let p = MeshPolicy {
24029 retries,
24030 ..MeshPolicy::default()
24031 };
24032 assert_eq!(
24033 p.retries(),
24034 retries,
24035 "MeshPolicy::retries must return :politicas :retries \
24036 verbatim (got {:?}, expected {retries:?})",
24037 p.retries(),
24038 );
24039 assert_eq!(
24040 p.retries(),
24041 p.retries,
24042 "MeshPolicy::retries must byte-equal the raw .retries \
24043 field access across every value in the accept-set",
24044 );
24045 }
24046 }
24047
24048 #[test]
24049 fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
24050 // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
24051 // must key off [`MeshPolicy::retries`], not the raw `.retries`
24052 // field access. Structurally: toggling ONLY the `retries` slot
24053 // on an otherwise-default MeshPolicy must flip `is_empty()`
24054 // from `true` (all-`None`) to `false` (one axis carries a
24055 // value); the flip must be observed for every value in the
24056 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
24057 // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
24058 // the emptiness semantic reads "any axis carries a value" —
24059 // not "any axis carries a value the validate gate accepts" —
24060 // the same non-collapsing shape the peer M2
24061 // [`crate::LimitsSpec::is_empty`] /
24062 // [`crate::BehaviorSpec::is_empty`] predicates carry.
24063 //
24064 // Pins against a future silent detour that re-derived the
24065 // emptiness predicate off a peer axis (an accidental
24066 // `.rate_limit.is_none()`-only chain that dropped the
24067 // `retries` arm entirely), a `retries == Some(_)` collapse
24068 // that key-off a validate-gate-clamped bounds check (which
24069 // would silently classify a past-the-guard `Some(u32::MAX)`
24070 // as empty because it fails the `1..=POLICY_RETRIES_MAX`
24071 // check), or an accessor-side detour that no longer names the
24072 // substrate-primitive typed dispatch.
24073 //
24074 // Sibling of the peer per-`:politicas`
24075 // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
24076 // pin on the sibling `Option<Copy-T>` optional-scalar axis —
24077 // same "the emptiness predicate must route through the
24078 // substrate-primitive typed dispatch" discipline extended onto
24079 // the peer per-`:politicas` `Option<u32>` axis.
24080 let empty = MeshPolicy::default();
24081 assert!(
24082 empty.is_empty(),
24083 "MeshPolicy::default() must be is_empty() — every axis \
24084 defaults to None",
24085 );
24086 for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
24087 let p = MeshPolicy {
24088 retries,
24089 ..MeshPolicy::default()
24090 };
24091 assert!(
24092 !p.is_empty(),
24093 "MeshPolicy::is_empty must return false when \
24094 :retries is {retries:?} — the emptiness \
24095 predicate reads \"any axis carries a value\", not \
24096 \"any axis carries a value the validate gate \
24097 accepts\"",
24098 );
24099 assert_eq!(
24100 p.retries().is_none(),
24101 p.is_empty(),
24102 "when :retries is the only set axis, is_empty() \
24103 must equal retries().is_none() — the accessor and \
24104 the emptiness predicate must route through the same \
24105 substrate-primitive typed dispatch on the :retries \
24106 arm",
24107 );
24108 }
24109 }
24110
24111 #[test]
24112 fn mesh_policy_retries_projects_option_u32_by_copy() {
24113 // The by-copy pin: [`MeshPolicy::retries`] returns
24114 // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
24115 // accessor must return by value, not by reference. Sibling of
24116 // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
24117 // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
24118 // extended onto the sibling `Option<u32>` copy-invariant
24119 // shape — the accessor's returned `Option<u32>` must outlive
24120 // `&self` (multiple calls must return equal values from a
24121 // dropped-`&self` copy, since the returned Option carries no
24122 // borrow), and calling the accessor twice on the same
24123 // MeshPolicy must yield the same `Option<u32>` verbatim
24124 // (idempotent, no side effects on `&self`).
24125 //
24126 // Pins against a future silent detour that returned
24127 // `Option<&u32>` (which would type-check but silently break
24128 // every downstream caller — [`crate::render::single_field_overlay`]'s
24129 // first parameter is `Option<T: Clone>`, and `&u32` would
24130 // fold to a detached copy at the call site), an accidental
24131 // `Option::as_ref()` projection (`self.retries.as_ref()` would
24132 // also type-check but return `Option<&u32>`), or a one-arm-
24133 // only accessor that reads `Some(*n)` in the Some arm but
24134 // reads a fresh `Default::default()` (`0_u32`) in the None
24135 // arm.
24136 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
24137 let p = MeshPolicy {
24138 retries,
24139 ..MeshPolicy::default()
24140 };
24141 let first = p.retries();
24142 let second = p.retries();
24143 assert_eq!(
24144 first, second,
24145 "MeshPolicy::retries must be idempotent — two \
24146 successive calls on the same &self must return the \
24147 same Option<u32>",
24148 );
24149 assert_eq!(
24150 first, retries,
24151 "MeshPolicy::retries must return :politicas :retries \
24152 verbatim by copy — got {first:?}, expected {retries:?}",
24153 );
24154 }
24155 }
24156
24157 #[test]
24158 fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
24159 // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
24160 // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
24161 // return the `:politicas :timeout` typed [`Duration`] verbatim
24162 // as an `Option<Duration>`, byte-equal to the raw field access
24163 // across every representative value in the accept-set — `None`
24164 // (cluster default applies — typically the gateway class's
24165 // implementation-side per-request wall-clock cap the caixa-mesh
24166 // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
24167 // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
24168 // set the surrounding `AplicacaoSpec::validate_politicas` gate
24169 // carves out on the sibling `PolicyTimeoutZero` /
24170 // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
24171 // (the upper boundary the same gate carves out on the sibling
24172 // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
24173 // (a past-the-guard sentinel that pins the accessor doesn't
24174 // perform a silent bounds-collapse into `None` on the zero-
24175 // Duration arm — validate rejects zero but the accessor must
24176 // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
24177 // past-the-guard sentinel that pins the accessor doesn't
24178 // perform a silent bounds-collapse at the return path).
24179 //
24180 // Sibling of the peer per-`:politicas`
24181 // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
24182 // `Option<u32>` optional-scalar axis and the peer per-
24183 // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
24184 // pin on the sibling `Option<bool>` optional-scalar axis,
24185 // extended onto the peer per-`:politicas` `Option<Duration>`
24186 // shape — third `Option<Copy-T>`-return accessor on the M3
24187 // mesh-slot family. Pins against a future silent detour that
24188 // re-derived the per-call cap from a peer axis (an accidental
24189 // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
24190 // read the breaker's rolling-window duration as a per-call
24191 // deadline), a `None → Some(Duration::MAX)` cluster-default
24192 // projection (which would silently re-introduce the
24193 // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
24194 // blocking" arm at the emit boundary), or a bounds-collapsing
24195 // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
24196 // (the `AplicacaoSpec::validate` gate owns the bounds; the
24197 // accessor must ship the raw slot verbatim so a validate-time
24198 // gate regression surfaces at the emit boundary rather than
24199 // being silently absorbed).
24200 for timeout in [
24201 None,
24202 Some(Duration::from_millis(1)),
24203 Some(POLICY_TIMEOUT_MAX),
24204 Some(Duration::ZERO),
24205 Some(Duration::MAX),
24206 ] {
24207 let p = MeshPolicy {
24208 timeout,
24209 ..MeshPolicy::default()
24210 };
24211 assert_eq!(
24212 p.timeout(),
24213 timeout,
24214 "MeshPolicy::timeout must return :politicas :timeout \
24215 verbatim (got {:?}, expected {timeout:?})",
24216 p.timeout(),
24217 );
24218 assert_eq!(
24219 p.timeout(),
24220 p.timeout,
24221 "MeshPolicy::timeout must byte-equal the raw .timeout \
24222 field access across every value in the accept-set",
24223 );
24224 }
24225 }
24226
24227 #[test]
24228 fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
24229 // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
24230 // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
24231 // field access. Structurally: toggling ONLY the `timeout` slot
24232 // on an otherwise-default MeshPolicy must flip `is_empty()`
24233 // from `true` (all-`None`) to `false` (one axis carries a
24234 // value); the flip must be observed for every value in the
24235 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
24236 // gate accepts (`Some(Duration::from_millis(1))`,
24237 // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
24238 // reads "any axis carries a value" — not "any axis carries a
24239 // value the validate gate accepts" — the same non-collapsing
24240 // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
24241 // [`crate::BehaviorSpec::is_empty`] predicates carry.
24242 //
24243 // Pins against a future silent detour that re-derived the
24244 // emptiness predicate off a peer axis (an accidental
24245 // `.rate_limit.is_none()`-only chain that dropped the
24246 // `timeout` arm entirely), a `timeout == Some(_)` collapse
24247 // that key-off a validate-gate-clamped bounds check (which
24248 // would silently classify a past-the-guard `Some(Duration::MAX)`
24249 // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
24250 // check), or an accessor-side detour that no longer names the
24251 // substrate-primitive typed dispatch.
24252 //
24253 // Sibling of the peer per-`:politicas`
24254 // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
24255 // the sibling `Option<u32>` optional-scalar axis and the peer
24256 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
24257 // accessor-composition pin on the sibling `Option<bool>`
24258 // optional-scalar axis — same "the emptiness predicate must
24259 // route through the substrate-primitive typed dispatch"
24260 // discipline extended onto the peer per-`:politicas`
24261 // `Option<Duration>` axis.
24262 let empty = MeshPolicy::default();
24263 assert!(
24264 empty.is_empty(),
24265 "MeshPolicy::default() must be is_empty() — every axis \
24266 defaults to None",
24267 );
24268 for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
24269 let p = MeshPolicy {
24270 timeout,
24271 ..MeshPolicy::default()
24272 };
24273 assert!(
24274 !p.is_empty(),
24275 "MeshPolicy::is_empty must return false when \
24276 :timeout is {timeout:?} — the emptiness \
24277 predicate reads \"any axis carries a value\", not \
24278 \"any axis carries a value the validate gate \
24279 accepts\"",
24280 );
24281 assert_eq!(
24282 p.timeout().is_none(),
24283 p.is_empty(),
24284 "when :timeout is the only set axis, is_empty() \
24285 must equal timeout().is_none() — the accessor and \
24286 the emptiness predicate must route through the same \
24287 substrate-primitive typed dispatch on the :timeout \
24288 arm",
24289 );
24290 }
24291 }
24292
24293 #[test]
24294 fn mesh_policy_timeout_projects_option_duration_by_copy() {
24295 // The by-copy pin: [`MeshPolicy::timeout`] returns
24296 // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
24297 // and the accessor must return by value, not by reference.
24298 // Sibling of the peer per-`:politicas`
24299 // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
24300 // sibling `Option<u32>` optional-scalar axis and the peer
24301 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
24302 // by-copy pin on the sibling `Option<bool>` optional-scalar
24303 // axis, extended onto the peer per-`:politicas`
24304 // `Option<Duration>` copy-invariant shape — the accessor's
24305 // returned `Option<Duration>` must outlive `&self` (multiple
24306 // calls must return equal values from a dropped-`&self`
24307 // copy, since the returned Option carries no borrow), and
24308 // calling the accessor twice on the same MeshPolicy must
24309 // yield the same `Option<Duration>` verbatim (idempotent, no
24310 // side effects on `&self`).
24311 //
24312 // Pins against a future silent detour that returned
24313 // `Option<&Duration>` (which would type-check but silently
24314 // break every downstream caller — [`crate::render::single_field_overlay`]'s
24315 // first parameter is `Option<T: Clone>`, and `&Duration`
24316 // would fold to a detached copy at the call site), an
24317 // accidental `Option::as_ref()` projection
24318 // (`self.timeout.as_ref()` would also type-check but return
24319 // `Option<&Duration>`), or a one-arm-only accessor that
24320 // reads `Some(*d)` in the Some arm but reads a fresh
24321 // `Default::default()` (`Duration::ZERO`) in the None arm
24322 // (which would silently re-classify every unset `:timeout`
24323 // as the `PolicyTimeoutZero`-refused zero-Duration value at
24324 // the accessor boundary).
24325 for timeout in [
24326 None,
24327 Some(Duration::from_millis(1)),
24328 Some(POLICY_TIMEOUT_MAX),
24329 Some(Duration::ZERO),
24330 Some(Duration::MAX),
24331 ] {
24332 let p = MeshPolicy {
24333 timeout,
24334 ..MeshPolicy::default()
24335 };
24336 let first = p.timeout();
24337 let second = p.timeout();
24338 assert_eq!(
24339 first, second,
24340 "MeshPolicy::timeout must be idempotent — two \
24341 successive calls on the same &self must return the \
24342 same Option<Duration>",
24343 );
24344 assert_eq!(
24345 first, timeout,
24346 "MeshPolicy::timeout must return :politicas :timeout \
24347 verbatim by copy — got {first:?}, expected {timeout:?}",
24348 );
24349 }
24350 }
24351
24352 #[test]
24353 fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
24354 // The canonical per-`:politicas` `:rate-limit` Envoy-
24355 // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
24356 // [`MeshPolicy::rate_limit`] must return the `:politicas
24357 // :rate-limit` typed [`RateLimit`] verbatim as an
24358 // `Option<RateLimit>`, byte-equal to the raw field access
24359 // across every representative value in the accept-set — `None`
24360 // (cluster default applies — no per-Aplicacao rate declaration,
24361 // the gateway-class per-listener default arm the future caixa-
24362 // mesh `local_rate_limit_overlay` emitter documents),
24363 // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
24364 // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
24365 // accept-set the surrounding
24366 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
24367 // sibling `PolicyRateLimitZero` refusal, paired with the
24368 // canonical-window "1 second" arm of the three-unit
24369 // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
24370 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
24371 // (the upper boundary the same gate carves out on the sibling
24372 // `PolicyRateLimitExceedsCap` refusal, paired with the
24373 // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
24374 // (a past-the-guard sentinel that pins the accessor doesn't
24375 // perform a silent bounds-collapse into `None` on the
24376 // zero-rate/zero-window arm — validate rejects zero but the
24377 // accessor must ship the raw slot verbatim so a validate-time
24378 // gate regression surfaces at the emit boundary rather than
24379 // being silently absorbed), and
24380 // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
24381 // (a past-the-guard sentinel that pins the accessor doesn't
24382 // perform a silent bounds-collapse at the return path).
24383 //
24384 // First `Option<Copy-composite-T>`-return accessor pin on the
24385 // M3 mesh-slot family (peer of the sibling per-`:politicas`
24386 // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
24387 // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
24388 // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
24389 // Copy accessor pins, extended onto the peer per-`:politicas`
24390 // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
24391 // and the accessor returns by value). Pins against a future
24392 // silent detour that re-derived the rate declaration from a
24393 // peer axis (an accidental
24394 // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
24395 // collapse that read the breaker's trip threshold + rolling
24396 // window as a rate declaration), a `None → Some(default())`
24397 // cluster-default projection (which would silently re-
24398 // introduce a "cluster default is 0/s" arm the emit boundary
24399 // would take as "declared but inert" — the canonical
24400 // declared-but-inert footgun the sibling
24401 // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
24402 // amplification-shape axis), a bounds-collapsing accessor
24403 // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
24404 // clamped `rl.window` through [`is_canonical_rate_limit_window`]
24405 // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
24406 // accessor must ship the raw slot verbatim), or a
24407 // by-reference detour (`Option<&RateLimit>`) that broke every
24408 // downstream consumer keying off `Option<RateLimit>` by-copy.
24409 for rl in [
24410 None,
24411 Some(RateLimit {
24412 rate: 1,
24413 window: Duration::from_secs(1),
24414 }),
24415 Some(RateLimit {
24416 rate: POLICY_RATE_LIMIT_MAX,
24417 window: Duration::from_secs(3600),
24418 }),
24419 Some(RateLimit {
24420 rate: 0,
24421 window: Duration::ZERO,
24422 }),
24423 Some(RateLimit {
24424 rate: u32::MAX,
24425 window: Duration::MAX,
24426 }),
24427 ] {
24428 let p = MeshPolicy {
24429 rate_limit: rl,
24430 ..MeshPolicy::default()
24431 };
24432 assert_eq!(
24433 p.rate_limit(),
24434 rl,
24435 "MeshPolicy::rate_limit must return :politicas :rate-limit \
24436 verbatim (got {:?}, expected {rl:?})",
24437 p.rate_limit(),
24438 );
24439 assert_eq!(
24440 p.rate_limit(),
24441 p.rate_limit,
24442 "MeshPolicy::rate_limit must byte-equal the raw \
24443 .rate_limit field access across every value in the \
24444 accept-set",
24445 );
24446 }
24447 }
24448
24449 #[test]
24450 fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
24451 // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
24452 // must key off [`MeshPolicy::rate_limit`], not the raw
24453 // `.rate_limit` field access. Structurally: toggling ONLY the
24454 // `rate_limit` slot on an otherwise-default MeshPolicy must
24455 // flip `is_empty()` from `true` (all-`None`) to `false` (one
24456 // axis carries a value); the flip must be observed for every
24457 // representative value in the accept-set the surrounding
24458 // [`AplicacaoSpec::validate_politicas`] gate accepts
24459 // (`Some(RateLimit { rate: 1, window: 1s })`,
24460 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
24461 // since the emptiness semantic reads "any axis carries a
24462 // value" — not "any axis carries a value the validate gate
24463 // accepts" — the same non-collapsing shape the peer M2
24464 // [`crate::LimitsSpec::is_empty`] /
24465 // [`crate::BehaviorSpec::is_empty`] predicates carry.
24466 //
24467 // Pins against a future silent detour that re-derived the
24468 // emptiness predicate off a peer axis (an accidental
24469 // `.timeout.is_none()`-only chain that dropped the
24470 // `rate_limit` arm entirely — the last unlifted inline field
24471 // access on `is_empty` before this lift), a `rate_limit ==
24472 // Some(_)` collapse that key-off a validate-gate-clamped
24473 // bounds check (which would silently classify a past-the-
24474 // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
24475 // because it fails the value-shape gate), or an accessor-
24476 // side detour that no longer names the substrate-primitive
24477 // typed dispatch.
24478 //
24479 // Fourth "the emptiness predicate must route through the
24480 // substrate-primitive typed dispatch" composition pin on the
24481 // M3 mesh-slot family — closes the last unlifted composition
24482 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
24483 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
24484 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
24485 // 7073d0f is_empty-composition pins on the sibling primitive-
24486 // Copy axes, extended onto the peer per-`:politicas`
24487 // composite-Copy `Option<RateLimit>` axis).
24488 let empty = MeshPolicy::default();
24489 assert!(
24490 empty.is_empty(),
24491 "MeshPolicy::default() must be is_empty() — every axis \
24492 defaults to None",
24493 );
24494 for rl in [
24495 RateLimit {
24496 rate: 1,
24497 window: Duration::from_secs(1),
24498 },
24499 RateLimit {
24500 rate: POLICY_RATE_LIMIT_MAX,
24501 window: Duration::from_secs(3600),
24502 },
24503 ] {
24504 let p = MeshPolicy {
24505 rate_limit: Some(rl),
24506 ..MeshPolicy::default()
24507 };
24508 assert!(
24509 !p.is_empty(),
24510 "MeshPolicy::is_empty must return false when \
24511 :rate-limit is {rl:?} — the emptiness predicate \
24512 reads \"any axis carries a value\", not \"any axis \
24513 carries a value the validate gate accepts\"",
24514 );
24515 assert_eq!(
24516 p.rate_limit().is_none(),
24517 p.is_empty(),
24518 "when :rate-limit is the only set axis, is_empty() \
24519 must equal rate_limit().is_none() — the accessor \
24520 and the emptiness predicate must route through the \
24521 same substrate-primitive typed dispatch on the \
24522 :rate-limit arm",
24523 );
24524 }
24525 }
24526
24527 #[test]
24528 fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
24529 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24530 // `:rate-limit` value-shape gate must key off
24531 // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
24532 // field bind. Structurally: a `MeshPolicy` whose only set
24533 // axis is a `Some(RateLimit { rate: 0, .. })` must surface
24534 // the `PolicyRateLimitZero` refusal exactly, and the same
24535 // MeshPolicy with the rate at the canonical lower boundary
24536 // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
24537 // The pair jointly pins the accessor + validate-gate
24538 // composition: any future silent detour that had the accessor
24539 // omit the `Some(RateLimit { rate: 0, .. })` arm (a
24540 // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
24541 // silently absorb the `PolicyRateLimitZero` refusal at the
24542 // accessor boundary — the composition pin catches that at
24543 // caixa-core build time.
24544 //
24545 // Sibling of the peer [`validate_politicas`]
24546 // `:mtls-required` / `:retries` / `:timeout` composition pins
24547 // on the sibling primitive-Copy optional-scalar axes — same
24548 // "the validate / shape-gate predicate must route through the
24549 // substrate-primitive typed dispatch" discipline extended
24550 // onto the peer per-`:politicas` composite-Copy
24551 // `Option<RateLimit>` axis. Second composition-with-accessor
24552 // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
24553 // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
24554 let mut spec = three_member_spec();
24555 spec.politicas = MeshPolicy {
24556 rate_limit: Some(RateLimit {
24557 rate: 0,
24558 window: Duration::from_secs(1),
24559 }),
24560 ..MeshPolicy::default()
24561 };
24562 assert!(
24563 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
24564 "validate_politicas must reject rate == 0 with \
24565 PolicyRateLimitZero — the accessor and the validate gate \
24566 must route through the same substrate-primitive typed \
24567 dispatch on the :rate-limit zero-floor arm",
24568 );
24569 spec.politicas = MeshPolicy {
24570 rate_limit: Some(RateLimit {
24571 rate: 1,
24572 window: Duration::from_secs(1),
24573 }),
24574 ..MeshPolicy::default()
24575 };
24576 assert!(
24577 spec.validate().is_ok(),
24578 "validate_politicas must accept rate == 1 (the canonical \
24579 lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
24580 set) with a canonical 1s window",
24581 );
24582 }
24583
24584 #[test]
24585 fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
24586 // The canonical per-`:politicas` `:circuit-breaker` Envoy-
24587 // `outlier_detection`-mesh consecutive-failure-ejection scalar
24588 // pin: [`MeshPolicy::circuit_breaker`] must return the
24589 // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
24590 // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
24591 // raw field access across every representative value in the
24592 // accept-set — `None` (cluster default applies — no
24593 // per-Aplicacao breaker declaration, the gateway-class per-
24594 // listener default arm the future caixa-mesh
24595 // `outlier_detection_overlay` emitter documents),
24596 // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
24597 // (the lower boundary of the accept-set the surrounding
24598 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
24599 // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
24600 // refusals),
24601 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
24602 // (the upper boundary the same gate carves out on the sibling
24603 // `PolicyBreakerMaxFailuresExceedsCap` /
24604 // `PolicyBreakerWindowExceedsCap` refusals),
24605 // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
24606 // (a past-the-guard sentinel that pins the accessor doesn't
24607 // perform a silent bounds-collapse into `None` on the
24608 // zero-failures/zero-window arm — validate rejects zero but
24609 // the accessor must ship the raw slot verbatim so a validate-
24610 // time gate regression surfaces at the emit boundary rather
24611 // than being silently absorbed), and
24612 // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
24613 // (a past-the-guard sentinel that pins the accessor doesn't
24614 // perform a silent bounds-collapse at the return path).
24615 //
24616 // Second `Option<Copy-composite-T>`-return accessor pin on the
24617 // M3 mesh-slot family (peer of the sibling per-`:politicas`
24618 // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
24619 // composite-Copy accessor pin, and of the sibling per-
24620 // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
24621 // [`MeshPolicy::retries`] bdfb399 /
24622 // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
24623 // accessor pins). Pins against a future silent detour that
24624 // re-derived the breaker declaration from a peer axis (an
24625 // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
24626 // collapse that read the rate-limit's bucket capacity + refill
24627 // period as a breaker declaration), a `None → Some(default())`
24628 // cluster-default projection (which would silently re-
24629 // introduce the `PolicyBreakerZeroFailures` /
24630 // `PolicyBreakerZeroWindow` refusal cases at the emit
24631 // boundary), a bounds-collapsing accessor that clamped
24632 // `cb.max_failures` through
24633 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
24634 // through [`POLICY_BREAKER_WINDOW_MAX`] (the
24635 // [`AplicacaoSpec::validate`] gate owns the bounds; the
24636 // accessor must ship the raw slot verbatim), or a
24637 // by-reference detour (`Option<&CircuitBreaker>`) that broke
24638 // every downstream consumer keying off `Option<CircuitBreaker>`
24639 // by-copy.
24640 for cb in [
24641 None,
24642 Some(CircuitBreaker {
24643 max_failures: 1,
24644 window: Duration::from_millis(1),
24645 }),
24646 Some(CircuitBreaker {
24647 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
24648 window: POLICY_BREAKER_WINDOW_MAX,
24649 }),
24650 Some(CircuitBreaker {
24651 max_failures: 0,
24652 window: Duration::ZERO,
24653 }),
24654 Some(CircuitBreaker {
24655 max_failures: u32::MAX,
24656 window: Duration::MAX,
24657 }),
24658 ] {
24659 let p = MeshPolicy {
24660 circuit_breaker: cb,
24661 ..MeshPolicy::default()
24662 };
24663 assert_eq!(
24664 p.circuit_breaker(),
24665 cb,
24666 "MeshPolicy::circuit_breaker must return :politicas \
24667 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
24668 p.circuit_breaker(),
24669 );
24670 assert_eq!(
24671 p.circuit_breaker(),
24672 p.circuit_breaker,
24673 "MeshPolicy::circuit_breaker must byte-equal the raw \
24674 .circuit_breaker field access across every value in \
24675 the accept-set",
24676 );
24677 }
24678 }
24679
24680 #[test]
24681 fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
24682 // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
24683 // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
24684 // `.circuit_breaker` field access. Structurally: toggling ONLY
24685 // the `circuit_breaker` slot on an otherwise-default MeshPolicy
24686 // must flip `is_empty()` from `true` (all-`None`) to `false`
24687 // (one axis carries a value); the flip must be observed for
24688 // every representative value in the accept-set the surrounding
24689 // [`AplicacaoSpec::validate_politicas`] gate accepts
24690 // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
24691 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
24692 // since the emptiness semantic reads "any axis carries a
24693 // value" — not "any axis carries a value the validate gate
24694 // accepts" — the same non-collapsing shape the peer M2
24695 // [`crate::LimitsSpec::is_empty`] /
24696 // [`crate::BehaviorSpec::is_empty`] predicates carry.
24697 //
24698 // Pins against a future silent detour that re-derived the
24699 // emptiness predicate off a peer axis (an accidental
24700 // `.rate_limit.is_none()`-only chain that dropped the
24701 // `circuit_breaker` arm entirely — the last unlifted inline
24702 // field access on `is_empty` before this lift), a
24703 // `circuit_breaker == Some(_)` collapse that key-off a
24704 // validate-gate-clamped bounds check (which would silently
24705 // classify a past-the-guard `Some(CircuitBreaker { max_failures:
24706 // 0, window: 0s })` as empty because it fails the value-shape
24707 // gate), or an accessor-side detour that no longer names the
24708 // substrate-primitive typed dispatch.
24709 //
24710 // Fifth "the emptiness predicate must route through the
24711 // substrate-primitive typed dispatch" composition pin on the
24712 // M3 mesh-slot family — closes the last unlifted composition
24713 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
24714 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
24715 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
24716 // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
24717 // composition pins on the sibling primitive-Copy + composite-
24718 // Copy axes, extended onto the peer per-`:politicas`
24719 // composite-Copy `Option<CircuitBreaker>` axis).
24720 let empty = MeshPolicy::default();
24721 assert!(
24722 empty.is_empty(),
24723 "MeshPolicy::default() must be is_empty() — every axis \
24724 defaults to None",
24725 );
24726 for cb in [
24727 CircuitBreaker {
24728 max_failures: 1,
24729 window: Duration::from_millis(1),
24730 },
24731 CircuitBreaker {
24732 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
24733 window: POLICY_BREAKER_WINDOW_MAX,
24734 },
24735 ] {
24736 let p = MeshPolicy {
24737 circuit_breaker: Some(cb),
24738 ..MeshPolicy::default()
24739 };
24740 assert!(
24741 !p.is_empty(),
24742 "MeshPolicy::is_empty must return false when \
24743 :circuit-breaker is {cb:?} — the emptiness predicate \
24744 reads \"any axis carries a value\", not \"any axis \
24745 carries a value the validate gate accepts\"",
24746 );
24747 assert_eq!(
24748 p.circuit_breaker().is_none(),
24749 p.is_empty(),
24750 "when :circuit-breaker is the only set axis, \
24751 is_empty() must equal circuit_breaker().is_none() — \
24752 the accessor and the emptiness predicate must route \
24753 through the same substrate-primitive typed dispatch \
24754 on the :circuit-breaker arm",
24755 );
24756 }
24757 }
24758
24759 #[test]
24760 fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
24761 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24762 // `:circuit-breaker` value-shape gate must key off
24763 // [`MeshPolicy::circuit_breaker`], not the raw
24764 // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
24765 // whose only set axis is a `Some(CircuitBreaker { max_failures:
24766 // 0, .. })` must surface the `PolicyBreakerZeroFailures`
24767 // refusal exactly, and the same MeshPolicy with the breaker at
24768 // the canonical lower boundary
24769 // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
24770 // pass validate. The pair jointly pins the accessor +
24771 // validate-gate composition: any future silent detour that had
24772 // the accessor omit the `Some(CircuitBreaker { max_failures:
24773 // 0, .. })` arm (a
24774 // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
24775 // collapse) would silently absorb the
24776 // `PolicyBreakerZeroFailures` refusal at the accessor
24777 // boundary — the composition pin catches that at caixa-core
24778 // build time.
24779 //
24780 // Sibling of the peer [`validate_politicas`]
24781 // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
24782 // composition pins on the sibling primitive-Copy + composite-
24783 // Copy optional-scalar axes — same "the validate / shape-gate
24784 // predicate must route through the substrate-primitive typed
24785 // dispatch" discipline extended onto the peer per-`:politicas`
24786 // composite-Copy `Option<CircuitBreaker>` axis. Second
24787 // composition-with-accessor pin on the M3 mesh-slot
24788 // `Option<CircuitBreaker>` arm alongside the
24789 // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
24790 let mut spec = three_member_spec();
24791 spec.politicas = MeshPolicy {
24792 circuit_breaker: Some(CircuitBreaker {
24793 max_failures: 0,
24794 window: Duration::from_millis(1),
24795 }),
24796 ..MeshPolicy::default()
24797 };
24798 assert!(
24799 matches!(
24800 spec.validate(),
24801 Err(AplicacaoError::PolicyBreakerZeroFailures)
24802 ),
24803 "validate_politicas must reject max_failures == 0 with \
24804 PolicyBreakerZeroFailures — the accessor and the validate \
24805 gate must route through the same substrate-primitive \
24806 typed dispatch on the :circuit-breaker zero-floor arm",
24807 );
24808 spec.politicas = MeshPolicy {
24809 circuit_breaker: Some(CircuitBreaker {
24810 max_failures: 1,
24811 window: Duration::from_millis(1),
24812 }),
24813 ..MeshPolicy::default()
24814 };
24815 assert!(
24816 spec.validate().is_ok(),
24817 "validate_politicas must accept a CircuitBreaker at the \
24818 canonical lower boundary (max_failures = 1, window = \
24819 1ms) — the accessor and the validate gate must route \
24820 through the same substrate-primitive typed dispatch on \
24821 the :circuit-breaker arm",
24822 );
24823 }
24824
24825 #[test]
24826 fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
24827 // The canonical per-`:politicas :circuit-breaker` `:max-failures`
24828 // Envoy-outlier-detection trip-threshold scalar pin:
24829 // [`CircuitBreaker::max_failures`] must return the
24830 // `:politicas :circuit-breaker :max-failures` typed `u32`
24831 // verbatim, byte-equal to the raw field access across every
24832 // representative value in the accept-set — `1` (the lower
24833 // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
24834 // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
24835 // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
24836 // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
24837 // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
24838 // refusal), `0` (a past-the-guard sentinel that pins the accessor
24839 // doesn't perform a silent bounds-collapse into `1` on the zero
24840 // arm — validate rejects zero but the accessor must ship the
24841 // raw slot verbatim so a validate-time gate regression surfaces
24842 // at the emit boundary rather than being silently absorbed),
24843 // `u32::MAX` (a past-the-guard sentinel that pins the accessor
24844 // doesn't perform a silent bounds-collapse through
24845 // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
24846 //
24847 // First sub-struct required-scalar accessor pin on the M3
24848 // mesh-slot family — sibling in shape to the peer per-`:membros`
24849 // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
24850 // (a40b0e3) required-`String`-carry accessor pins and the peer
24851 // per-`:contratos` [`WitContract::source`] /
24852 // [`WitContract::destination`] (7f0fd43) required-`String`-carry
24853 // accessor pins, extended onto the peer per-`CircuitBreaker`
24854 // required-`u32` scalar-value axis. Pins against a future silent
24855 // detour that re-derived the trip threshold from a peer axis (an
24856 // accidental `self.window.as_secs() as u32` collapse that read
24857 // the breaker's rolling-window duration as a failure count), a
24858 // `0 → 1` cluster-default projection (which would silently absorb
24859 // the `PolicyBreakerZeroFailures` refusal case at the accessor
24860 // boundary), or a bounds-collapsing accessor that clamped the
24861 // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
24862 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
24863 // must ship the raw slot verbatim).
24864 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
24865 let cb = CircuitBreaker {
24866 max_failures,
24867 window: Duration::from_secs(60),
24868 };
24869 assert_eq!(
24870 cb.max_failures(),
24871 max_failures,
24872 "CircuitBreaker::max_failures must return :politicas \
24873 :circuit-breaker :max-failures verbatim (got {}, \
24874 expected {max_failures})",
24875 cb.max_failures(),
24876 );
24877 assert_eq!(
24878 cb.max_failures(),
24879 cb.max_failures,
24880 "CircuitBreaker::max_failures must byte-equal the raw \
24881 .max_failures field access across every value in the \
24882 u32 accept-set",
24883 );
24884 }
24885 }
24886
24887 #[test]
24888 fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
24889 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24890 // `:circuit-breaker :max-failures` zero-floor arm must key off
24891 // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
24892 // field access. Structurally: a `CircuitBreaker { max_failures:
24893 // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
24894 // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
24895 // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
24896 // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
24897 // pass validate. The pair jointly pins the accessor +
24898 // validate-gate composition: any future silent detour that had
24899 // the accessor return a fresh `1` on the zero arm (a
24900 // `.max_failures().max(1)` collapse) would silently absorb the
24901 // `PolicyBreakerZeroFailures` refusal at the accessor boundary
24902 // and the validate gate would accept a struct-literal
24903 // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
24904 // catches that at caixa-core build time.
24905 //
24906 // Peer of the sibling per-`:politicas`
24907 // [`MeshPolicy::mtls_required`] (c0110f1) /
24908 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
24909 // (7073d0f) accessor-composition pins on the sibling optional-
24910 // scalar axes — same "the validate / shape-gate predicate must
24911 // route through the substrate-primitive typed dispatch"
24912 // discipline extended onto the peer per-`CircuitBreaker`
24913 // required-scalar composition axis.
24914 let mut spec = three_member_spec();
24915 spec.politicas = MeshPolicy {
24916 circuit_breaker: Some(CircuitBreaker {
24917 max_failures: 0,
24918 window: Duration::from_secs(60),
24919 }),
24920 ..MeshPolicy::default()
24921 };
24922 assert!(
24923 matches!(
24924 spec.validate(),
24925 Err(AplicacaoError::PolicyBreakerZeroFailures)
24926 ),
24927 "validate_politicas must reject max_failures == 0 with \
24928 PolicyBreakerZeroFailures — the accessor and the validate \
24929 gate must route through the same substrate-primitive typed \
24930 dispatch on the :max-failures zero-floor arm",
24931 );
24932 spec.politicas = MeshPolicy {
24933 circuit_breaker: Some(CircuitBreaker {
24934 max_failures: 1,
24935 window: Duration::from_secs(60),
24936 }),
24937 ..MeshPolicy::default()
24938 };
24939 assert!(
24940 spec.validate().is_ok(),
24941 "validate_politicas must accept max_failures == 1 (the \
24942 lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
24943 accept-set)",
24944 );
24945 }
24946
24947 #[test]
24948 fn circuit_breaker_max_failures_projects_u32_by_copy() {
24949 // The by-copy pin: [`CircuitBreaker::max_failures`] returns
24950 // `u32` by copy — `u32` is `Copy` and the accessor must return
24951 // by value, not by reference. Peer of the sibling
24952 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
24953 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
24954 // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
24955 // optional-scalar axes, extended onto the peer
24956 // per-`CircuitBreaker` required-`u32` copy-invariant shape —
24957 // the accessor's returned `u32` must outlive `&self` (multiple
24958 // calls must return equal values from a dropped-`&self` copy,
24959 // since the returned scalar carries no borrow), and calling
24960 // the accessor twice on the same CircuitBreaker must yield the
24961 // same `u32` verbatim (idempotent, no side effects on `&self`).
24962 //
24963 // Pins against a future silent detour that returned `&u32`
24964 // (which would type-check but silently break every downstream
24965 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
24966 // first parameter is `u32`, and `&u32` would fold to a detached
24967 // copy at the call site with a `*` deref the sibling accessors
24968 // don't need), an accidental `.max_failures.wrapping_add(0)`
24969 // detour that returned a fresh copy through an arithmetic
24970 // no-op (breaking a future `const fn` regression), or a
24971 // one-arm-only accessor that returned a saturating value on
24972 // some sentinel input (breaking the pass-through invariant the
24973 // sibling required-scalar accessors carry).
24974 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
24975 let cb = CircuitBreaker {
24976 max_failures,
24977 window: Duration::from_secs(60),
24978 };
24979 let first = cb.max_failures();
24980 let second = cb.max_failures();
24981 assert_eq!(
24982 first, second,
24983 "CircuitBreaker::max_failures must be idempotent — two \
24984 successive calls on the same &self must return the \
24985 same u32",
24986 );
24987 assert_eq!(
24988 first, max_failures,
24989 "CircuitBreaker::max_failures must return :politicas \
24990 :circuit-breaker :max-failures verbatim by copy — \
24991 got {first}, expected {max_failures}",
24992 );
24993 }
24994 }
24995
24996 #[test]
24997 fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
24998 // The canonical per-`:politicas :circuit-breaker` `:window`
24999 // Envoy-outlier-detection rolling-observation-interval scalar
25000 // pin: [`CircuitBreaker::window`] must return the
25001 // `:politicas :circuit-breaker :window` typed `Duration`
25002 // verbatim, byte-equal to the raw field access across every
25003 // representative value in the accept-set — `Duration::from_millis(1)`
25004 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
25005 // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
25006 // gate carves out on the sibling `PolicyBreakerZeroWindow`
25007 // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
25008 // same gate carves out on the sibling
25009 // `PolicyBreakerWindowExceedsCap` refusal),
25010 // `Duration::ZERO` (a past-the-guard sentinel that pins the
25011 // accessor doesn't perform a silent bounds-collapse into
25012 // `Duration::from_millis(1)` on the zero arm — validate rejects
25013 // zero but the accessor must ship the raw slot verbatim so a
25014 // validate-time gate regression surfaces at the emit boundary
25015 // rather than being silently absorbed),
25016 // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
25017 // far above the 1h cap — that pins the accessor doesn't perform
25018 // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
25019 // at the return path).
25020 //
25021 // Second sub-struct required-scalar accessor pin on the M3
25022 // mesh-slot family — sibling in shape to the just-landed
25023 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
25024 // (3a74062) required-`u32` accessor pin on the peer
25025 // per-`CircuitBreaker` required-axis, extended onto the
25026 // per-sub-struct required-`Duration` axis. Pins against a
25027 // future silent detour that re-derived the observation window
25028 // from a peer axis (an accidental
25029 // `Duration::from_secs(self.max_failures as u64)` collapse that
25030 // read the breaker's trip count as an observation-interval
25031 // duration), a `Duration::ZERO → Duration::from_millis(1)`
25032 // cluster-default projection (which would silently absorb the
25033 // `PolicyBreakerZeroWindow` refusal case at the accessor
25034 // boundary), or a bounds-collapsing accessor that clamped the
25035 // return through `POLICY_BREAKER_WINDOW_MAX` (the
25036 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25037 // must ship the raw slot verbatim).
25038 for window in [
25039 Duration::from_millis(1),
25040 POLICY_BREAKER_WINDOW_MAX,
25041 Duration::ZERO,
25042 Duration::from_secs(86_400),
25043 ] {
25044 let cb = CircuitBreaker {
25045 max_failures: 5,
25046 window,
25047 };
25048 assert_eq!(
25049 cb.window(),
25050 window,
25051 "CircuitBreaker::window must return :politicas \
25052 :circuit-breaker :window verbatim (got {:?}, \
25053 expected {window:?})",
25054 cb.window(),
25055 );
25056 assert_eq!(
25057 cb.window(),
25058 cb.window,
25059 "CircuitBreaker::window must byte-equal the raw \
25060 .window field access across every value in the \
25061 Duration accept-set",
25062 );
25063 }
25064 }
25065
25066 #[test]
25067 fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
25068 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25069 // `:circuit-breaker :window` zero-floor arm must key off
25070 // [`CircuitBreaker::window`], not the raw `.window` field
25071 // access. Structurally: a `CircuitBreaker { window:
25072 // Duration::ZERO, .. }` embedded in a
25073 // `:politicas :circuit-breaker` slot must surface the
25074 // `PolicyBreakerZeroWindow` refusal exactly, and a
25075 // `CircuitBreaker { window: Duration::from_millis(1), .. }`
25076 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
25077 // accept-set) must pass validate. The pair jointly pins the
25078 // accessor + validate-gate composition: any future silent
25079 // detour that had the accessor return a fresh
25080 // `Duration::from_millis(1)` on the zero arm (a
25081 // `.window().max(Duration::from_millis(1))` collapse) would
25082 // silently absorb the `PolicyBreakerZeroWindow` refusal at the
25083 // accessor boundary and the validate gate would accept a
25084 // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
25085 // — the composition pin catches that at caixa-core build time.
25086 //
25087 // Peer of the sibling per-`CircuitBreaker`
25088 // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
25089 // pin on the peer required-scalar `:max-failures` axis — same
25090 // "the validate / shape-gate predicate must route through the
25091 // substrate-primitive typed dispatch" discipline extended onto
25092 // the peer per-`CircuitBreaker` required-`Duration` composition
25093 // axis.
25094 let mut spec = three_member_spec();
25095 spec.politicas = MeshPolicy {
25096 circuit_breaker: Some(CircuitBreaker {
25097 max_failures: 5,
25098 window: Duration::ZERO,
25099 }),
25100 ..MeshPolicy::default()
25101 };
25102 assert!(
25103 matches!(
25104 spec.validate(),
25105 Err(AplicacaoError::PolicyBreakerZeroWindow)
25106 ),
25107 "validate_politicas must reject window == Duration::ZERO \
25108 with PolicyBreakerZeroWindow — the accessor and the \
25109 validate gate must route through the same substrate-\
25110 primitive typed dispatch on the :window zero-floor arm",
25111 );
25112 spec.politicas = MeshPolicy {
25113 circuit_breaker: Some(CircuitBreaker {
25114 max_failures: 5,
25115 window: Duration::from_millis(1),
25116 }),
25117 ..MeshPolicy::default()
25118 };
25119 assert!(
25120 spec.validate().is_ok(),
25121 "validate_politicas must accept window == \
25122 Duration::from_millis(1) (the lower boundary of the \
25123 1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
25124 );
25125 }
25126
25127 #[test]
25128 fn circuit_breaker_window_projects_duration_by_copy() {
25129 // The by-copy pin: [`CircuitBreaker::window`] returns
25130 // `Duration` by copy — `Duration` is `Copy` and the accessor
25131 // must return by value, not by reference. Peer of the sibling
25132 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
25133 // (3a74062) by-copy pin on the peer required-scalar
25134 // `:max-failures` axis, extended onto the peer
25135 // per-`CircuitBreaker` required-`Duration` copy-invariant shape
25136 // — the accessor's returned `Duration` must outlive `&self`
25137 // (multiple calls must return equal values from a
25138 // dropped-`&self` copy, since the returned scalar carries no
25139 // borrow), and calling the accessor twice on the same
25140 // CircuitBreaker must yield the same `Duration` verbatim
25141 // (idempotent, no side effects on `&self`).
25142 //
25143 // Pins against a future silent detour that returned
25144 // `&Duration` (which would type-check but silently break every
25145 // downstream `Duration`-by-value consumer —
25146 // [`crate::render::require_positive_canonical_bounded_duration`]'s
25147 // first parameter is `Duration`, and `&Duration` would fold to
25148 // a detached copy at the call site with a `*` deref the sibling
25149 // accessors don't need), an accidental `.window + Duration::ZERO`
25150 // detour that returned a fresh copy through an arithmetic
25151 // no-op (breaking a future `const fn` regression), or a
25152 // one-arm-only accessor that returned a saturating value on
25153 // some sentinel input (breaking the pass-through invariant the
25154 // sibling required-scalar accessors carry).
25155 for window in [
25156 Duration::from_millis(1),
25157 POLICY_BREAKER_WINDOW_MAX,
25158 Duration::ZERO,
25159 Duration::from_secs(86_400),
25160 ] {
25161 let cb = CircuitBreaker {
25162 max_failures: 5,
25163 window,
25164 };
25165 let first = cb.window();
25166 let second = cb.window();
25167 assert_eq!(
25168 first, second,
25169 "CircuitBreaker::window must be idempotent — two \
25170 successive calls on the same &self must return the \
25171 same Duration",
25172 );
25173 assert_eq!(
25174 first, window,
25175 "CircuitBreaker::window must return :politicas \
25176 :circuit-breaker :window verbatim by copy — \
25177 got {first:?}, expected {window:?}",
25178 );
25179 }
25180 }
25181
25182 #[test]
25183 fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
25184 // Apex-identity pair-invariant pin composing both substrate-
25185 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
25186 // and [`WitContract::destination`] — at the emit-side call shape
25187 // every per-`(:de, :para)` CNP L4 port reader now takes. The
25188 // invariant, evaluated per-edge:
25189 //
25190 // spec.port_for_destination(c.destination()) == expected_port
25191 //
25192 // where `expected_port` is `entrada.port` when
25193 // `c.destination() == entrada.destination()` and
25194 // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
25195 // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
25196 // pin on the per-`:entrada` axis — that pin encodes the apex
25197 // ingress L4 identity via `entrada.destination()`; this pin
25198 // encodes the per-edge L4 identity via `c.destination()`, and
25199 // both compose on the same substrate-primitive resolver so a
25200 // future refactor that silently split either accessor's apex
25201 // behavior surfaces at caixa-core build time.
25202 let mut spec = three_member_spec();
25203 if let Some(e) = spec.entrada.as_mut() {
25204 e.para = "cart".into();
25205 e.port = 8443;
25206 }
25207 let apex_contract = WitContract {
25208 de: "checkout".into(),
25209 para: "cart".into(),
25210 wit: "wasi:http/proxy".into(),
25211 endpoint: Some("/hello".into()),
25212 subject: None,
25213 slot: None,
25214 };
25215 assert_eq!(
25216 spec.port_for_destination(apex_contract.destination()),
25217 8443,
25218 "`spec.port_for_destination(c.destination())` must equal \
25219 `entrada.port` when the contract callee names the ingress \
25220 apex — the CNP per-edge L4 port and the HTTPRoute apex \
25221 backendRef port share this substrate-primitive resolver.",
25222 );
25223 let non_apex_contract = WitContract {
25224 de: "cart".into(),
25225 para: "payment".into(),
25226 wit: "wasi:http/proxy".into(),
25227 endpoint: Some("/charge".into()),
25228 subject: None,
25229 slot: None,
25230 };
25231 assert_eq!(
25232 spec.port_for_destination(non_apex_contract.destination()),
25233 DEFAULT_SERVICO_PORT,
25234 "`spec.port_for_destination(c.destination())` must fall back \
25235 to the substrate-canonical port floor when the contract \
25236 callee is not the ingress apex — the resolver's non-apex \
25237 arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
25238 );
25239 }
25240
25241 #[test]
25242 fn membro_key_consts_are_lower_camel_case_shape() {
25243 // Shape-pin: every `MEMBRO_KEY_*` const must be a
25244 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25245 // `kebab-case` hyphens, no leading colon, no `PascalCase`
25246 // leading capital, no whitespace / dots) — the canonical shape
25247 // the `#[serde(rename_all = "camelCase")]` derive produces on
25248 // [`Membro`]. A future flip to a non-camelCase attribute at
25249 // the derive surfaces both here (this test fails on the
25250 // stale-constant shape) and at
25251 // `membro_serde_keys_match_lifted_membro_key_consts` (that test
25252 // fails on the mismatch between const and derive). Peer with
25253 // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
25254 // on the sibling `SupervisorSpec` top-level axis.
25255 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
25256 assert!(
25257 !key.is_empty(),
25258 "MEMBRO_KEY_* must be non-empty (got {key:?})"
25259 );
25260 let first = key.chars().next().unwrap();
25261 assert!(
25262 first.is_ascii_lowercase(),
25263 "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
25264 (got {key:?}, leads with {first:?})",
25265 );
25266 assert!(
25267 key.chars().all(|c| c.is_ascii_alphanumeric()),
25268 "MEMBRO_KEY_* must be ASCII-alphanumeric only \
25269 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25270 );
25271 }
25272 }
25273
25274 // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
25275
25276 #[test]
25277 fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
25278 // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
25279 // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
25280 // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
25281 // keys the `#[serde(rename_all = "camelCase")]` attribute on
25282 // [`WitContract`] emits for the required-triad. The three
25283 // sibling payload-arm keys already pin under
25284 // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
25285 // `STORE_FIELD_NAME` — pin all six alongside so a future
25286 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
25287 // verbatim-field-name flip at the derive attribute (any of which
25288 // would silently break every downstream JSON consumer that
25289 // reaches for one of the six via `Value::get(...)`) surfaces
25290 // here as a build-time test failure at `aplicacao.rs`, not as an
25291 // apply-time `.get(<stale-canonical-const>)` returning `None`
25292 // far from the derive-attr drift's commit. Peer with the sibling
25293 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
25294 // pin on the M3 `:membros` per-entry axis — same discipline the
25295 // `Membro` per-entry lift established, extended here to the
25296 // sibling M3 `WitContract` per-`:contratos` entry axis, the last
25297 // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
25298 // axis on the Aplicacao surface without a lifted serde-key peer.
25299 let c = WitContract {
25300 de: "cart".into(),
25301 para: "catalog".into(),
25302 wit: "wasi:http/proxy".into(),
25303 endpoint: Some("/lookup".into()),
25304 subject: None,
25305 slot: None,
25306 };
25307 let json = serde_json::to_string(&c).unwrap();
25308 for key in [
25309 crate::CONTRATO_KEY_DE,
25310 crate::CONTRATO_KEY_PARA,
25311 crate::CONTRATO_KEY_WIT,
25312 WitTarget::HTTP_FIELD_NAME,
25313 ] {
25314 let quoted = format!("\"{key}\"");
25315 assert!(
25316 json.contains("ed),
25317 "serialized WitContract must carry the lifted \
25318 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
25319 {quoted} verbatim in the JSON emission (got: {json})",
25320 );
25321 }
25322
25323 // Pin the two remaining payload-arm keys by round-tripping a
25324 // `WitContract` under each payload-shape (pub-sub, store) — the
25325 // required-triad appears on every emission but the payload arms
25326 // only surface when their `Option<String>` field is `Some`.
25327 let pubsub = WitContract {
25328 de: "cart".into(),
25329 para: "events".into(),
25330 wit: "nats:pub-sub".into(),
25331 endpoint: None,
25332 subject: Some("orders.placed".into()),
25333 slot: None,
25334 };
25335 let pubsub_json = serde_json::to_string(&pubsub).unwrap();
25336 let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
25337 assert!(
25338 pubsub_json.contains(&pubsub_quoted),
25339 "serialized pub-sub WitContract must carry the lifted \
25340 WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
25341 verbatim in the JSON emission (got: {pubsub_json})",
25342 );
25343 let store = WitContract {
25344 de: "cart".into(),
25345 para: "sessions".into(),
25346 wit: "wasi:keyvalue/store".into(),
25347 endpoint: None,
25348 subject: None,
25349 slot: Some("cart/$id".into()),
25350 };
25351 let store_json = serde_json::to_string(&store).unwrap();
25352 let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
25353 assert!(
25354 store_json.contains(&store_quoted),
25355 "serialized store WitContract must carry the lifted \
25356 WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
25357 verbatim in the JSON emission (got: {store_json})",
25358 );
25359 }
25360
25361 #[test]
25362 fn contrato_key_consts_are_pairwise_distinct() {
25363 // Cross-axis drift-detection pin: a future collapse of the six
25364 // canonical [`WitContract`] per-entry byte-strings onto the same
25365 // value (e.g. an accidental copy-paste flip of
25366 // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
25367 // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
25368 // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
25369 // every downstream probe on one axis onto the sibling axis's
25370 // overlay entry and pass every propagation-probe test that
25371 // expected only the stale axis's value. Peer of the sibling
25372 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
25373 // widened here to the six-way axis the `WitContract`
25374 // required-triad + `WitTarget` payload-triad jointly cover.
25375 let all = [
25376 crate::CONTRATO_KEY_DE,
25377 crate::CONTRATO_KEY_PARA,
25378 crate::CONTRATO_KEY_WIT,
25379 WitTarget::HTTP_FIELD_NAME,
25380 WitTarget::PUBSUB_FIELD_NAME,
25381 WitTarget::STORE_FIELD_NAME,
25382 ];
25383 for (i, a) in all.iter().enumerate() {
25384 for b in all.iter().skip(i + 1) {
25385 assert_ne!(
25386 a, b,
25387 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
25388 must be pairwise-distinct canonical byte-sequences \
25389 — got `{a}` == `{b}`",
25390 );
25391 }
25392 }
25393 }
25394
25395 #[test]
25396 fn contrato_key_consts_are_lower_camel_case_shape() {
25397 // Shape-pin: every `CONTRATO_KEY_*` (and every peer
25398 // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
25399 // byte-sequence (no `snake_case` underscores, no `kebab-case`
25400 // hyphens, no leading colon, no `PascalCase` leading capital, no
25401 // whitespace / dots) — the canonical shape the
25402 // `#[serde(rename_all = "camelCase")]` derive produces on
25403 // [`WitContract`]. A future flip to a non-camelCase attribute at
25404 // the derive surfaces both here (this test fails on the
25405 // stale-constant shape) and at
25406 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25407 // (that test fails on the mismatch between const and derive).
25408 // Peer with `membro_key_consts_are_lower_camel_case_shape`
25409 // (ce80ca0) on the sibling `Membro` per-entry axis.
25410 for key in [
25411 crate::CONTRATO_KEY_DE,
25412 crate::CONTRATO_KEY_PARA,
25413 crate::CONTRATO_KEY_WIT,
25414 WitTarget::HTTP_FIELD_NAME,
25415 WitTarget::PUBSUB_FIELD_NAME,
25416 WitTarget::STORE_FIELD_NAME,
25417 ] {
25418 assert!(
25419 !key.is_empty(),
25420 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
25421 non-empty (got {key:?})"
25422 );
25423 let first = key.chars().next().unwrap();
25424 assert!(
25425 first.is_ascii_lowercase(),
25426 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
25427 with an ASCII-lowercase byte (got {key:?}, leads with \
25428 {first:?})",
25429 );
25430 assert!(
25431 key.chars().all(|c| c.is_ascii_alphanumeric()),
25432 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
25433 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
25434 whitespace (got {key:?})",
25435 );
25436 }
25437 }
25438
25439 // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
25440
25441 #[test]
25442 fn entrada_serde_keys_match_lifted_entrada_key_consts() {
25443 // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
25444 // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
25445 // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
25446 // name the exact camelCase JSON keys the
25447 // `#[serde(rename_all = "camelCase")]` attribute on
25448 // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
25449 // pin that each canonical byte-sequence appears verbatim in the
25450 // JSON — a future accidental `rename_all = "snake_case"` /
25451 // `"kebab-case"` / verbatim-field-name flip at the derive
25452 // attribute (any of which would silently break every downstream
25453 // JSON consumer that reaches for one of the four consts via
25454 // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
25455 // emitter's per-Aplicacao hostname/paths/port projection, the
25456 // future `app-operator` reconciler's per-Aplicacao ingress
25457 // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
25458 // materializer's admission-time cross-check) surfaces here as
25459 // a build-time test failure at `aplicacao.rs`, not as an
25460 // apply-time `.get(<stale-canonical-const>)` returning `None`
25461 // far from the derive-attr drift's commit. Peer with the
25462 // sibling
25463 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25464 // (ca463a4) and
25465 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
25466 // pins on the M3 collection-slot atom axes — same discipline
25467 // both collection-slot lifts established, extended here to the
25468 // singleton `:entrada` mesh-slot atom axis, the last M3
25469 // typed-struct top-level `#[serde(rename_all = "camelCase")]`
25470 // axis on the Aplicacao surface without a lifted serde-key
25471 // peer.
25472 let e = Entrada {
25473 host: "checkout.quero.cloud".into(),
25474 para: "cart".into(),
25475 paths: vec!["/cart".into()],
25476 port: 8080,
25477 };
25478 let json = serde_json::to_string(&e).unwrap();
25479 for key in [
25480 crate::ENTRADA_KEY_HOST,
25481 crate::ENTRADA_KEY_PARA,
25482 crate::ENTRADA_KEY_PATHS,
25483 crate::ENTRADA_KEY_PORT,
25484 ] {
25485 let quoted = format!("\"{key}\"");
25486 assert!(
25487 json.contains("ed),
25488 "serialized Entrada must carry the lifted ENTRADA_KEY_* \
25489 byte-sequence {quoted} verbatim in the JSON emission \
25490 (got: {json})",
25491 );
25492 }
25493 }
25494
25495 #[test]
25496 fn entrada_key_consts_are_pairwise_distinct() {
25497 // Cross-axis drift-detection pin: a future collapse of the four
25498 // canonical [`Entrada`] singleton byte-strings onto the same
25499 // value (e.g. an accidental copy-paste flip of
25500 // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
25501 // silently reroute every downstream probe on one axis onto the
25502 // sibling axis's overlay entry and pass every propagation-probe
25503 // test that expected only the stale axis's value — the
25504 // Gateway/HTTPRoute emitter would read the hostname string
25505 // where the destination-Servico name was expected (or vice
25506 // versa), the admission-webhook cross-check would compare the
25507 // wrong pair of values, and the resulting Gateway resource
25508 // would either be admitted with garbage or rejected at the
25509 // controller far from the rebrand commit's source. Peer of the
25510 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
25511 // tetrad (40cc4e5), the two-way distinct pin on the
25512 // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
25513 // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
25514 // triad (ca463a4).
25515 let all = [
25516 crate::ENTRADA_KEY_HOST,
25517 crate::ENTRADA_KEY_PARA,
25518 crate::ENTRADA_KEY_PATHS,
25519 crate::ENTRADA_KEY_PORT,
25520 ];
25521 for (i, a) in all.iter().enumerate() {
25522 for b in all.iter().skip(i + 1) {
25523 assert_ne!(
25524 a, b,
25525 "ENTRADA_KEY_* consts must be pairwise-distinct \
25526 canonical byte-sequences — got `{a}` == `{b}`",
25527 );
25528 }
25529 }
25530 }
25531
25532 #[test]
25533 fn entrada_key_consts_are_lower_camel_case_shape() {
25534 // Shape-pin: every `ENTRADA_KEY_*` const must be a
25535 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25536 // `kebab-case` hyphens, no leading colon, no `PascalCase`
25537 // leading capital, no whitespace / dots) — the canonical shape
25538 // the `#[serde(rename_all = "camelCase")]` derive produces on
25539 // [`Entrada`]. A future flip to a non-camelCase attribute at
25540 // the derive surfaces both here (this test fails on the
25541 // stale-constant shape) and at
25542 // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
25543 // test fails on the mismatch between const and derive). Peer
25544 // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
25545 // and `contrato_key_consts_are_lower_camel_case_shape`
25546 // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
25547 // entry axes.
25548 for key in [
25549 crate::ENTRADA_KEY_HOST,
25550 crate::ENTRADA_KEY_PARA,
25551 crate::ENTRADA_KEY_PATHS,
25552 crate::ENTRADA_KEY_PORT,
25553 ] {
25554 assert!(
25555 !key.is_empty(),
25556 "ENTRADA_KEY_* must be non-empty (got {key:?})"
25557 );
25558 let first = key.chars().next().unwrap();
25559 assert!(
25560 first.is_ascii_lowercase(),
25561 "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
25562 (got {key:?}, leads with {first:?})",
25563 );
25564 assert!(
25565 key.chars().all(|c| c.is_ascii_alphanumeric()),
25566 "ENTRADA_KEY_* must be ASCII-alphanumeric only \
25567 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25568 );
25569 }
25570 }
25571
25572 // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
25573
25574 #[test]
25575 fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
25576 // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
25577 // ([`crate::POLITICAS_KEY_TIMEOUT`] /
25578 // [`crate::POLITICAS_KEY_RETRIES`] /
25579 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
25580 // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
25581 // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
25582 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
25583 // on [`MeshPolicy`] emits. Three of the five axes
25584 // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
25585 // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
25586 // camelCase transforms — the derive-attribute is load-bearing
25587 // on those, unlike the sibling `Entrada` / `Membro` /
25588 // `WitContract` structs whose fields are all lowercase-single-
25589 // word and where the derive is a no-op on every axis.
25590 // Serialize a fully-populated [`MeshPolicy`] (every axis
25591 // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
25592 // on none of the five slots) and pin that each canonical
25593 // byte-sequence appears verbatim in the JSON — a future
25594 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
25595 // verbatim-field-name flip at the derive attribute (any of
25596 // which would silently break every downstream JSON consumer
25597 // that reaches for one of the five consts via
25598 // `Value::get(...)` — the future M4 per-edge `:politicas`
25599 // overlay projection onto Cilium `L7Rules` and Gateway API
25600 // `HTTPRoute` backend timeouts, the future
25601 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
25602 // admission-time mesh-policy cross-check, the future
25603 // `feira lint` per-`:politicas` bound-check gate) surfaces here
25604 // as a build-time test failure at `aplicacao.rs`, not as an
25605 // apply-time `.get(<stale-canonical-const>)` returning `None`
25606 // far from the derive-attr drift's commit. Peer with the
25607 // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
25608 // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25609 // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
25610 // (ce80ca0) pins on the M3 collection-slot / singleton-slot
25611 // atom axes — same discipline every M3 sibling lift
25612 // established, extended here to the singleton `:politicas`
25613 // mesh-slot atom axis, closing the last M3 typed-struct
25614 // top-level `#[serde(rename_all = "camelCase")]` axis on the
25615 // Aplicacao surface without a lifted serde-key peer.
25616 let p = MeshPolicy {
25617 timeout: Some(Duration::from_secs(30)),
25618 retries: Some(3),
25619 circuit_breaker: Some(CircuitBreaker {
25620 max_failures: 5,
25621 window: Duration::from_secs(60),
25622 }),
25623 mtls_required: Some(true),
25624 rate_limit: Some(RateLimit {
25625 rate: 100,
25626 window: Duration::from_secs(1),
25627 }),
25628 };
25629 let json = serde_json::to_string(&p).unwrap();
25630 for key in [
25631 crate::POLITICAS_KEY_TIMEOUT,
25632 crate::POLITICAS_KEY_RETRIES,
25633 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
25634 crate::POLITICAS_KEY_MTLS_REQUIRED,
25635 crate::POLITICAS_KEY_RATE_LIMIT,
25636 ] {
25637 let quoted = format!("\"{key}\"");
25638 assert!(
25639 json.contains("ed),
25640 "serialized MeshPolicy must carry the lifted \
25641 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
25642 JSON emission (got: {json})",
25643 );
25644 }
25645 }
25646
25647 #[test]
25648 fn politicas_key_consts_are_pairwise_distinct() {
25649 // Cross-axis drift-detection pin: a future collapse of the five
25650 // canonical [`MeshPolicy`] singleton byte-strings onto the same
25651 // value (e.g. an accidental copy-paste flip of
25652 // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
25653 // would silently reroute every downstream probe on one axis
25654 // onto the sibling axis's overlay entry and pass every
25655 // propagation-probe test that expected only the stale axis's
25656 // value — the M4 per-edge `:politicas` overlay projection would
25657 // read the retry-count string where the timeout duration was
25658 // expected (or vice versa), the CR materializer's admission
25659 // cross-check would compare the wrong pair of values, and the
25660 // resulting mesh reconciler would either bind the wrong axis
25661 // or reject the resource at reconcile far from the rebrand
25662 // commit's source. Peer of the sibling four-way distinct pin
25663 // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
25664 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
25665 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
25666 // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
25667 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
25668 let all = [
25669 crate::POLITICAS_KEY_TIMEOUT,
25670 crate::POLITICAS_KEY_RETRIES,
25671 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
25672 crate::POLITICAS_KEY_MTLS_REQUIRED,
25673 crate::POLITICAS_KEY_RATE_LIMIT,
25674 ];
25675 for (i, a) in all.iter().enumerate() {
25676 for b in all.iter().skip(i + 1) {
25677 assert_ne!(
25678 a, b,
25679 "POLITICAS_KEY_* consts must be pairwise-distinct \
25680 canonical byte-sequences — got `{a}` == `{b}`",
25681 );
25682 }
25683 }
25684 }
25685
25686 #[test]
25687 fn politicas_key_consts_are_lower_camel_case_shape() {
25688 // Shape-pin: every `POLITICAS_KEY_*` const must be a
25689 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25690 // `kebab-case` hyphens, no leading colon, no `PascalCase`
25691 // leading capital, no whitespace / dots) — the canonical shape
25692 // the `#[serde(rename_all = "camelCase")]` derive produces on
25693 // [`MeshPolicy`]. A future flip to a non-camelCase attribute
25694 // at the derive surfaces both here (this test fails on the
25695 // stale-constant shape) and at
25696 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
25697 // (that test fails on the mismatch between const and derive).
25698 // Peer with `entrada_key_consts_are_lower_camel_case_shape`
25699 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
25700 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
25701 // (ca463a4) on the sibling M3 typed-struct axes.
25702 for key in [
25703 crate::POLITICAS_KEY_TIMEOUT,
25704 crate::POLITICAS_KEY_RETRIES,
25705 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
25706 crate::POLITICAS_KEY_MTLS_REQUIRED,
25707 crate::POLITICAS_KEY_RATE_LIMIT,
25708 ] {
25709 assert!(
25710 !key.is_empty(),
25711 "POLITICAS_KEY_* must be non-empty (got {key:?})"
25712 );
25713 let first = key.chars().next().unwrap();
25714 assert!(
25715 first.is_ascii_lowercase(),
25716 "POLITICAS_KEY_* must lead with an ASCII-lowercase \
25717 byte (got {key:?}, leads with {first:?})",
25718 );
25719 assert!(
25720 key.chars().all(|c| c.is_ascii_alphanumeric()),
25721 "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
25722 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25723 );
25724 }
25725 }
25726
25727 // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
25728
25729 #[test]
25730 fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
25731 // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
25732 // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
25733 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
25734 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
25735 // [`CircuitBreaker`] emits inside the
25736 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
25737 // two axes (`max_failures` → `maxFailures`) is a non-trivial
25738 // camelCase transform — the derive-attribute is load-bearing on
25739 // that axis, unlike the sibling `window` field where the derive
25740 // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
25741 // pin that each canonical byte-sequence appears verbatim in the
25742 // JSON — a future accidental `rename_all = "snake_case"` /
25743 // `"kebab-case"` / verbatim-field-name flip at the derive
25744 // attribute (any of which would silently break every downstream
25745 // JSON consumer that reaches for one of the two consts via
25746 // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
25747 // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
25748 // per-edge `:politicas` overlay projection onto the mesh's
25749 // per-backend consecutive-failure-counter tripping threshold, the
25750 // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
25751 // admission-time breaker cross-check, the future `feira lint`
25752 // per-`:politicas :circuit-breaker` bound-check gate) surfaces
25753 // here as a build-time test failure at `aplicacao.rs`, not as an
25754 // apply-time `.get(<stale-canonical-const>)` returning `None`
25755 // far from the derive-attr drift's commit. Peer with the sibling
25756 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
25757 // (b55cca7) parent-axis pin — that test pins the outer
25758 // sub-block key the derive on [`MeshPolicy`] emits, this test
25759 // pins the inner keys the derive on the payload type emits, so
25760 // the two together lock the whole [`MeshPolicy`] breaker-tuning
25761 // shape end-to-end at build time.
25762 let cb = CircuitBreaker {
25763 max_failures: 5,
25764 window: Duration::from_secs(60),
25765 };
25766 let json = serde_json::to_string(&cb).unwrap();
25767 for key in [
25768 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
25769 crate::CIRCUIT_BREAKER_KEY_WINDOW,
25770 ] {
25771 let quoted = format!("\"{key}\"");
25772 assert!(
25773 json.contains("ed),
25774 "serialized CircuitBreaker must carry the lifted \
25775 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
25776 in the JSON emission (got: {json})",
25777 );
25778 }
25779 }
25780
25781 #[test]
25782 fn circuit_breaker_key_consts_are_pairwise_distinct() {
25783 // Cross-axis drift-detection pin: a future collapse of the two
25784 // canonical [`CircuitBreaker`] sub-block byte-strings onto the
25785 // same value (e.g. an accidental copy-paste flip of
25786 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
25787 // `"maxFailures"`) would silently reroute every downstream
25788 // probe on one axis onto the sibling axis's overlay entry and
25789 // pass every propagation-probe test that expected only the
25790 // stale axis's value — the M4 per-edge `:politicas` overlay
25791 // projection would read the failure-count where the window
25792 // duration was expected (or vice versa), the CR materializer's
25793 // admission cross-check would compare the wrong pair of values,
25794 // and the resulting mesh reconciler would either bind the wrong
25795 // axis or reject the resource at reconcile far from the rebrand
25796 // commit's source. Peer of the sibling five-way distinct pin on
25797 // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
25798 // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
25799 // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
25800 // six-way distinct pin on the `CONTRATO_KEY_*` triad +
25801 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
25802 let all = [
25803 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
25804 crate::CIRCUIT_BREAKER_KEY_WINDOW,
25805 ];
25806 for (i, a) in all.iter().enumerate() {
25807 for b in all.iter().skip(i + 1) {
25808 assert_ne!(
25809 a, b,
25810 "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
25811 canonical byte-sequences — got `{a}` == `{b}`",
25812 );
25813 }
25814 }
25815 }
25816
25817 #[test]
25818 fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
25819 // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
25820 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25821 // `kebab-case` hyphens, no leading colon, no `PascalCase`
25822 // leading capital, no whitespace / dots) — the canonical shape
25823 // the `#[serde(rename_all = "camelCase")]` derive produces on
25824 // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
25825 // at the derive surfaces both here (this test fails on the
25826 // stale-constant shape) and at
25827 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
25828 // (that test fails on the mismatch between const and derive).
25829 // Peer with `politicas_key_consts_are_lower_camel_case_shape`
25830 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
25831 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
25832 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
25833 // (ca463a4) on the sibling M3 typed-struct axes.
25834 for key in [
25835 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
25836 crate::CIRCUIT_BREAKER_KEY_WINDOW,
25837 ] {
25838 assert!(
25839 !key.is_empty(),
25840 "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
25841 );
25842 let first = key.chars().next().unwrap();
25843 assert!(
25844 first.is_ascii_lowercase(),
25845 "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
25846 byte (got {key:?}, leads with {first:?})",
25847 );
25848 assert!(
25849 key.chars().all(|c| c.is_ascii_alphanumeric()),
25850 "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
25851 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25852 );
25853 }
25854 }
25855
25856 // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
25857
25858 #[test]
25859 fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
25860 // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
25861 // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
25862 // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
25863 // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
25864 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
25865 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
25866 // [`Placement`] emits. One of the four axes (`shard_key` →
25867 // `shardKey`) is a non-trivial camelCase transform — the
25868 // derive-attribute is load-bearing on that axis, unlike the
25869 // sibling `estrategia` / `clusters` / `affinity` axes whose
25870 // source-side field names carry no `_` and where the derive is a
25871 // no-op. Serialize a fully-populated [`Placement`] (both
25872 // `Option`-carrying axes `Some(_)` so
25873 // `skip_serializing_if = "Option::is_none"` fires on neither of
25874 // the two optional slots) and pin that each canonical
25875 // byte-sequence appears verbatim in the JSON — a future
25876 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
25877 // verbatim-field-name flip at the derive attribute (any of which
25878 // would silently break every downstream consumer that reaches
25879 // for one of the four consts via
25880 // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
25881 // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
25882 // aggregator's per-cluster fanout filter keying off
25883 // `placement.clusters`, the M3 shard-pool dispatch materializer
25884 // keying off `placement.shardKey`, the M3 Adaptive compression
25885 // pass weighting off `placement.affinity`, every downstream
25886 // dispatcher branching on `placement.estrategia`, the future
25887 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
25888 // admission-time placement cross-check, the future `feira lint`
25889 // per-`:placement` bound-check gate) surfaces here as a
25890 // build-time test failure at `aplicacao.rs`, not as an
25891 // apply-time `.get(<stale-canonical-const>)` returning `None`
25892 // far from the derive-attr drift's commit. Peer with the sibling
25893 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
25894 // (b55cca7),
25895 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
25896 // (468e959),
25897 // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
25898 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25899 // (ca463a4), and
25900 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
25901 // pins on the M3 collection-slot / singleton-slot atom axes —
25902 // closes the last M3 typed-struct top-level
25903 // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
25904 // surface without a drift-detection pin.
25905 let p = Placement {
25906 estrategia: PlacementStrategy::Sharded,
25907 clusters: vec!["rio".into(), "mar".into()],
25908 affinity: Some("data-locality".into()),
25909 shard_key: Some("$tenantId".into()),
25910 };
25911 let json = serde_json::to_string(&p).unwrap();
25912 for key in [
25913 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
25914 crate::M3_PLACEMENT_KEY_CLUSTERS,
25915 crate::M3_PLACEMENT_KEY_AFFINITY,
25916 crate::M3_PLACEMENT_KEY_SHARD_KEY,
25917 ] {
25918 let quoted = format!("\"{key}\"");
25919 assert!(
25920 json.contains("ed),
25921 "serialized Placement must carry the lifted \
25922 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
25923 the JSON emission (got: {json})",
25924 );
25925 }
25926 }
25927
25928 #[test]
25929 fn m3_placement_key_consts_are_pairwise_distinct() {
25930 // Cross-axis drift-detection pin: a future collapse of the four
25931 // canonical [`Placement`] sub-block byte-strings onto the same
25932 // value (e.g. an accidental copy-paste flip of
25933 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
25934 // `"affinity"`) would silently reroute every downstream probe on
25935 // one axis onto the sibling axis's overlay entry and pass every
25936 // propagation-probe test that expected only the stale axis's
25937 // value — the M3 shard-pool dispatch materializer would read the
25938 // affinity placement-hint where the shard-selection template was
25939 // expected (or vice versa), the M3 Adaptive compression pass's
25940 // cross-check would compare the wrong pair of values, and the
25941 // resulting placement engine would either bind the wrong axis or
25942 // reject the resource at reconcile far from the rebrand commit's
25943 // source. Peer of the sibling two-way distinct pin on the
25944 // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
25945 // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
25946 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
25947 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
25948 // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
25949 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
25950 let all = [
25951 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
25952 crate::M3_PLACEMENT_KEY_CLUSTERS,
25953 crate::M3_PLACEMENT_KEY_AFFINITY,
25954 crate::M3_PLACEMENT_KEY_SHARD_KEY,
25955 ];
25956 for (i, a) in all.iter().enumerate() {
25957 for b in all.iter().skip(i + 1) {
25958 assert_ne!(
25959 a, b,
25960 "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
25961 canonical byte-sequences — got `{a}` == `{b}`",
25962 );
25963 }
25964 }
25965 }
25966
25967 #[test]
25968 fn m3_placement_key_consts_are_lower_camel_case_shape() {
25969 // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
25970 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25971 // `kebab-case` hyphens, no leading colon, no `PascalCase`
25972 // leading capital, no whitespace / dots) — the canonical shape
25973 // the `#[serde(rename_all = "camelCase")]` derive produces on
25974 // [`Placement`]. A future flip to a non-camelCase attribute at
25975 // the derive surfaces both here (this test fails on the stale-
25976 // constant shape) and at
25977 // `placement_serde_keys_match_lifted_m3_placement_key_consts`
25978 // (that test fails on the mismatch between const and derive).
25979 // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
25980 // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
25981 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
25982 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
25983 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
25984 // (ca463a4) on the sibling M3 typed-struct axes.
25985 for key in [
25986 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
25987 crate::M3_PLACEMENT_KEY_CLUSTERS,
25988 crate::M3_PLACEMENT_KEY_AFFINITY,
25989 crate::M3_PLACEMENT_KEY_SHARD_KEY,
25990 ] {
25991 assert!(
25992 !key.is_empty(),
25993 "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
25994 );
25995 let first = key.chars().next().unwrap();
25996 assert!(
25997 first.is_ascii_lowercase(),
25998 "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
25999 byte (got {key:?}, leads with {first:?})",
26000 );
26001 assert!(
26002 key.chars().all(|c| c.is_ascii_alphanumeric()),
26003 "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
26004 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26005 );
26006 }
26007 }
26008
26009 // ── AplicacaoSpec::port_for_destination — the substrate-canonical
26010 // destination-facing L4 port resolver every per-Aplicacao renderer
26011 // reaching for a per-destination Servico TCP port axis routes
26012 // through. The four pin tests below fix the four-way accept-set
26013 // the resolver must always honor: (:entrada-para-matches,
26014 // :entrada-para-mismatches, :entrada-none-so-fallback,
26015 // :entrada-port-non-default-honored) — drift on any arm surfaces
26016 // at caixa-core build time rather than at cluster-apply time.
26017
26018 #[test]
26019 fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
26020 // The typed `:entrada` block's `:para "cart"` matches the
26021 // queried destination, so the resolver returns the author-
26022 // declared `:port` scalar verbatim — the canonical "the
26023 // destination Servico IS the ingress apex, honor the typed
26024 // listener port" arm of the port-resolution dispatch.
26025 let mut spec = three_member_spec();
26026 if let Some(e) = spec.entrada.as_mut() {
26027 e.para = "cart".into();
26028 e.port = 9090;
26029 }
26030 assert_eq!(
26031 spec.port_for_destination("cart"),
26032 9090,
26033 "port_for_destination(entrada.para) must return entrada.port \
26034 verbatim, not the DEFAULT_SERVICO_PORT fallback"
26035 );
26036 }
26037
26038 #[test]
26039 fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
26040 // The typed `:entrada` block names `:para "cart"`, but the
26041 // queried destination is `"payment"` — a Servico that
26042 // participates in the mesh graph but is not the ingress apex.
26043 // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
26044 // canonical port floor, closing the "non-apex destination reads
26045 // the substrate default" arm. Same fixture the peer
26046 // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
26047 // pin at caixa-mesh exercises through the CNP emit-side path;
26048 // this pin exercises the shared underlying resolver directly.
26049 let spec = three_member_spec();
26050 assert_eq!(
26051 spec.port_for_destination("payment"),
26052 DEFAULT_SERVICO_PORT,
26053 "port_for_destination(non-apex-destination) must route \
26054 through the lifted DEFAULT_SERVICO_PORT canonical port floor"
26055 );
26056 }
26057
26058 #[test]
26059 fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
26060 // Internal-only Aplicacao — no `:entrada` block declared. Every
26061 // per-destination port query falls back to the lifted
26062 // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
26063 // the Aplicacao surface admits `:entrada None` (internal mesh
26064 // with no external gateway); every downstream renderer's per-
26065 // destination port axis must still resolve to a well-defined
26066 // scalar even without an ingress apex.
26067 let mut spec = three_member_spec();
26068 spec.entrada = None;
26069 assert_eq!(
26070 spec.port_for_destination("cart"),
26071 DEFAULT_SERVICO_PORT,
26072 "port_for_destination on an internal-only Aplicacao must \
26073 fall back to the lifted DEFAULT_SERVICO_PORT floor for \
26074 every destination"
26075 );
26076 assert_eq!(
26077 spec.port_for_destination("payment"),
26078 DEFAULT_SERVICO_PORT,
26079 "port_for_destination on an internal-only Aplicacao must \
26080 fall back uniformly across every destination — the fallback \
26081 is not entrada-shape-conditional"
26082 );
26083 }
26084
26085 #[test]
26086 fn port_for_destination_honors_non_default_entrada_port_verbatim() {
26087 // Structural pin against a hypothetical future refactor that
26088 // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
26089 // the resolver (a "normalize to the default when the author's
26090 // port matches the substrate default" collapse) — that would
26091 // break renderer sites that carry meaning on the emitted port
26092 // value beyond bare equality (a future per-cluster listener-
26093 // audit that keys off the author-declared port, not the
26094 // resolved-with-fallback port). Pin that a non-default
26095 // entrada.port is returned verbatim so drift here surfaces at
26096 // caixa-core build time.
26097 let mut spec = three_member_spec();
26098 if let Some(e) = spec.entrada.as_mut() {
26099 e.para = "cart".into();
26100 e.port = 8443;
26101 }
26102 assert_ne!(
26103 8443, DEFAULT_SERVICO_PORT,
26104 "test fixture must probe a port distinct from \
26105 DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
26106 );
26107 assert_eq!(
26108 spec.port_for_destination("cart"),
26109 8443,
26110 "port_for_destination(entrada.para) must return entrada.port \
26111 verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
26112 );
26113 }
26114
26115 #[test]
26116 fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
26117 // Apex-identity pair-invariant pin composing both substrate-
26118 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26119 // and [`Entrada::destination`] — at the emit-side call shape
26120 // every per-Aplicacao renderer's ingress-apex L4 port reader
26121 // now takes. The invariant:
26122 //
26123 // spec.port_for_destination(entrada.destination()) == entrada.port
26124 //
26125 // holds by construction under today's single-destination
26126 // `:entrada` slot (`destination()` returns `entrada.para`, and
26127 // the resolver's apex arm matches `para == destination` and
26128 // returns `entrada.port`), and every downstream consumer that
26129 // composes the two accessors at the ingress apex — the
26130 // `caixa_mesh::gateway_routes` HTTPRoute per-rule
26131 // `backendRefs[0].port` emit-site path, the peer future M4 CR
26132 // materializer's admission-webhook that promotes the scalar to
26133 // a per-CR override overlay, every future per-Aplicacao snapshot
26134 // renderer's apex-facing L4 port reader — reaches through the
26135 // same composition. Pin the identity across four permutations
26136 // (`:para` × `:port` including a non-default port to exercise
26137 // the honor-verbatim arm and a non-cart `:para` to exercise
26138 // destination-agnostic identity) so a future refactor that
26139 // silently split either accessor's apex behavior surfaces at
26140 // caixa-core build time — a subtle `destination()` renaming
26141 // that returned `entrada.host.as_str()` instead of
26142 // `entrada.para.as_str()` would blow this pin loudly, closing
26143 // the last quiet failure mode the two lifts admit in composition.
26144 //
26145 // Peer discipline with the sibling caixa-mesh cross-crate pin
26146 // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
26147 // on the two-renderer pair-invariant axis; this pin encodes the
26148 // same two-consumer coherence rule at the substrate-primitive
26149 // level so the invariant survives even if every renderer is
26150 // deleted.
26151 for (para, port) in [
26152 ("cart", DEFAULT_SERVICO_PORT),
26153 ("cart", 8443u16),
26154 ("payment", 9090u16),
26155 ("catalog", 443u16),
26156 ] {
26157 let mut spec = three_member_spec();
26158 if let Some(e) = spec.entrada.as_mut() {
26159 e.para = para.into();
26160 e.port = port;
26161 }
26162 let expected_port = spec
26163 .entrada()
26164 .expect("three_member_spec carries a typed `:entrada` block")
26165 .port();
26166 let composed_port = {
26167 let entrada = spec.entrada().expect("entrada present");
26168 spec.port_for_destination(entrada.destination())
26169 };
26170 assert_eq!(
26171 composed_port, expected_port,
26172 "`spec.port_for_destination(entrada.destination())` must \
26173 equal `entrada.port` under today's single-destination \
26174 `:entrada` slot — this is the apex-identity contract \
26175 every downstream ingress-apex L4 port reader relies on. \
26176 Input :entrada :para: {para:?}, :entrada :port: {port}"
26177 );
26178 }
26179 }
26180
26181 #[test]
26182 fn port_for_destination_apex_arm_routes_through_destination_accessor() {
26183 // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
26184 // per-`:entrada` apex-arm membership probe must key off
26185 // [`Entrada::destination`], not the raw `.para` field access.
26186 // Structurally: setting ONLY the `:entrada :para` field to a
26187 // fresh non-cart destination on an otherwise-well-formed
26188 // Aplicacao must (1) leave `e.destination()` byte-equal to
26189 // `e.para.as_str()` (the accessor is byte-projective by
26190 // definition), and (2) cause the resolver's apex arm to fire
26191 // and return `entrada.port` at exactly that new destination
26192 // while every other destination string falls through to
26193 // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
26194 // membership check. Pins against a future silent detour that
26195 // (a) re-derived the apex-arm membership probe off
26196 // `e.para == destination` in `port_for_destination` instead of
26197 // `e.destination() == destination`, silently disagreeing with
26198 // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
26199 // consumers (`entrada.destination()` at
26200 // caixa-mesh/src/lib.rs:3173, `c.destination()` at
26201 // caixa-mesh/src/lib.rs:2739) that already reach through the
26202 // accessor, (b) accessor-side introduced a per-tenant alias
26203 // arm the caller was unaware of, silently rewriting an
26204 // author-declared `:para "cart"` value to a canary-aliased
26205 // form — the raw-field-access resolver would fall through to
26206 // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
26207 // while the peer emit-site consumers landed on the aliased
26208 // destination, splitting the ingress-apex L4 port at
26209 // cluster-apply time.
26210 //
26211 // Peer of the sibling
26212 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
26213 // (d0de220) composition pin on the per-`:membros` refusal-arm
26214 // axis — same "the shape-gate predicate must route through the
26215 // substrate-primitive typed dispatch" discipline extended onto
26216 // the per-`:entrada` apex-arm membership-probe axis. Closes
26217 // the last unlifted `.para` production-code read site on
26218 // `Entrada` in `caixa-core` — after this converge every
26219 // `caixa-core` `.para` field access outside the accessor's own
26220 // body and outside the `WitContract` per-`:contratos` sibling
26221 // axis is either a test-side field-setter or a doc-comment
26222 // reference.
26223 for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
26224 let mut spec = three_member_spec();
26225 if let Some(e) = spec.entrada.as_mut() {
26226 e.para = para.into();
26227 e.port = port;
26228 }
26229 let e = spec
26230 .entrada
26231 .as_ref()
26232 .expect("three_member_spec carries a typed `:entrada` block");
26233 assert_eq!(
26234 e.destination(),
26235 e.para.as_str(),
26236 "Entrada::destination must byte-equal the .para field \
26237 access — an accessor-side detour that no longer \
26238 projects the raw field would silently split this \
26239 drift-detection test from the port_for_destination \
26240 apex-arm membership probe",
26241 );
26242 assert_eq!(
26243 spec.port_for_destination(para),
26244 port,
26245 "port_for_destination must key off the accessor-projected \
26246 destination and return `entrada.port` on the apex arm — \
26247 input :entrada :para: {para:?}, :entrada :port: {port}",
26248 );
26249 assert_eq!(
26250 spec.port_for_destination("ghost-destination-never-a-member"),
26251 DEFAULT_SERVICO_PORT,
26252 "port_for_destination must fall through to \
26253 DEFAULT_SERVICO_PORT on a non-matching destination \
26254 under the accessor-projected membership check — input \
26255 :entrada :para: {para:?}, :entrada :port: {port}",
26256 );
26257 }
26258 }
26259
26260 #[test]
26261 fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
26262 // The canonical per-`:politicas :rate-limit` `:rate`
26263 // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
26264 // [`RateLimit::rate`] must return the `:politicas :rate-limit`
26265 // typed `u32` verbatim, byte-equal to the raw field access
26266 // across every representative value in the accept-set — `1` (the
26267 // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
26268 // the surrounding [`AplicacaoSpec::validate_politicas`] gate
26269 // carves out on the sibling `PolicyRateLimitZero` refusal),
26270 // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
26271 // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
26272 // `0` (a past-the-guard sentinel that pins the accessor doesn't
26273 // perform a silent bounds-collapse into `1` on the zero arm —
26274 // validate rejects zero but the accessor must ship the raw slot
26275 // verbatim so a validate-time gate regression surfaces at the
26276 // emit boundary rather than being silently absorbed), `u32::MAX`
26277 // (a past-the-guard sentinel that pins the accessor doesn't
26278 // perform a silent bounds-collapse through
26279 // `POLICY_RATE_LIMIT_MAX` at the return path).
26280 //
26281 // First sub-struct required-scalar accessor pin on the
26282 // `RateLimit` axis — sibling in shape to the peer
26283 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
26284 // required-`u32` accessor pin on the peer per-sub-struct
26285 // required-axis. Pins against a future silent detour that
26286 // re-derived the token capacity from a peer axis (an accidental
26287 // `self.window.as_secs() as u32` collapse that read the
26288 // rate-limit window duration as a token count), a `0 → 1`
26289 // cluster-default projection (which would silently absorb the
26290 // `PolicyRateLimitZero` refusal case at the accessor boundary),
26291 // or a bounds-collapsing accessor that clamped the return
26292 // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
26293 // gate owns the bounds; the accessor must ship the raw slot
26294 // verbatim).
26295 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
26296 let rl = RateLimit {
26297 rate,
26298 window: Duration::from_secs(1),
26299 };
26300 assert_eq!(
26301 rl.rate(),
26302 rate,
26303 "RateLimit::rate must return :politicas :rate-limit :rate \
26304 verbatim (got {}, expected {rate})",
26305 rl.rate(),
26306 );
26307 assert_eq!(
26308 rl.rate(),
26309 rl.rate,
26310 "RateLimit::rate must byte-equal the raw .rate field \
26311 access across every value in the u32 accept-set",
26312 );
26313 }
26314 }
26315
26316 #[test]
26317 fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
26318 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26319 // `:rate-limit :rate` zero-floor arm must key off
26320 // [`RateLimit::rate`], not the raw `.rate` field access.
26321 // Structurally: a `RateLimit { rate: 0, window:
26322 // Duration::from_secs(1) }` embedded in a `:politicas
26323 // :rate-limit` slot must surface the `PolicyRateLimitZero`
26324 // refusal exactly, and a `RateLimit { rate: 1, window:
26325 // Duration::from_secs(1) }` (the lower boundary of the
26326 // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
26327 // The pair jointly pins the accessor + validate-gate composition:
26328 // any future silent detour that had the accessor return a fresh
26329 // `1` on the zero arm (a `.rate().max(1)` collapse) would
26330 // silently absorb the `PolicyRateLimitZero` refusal at the
26331 // accessor boundary and the validate gate would accept a
26332 // struct-literal `RateLimit { rate: 0, .. }` — the composition
26333 // pin catches that at caixa-core build time.
26334 //
26335 // Peer of the sibling per-`CircuitBreaker`
26336 // [`CircuitBreaker::max_failures`] (3a74062) /
26337 // [`CircuitBreaker::window`] (373957f) accessor-composition
26338 // pins on the peer required-scalar axes — same "the validate /
26339 // shape-gate predicate must route through the substrate-primitive
26340 // typed dispatch" discipline extended onto the peer
26341 // per-`RateLimit` required-`u32` composition axis.
26342 let mut spec = three_member_spec();
26343 spec.politicas = MeshPolicy {
26344 rate_limit: Some(RateLimit {
26345 rate: 0,
26346 window: Duration::from_secs(1),
26347 }),
26348 ..MeshPolicy::default()
26349 };
26350 assert!(
26351 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
26352 "validate_politicas must reject rate == 0 with \
26353 PolicyRateLimitZero — the accessor and the validate gate \
26354 must route through the same substrate-primitive typed \
26355 dispatch on the :rate zero-floor arm",
26356 );
26357 spec.politicas = MeshPolicy {
26358 rate_limit: Some(RateLimit {
26359 rate: 1,
26360 window: Duration::from_secs(1),
26361 }),
26362 ..MeshPolicy::default()
26363 };
26364 assert!(
26365 spec.validate().is_ok(),
26366 "validate_politicas must accept rate == 1 (the lower \
26367 boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
26368 );
26369 }
26370
26371 #[test]
26372 fn rate_limit_rate_projects_u32_by_copy() {
26373 // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
26374 // `u32` is `Copy` and the accessor must return by value, not by
26375 // reference. Peer of the sibling per-`CircuitBreaker`
26376 // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
26377 // peer required-scalar `:max-failures` axis, extended onto the
26378 // peer per-`RateLimit` required-`u32` copy-invariant shape —
26379 // the accessor's returned `u32` must outlive `&self` (multiple
26380 // calls must return equal values from a dropped-`&self` copy,
26381 // since the returned scalar carries no borrow), and calling the
26382 // accessor twice on the same RateLimit must yield the same
26383 // `u32` verbatim (idempotent, no side effects on `&self`).
26384 //
26385 // Pins against a future silent detour that returned `&u32`
26386 // (which would type-check but silently break every downstream
26387 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
26388 // first parameter is `u32`, and `&u32` would fold to a detached
26389 // copy at the call site with a `*` deref the sibling accessors
26390 // don't need), an accidental `.rate.wrapping_add(0)` detour that
26391 // returned a fresh copy through an arithmetic no-op (breaking a
26392 // future `const fn` regression), or a one-arm-only accessor
26393 // that returned a saturating value on some sentinel input
26394 // (breaking the pass-through invariant the sibling required-
26395 // scalar accessors carry).
26396 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
26397 let rl = RateLimit {
26398 rate,
26399 window: Duration::from_secs(1),
26400 };
26401 let first = rl.rate();
26402 let second = rl.rate();
26403 assert_eq!(
26404 first, second,
26405 "RateLimit::rate must be idempotent — two successive \
26406 calls on the same &self must return the same u32",
26407 );
26408 assert_eq!(
26409 first, rate,
26410 "RateLimit::rate must return :politicas :rate-limit :rate \
26411 verbatim by copy — got {first}, expected {rate}",
26412 );
26413 }
26414 }
26415
26416 #[test]
26417 fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
26418 // The canonical per-`:politicas :rate-limit` `:window`
26419 // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
26420 // pin: [`RateLimit::window`] must return the
26421 // `:politicas :rate-limit :window` typed `Duration` verbatim,
26422 // byte-equal to the raw field access across every
26423 // representative value in the accept-set — `Duration::from_secs(1)`
26424 // (the `"s"` canonical window, the lower row of
26425 // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
26426 // [`AplicacaoSpec::validate_politicas`] gate accepts via
26427 // [`is_canonical_rate_limit_window`]),
26428 // `Duration::from_secs(60)` (the `"m"` canonical window, the
26429 // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
26430 // window, the upper row), `Duration::ZERO` (a past-the-guard
26431 // sentinel that pins the accessor doesn't perform a silent
26432 // bounds-collapse into `Duration::from_secs(1)` on the zero
26433 // arm — validate rejects an off-set window through
26434 // `PolicyRateLimitWindowNotCanonical` but the accessor must
26435 // ship the raw slot verbatim so a validate-time gate
26436 // regression surfaces at the emit boundary rather than being
26437 // silently absorbed), `Duration::from_millis(500)` (a
26438 // sub-canonical past-the-guard sentinel that pins the accessor
26439 // doesn't silently normalize a non-canonical fractional
26440 // magnitude onto the nearest canonical row).
26441 //
26442 // Second sub-struct required-scalar accessor pin on the
26443 // `RateLimit` axis — sibling in shape to the just-landed
26444 // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
26445 // accessor pin on the peer per-sub-struct required-axis,
26446 // extended onto the per-`RateLimit` required-`Duration` axis.
26447 // Pins against a future silent detour that re-derived the
26448 // refill period from a peer axis (an accidental
26449 // `Duration::from_secs(self.rate as u64)` collapse that read
26450 // the rate-limit token capacity as a refill-interval
26451 // duration), a `Duration::ZERO → Duration::from_secs(1)`
26452 // canonical-default projection (which would silently absorb
26453 // the `PolicyRateLimitWindowNotCanonical` refusal case at the
26454 // accessor boundary), or a canonical-set-collapsing accessor
26455 // that clamped the return through [`rate_limit_window_unit`]
26456 // (the `AplicacaoSpec::validate` gate owns the canonical-set
26457 // membership; the accessor must ship the raw slot verbatim).
26458 for window in [
26459 Duration::from_secs(1),
26460 Duration::from_secs(60),
26461 Duration::from_secs(3600),
26462 Duration::ZERO,
26463 Duration::from_millis(500),
26464 ] {
26465 let rl = RateLimit { rate: 100, window };
26466 assert_eq!(
26467 rl.window(),
26468 window,
26469 "RateLimit::window must return :politicas :rate-limit :window \
26470 verbatim (got {:?}, expected {window:?})",
26471 rl.window(),
26472 );
26473 assert_eq!(
26474 rl.window(),
26475 rl.window,
26476 "RateLimit::window must byte-equal the raw .window field \
26477 access across every value in the Duration accept-set",
26478 );
26479 }
26480 }
26481
26482 #[test]
26483 fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
26484 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26485 // `:rate-limit :window` canonical-set arm must key off
26486 // [`RateLimit::window`], not the raw `.window` field access.
26487 // Structurally: a `RateLimit { window: Duration::from_millis(500),
26488 // .. }` embedded in a `:politicas :rate-limit` slot must
26489 // surface the `PolicyRateLimitWindowNotCanonical` refusal
26490 // exactly (with the sub-canonical `Duration::from_millis(500)`
26491 // magnitude carried through verbatim), and a `RateLimit
26492 // { window: Duration::from_secs(1), .. }` (the lower row of
26493 // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
26494 // The pair jointly pins the accessor + validate-gate
26495 // composition: any future silent detour that had the accessor
26496 // normalize the off-set window to the nearest canonical row
26497 // (a `.window().max(Duration::from_secs(1))` collapse, or a
26498 // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
26499 // collapse) would silently absorb the
26500 // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
26501 // boundary — including a drift in the error's `window` payload
26502 // (the emit-side diagnostic reader keys off the offending
26503 // magnitude verbatim, so a normalization at the accessor
26504 // boundary would silently pin the wrong magnitude in the
26505 // refusal). The composition pin catches that at caixa-core
26506 // build time.
26507 //
26508 // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
26509 // (7f81a60) accessor-composition pin on the peer required-
26510 // scalar `:rate` axis — same "the validate / shape-gate
26511 // predicate must route through the substrate-primitive typed
26512 // dispatch, and the error payload must project through the
26513 // same accessor" discipline extended onto the peer
26514 // per-`RateLimit` required-`Duration` composition axis.
26515 let mut spec = three_member_spec();
26516 spec.politicas = MeshPolicy {
26517 rate_limit: Some(RateLimit {
26518 rate: 100,
26519 window: Duration::from_millis(500),
26520 }),
26521 ..MeshPolicy::default()
26522 };
26523 match spec.validate() {
26524 Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
26525 assert_eq!(
26526 window,
26527 Duration::from_millis(500),
26528 "PolicyRateLimitWindowNotCanonical must carry the \
26529 offending :window magnitude verbatim through the \
26530 accessor — got {window:?}, expected 500ms",
26531 );
26532 }
26533 other => panic!(
26534 "validate_politicas must reject non-canonical :window \
26535 with PolicyRateLimitWindowNotCanonical — the accessor \
26536 and the validate gate must route through the same \
26537 substrate-primitive typed dispatch on the :window \
26538 canonical-set arm; got {other:?}",
26539 ),
26540 }
26541 spec.politicas = MeshPolicy {
26542 rate_limit: Some(RateLimit {
26543 rate: 100,
26544 window: Duration::from_secs(1),
26545 }),
26546 ..MeshPolicy::default()
26547 };
26548 assert!(
26549 spec.validate().is_ok(),
26550 "validate_politicas must accept window == Duration::from_secs(1) \
26551 (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
26552 );
26553 }
26554
26555 #[test]
26556 fn rate_limit_window_projects_duration_by_copy() {
26557 // The by-copy pin: [`RateLimit::window`] returns `Duration`
26558 // by copy — `Duration` is `Copy` and the accessor must return
26559 // by value, not by reference. Peer of the sibling per-`RateLimit`
26560 // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
26561 // required-scalar `:rate` axis, extended onto the peer
26562 // per-`RateLimit` required-`Duration` copy-invariant shape —
26563 // the accessor's returned `Duration` must outlive `&self`
26564 // (multiple calls must return equal values from a
26565 // dropped-`&self` copy, since the returned scalar carries no
26566 // borrow), and calling the accessor twice on the same
26567 // RateLimit must yield the same `Duration` verbatim
26568 // (idempotent, no side effects on `&self`).
26569 //
26570 // Pins against a future silent detour that returned
26571 // `&Duration` (which would type-check but silently break every
26572 // downstream `Duration`-by-value consumer —
26573 // [`is_canonical_rate_limit_window`]'s first parameter is
26574 // `Duration`, and `&Duration` would fold to a detached copy at
26575 // the call site with a `*` deref the sibling accessors don't
26576 // need), an accidental `.window + Duration::ZERO` detour that
26577 // returned a fresh copy through an arithmetic no-op (breaking
26578 // a future `const fn` regression), or a one-arm-only accessor
26579 // that returned a canonical fallback on some sentinel input
26580 // (breaking the pass-through invariant the sibling required-
26581 // scalar accessors carry).
26582 for window in [
26583 Duration::from_secs(1),
26584 Duration::from_secs(60),
26585 Duration::from_secs(3600),
26586 Duration::ZERO,
26587 Duration::from_millis(500),
26588 ] {
26589 let rl = RateLimit { rate: 100, window };
26590 let first = rl.window();
26591 let second = rl.window();
26592 assert_eq!(
26593 first, second,
26594 "RateLimit::window must be idempotent — two successive \
26595 calls on the same &self must return the same Duration",
26596 );
26597 assert_eq!(
26598 first, window,
26599 "RateLimit::window must return :politicas :rate-limit :window \
26600 verbatim by copy — got {first:?}, expected {window:?}",
26601 );
26602 }
26603 }
26604
26605 #[test]
26606 fn placement_estrategia_default_pins_m3_canonical_value() {
26607 // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
26608 // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
26609 // active-active-across-every-named-cluster arm, the closest
26610 // canonical M3 production reference the substrate carries and
26611 // the arm the caixa-mesh `programs.yaml` fan-out already keys off
26612 // for every un-`:placement`-declared Aplicacao. Pinning the arm
26613 // here surfaces a future rebrand of the M3-canonical
26614 // distribution default (a widening to `Sharded` once the
26615 // substrate discovers hash-keyed distribution as the more
26616 // common production shape, a tightening to `SingleNode` for
26617 // stateful Erlang/OTP distributed-app-takeover semantics
26618 // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
26619 // operator pins through a future `:placement-overrides` slot)
26620 // as a deliberate test edit, not a silent contract migration.
26621 // Peer of the sibling M2 per-supervisor value pins
26622 // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
26623 // /
26624 // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
26625 // extended onto the M3 mesh-primitive-defining `:placement
26626 // :estrategia` axis.
26627 assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
26628 }
26629
26630 #[test]
26631 fn placement_strategy_default_routes_through_lifted_default() {
26632 // Composition pin: the [`Default for PlacementStrategy`] impl's
26633 // return arm must route through the substrate-canonical
26634 // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
26635 // a raw `Self::Replicated` arm. Prior to the lift the impl
26636 // carried an inline `Self::Replicated` arm with no compile-time
26637 // link back to the shared M3-canonical `Replicated` arm the
26638 // paired [`Default for Placement`] impl's struct-literal
26639 // `estrategia` field, the serde-side `#[serde(default)]` on
26640 // [`Placement::estrategia`] that resolves an author-omitted
26641 // wire-form `:placement :estrategia` scalar through the impl,
26642 // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
26643 // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
26644 // routes through [`Placement::default`] which routes through the
26645 // strategy default) all key off — so a future rebrand of the
26646 // M3-canonical distribution default would have had to be threaded
26647 // through the `Default` impl and the three peer routes in
26648 // lockstep or the four consumers would silently split. Byte-
26649 // parity against the lifted constant closes the split. Peer of
26650 // the sibling
26651 // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
26652 // /
26653 // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
26654 // composition pins on the M2 per-supervisor axes.
26655 assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
26656 }
26657
26658 #[test]
26659 fn placement_default_estrategia_routes_through_lifted_default() {
26660 // Composition pin: the [`Default for Placement`] impl's
26661 // struct-literal `estrategia` field must route through the
26662 // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
26663 // `pub const` (either directly, or via the [`PlacementStrategy::default`]
26664 // impl that the sibling
26665 // `placement_strategy_default_routes_through_lifted_default` pin
26666 // already routes onto the constant). Structurally: every
26667 // `Placement::default()` call must yield an `estrategia` field
26668 // byte-equal to the lifted constant so the two paired defaults —
26669 // the [`Default for PlacementStrategy`] impl arm and the
26670 // struct-literal default arm here — cannot silently split on any
26671 // future M3-canonical distribution-default rebrand. Peer of the
26672 // sibling M2
26673 // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
26674 // byte-parity pin on the [`Default for SupervisorSpec`]
26675 // struct-literal `estrategia` field extended onto the M3
26676 // mesh-primitive-defining slot family.
26677 assert_eq!(
26678 Placement::default().estrategia,
26679 PLACEMENT_ESTRATEGIA_DEFAULT,
26680 );
26681 }
26682
26683 #[test]
26684 fn placement_serde_default_estrategia_routes_through_lifted_default() {
26685 // Composition pin: the serde-side `#[serde(default)]` on
26686 // [`Placement::estrategia`] — the wire-format author-omitted
26687 // `:placement :estrategia` arm — must resolve onto the substrate-
26688 // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
26689 // (via the [`Default for PlacementStrategy`] impl the sibling
26690 // `placement_strategy_default_routes_through_lifted_default` pin
26691 // already routes onto the constant). Structurally: a `Placement`
26692 // deserialized from a payload that omits the `estrategia` key
26693 // must yield an `estrategia` field byte-equal to the lifted
26694 // constant, so the wire-format author-omitted arm and the
26695 // [`PlacementStrategy::default`] impl arm cannot silently split
26696 // on any future M3-canonical distribution-default rebrand. Peer
26697 // of the sibling M2
26698 // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
26699 // byte-parity pin on the wire-format author-omitted `:children
26700 // :restart` scalar extended onto the M3 mesh-primitive-defining
26701 // slot family.
26702 let omitted: Placement = serde_json::from_str("{}")
26703 .expect("Placement must deserialize with the estrategia key omitted");
26704 assert_eq!(
26705 omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
26706 "an author-omitted :placement :estrategia slot must degrade onto \
26707 the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
26708 {:?}, expected {:?})",
26709 omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
26710 );
26711 }
26712}