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 #[must_use]
2974 pub fn canonical_unit(&self) -> Option<RateLimitUnit> {
2975 RateLimitUnit::from_window(self.window)
2976 }
2977}
2978
2979/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
2980/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
2981/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
2982///
2983/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
2984/// the `:politicas :rate-limit` unit surface reads from
2985/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
2986/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
2987/// [`is_canonical_rate_limit_window`] predicate the
2988/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
2989/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
2990/// projection) now lives inside this typed enum's `match self` arms — a
2991/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
2992/// `rate_limit_action` grows daily-bucket support) is one new variant
2993/// plus the exhaustiveness arms on the four methods, so every consumer
2994/// picks it up by compile-time construction rather than a runtime
2995/// table-scan miss.
2996///
2997/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
2998/// scanned via `find_map` at every projection call — an untyped runtime
2999/// walk that carried no compile-time link between the parse arm's
3000/// accepted suffixes, the render arm's emitted suffixes, and the
3001/// validate gate's accepted windows. A future rate-limit-unit addition
3002/// that landed one row without threading through the other consumers
3003/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3004/// silently split the accepted-set across the three consumers — the
3005/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3006/// for a 24h window that parse can't round-trip, the validate gate
3007/// misses one canonical window. Lifting the pairs onto a typed
3008/// closed-set enum with exhaustive `match` arms makes any such
3009/// half-landed extension a caixa-core build error (the compiler enforces
3010/// arm coverage on every method), not a silent per-consumer drift
3011/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3012/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3013/// [`crate::supervisor::RestartStrategy`],
3014/// [`crate::supervisor::RestartPolicy`],
3015/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3016/// closed-set typed enums carry on their respective closed-set axes —
3017/// extended onto the seventh closed-set typed-enum discriminator axis
3018/// on the caixa typed surface (the `:politicas :rate-limit :window`
3019/// canonical-unit axis).
3020#[derive(
3021 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3022)]
3023pub enum RateLimitUnit {
3024 /// 1-second window — canonical author-surface suffix `"s"`
3025 /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3026 /// with a 1s magnitude.
3027 Second,
3028 /// 1-minute window — canonical author-surface suffix `"m"`
3029 /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3030 /// with a 60s magnitude.
3031 Minute,
3032 /// 1-hour window — canonical author-surface suffix `"h"`
3033 /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3034 /// with a 3600s magnitude.
3035 Hour,
3036}
3037
3038impl RateLimitUnit {
3039 /// Exhaustive iteration surface for every consumer that reads the
3040 /// full canonical-unit set (the byte-parity witness against the
3041 /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3042 /// webhook's accepted-suffix listing in its rejection body, any
3043 /// future round-trip fuzz harness). A future variant addition to
3044 /// [`RateLimitUnit`] extends this slice as a single edit and every
3045 /// consumer picks up the new entry by construction — the compiler-
3046 /// checked exhaustiveness on the sibling method `match` arms is the
3047 /// build-time guarantee that no arm forgets to grow.
3048 pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3049
3050 /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3051 /// string every `<n>/<unit>` rate-limit shape carries after its
3052 /// `/` separator. The single source of truth the codec's parse and
3053 /// render arms both dispatch on: the parse arm matches an incoming
3054 /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3055 /// output; the render arm emits the entry's `as_suffix` verbatim
3056 /// after the rate magnitude.
3057 #[must_use]
3058 pub const fn as_suffix(self) -> &'static str {
3059 match self {
3060 Self::Second => "s",
3061 Self::Minute => "m",
3062 Self::Hour => "h",
3063 }
3064 }
3065
3066 /// Canonical `Duration` for this unit — the token-bucket refill
3067 /// period the [`RateLimit::window`] axis carries when the surrounding
3068 /// slot's `:rate-limit` author surface named this unit.
3069 #[must_use]
3070 pub const fn window(self) -> Duration {
3071 Duration::from_secs(match self {
3072 Self::Second => 1,
3073 Self::Minute => 60,
3074 Self::Hour => 3_600,
3075 })
3076 }
3077
3078 /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3079 /// `None` when `suffix` is outside the closed-set arm-string set
3080 /// [`Self::as_suffix`] emits. The single `str → Self` projection
3081 /// [`rate_limit_codec::parse`] consumes.
3082 #[must_use]
3083 pub fn from_suffix(suffix: &str) -> Option<Self> {
3084 Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3085 }
3086
3087 /// Recognize a canonical rate-limit `Duration` as one of the three
3088 /// arms, or `None` when `window` carries sub-second residue or a
3089 /// second-magnitude outside the closed-set arm-window set
3090 /// [`Self::window`] emits. The single `Duration → Self` projection
3091 /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3092 /// both consume.
3093 #[must_use]
3094 pub fn from_window(window: Duration) -> Option<Self> {
3095 if window.subsec_nanos() != 0 {
3096 return None;
3097 }
3098 Self::ALL.iter().copied().find(|u| u.window() == window)
3099 }
3100
3101 /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3102 /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3103 /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3104 /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3105 /// consumes.
3106 ///
3107 /// The peer `Duration → &'static str` axis folded onto the substrate
3108 /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3109 /// production consumers ([`rate_limit_codec::render`] and
3110 /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3111 /// migrated (61421a6): the free helper's `Duration → &str` projection
3112 /// is now the two-step composition
3113 /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3114 /// reads through the typed accessor. This lift closes the peer
3115 /// `&str → Duration` axis by folding the vestigial module-private
3116 /// `rate_limit_window_from_unit` delegate onto this associated method
3117 /// — the codec's parse arm and every future wire-side consumer of the
3118 /// `&str → Duration` projection (a future admission-webhook that
3119 /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3120 /// before it's promoted to a validated typed slot, a future
3121 /// `feira lint` shape-probe that reads the author-surface bytes
3122 /// verbatim) now reach for exactly one typed dispatch on the
3123 /// substrate primitive.
3124 ///
3125 /// Same "closed-set typed-enum discriminator with canonical
3126 /// projections per axis" discipline the sibling [`Self::as_suffix`]
3127 /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3128 /// methods carry — this associated method closes the fifth (and last
3129 /// unlifted) projection axis on the arm-table, so the closed-set enum
3130 /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3131 /// consumer of the `:politicas :rate-limit :window` axis reaches
3132 /// through. A future rate-limit-unit addition (a `"d"` day suffix
3133 /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3134 /// `"ms"` sub-second window once high-throughput per-edge policies
3135 /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3136 /// variant plus one arm per method — the compiler enforces
3137 /// exhaustiveness on every consumer's `match self` arms and picks
3138 /// the new unit up by construction across all five projections.
3139 #[must_use]
3140 pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3141 Self::from_suffix(suffix).map(Self::window)
3142 }
3143}
3144
3145/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3146/// every consumer that formats a canonical rate-limit unit as user-
3147/// facing text (future M4 admission-webhook rejection bodies naming
3148/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3149/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3150/// codec's parse arm accepts and the render arm emits. Same
3151/// as_str-through-Display convergence discipline the sibling
3152/// [`PlacementStrategy`], [`crate::CaixaKind`],
3153/// [`crate::supervisor::RestartStrategy`], and
3154/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3155impl std::fmt::Display for RateLimitUnit {
3156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3157 f.write_str(self.as_suffix())
3158 }
3159}
3160
3161/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3162/// validated [`MeshPolicy::timeout`] past
3163/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3164/// (inclusive on both ends, integer-millisecond magnitudes by the
3165/// canonical-form gate immediately preceding).
3166///
3167/// The typed field is `Option<Duration>` (the zero-floor arm
3168/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3169/// `Duration::ZERO`, and the canonical-form arm
3170/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3171/// sub-millisecond residue), so a programmatic struct literal
3172/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3173/// 24h) and the equivalent author-surface form
3174/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3175/// integer-hour magnitude) both round-trip cleanly through serde — a
3176/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3177/// above the documented production-playbook band (Envoy default `15s`,
3178/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3179/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3180/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3181/// at `~3600s`) silently degenerates the mesh-policy contract: the
3182/// per-call deadline is structurally so long that no realistic
3183/// synchronous-`:contratos` traversal can reach it, so the typed slot
3184/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3185/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3186/// blocking" degenerates to a nominal-only contract on the
3187/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3188/// the sibling `:politicas :retries` axis and the
3189/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3190/// `:politicas :circuit-breaker :max-failures` axis — all three close
3191/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3192/// footgun the prior zero-floor-and-canonical-form-only checks left
3193/// open.
3194///
3195/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3196/// shared duration codec emits (`"<n>h"` for any integer-hour
3197/// magnitude) — every value in the canonical authoring form's
3198/// `<integer><unit>` grammar at or below this cap renders to a clean
3199/// canonical string. The cap sits an order of magnitude above every
3200/// documented production-playbook recommendation band (Envoy default
3201/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3202/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3203/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3204/// below the clearly-pathological "effectively no timeout" floor
3205/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3206/// want for a long-running synchronous workflow, but a hard wall above
3207/// which the mesh-level deadline is structurally a non-deadline.
3208/// Lifted as a typed `pub const` so the bound has exactly one source
3209/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3210/// materializer's admission webhook and the caixa-mesh-side
3211/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3212/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3213/// other typed upper bound in this crate carries
3214/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3215/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3216/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3217/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3218pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3219
3220/// Upper-bound ceiling on the `:politicas :retries` axis — every
3221/// validated [`MeshPolicy::retries`] past
3222/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3223///
3224/// The typed slot is `Option<u32>` (`None` = no retries on transient
3225/// failure; `Some(0)` already rejected by the
3226/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3227/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3228/// .. }`) and the equivalent author-surface form
3229/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3230/// serde / the codec — a structurally unbounded `u32` ceiling. The
3231/// runtime substrate that consumes the value (Envoy's
3232/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3233/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3234/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3235/// admission cap is 10) translates a four-billion-retry policy into a
3236/// thundering-herd amplification vector on transient failure — the
3237/// caller's one request fans out to `retries` server-side calls per
3238/// edge per traversal, multiplying load by `(retries+1)^depth` across
3239/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3240/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3241/// invariant on the retry axis; both belong at the typed-slot layer.
3242///
3243/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3244/// upstream mesh-policy schema that documents one) and sits above the
3245/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3246/// every documented production playbook): a value the author can
3247/// plausibly want, but a hard wall above which the policy is
3248/// structurally a footgun. Lifted as a typed `pub const` so the bound
3249/// has exactly one source of truth — a future axis reaching for the
3250/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3251/// materializer's admission webhook, the caixa-mesh-side
3252/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3253/// one place. Same shape every other typed upper bound in this crate
3254/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3255/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3256/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3257/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3258pub const POLICY_RETRIES_MAX: u32 = 10;
3259
3260/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3261/// axis — every validated [`CircuitBreaker::max_failures`] past
3262/// [`AplicacaoSpec::validate_politicas`] lies in
3263/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3264///
3265/// The typed field is `u32` (the zero-floor arm
3266/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3267/// `0` — a breaker that trips on the first call), so a programmatic
3268/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3269/// and the equivalent author-surface form
3270/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3271/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3272/// `max_failures` value far above the documented production-playbook
3273/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3274/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3275/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3276/// typical 5–50) silently disables the breaker's protection role:
3277/// the threshold is structurally so high that no realistic
3278/// failures-per-`:window` traffic shape can reach it, so the breaker
3279/// never trips and the typed slot becomes a no-op carried on every
3280/// emitted Envoy / Cilium L7 overlay. Pairs with the
3281/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3282/// axis — both close the "structurally unbounded `u32` ceiling on a
3283/// typed policy axis" footgun the prior zero-floor-only checks left
3284/// open.
3285///
3286/// The `1000` ceiling sits an order of magnitude above every
3287/// documented upstream production-playbook recommendation band (the
3288/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3289/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3290/// the clearly-pathological "effectively no protection"
3291/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3292/// plausibly want at hyperscale, but a hard wall above which the
3293/// policy is structurally a no-op. Lifted as a typed `pub const` so
3294/// the bound has exactly one source of truth — the future M4
3295/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3296/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3297/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3298/// one place. Same shape every other typed upper bound in this crate
3299/// carries ([`POLICY_RETRIES_MAX`],
3300/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3301/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3302/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3303pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3304
3305/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3306/// every validated [`CircuitBreaker::window`] past
3307/// [`AplicacaoSpec::validate_politicas`] lies in
3308/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3309/// integer-millisecond magnitudes by the canonical-form gate
3310/// immediately preceding).
3311///
3312/// The typed field is `Duration` (the zero-floor arm
3313/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3314/// `Duration::ZERO`, and the canonical-form arm
3315/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3316/// sub-millisecond residue), so a programmatic struct literal
3317/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3318/// and the equivalent author-surface form
3319/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3320/// integer-hour magnitude) both round-trip cleanly through serde — a
3321/// structurally unbounded `Duration` ceiling. A `:window` value far
3322/// above the documented production-playbook band (Hystrix
3323/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3324/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3325/// Istio `outlierDetection.interval` default `10s`, Envoy
3326/// `outlier_detection.interval` default `10s`, AWS App Mesh
3327/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3328/// breaker's role: a rolling-window failure counter whose window is
3329/// hours long is operationally a lifetime counter, the breaker's
3330/// "recent failures" memory is structurally so long that transient
3331/// failures are never forgotten, and the typed slot becomes a no-op
3332/// trigger that trips once and stays tripped for the lifetime of the
3333/// component carried on every emitted Envoy / Cilium L7 overlay.
3334///
3335/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3336/// shared duration codec emits (`"<n>h"` for any integer-hour
3337/// magnitude) — every value in the canonical authoring form's
3338/// `<integer><unit>` grammar at or below this cap renders to a clean
3339/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3340/// cap on the first typed-`Duration` `:politicas` axis: the two
3341/// duration-typed `:politicas` axes now share a single uniform top
3342/// edge so the next typed-slot wiring (the future caixa-mesh
3343/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3344/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3345/// admission webhook) reaches for either field knowing the value is
3346/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3347/// sits two orders of magnitude above every documented upstream
3348/// production-playbook recommendation band (Hystrix / resilience4j /
3349/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3350/// and below the clearly-pathological "rolling window degenerates to
3351/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3352/// author can plausibly want for a very-low-traffic long-tail
3353/// failure-detection window, but a hard wall above which the breaker's
3354/// rolling-window contract is structurally a lifetime-counter contract.
3355/// Lifted as a typed `pub const` so the bound has exactly one source
3356/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3357/// materializer's admission webhook and the caixa-mesh-side
3358/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3359/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3360/// other typed upper bound in this crate carries
3361/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3362/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3363/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3364/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3365/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3366pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3367
3368/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3369/// every validated [`RateLimit::rate`] past
3370/// [`AplicacaoSpec::validate_politicas`] lies in
3371/// `1..=POLICY_RATE_LIMIT_MAX`.
3372///
3373/// The typed field is `u32` (the zero-floor arm
3374/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3375/// zero-rate limit denies every request, the canonical "I forgot
3376/// that 0 means deny-everything" footgun), so a programmatic struct
3377/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3378/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3379/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3380/// round-trip cleanly through serde — a structurally unbounded `u32`
3381/// ceiling. The runtime substrate consuming the value (Envoy's
3382/// `local_rate_limit.token_bucket.max_tokens`, the future
3383/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3384/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3385/// rate-limit into a no-op rate-limiter: the bucket capacity is
3386/// structurally so high no realistic per-edge traffic shape can
3387/// drain it, the limiter never trips, and the typed slot becomes a
3388/// "rate-limit declared, no enforcement" footgun — the canonical
3389/// declared-but-inert shape every other `:politicas` cap arm
3390/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3391/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3392///
3393/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3394/// above every documented upstream production-playbook recommendation
3395/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3396/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3397/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3398/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3399/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3400/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3401/// `u32::MAX`): a value the author can plausibly want at hyperscale
3402/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3403/// /h-window arm), but a hard wall above which the policy is
3404/// structurally a no-op carried verbatim on every emitted Envoy /
3405/// Cilium L7 overlay. The cap brackets all three canonical windows
3406/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3407/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3408/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3409/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3410/// has exactly one source of truth — the future M4
3411/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3412/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3413/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3414/// one place. Same shape every other typed upper bound in this crate
3415/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3416/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3417/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3418/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3419/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3420/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3421pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3422
3423// `:entrada :host` total-length and per-label cap axes route through
3424// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3425// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3426// pair of aplicacao-private aliases the previous `validate_entrada_host`
3427// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3428// = 63`) were structurally the same K8s Gateway API v1 Hostname
3429// admission-schema bounds — the total-length cap on the OpenAPI
3430// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3431// same regex — that the peer axes at the caixa-core::render level pin,
3432// so hoisting both readers onto the shared lifted constants closes the
3433// third-occurrence duplication threshold structurally: the M4
3434// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3435// label validator, the future per-`Certificate` SAN emitter, and every
3436// other per-Gateway-API-Hostname landing site reach the same one place
3437// as the `:entrada :host` gate does — no per-axis alias drift surface
3438// between them, by construction.
3439
3440/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3441/// extractor expression — the upper bound `validate_placement_shard_key`
3442/// enforces on every well-shaped shard-key past validate. The realistic
3443/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3444/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3445/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3446/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3447/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3448/// in `:shard-key`" footgun at validate time rather than at the future
3449/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3450const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3451
3452/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3453/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3454/// that maps the shared parser-shaped reason into the
3455/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3456/// is self-locating (the offending `caixa:` is named verbatim) and
3457/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3458/// fix it in one edit. Same diagnostic shape as
3459/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3460/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3461fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3462 // Empty is already gated by `MembroCaixaEmpty` at the call site;
3463 // re-checking here keeps the predicate usable from any future
3464 // call site (the M4 CR materializer) without an empty-check
3465 // footgun. The shared
3466 // [`crate::render::require_valid_dns_1123_label`] helper brackets
3467 // the empty-first + shape cascade every peer name axis
3468 // (`:placement :clusters`, `:placement :affinity`, `:contratos
3469 // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3470 // `:upgrade-from :module`) routes through, so drift between the
3471 // eight axes' accepted DNS-1123-label sets is structurally
3472 // impossible.
3473 crate::render::require_valid_dns_1123_label(
3474 caixa,
3475 || AplicacaoError::MembroCaixaEmpty,
3476 |reason| AplicacaoError::MembroCaixaInvalid {
3477 caixa: caixa.to_string(),
3478 reason,
3479 },
3480 )
3481}
3482
3483/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3484/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3485/// that maps the shared parser-shaped reason into the
3486/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3487///
3488/// Cluster names land in DNS-1123-label territory across every consumer:
3489/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3490/// the `lareira-fleet-programs` aggregator applies to scope programs to
3491/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3492/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3493/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3494/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3495/// side schema enforces the DNS-1123 label rule on admission; a
3496/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3497/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3498/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3499/// only gate and the failure surfaces as a no-match at filter time —
3500/// the workload doesn't land in the named cluster, with no diagnostic
3501/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3502/// build time mirrors the `:membros :caixa` value-shape trajectory
3503/// (3f9d7a0) on the peer name axis.
3504///
3505/// The diagnostic carries the offending `cluster:` verbatim plus a
3506/// parser-shaped `reason:` naming the specific violation, so the
3507/// author can grep their caixa.lisp for `:clusters` and fix it in
3508/// one edit. Same diagnostic shape as
3509/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3510fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3511 // Empty is already gated by `PlacementClusterEmpty` at the call
3512 // site; re-checking here keeps the predicate usable from any
3513 // future call site (the M4 CR materializer's per-cluster validator)
3514 // without an empty-check footgun. Routes through the shared
3515 // [`crate::render::require_valid_dns_1123_label`] gate the peer
3516 // name axes each land on.
3517 crate::render::require_valid_dns_1123_label(
3518 cluster,
3519 || AplicacaoError::PlacementClusterEmpty,
3520 |reason| AplicacaoError::PlacementClusterInvalid {
3521 cluster: cluster.to_string(),
3522 reason,
3523 },
3524 )
3525}
3526
3527/// Reject `:placement :affinity` hints whose shape can never legitimately
3528/// land in any downstream selector or label-keyed routing axis. Thin
3529/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3530/// shared parser-shaped reason into the
3531/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3532/// diagnostic is self-locating (the offending `:affinity` is named
3533/// verbatim) and the author can grep their caixa.lisp for
3534/// `:affinity "<hint>"` and fix it in one edit.
3535///
3536/// The `:affinity` slot carries a placement-engine hint — canonical
3537/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3538/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3539/// compression overlay and the future M4 placement-engine's per-hint
3540/// routing axis. Each downstream consumer (caixa-mesh's
3541/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3542/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3543/// `spec.placement.affinity` admission rule, the future M4 per-hint
3544/// node-affinity / pod-affinity rule generator keying off the same
3545/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3546/// selector) requires the value to be a DNS-1123 label — K8s label
3547/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3548/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3549/// admission rule the apiserver enforces.
3550///
3551/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3552/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3553/// Python-module-name leak), `:affinity "data.locality"` (the
3554/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3555/// `:affinity "data-locality-"` (boundary-hyphen violation),
3556/// `:affinity "data locality"` (paste-from-doc whitespace),
3557/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3558/// 64-byte over-cap slug silently passed the empty-only check and the
3559/// failure surfaced as a no-match at the M3 Adaptive compression
3560/// overlay's filter time (`placement.affinity` carried a malformed
3561/// value, no node matched, the workload landed on the default
3562/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3563/// the empty-:affinity / empty-shard-key / zero-:politicas /
3564/// empty-:contratos-target gates already close on every other
3565/// declare-but-no-opinion axis. Lifting the rejection to a build-time
3566/// gate closes the fifth typed slot on the Aplicacao surface to land
3567/// on the canonical DNS-1123 label floor (after the four Servico-name
3568/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
3569/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
3570/// b0e8748).
3571///
3572/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
3573/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
3574/// validated values are guaranteed-accepted by the apiserver without
3575/// re-validation at any downstream renderer or admission layer.
3576fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
3577 // Empty is gated separately at the call site for a self-locating
3578 // diagnostic; re-checking here keeps the predicate usable from any
3579 // future call site (the M4 CR materializer's per-affinity
3580 // validator) without an empty-check footgun. Routes through the
3581 // shared [`crate::render::require_valid_dns_1123_label`] gate the
3582 // peer name axes each land on.
3583 crate::render::require_valid_dns_1123_label(
3584 affinity,
3585 || AplicacaoError::PlacementAffinityEmpty,
3586 |reason| AplicacaoError::PlacementAffinityInvalid {
3587 affinity: affinity.to_string(),
3588 reason,
3589 },
3590 )
3591}
3592
3593/// Reject `:placement :shard-key` extractor expressions whose shape can
3594/// never legitimately drive the future M4 Akka-style cluster-sharding
3595/// reconciler's hash-extractor pass. Maps the per-byte / length checks
3596/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
3597/// diagnostic is self-locating (the offending `:shard-key` value is
3598/// named verbatim alongside the parser-shaped reason) and the author can
3599/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
3600/// edit.
3601///
3602/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
3603/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
3604/// expression naming the message property to hash on. The realistic
3605/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
3606/// property name; `$tenantId` — Akka entity-id placeholder;
3607/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
3608/// `${tenant}` — interpolation-style template) all sit in the printable
3609/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
3610/// multi-line blob landing in `:shard-key`, an embedded space from a
3611/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
3612/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
3613/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
3614/// check and the failure surfaces at the future M4 reconciler's hash
3615/// pass as a runtime extractor-evaluation error far from the source
3616/// `caixa.lisp`, with no field naming which member's `:shard-key`
3617/// carried the offending value.
3618///
3619/// The contract — the printable ASCII single-token intersection-floor
3620/// every Akka-style entity-id extractor implementation admits:
3621///
3622/// - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
3623/// peer DNS-1123-label-shaped `:placement :affinity` /
3624/// `:placement :clusters` identifier axes; realistic shard-keys sit
3625/// well under 32 bytes, the cap surfaces paste-from-doc multi-line
3626/// blob footguns at validate time;
3627/// - every byte in the printable ASCII range `0x21..=0x7E` —
3628/// rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
3629/// `"$tenantId\n"` from paste-from-aligned-doc /
3630/// paste-from-shell-heredoc), control characters (`\x00..\x1F`,
3631/// `\x7F` — the canonical "embedded null from a copy-paste-binary
3632/// footgun"), and non-ASCII bytes (`"$tenàntId"` —
3633/// un-Punycode-encoded IDN that round-trips inconsistently across
3634/// NFC/NFD normalization).
3635///
3636/// The accepted set is broader than the DNS-1123 label floor the peer
3637/// `:placement :clusters` / `:placement :affinity` axes use because the
3638/// `:shard-key` value is not a K8s `metadata.name` / label-selector
3639/// landing site; it's an extractor expression the future Akka-style
3640/// reconciler reads as a property reference. The realistic forms
3641/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
3642/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
3643/// but every Akka-style entity-id extractor parses. The
3644/// printable-ASCII-token floor accepts every shape any such extractor
3645/// would accept while rejecting the cross-implementation footguns
3646/// (whitespace breaks token boundaries; non-ASCII round-trips
3647/// inconsistently across YAML emitters and NFC/NFD normalization;
3648/// control characters silently corrupt the next read).
3649///
3650/// Until this gate landed `validate_placement` only refused the
3651/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
3652/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
3653/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
3654/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
3655/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
3656/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
3657/// control character from paste-from-binary, the 64-byte over-cap
3658/// paste-from-doc multi-line slug) silently passed validate. The future
3659/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
3660/// would then surface the malformed value either as a runtime
3661/// extractor-evaluation error (whitespace breaks the extractor's token
3662/// boundary, no match) or as a silently-different shard assignment
3663/// across YAML emitters (non-ASCII normalizes differently between the
3664/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
3665/// parser, the same entity ID maps to two distinct shards on a
3666/// re-render). Lifting the shape gate to caixa-build time makes the
3667/// extractor-floor invariant a structural property of every validated
3668/// `Placement`: every `Sharded` placement past `validate_placement` has
3669/// a `:shard-key` the future M4 reconciler can hash without
3670/// re-validating at the runtime layer.
3671///
3672/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
3673/// [`AplicacaoError::ContratoSubjectInvalid`] /
3674/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
3675/// on the peer `:contratos` payload axes — each lifts the
3676/// runtime-side parser's intersection-floor to a caixa-build-time gate,
3677/// closing the canonical "this passed validate but the runtime parser
3678/// rejected it" surprise.
3679fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
3680 // Empty is gated separately at the call site via the more
3681 // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
3682 // re-checking here keeps the predicate usable from any future call
3683 // site (the M4 CR materializer's per-shard-key validator) without
3684 // an empty-check footgun.
3685 if key.is_empty() {
3686 return Err(AplicacaoError::ShardedKeyEmpty);
3687 }
3688 if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
3689 return Err(AplicacaoError::ShardKeyInvalid {
3690 shard_key: key.to_string(),
3691 reason: format!(
3692 "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
3693 (got {} bytes; realistic Akka-style entity-id extractor expressions \
3694 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
3695 well under 32 bytes, this length suggests a paste-from-doc \
3696 multi-line blob landed in `:shard-key` instead of a single-token \
3697 extractor expression)",
3698 key.len()
3699 ),
3700 });
3701 }
3702 for &b in key.as_bytes() {
3703 if (0x21..=0x7E).contains(&b) {
3704 continue;
3705 }
3706 let reason = if b == b' ' {
3707 "contains a space (Akka-style entity-id extractor expressions are \
3708 single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
3709 whitespace breaks the extractor's token boundary at the runtime layer, \
3710 and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
3711 a multi-token blob in one `:shard-key` slot)"
3712 .to_string()
3713 } else if b == b'\t' {
3714 "contains a tab character (paste-from-aligned-doc footgun; the \
3715 Akka-style entity-id extractor reads `:shard-key` as a single-token \
3716 reference, embedded whitespace breaks the token boundary at the \
3717 runtime hash-extractor pass)"
3718 .to_string()
3719 } else if b == b'\n' || b == b'\r' {
3720 format!(
3721 "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
3722 paste-from-multiline-doc footgun; the Akka-style entity-id \
3723 extractor reads `:shard-key` as a single-token reference, embedded \
3724 newlines either truncate the value at the YAML emitter layer or \
3725 break the token boundary at the runtime hash-extractor pass)"
3726 )
3727 } else if b < 0x20 || b == 0x7F {
3728 format!(
3729 "contains control character 0x{b:02x} (the canonical \
3730 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
3731 control characters silently corrupt round-trip serialization \
3732 across YAML emitters and break the runtime hash-extractor's \
3733 single-token parser)"
3734 )
3735 } else {
3736 format!(
3737 "contains non-ASCII byte 0x{b:02x} (the canonical \
3738 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
3739 inconsistently across NFC/NFD normalization on APFS / ext4 / \
3740 across YAML emitter implementations — the same entity ID can \
3741 silently map to two distinct shards on a re-render. Use a \
3742 printable-ASCII extractor expression like `tenantId`, \
3743 `$tenantId`, or `metadata.tenantId`)"
3744 )
3745 };
3746 return Err(AplicacaoError::ShardKeyInvalid {
3747 shard_key: key.to_string(),
3748 reason,
3749 });
3750 }
3751 Ok(())
3752}
3753
3754/// Reject `:contratos :de` / `:contratos :para` values whose shape
3755/// can never legitimately match a validated `:membros :caixa`. Thin
3756/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3757/// shared parser-shaped reason into the
3758/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
3759/// diagnostic is self-locating (which slot — `:de` or `:para` — and
3760/// the offending value verbatim) and the author can grep their
3761/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
3762/// one edit.
3763///
3764/// Until this gate landed an empty or DNS-1123-malformed `:de` /
3765/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
3766/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
3767/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
3768/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
3769/// un-Punycode-encoded IDN) silently passed the per-axis check and
3770/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
3771/// membership lookup — diagnostic-framed as "this caixa is not in
3772/// `:membros`" when the root cause is "this `:de` value is not a
3773/// well-shaped Servico-name identifier and could never legitimately
3774/// match any validated member". Because every `:membros :caixa` is
3775/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
3776/// `names` HashSet structurally never contains an empty / malformed
3777/// string, so the membership lookup arm misframes every empty /
3778/// malformed input. Lifting the shape arm ahead of the lookup
3779/// preserves the legitimate `ContratoMemberMissing` arm (a
3780/// well-shaped `:de` that simply isn't in `:membros` — a phantom
3781/// reference) while routing every structurally-impossible-to-match
3782/// input through the narrower self-locating shape diagnostic.
3783///
3784/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3785/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
3786/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
3787/// to land on the canonical [`crate::render::is_dns_1123_label`]
3788/// floor. The `slot: &'static str` field carries the kebab-case
3789/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
3790/// per-callback-slot diagnostic shape and the
3791/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
3792/// (85f102c) cross-list-tag pattern.
3793fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
3794 // Routes through the shared
3795 // [`crate::render::require_valid_dns_1123_label`] gate the peer
3796 // name axes each land on. The `slot: &'static str` field flows
3797 // through both error variants so the diagnostic names which
3798 // per-edge axis (`:de` vs `:para`) the offending value came from.
3799 crate::render::require_valid_dns_1123_label(
3800 caixa,
3801 || AplicacaoError::ContratoCaixaEmpty { slot },
3802 |reason| AplicacaoError::ContratoCaixaInvalid {
3803 slot,
3804 caixa: caixa.to_string(),
3805 reason,
3806 },
3807 )
3808}
3809
3810/// Reject `:entrada :para` values whose shape can never legitimately
3811/// match a validated `:membros :caixa`. Thin wrapper around
3812/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
3813/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
3814/// variant, so the diagnostic is self-locating (the offending
3815/// `:entrada :para` value is named verbatim) and the author can grep
3816/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
3817///
3818/// Until this gate landed an empty or DNS-1123-malformed `:entrada
3819/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
3820/// ADR typo, `:para "my_cart"` the Python-module-name leak,
3821/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
3822/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
3823/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
3824/// silently passed the per-axis check and surfaced as
3825/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
3826/// — diagnostic-framed as "this caixa is not in `:membros`" when the
3827/// root cause is "this `:entrada :para` value is not a well-shaped
3828/// Servico-name identifier and could never legitimately match any
3829/// validated member". Because every `:membros :caixa` is shape-
3830/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
3831/// `HashSet` structurally never contains an empty / malformed string,
3832/// so the membership lookup arm misframes every empty / malformed
3833/// input. Lifting the shape arm ahead of the lookup preserves the
3834/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
3835/// simply isn't in `:membros` — a phantom reference) while routing
3836/// every structurally-impossible-to-match input through the narrower
3837/// self-locating shape diagnostic.
3838///
3839/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
3840/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
3841/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
3842/// fourth and last Aplicacao-level Servico-name reference axis to
3843/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
3844/// No `slot: &'static str` field because there is only one axis
3845/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
3846/// the simpler shape mirrors [`validate_membro_caixa`] and
3847/// [`validate_placement_cluster`].
3848fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
3849 // Empty is gated separately at the call site for a self-locating
3850 // diagnostic; re-checking here keeps the predicate usable from any
3851 // future call site (the M4 CR materializer's per-`:entrada`
3852 // validator) without an empty-check footgun. Routes through the
3853 // shared [`crate::render::require_valid_dns_1123_label`] gate the
3854 // peer name axes each land on.
3855 crate::render::require_valid_dns_1123_label(
3856 para,
3857 || AplicacaoError::EntradaParaEmpty,
3858 |reason| AplicacaoError::EntradaParaInvalid {
3859 para: para.to_string(),
3860 reason,
3861 },
3862 )
3863}
3864
3865/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
3866/// would refuse at admission time. The contract — exactly the regex
3867/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
3868/// and `HTTPRoute.spec.hostnames[]`,
3869/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
3870/// (max length 253; per-label max length 63):
3871///
3872/// - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
3873/// uppercase, no underscore, no Unicode/IDN — IDN must be
3874/// pre-encoded as Punycode `xn--…` by the author);
3875/// - exactly one optional leading wildcard label (`*.`); a wildcard
3876/// in any non-leading label position is rejected;
3877/// - each `.`-separated label is 1..=63 bytes, with non-hyphen
3878/// alphanumeric at both boundaries (no `-foo`, no `foo-`);
3879/// - total length 1..=253 bytes;
3880/// - no IPv4 literal (Gateway API forbids IP literals);
3881/// - no scheme (`https://`, `http://`), no port (`:8080`), no
3882/// whitespace, no path (`/`).
3883///
3884/// Lifted as a typed gate (rather than an inline cascade in
3885/// `validate()`) so the contract lives in one place — every future
3886/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3887/// materializer's host validator, the future per-`:entrada` SAN
3888/// emission for cert-manager Certificates, the multi-`:entrada`
3889/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
3890/// for the same predicate, not its own. Same compounding shape as
3891/// `is_canonical_rate_limit_window` (808017c) and
3892/// [`WitTarget::label`] (previously the free `contrato_target_label`
3893/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
3894/// per-variant label match is compiler-checked-exhaustive).
3895///
3896/// The diagnostic carries the offending `host:` verbatim plus a
3897/// parser-shaped `reason:` naming the specific violation, so the
3898/// author can grep their caixa.lisp for `:host "<host>"` and fix it
3899/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
3900/// (9888b13).
3901fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
3902 // Empty is already gated by `EmptyEntradaHost` at the call site;
3903 // re-checking here keeps the predicate usable from any future
3904 // call site (M4 CR materializer) without an empty-check footgun.
3905 if host.is_empty() {
3906 return Err(AplicacaoError::EmptyEntradaHost);
3907 }
3908 if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
3909 return Err(AplicacaoError::EntradaHostInvalid {
3910 host: host.to_string(),
3911 reason: format!(
3912 "exceeds Gateway API v1 Hostname max length of {cap} bytes \
3913 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
3914 host.len(),
3915 cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
3916 ),
3917 });
3918 }
3919 if host.contains("://") {
3920 return Err(AplicacaoError::EntradaHostInvalid {
3921 host: host.to_string(),
3922 reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
3923 Gateway API takes the bare hostname)"
3924 .to_string(),
3925 });
3926 }
3927 if host.contains('/') {
3928 return Err(AplicacaoError::EntradaHostInvalid {
3929 host: host.to_string(),
3930 reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
3931 matching is in `:entrada :paths`)"
3932 .to_string(),
3933 });
3934 }
3935 // After the `://` scheme-prefix and `/` path arms have ruled out the
3936 // two `:`-bearing shapes the Gateway API actively rejects with
3937 // location-shaped diagnostics, any remaining `:` in the host body is
3938 // either the canonical "I put the port in the `:host` slot"
3939 // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
3940 // slot lives one axis away on the same `:entrada` block) or an
3941 // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
3942 // Hostname forbids identically to the IPv4-literal arm below. Both
3943 // shapes silently fell through the `://` and `/` arms before this
3944 // lift and surfaced as a deep `label "<rest>:<port>" contains
3945 // invalid character ':'` diagnostic from the per-byte loop near the
3946 // bottom of this predicate, which named the offending byte but not
3947 // the canonical authoring fix — for the port case the author has to
3948 // know the `:entrada` block carries a separate `:port u16` slot
3949 // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
3950 // move the value over; for the IPv6 case the author has to know
3951 // Gateway API v1 forbids IP literals across the board. The contract
3952 // doc-comment above already promises "no port (`:8080`)" verbatim
3953 // in the rejected-shape enumeration but the predicate's
3954 // implementation refused the `:` only as a side-effect of the
3955 // per-label `[a-z0-9-]` character-class loop; this arm brings the
3956 // implementation in line with the documented contract by surfacing
3957 // the canonical fix at the top-level shape gate, peer with how the
3958 // `://` arm names the scheme prefix and the `/` arm names the
3959 // `:entrada :paths` axis. Same compounding trajectory the recent
3960 // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
3961 // — the typed slot's rejected set matches the apiserver's rejected
3962 // set, structurally, with a self-locating diagnostic at the
3963 // offending axis instead of a deep parser-shape leak.
3964 if host.contains(':') {
3965 return Err(AplicacaoError::EntradaHostInvalid {
3966 host: host.to_string(),
3967 reason: "must not contain `:` (the port belongs in the `:entrada :port` \
3968 slot — a separate `u16` axis on the same `:entrada` block, \
3969 defaulting to 8080 — not in the host body; drop the `:<port>` \
3970 suffix and author the bare hostname. If you intended an IPv6 \
3971 literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
3972 Hostname forbids IP literals identically to the IPv4-literal \
3973 arm — use a DNS name)"
3974 .to_string(),
3975 });
3976 }
3977 // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
3978 // predicate — the same single source of truth every peer
3979 // ASCII-whitespace scan in caixa-core flows through: the four
3980 // typed-magnitude codec sites (`limits::parse_byte_size` backing
3981 // `:limits :memory`, `limits::parse_duration` backing `:limits
3982 // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
3983 // `aplicacao::rate_limit_codec::parse` backing `:politicas
3984 // :rate-limit`) and the shared duration codec
3985 // (`supervisor::duration_codec::parse`) backing `:supervisor
3986 // :restart-window` / `:politicas :timeout` / `:politicas
3987 // :circuit-breaker :window`. This landing closes the last string-typed
3988 // slot in caixa-core still calling `.bytes().any(|b|
3989 // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
3990 // across every typed slot now shares one predicate, so a future
3991 // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
3992 // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
3993 // deliberately excluded from the peer non-ASCII predicate) can
3994 // extend at this shared site in one edit rather than seven
3995 // independent scans diverging over time. Naming the offending byte
3996 // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
3997 // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
3998 // the offending byte verbatim" discipline every peer codec site
3999 // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4000 // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4001 if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4002 return Err(AplicacaoError::EntradaHostInvalid {
4003 host: host.to_string(),
4004 reason: format!(
4005 "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4006 Hostname is a single-token DNS name — leading, trailing, \
4007 or embedded whitespace breaks the K8s apiserver's Hostname \
4008 regex at admission time; the paste-from-aligned-doc / \
4009 paste-from-shell-history / paste-from-CSV footgun silently \
4010 lands a multi-token blob in `:entrada :host`. Strip every \
4011 whitespace byte and author the bare hostname — space \
4012 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4013 refuse identically)"
4014 ),
4015 });
4016 }
4017 // Peer of the ASCII-whitespace scan above: route the non-ASCII
4018 // subset of Unicode `White_Space` through the shared
4019 // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4020 // single source of truth every peer non-ASCII-whitespace scan in
4021 // caixa-core flows through: `limits::parse_byte_size` (`:limits
4022 // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4023 // `limits::parse_millicores` (`:limits :cpu`),
4024 // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4025 // and `supervisor::duration_codec::parse` (`:supervisor
4026 // :restart-window` / `:politicas :timeout` / `:politicas
4027 // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4028 // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4029 // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4030 // paste-from-web-doc), or an EM-SPACE-split host
4031 // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4032 // survived this predicate's ASCII byte-scan (none of the UTF-8
4033 // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4034 // `u8::is_ascii_whitespace`), then landed on the per-label
4035 // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4036 // predicate with the generic `label "…" must start and end with an
4037 // alphanumeric` diagnostic — a "far from source at build-time"
4038 // leak that names the label-shape violation but not the
4039 // paste-from-typography origin the author actually needs to fix.
4040 // Peer with the four codec sites the 1b75b38 landing pinned: the
4041 // typed slot's diagnostic axis names the offending codepoint
4042 // (`U+XXXX`) verbatim rather than laundering the value through a
4043 // downstream label-shape arm, so the author can grep their
4044 // caixa.lisp for the invisible codepoint at the surfaced position
4045 // rather than eyeball a multi-byte host for embedded NBSP / LINE
4046 // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4047 // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4048 // drift between any two typed-slot sites' non-ASCII-whitespace
4049 // rejection set becomes a single-edit fix at the shared predicate
4050 // rather than N independent inline scans diverging over time, and
4051 // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4052 // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4053 // `char::is_whitespace`" class the peer non-ASCII predicate's
4054 // doc-comment names as the follow-up trajectory) extends at the
4055 // shared predicate in one edit rather than seven.
4056 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4057 return Err(AplicacaoError::EntradaHostInvalid {
4058 host: host.to_string(),
4059 reason: format!(
4060 "contains non-ASCII Unicode whitespace character {ch:?} \
4061 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4062 single-token DNS name limited to `[a-z0-9-]` labels; \
4063 the paste-from-typography footgun silently lands an \
4064 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4065 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4066 `U+3000`, and every other member of the Unicode \
4067 `White_Space` property outside the ASCII byte range) \
4068 in `:entrada :host`, which the K8s apiserver's \
4069 Hostname regex refuses at admission time far from the \
4070 caixa.lisp source line. Strip every non-ASCII \
4071 whitespace character and author the bare hostname \
4072 with only ASCII bytes (write \"checkout.quero.cloud\" \
4073 verbatim)",
4074 codepoint = ch as u32,
4075 ),
4076 });
4077 }
4078
4079 // Strip the optional single leading wildcard label *before* the
4080 // trailing-dot check so the bare `"*."` form surfaces the more
4081 // self-locating "wildcard without domain" diagnostic instead of
4082 // the generic "trailing dot" one.
4083 let (had_wildcard, rest) = match host.strip_prefix("*.") {
4084 Some(r) => (true, r),
4085 None => (false, host),
4086 };
4087 if had_wildcard && rest.is_empty() {
4088 return Err(AplicacaoError::EntradaHostInvalid {
4089 host: host.to_string(),
4090 reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4091 });
4092 }
4093 if rest.contains('*') {
4094 return Err(AplicacaoError::EntradaHostInvalid {
4095 host: host.to_string(),
4096 reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4097 no inner or trailing `*` labels"
4098 .to_string(),
4099 });
4100 }
4101 if rest.ends_with('.') {
4102 return Err(AplicacaoError::EntradaHostInvalid {
4103 host: host.to_string(),
4104 reason: "must not have a trailing `.` (Gateway API hostnames are not \
4105 fully-qualified with a root dot; the apiserver regex rejects \
4106 trailing dots)"
4107 .to_string(),
4108 });
4109 }
4110
4111 // Reject pure IPv4 literals: four dot-separated labels, every
4112 // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4113 // literals as Hostnames.
4114 let labels: Vec<&str> = rest.split('.').collect();
4115 if labels.len() == 4
4116 && labels
4117 .iter()
4118 .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4119 {
4120 return Err(AplicacaoError::EntradaHostInvalid {
4121 host: host.to_string(),
4122 reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4123 literals; use a DNS name)"
4124 .to_string(),
4125 });
4126 }
4127
4128 // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4129 // hyphen, with non-hyphen at both boundaries.
4130 for label in &labels {
4131 if label.is_empty() {
4132 return Err(AplicacaoError::EntradaHostInvalid {
4133 host: host.to_string(),
4134 reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4135 });
4136 }
4137 if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4138 return Err(AplicacaoError::EntradaHostInvalid {
4139 host: host.to_string(),
4140 reason: format!(
4141 "label {label:?} exceeds DNS-1123 label max length of \
4142 {cap} bytes (got {} bytes)",
4143 label.len(),
4144 cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4145 ),
4146 });
4147 }
4148 let bytes = label.as_bytes();
4149 if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4150 return Err(AplicacaoError::EntradaHostInvalid {
4151 host: host.to_string(),
4152 reason: format!(
4153 "label {label:?} must start and end with an alphanumeric \
4154 (no leading or trailing `-`)"
4155 ),
4156 });
4157 }
4158 for &b in bytes {
4159 let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4160 if !valid {
4161 let msg = if b.is_ascii_uppercase() {
4162 format!(
4163 "label {label:?} contains uppercase character {ch:?} \
4164 (Gateway API hostnames are lowercase-only; use {lower:?})",
4165 ch = b as char,
4166 lower = label.to_ascii_lowercase()
4167 )
4168 } else if b == b'_' {
4169 format!(
4170 "label {label:?} contains `_` (Gateway API hostnames \
4171 allow only `[a-z0-9-]`; use `-` instead)"
4172 )
4173 } else {
4174 format!(
4175 "label {label:?} contains invalid character {ch:?} \
4176 (Gateway API hostnames allow only `[a-z0-9-]`)",
4177 ch = b as char
4178 )
4179 };
4180 return Err(AplicacaoError::EntradaHostInvalid {
4181 host: host.to_string(),
4182 reason: msg,
4183 });
4184 }
4185 }
4186 }
4187 Ok(())
4188}
4189
4190/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4191/// would refuse at admission time. Thin wrapper around
4192/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4193/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4194/// variant, preserving the more self-locating
4195/// [`AplicacaoError::EntradaPathEmpty`] /
4196/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4197/// path fails those narrower invariants first.
4198///
4199/// The contract is the canonical HTTP-path grammar — `1..=
4200/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4201/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4202/// whitespace/control/non-ASCII bytes — shared with the
4203/// `:contratos :endpoint` axis through the lifted predicate so drift
4204/// between either landing site and the K8s apiserver-side
4205/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4206/// the predicate, not a per-renderer "this passed validate but failed
4207/// admission" surprise. The diagnostic carries the offending `path:`
4208/// verbatim plus a parser-shaped `reason:` naming the specific
4209/// violation, so the author can grep their caixa.lisp for `:paths`
4210/// and fix it in one edit. Same diagnostic shape as
4211/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4212/// axis.
4213fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4214 // Empty and missing-leading-`/` are already gated at the call
4215 // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4216 // checking here keeps the per-axis narrower diagnostics in force
4217 // when the predicate is reached directly (and `is_gateway_api_http_path`
4218 // itself defends against `bytes[0]`-style indexing on empty
4219 // input).
4220 if path.is_empty() {
4221 return Err(AplicacaoError::EntradaPathEmpty);
4222 }
4223 if !path.starts_with('/') {
4224 return Err(AplicacaoError::EntradaPathNotAbsolute {
4225 path: path.to_string(),
4226 });
4227 }
4228 crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4229 AplicacaoError::EntradaPathInvalid {
4230 path: path.to_string(),
4231 reason,
4232 }
4233 })
4234}
4235
4236mod rate_limit_codec {
4237 // `Duration` is no longer named here — the codec routes through
4238 // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4239 // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4240 // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4241 // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4242 // closed-set enum's arm-table rather than through vestigial free-helper
4243 // delegates.
4244 use super::{RateLimit, RateLimitUnit};
4245 use serde::{Deserialize, Deserializer, Serializer};
4246
4247 pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4248 match v {
4249 Some(rl) => s.serialize_str(&render(*rl)),
4250 None => s.serialize_none(),
4251 }
4252 }
4253
4254 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4255 let opt: Option<String> = Option::deserialize(d)?;
4256 match opt {
4257 None => Ok(None),
4258 Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4259 }
4260 }
4261
4262 fn parse(s: &str) -> Result<RateLimit, String> {
4263 // Whitespace-rejection arm — peer with the leading-`+`
4264 // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4265 // same canonical-form render-determinism axis. Until this gate
4266 // landed the parser silently tolerated leading / trailing /
4267 // internal whitespace via the top-level `s.trim()` and the
4268 // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4269 // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4270 // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4271 // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4272 // serde silently round-tripped to `"100/s"` on the next emit
4273 // (a *different* canonical string) — breaking the THEORY.md
4274 // Part V render-determinism contract on the same
4275 // canonical-form-drift axis the leading-`+` arm below (the
4276 // 4eeae98 predecessor) and the leading-zero arm below (the
4277 // 4f46830 predecessor) already close.
4278 //
4279 // The canonical author shape is `<integer>/<s|m|h>` with no
4280 // whitespace bytes anywhere — every string [`render`] emits
4281 // carries none, so the parser's accepted set must match for
4282 // serialize / deserialize to round-trip losslessly. This gate
4283 // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4284 // `unit.trim()` calls below strict no-ops on the accepted set
4285 // (every byte-position match they would perform is now already
4286 // trimmed away by the accepted set itself), while the arm
4287 // surfaces every rejected whitespace-carrying shape with a
4288 // self-locating diagnostic naming the offending byte and the
4289 // canonical form the author intended, peer with every prior
4290 // canonical-form-drift arm on this codec.
4291 //
4292 // Routed through the lifted
4293 // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4294 // same source of truth the four peer typed-magnitude codec
4295 // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4296 // `limits::parse_millicores`, `supervisor::duration_codec`)
4297 // share. `u8::is_ascii_whitespace()` at the predicate covers
4298 // the five WhatWG-conformant ASCII whitespace bytes (space,
4299 // tab, LF, FF, CR); the "single lifted predicate" discipline
4300 // the peer non-ASCII arm below carries on the strictly-
4301 // complementary Unicode `White_Space` class extends here to
4302 // the ASCII byte set as well.
4303 if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4304 return Err(format!(
4305 "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4306 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4307 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4308 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4309 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4310 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4311 on first serialize — breaking the THEORY.md Part V render-determinism \
4312 contract every typed slot carries. Strip every whitespace byte (write \
4313 `\"100/s\"` verbatim)"
4314 ));
4315 }
4316 // Non-ASCII Unicode `White_Space` arm — the strictly-
4317 // complementary class the ASCII arm above cannot see.
4318 // `str::trim` at the top of every peer codec uses
4319 // `char::is_whitespace` (Unicode `White_Space`, strictly
4320 // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4321 // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4322 // survives the byte-scan (its UTF-8 bytes are not in
4323 // `is_ascii_whitespace`), gets silently stripped by the
4324 // top-level `s.trim()` below, and the value round-trips
4325 // through `render` to a *different* canonical form
4326 // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4327 // render-determinism contract every typed slot carries.
4328 // Closed here (`:politicas :rate-limit`) and at the three
4329 // peer codec sites (`limits::parse_byte_size`,
4330 // `limits::parse_duration`, `supervisor::duration_codec`)
4331 // through the shared
4332 // [`crate::render::find_non_ascii_whitespace_char`] predicate
4333 // — the "single lifted predicate across all four codec sites
4334 // in one follow-up run" the 24a8ad4 commit body's `Forward
4335 // compounding` bullet named as the next compounding step.
4336 if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4337 return Err(format!(
4338 "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4339 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4340 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4341 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4342 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4343 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4344 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4345 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4346 silently strips it at parse entry, and the value round-trips through \
4347 `render` to a *different* canonical form (`\"100/s\"`) on first \
4348 serialize — breaking the THEORY.md Part V render-determinism contract \
4349 every typed slot carries. Strip every non-ASCII whitespace character \
4350 (write `\"100/s\"` verbatim with only ASCII bytes)",
4351 cp = ch as u32
4352 ));
4353 }
4354 let s = s.trim();
4355 let (rate_str, unit) = s
4356 .split_once('/')
4357 .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4358 let rate_trim = rate_str.trim();
4359 // The canonical authoring form for `:politicas :rate-limit` is
4360 // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4361 // non-negative integer with no decimal point and no leading
4362 // sign, so the parser's accepted set must match for
4363 // serialize/deserialize to round-trip without canonical-form
4364 // drift. Until this gate landed the parser accepted any
4365 // `u32::from_str`-shaped magnitude — and current Rust
4366 // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4367 // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4368 // serde silently round-tripped to `"100/s"` on the next emit
4369 // (a *different* canonical string) — breaking the THEORY.md
4370 // Part V render-determinism contract on the fifth typed-codec
4371 // surface in caixa-core (peer with the four duration codecs the
4372 // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4373 // already covered: `supervisor::duration_codec` backing three
4374 // typed-duration slots, `limits::parse_duration` backing
4375 // `:limits :wall-clock`, `limits::parse_byte_size` backing
4376 // `:limits :memory`). The fractional / decimal-shaped sibling
4377 // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4378 // existing rejection arm, but the diagnostic is value-laundered
4379 // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4380 // doesn't name the canonical-form remediation or the round-trip
4381 // drift the next emit would produce); this gate lifts the
4382 // fractional arm onto the same canonical-form diagnostic the
4383 // peer codecs carry.
4384 //
4385 // Strict canonical form: every byte of the magnitude is an
4386 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4387 // inputs the gate distinguishes "non-canonical-but-numeric"
4388 // (parses as f64 or i64 — surfaced with a self-locating
4389 // diagnostic naming the canonical authoring form and the
4390 // round-trip drift the rejected shape would produce on first
4391 // serialize) from "garbage" (parses as neither — surfaced with
4392 // the existing narrower `"not a u32"` wording so its
4393 // diagnostic shape remains stable for the parser-shape footgun
4394 // case).
4395 //
4396 // Routed through the lifted
4397 // [`crate::render::is_digit_only_magnitude`] predicate — the
4398 // same source of truth the four peer typed-magnitude codec
4399 // sites share.
4400 let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4401 if !digit_only {
4402 let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4403 if numeric {
4404 return Err(format!(
4405 "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4406 canonical authoring form for `:politicas :rate-limit` is \
4407 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4408 with no decimal point and no leading `+` / `-` sign. A fractional / \
4409 signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4410 through `render` to a *different* canonical form (`\"1/s\"`, \
4411 `\"100/s\"`, parser-reject) on first serialize — breaking the \
4412 THEORY.md Part V render-determinism contract every typed slot \
4413 carries. Pick an integer rate that fits the desired window \
4414 (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4415 ));
4416 }
4417 return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4418 }
4419 // Leading-zero arm — peer with the prior `"+100/s"` arm above
4420 // (4eeae98's predecessor) on the same canonical-form
4421 // render-determinism axis. The digit-only gate accepts
4422 // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4423 // them losslessly (= 100, 0, 7), but `render` emits the
4424 // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4425 // a *different* canonical string on the next emit, breaking
4426 // the THEORY.md Part V render-determinism contract the same
4427 // way `"+100/s"` did before the leading-`+` arm landed. The
4428 // single-byte magnitude `"0"` itself round-trips losslessly
4429 // through `render` (`render(0)` emits `"0/s"`) — the
4430 // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4431 // what refuses rate-zero authoring, so `"0/s"` stays in the
4432 // accepted set at this codec layer and the diagnostic
4433 // partitioning between canonical-form drift (this arm) and
4434 // semantic-zero (the downstream gate) remains stable.
4435 // Peer with the future leading-zero arms on the three peer
4436 // typed-magnitude codecs the trajectory acknowledges:
4437 // `supervisor::duration_codec`, `limits::parse_duration`,
4438 // `limits::parse_byte_size` — each carries the same
4439 // canonical-form-drift class today; this gate lands the
4440 // discipline on the fourth typed-magnitude codec in
4441 // caixa-core first because the peer `"+100/s"` arm above is
4442 // the closest predecessor on the trajectory.
4443 //
4444 // Routed through the lifted
4445 // [`crate::render::is_leading_zero_padded_magnitude`]
4446 // predicate — the same source of truth the four peer
4447 // typed-magnitude codec sites share.
4448 if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4449 return Err(format!(
4450 "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4451 canonical authoring form for `:politicas :rate-limit` is \
4452 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4453 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4454 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4455 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4456 first serialize — breaking the THEORY.md Part V render-determinism \
4457 contract every typed slot carries. Strip the leading zeros (write \
4458 `\"100/s\"` instead of `\"0100/s\"`)"
4459 ));
4460 }
4461 // The digit-only gate guarantees every byte is `[0-9]`, and
4462 // the leading-zero arm above guarantees the magnitude is
4463 // either the single byte `"0"` or starts with `[1-9]`, so
4464 // the only way `u32::from_str` can fail here is overflow
4465 // (the magnitude exceeds `u32::MAX`). Surface that with an
4466 // overflow-shaped wording so the diagnostic names the
4467 // offending magnitude verbatim rather than collapsing onto
4468 // the non-canonical arm. Same shape
4469 // `supervisor::duration_codec` (1c55a2a) carries on the peer
4470 // duration-codec axis.
4471 let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4472 format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4473 })?;
4474 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4475 // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4476 // arm reads the `&str → Duration` projection through the
4477 // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4478 // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4479 // with [`super::RateLimitUnit::window`]) rather than the vestigial
4480 // module-private `rate_limit_window_from_unit` free helper the
4481 // predecessor 61421a6 left as the last unlifted delegate on this
4482 // axis. One typed dispatch on the substrate primitive instead of
4483 // one runtime call through the free-helper delegate; the sole
4484 // production consumer of the `&str → Duration` axis (this parse
4485 // arm) now reaches for exactly one typed method on the closed-set
4486 // enum, sibling to the codec's render arm's
4487 // [`super::RateLimit::canonical_unit`] dispatch on the paired
4488 // `Duration → RateLimitUnit` axis and to the validate gate's
4489 // [`super::RateLimit::canonical_unit`] shape-probe on the
4490 // canonical-window axis. A future rate-limit-unit addition (a
4491 // `"d"` day suffix once Envoy's `rate_limit_action` grows
4492 // daily-bucket support, a `"ms"` sub-second window once
4493 // high-throughput per-edge policies come into scope per
4494 // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4495 // on the closed-set enum, and the compiler enforces exhaustiveness
4496 // on every consumer's `match self` arms — this parse arm's
4497 // accepted-suffix set, the render arm's emitted-suffix set, the
4498 // validate gate's canonical-window set, and every future
4499 // per-`:contratos`-edge rate-limit-override overlay all pick it up
4500 // by construction.
4501 let unit = unit.trim();
4502 let window = RateLimitUnit::window_from_suffix(unit)
4503 .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4504 Ok(RateLimit { rate, window })
4505 }
4506
4507 fn render(rl: RateLimit) -> String {
4508 // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4509 // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4510 // this render arm reads the `Duration → RateLimitUnit` projection
4511 // through the substrate primitive [`super::RateLimit::canonical_unit`]
4512 // (returns `None` on every non-canonical window — the sub-second /
4513 // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4514 // formats the returned typed enum through its
4515 // [`std::fmt::Display`] impl (which routes through
4516 // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4517 // the substrate primitive instead of one runtime `find_map`
4518 // walk through the free-helper delegate chain
4519 // [`super::rate_limit_window_unit`] (the vestigial free helper's
4520 // sole production consumer was this arm; every other consumer of
4521 // the `Duration → unit` axis — the validate gate below and the
4522 // future M4 per-Aplicacao Envoy config reconciler — now reads
4523 // the same typed method).
4524 //
4525 // A future rate-limit-unit addition (a `"d"` day suffix once
4526 // Envoy's `rate_limit_action` grows daily-bucket support) is
4527 // one variant + one arm per method on the closed-set enum, and
4528 // the compiler enforces exhaustiveness on every consumer's
4529 // `match self` arms — the codec's `parse` accepted-suffix set,
4530 // this render arm's emitted-suffix set, the validate gate's
4531 // canonical-window set, and every future per-`:contratos`-edge
4532 // rate-limit-override overlay all pick it up by construction.
4533 if let Some(unit) = rl.canonical_unit() {
4534 format!("{}/{unit}", rl.rate())
4535 } else {
4536 // Defensive fallback for non-canonical windows. Note:
4537 // [`AplicacaoSpec::validate_politicas`] rejects any
4538 // non-canonical `:rate-limit :window` via
4539 // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4540 // a validated `RateLimit` never reaches this branch. The
4541 // emitted `<n>/<k>s` form is *not* round-trippable through
4542 // [`parse`] (which accepts only the closed-set
4543 // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4544 // explicit count) — the validate gate is what makes the
4545 // round-trip a structural property; this branch exists only
4546 // so a programmatic non-validated serialize doesn't panic.
4547 format!("{}/{}s", rl.rate(), rl.window().as_secs())
4548 }
4549 }
4550}
4551
4552// ── placement strategy ───────────────────────────────────────────────
4553
4554/// How the Aplicacao distributes across clusters. Three options:
4555///
4556/// - `SingleNode` — one cluster runs the app at a time; takeover on
4557/// death (Erlang/OTP distributed-app semantics).
4558/// - `Replicated` — every named cluster runs an instance (active-active).
4559/// - `Sharded` — entities distribute by hash key across clusters
4560/// (Akka cluster sharding).
4561#[derive(
4562 Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4563)]
4564pub enum PlacementStrategy {
4565 SingleNode,
4566 Replicated,
4567 Sharded,
4568}
4569
4570impl Default for PlacementStrategy {
4571 fn default() -> Self {
4572 Self::Replicated
4573 }
4574}
4575
4576impl PlacementStrategy {
4577 /// Exhaustive iteration surface for every consumer that reads the
4578 /// full closed-set (the future M4 admission-webhook's accepted-
4579 /// strategy listing in its rejection body, a future `feira app
4580 /// placement --list` CLI-side surfacing of the accepted arm-set,
4581 /// any future round-trip fuzz harness). A future variant addition
4582 /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
4583 /// names as a trajectory item) extends this slice as a single edit
4584 /// and every consumer picks up the new entry by construction — the
4585 /// compiler-checked exhaustiveness on the sibling method `match`
4586 /// arms is the build-time guarantee that no arm forgets to grow.
4587 /// Same shape as the sibling closed-set typed enums'
4588 /// [`RateLimitUnit::ALL`] (6bce03d) and
4589 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
4590 /// surfaces — the third closed-set typed enum on the caixa surface
4591 /// to converge onto the same discipline.
4592 pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
4593
4594 /// Canonical camelCase-schema discriminator scalar this variant
4595 /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
4596 /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
4597 /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4598 /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
4599 /// every substrate consumer that dispatches on the strategy (the
4600 /// `lareira-fleet-programs` aggregator, the future `app-operator`
4601 /// reconciler, the M3 Adaptive compression pass) reads the same
4602 /// byte-string the `Serialize` derive emits — the pin test in
4603 /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
4604 /// asserts the two paths agree.
4605 #[must_use]
4606 pub const fn as_str(self) -> &'static str {
4607 match self {
4608 Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
4609 Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
4610 Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
4611 }
4612 }
4613
4614 /// Substrate-canonical reverse projection on the `:placement
4615 /// :estrategia` closed-set axis — parses the camelCase-schema
4616 /// discriminator scalar back to the typed variant, or `None` when
4617 /// `s` is outside the closed-set arm-string set [`Self::as_str`]
4618 /// emits. Dispatches on the same lifted
4619 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4620 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4621 /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
4622 /// [`Self::as_str`] emitter walks, so the parse and emit halves of
4623 /// the round-trip migrate through one caixa-core edit on any future
4624 /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
4625 /// §II.5 hint names as a trajectory item lands one variant + one
4626 /// arm per method and the compiler enforces exhaustiveness on every
4627 /// consumer's `match self` arms).
4628 ///
4629 /// Prior to this lift the substrate carried only the forward
4630 /// `Self → &str` projection (the [`Self::as_str`] emitter, the
4631 /// [`std::fmt::Display`] impl routed through it, the `Serialize`
4632 /// derive that emits the same byte-string under
4633 /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
4634 /// consumer that wanted to parse a wire-form strategy scalar had to
4635 /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
4636 /// => …, "Sharded" => …, _ => … }` cascade that expressed no
4637 /// compile-time link back to the typed variant's canonical lifted
4638 /// constant. A future variant rename or a per-arm serde-attribute
4639 /// drift would silently split the wire byte-string one non-serde
4640 /// consumer parsed from the one the emitter wrote, with the
4641 /// failure surfacing at parse time far from the rebrand commit.
4642 ///
4643 /// Same closed-set-reverse-projection discipline the sibling
4644 /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
4645 /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
4646 /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
4647 /// defining `:placement :estrategia` closed-set axis, the third
4648 /// substrate-side closed-set typed enum to converge on the two-way
4649 /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
4650 /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
4651 /// and side-step the [`std::str::FromStr`]-collision clippy
4652 /// (`clippy::should_implement_trait`) the plain `from_str` name
4653 /// carries; a future explicit [`std::str::FromStr`] impl can layer
4654 /// on top by delegating to this canonical arm-dispatch method.
4655 ///
4656 /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
4657 /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
4658 /// picks the diagnostic form appropriate for its use site — a
4659 /// future `feira app placement --set` CLI-side arg-parse that wants
4660 /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
4661 /// Sharded)"` diagnostic builds one on top by iterating
4662 /// [`Self::ALL`], while the future M4 admission-webhook's rejection
4663 /// path folds `None` onto its per-CR structured refusal body.
4664 #[must_use]
4665 pub fn from_wire(s: &str) -> Option<Self> {
4666 match s {
4667 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
4668 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
4669 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
4670 _ => None,
4671 }
4672 }
4673
4674 /// Substrate-canonical per-arm predicate naming the cross-slot
4675 /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
4676 /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
4677 /// consumes the paired [`Placement::shard_key`] axis (and therefore
4678 /// requires — and is the only strategy that permits — a non-empty
4679 /// `:shard-key` on the paired slot). Today the accept-set is the
4680 /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
4681 /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
4682 /// per-entity extractor expression; `SingleNode` (Erlang/OTP
4683 /// distributed-app takeover — §II.1) and `Replicated` (active-active
4684 /// across every named cluster) have no hash-keyed routing axis to
4685 /// consume the slot and refuse a declared-but-inert `:shard-key`
4686 /// through [`AplicacaoError::ShardKeyOnNonSharded`].
4687 ///
4688 /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
4689 /// satisfies `placement.shard_key().is_some() ==
4690 /// placement.estrategia().requires_shard_key()` by construction — the
4691 /// cross-slot partition the pin
4692 /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
4693 /// locks load-bearing, so every downstream consumer that reaches for
4694 /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
4695 /// CR materializer's per-CR shard-key resolver, the future
4696 /// [`feira app graph --shard-key`] per-Aplicacao column, the future
4697 /// per-cluster Akka-style cluster-sharding reconciler's per-entity
4698 /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
4699 /// shard-key requirement probe, a future author-facing tatara-lisp
4700 /// linter that flags `(:placement (:estrategia Replicated :shard-key
4701 /// "tenantId"))` shapes before `feira lint` reaches
4702 /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
4703 /// the substrate primitive — the predicate names *the cross-slot
4704 /// invariant*, not the arm identity.
4705 ///
4706 /// Prior to this lift the "does this strategy consume `:shard-key`"
4707 /// classification lived under the `gen_platform::IsVariant`-derived
4708 /// [`Self::is_sharded`] predicate at three fixture-builder sites in
4709 /// this crate (the [`tests::placement_strategy_variants_round_trip`]
4710 /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
4711 /// } else { None }` cascade, the
4712 /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
4713 /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
4714 /// "tenantId".to_string())` cascade, and the
4715 /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
4716 /// per-variant spec-mutator's identical `.is_sharded().then(…)`
4717 /// cascade). Each site conflated two semantically distinct questions:
4718 /// "is the variant `Sharded`?" (arm-identity, what
4719 /// [`Self::is_sharded`] answers) and "does the variant consume
4720 /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
4721 /// The two questions land on the same three-way answer under today's
4722 /// closed accept-set (both trip on the singleton `{Sharded}`), but a
4723 /// future arm addition that consumed `:shard-key` under a different
4724 /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
4725 /// §II.5 roadmap-hint names that hash-partitions across the cluster
4726 /// pool by client-IP hash rather than an author-declared extractor
4727 /// expression, a hypothetical `WeightedShard` variant that carries a
4728 /// shard-key + per-cluster weight table under a promoted M5
4729 /// adaptive-placement engine) or an addition that did *not* consume
4730 /// `:shard-key` on a semantically Sharded-shaped arm would silently
4731 /// split the two questions. Any consumer that read
4732 /// `.is_sharded().then(…)` for the shard-key requirement gate would
4733 /// silently misclassify the new arm as non-consuming — a fixture
4734 /// builder would omit `:shard-key` where the new arm required one and
4735 /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
4736 /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
4737 /// commit, a future M4 CR materializer would fall through the
4738 /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
4739 /// silently emit an empty extractor at the Akka reconciler layer.
4740 ///
4741 /// Lifting the classification as a substrate-primitive method on the
4742 /// closed-set typed enum names the cross-slot invariant on the
4743 /// primitive that owns the partition: every future arm addition
4744 /// declares its `:shard-key` consumption in one place (this predicate's
4745 /// `match self` arm-set), and every downstream consumer that reaches
4746 /// for the paired shape reads through one typed dispatch. Same
4747 /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
4748 /// per-arm predicate on the pre-projection WIT-shape axis and the
4749 /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
4750 /// paired predicate on the post-projection typed-view axis — a
4751 /// per-arm semantic-classification predicate paired with the
4752 /// arm-identity predicate the derive already emits, closing the drift
4753 /// footgun on the cross-slot invariant axis.
4754 ///
4755 /// Method-named `requires_shard_key` (not `has_shard_key`, not
4756 /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
4757 /// invariant reads as "this strategy *requires* the paired
4758 /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
4759 /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
4760 /// merely omit it. The `has_*` framing would read as an accessor
4761 /// (returning the presence of an already-carried value) rather than a
4762 /// requirement (naming the invariant the paired slot must satisfy).
4763 /// Returns `bool` (not `Option<()>` or a marker-type witness), same
4764 /// shape as the sibling [`WitContract::is_capability`] /
4765 /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
4766 /// arm-family, so every consumer reaches for `.requires_shard_key()`
4767 /// as a drop-in replacement for the `.is_sharded()` conflated read
4768 /// without a return-shape migration.
4769 #[must_use]
4770 pub const fn requires_shard_key(self) -> bool {
4771 match self {
4772 Self::Sharded => true,
4773 Self::SingleNode | Self::Replicated => false,
4774 }
4775 }
4776}
4777
4778// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
4779// cross-slot-invariant per-arm predicate: the module-scope const-eval
4780// assertions below trip at caixa-core build time (not test time) if a
4781// future edit rewires the predicate's arm-set away from the singleton
4782// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
4783// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
4784// runtime pin covers the same truth-table with a more descriptive
4785// diagnostic on failure; these const-eval items add a build-time failure
4786// surface strictly stronger than the runtime pin (a downstream renderer's
4787// `const`-context reader that composed against a rebound predicate would
4788// still surface here before the test suite even ran) and side-step the
4789// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
4790// would otherwise accumulate on the caixa-core module baseline.
4791const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
4792const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
4793const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
4794
4795/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
4796/// the pretty-printed byte-string every consumer that formats the strategy
4797/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
4798/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
4799/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
4800/// per-Aplicacao strategy line, the future M4 CR materializer's per-
4801/// admission-webhook rejection body) reaches for the same lifted
4802/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
4803/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
4804/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
4805/// `Serialize` derive already emits under
4806/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
4807/// [`PlacementStrategy::as_str`] helper already returns.
4808///
4809/// Until this lift landed the sibling OTP-shape typed enums —
4810/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
4811/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
4812/// so [`std::fmt::Display`] routes through the same discriminant string
4813/// the wire format emits) — carried a stable [`std::fmt::Display`]
4814/// surface but [`PlacementStrategy`] did not; every consumer reaching
4815/// for a strategy byte-string past the wire format had to pick between
4816/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
4817/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
4818/// derive), any two of which a future variant rename or
4819/// `#[serde(rename_all = "kebab-case")]` attribute would silently
4820/// desynchronize — with the failure surfacing as a downstream renderer /
4821/// operator's per-strategy dispatch reading one spelling while the wire
4822/// format emitted another, far from the source rebrand commit and with
4823/// no field naming the drift. Routing `Display` through
4824/// [`PlacementStrategy::as_str`] makes the three paths
4825/// (`Debug` for structural inspection, `Display` for user-facing text,
4826/// `Serialize` for the wire format) converge on the same lifted
4827/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
4828/// the diagnostic byte-string, and the pretty-printed byte-string move
4829/// as a single unit through one canonical declaration each, by
4830/// construction. Same trajectory as [`PlacementStrategy::as_str`]
4831/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
4832/// closes the third path.
4833///
4834/// Pin tests
4835/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
4836/// and
4837/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
4838/// assert the three paths agree byte-for-byte on every variant, so a
4839/// future variant rename or per-arm serde attribute drift is a build
4840/// error visible at caixa-core test time, not a silent per-consumer
4841/// dispatch miss at apply / reconcile time.
4842impl std::fmt::Display for PlacementStrategy {
4843 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4844 f.write_str(self.as_str())
4845 }
4846}
4847
4848/// Where the Aplicacao runs.
4849#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
4850#[serde(rename_all = "camelCase")]
4851pub struct Placement {
4852 /// Distribution strategy.
4853 #[serde(default)]
4854 pub estrategia: PlacementStrategy,
4855
4856 /// Named clusters that host this Aplicacao. Required for
4857 /// `Replicated` and `SingleNode`; for `Sharded` declares the
4858 /// shard pool.
4859 #[serde(default)]
4860 pub clusters: Vec<String>,
4861
4862 /// Optional hint to the placement engine: `"data-locality"`,
4863 /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
4864 #[serde(default, skip_serializing_if = "Option::is_none")]
4865 pub affinity: Option<String>,
4866
4867 /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
4868 #[serde(default, skip_serializing_if = "Option::is_none")]
4869 pub shard_key: Option<String>,
4870}
4871
4872impl Placement {
4873 /// Substrate-canonical per-`:placement` Akka-cluster-sharding
4874 /// `:shard-key` extractor-expression scalar accessor every consumer
4875 /// of the Aplicacao's hash-keyed distribution routing keys off —
4876 /// returns the author-declared `:placement :shard-key` byte-string
4877 /// verbatim as an `Option<&str>`, borrowed from the typed slot's
4878 /// own `Option<String>` storage; `None` when the slot is absent
4879 /// (the canonical shape under `:estrategia Replicated` /
4880 /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
4881 /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
4882 /// partition — `validate` refuses any `Placement` past this call
4883 /// that lands `Some` on a non-`Sharded` strategy or `None` on
4884 /// `Sharded`).
4885 ///
4886 /// The `:placement :shard-key` slot carries the Akka-style
4887 /// cluster-sharding entity-id extractor expression
4888 /// (MESH-COMPOSITION §II.4) — validated by
4889 /// [`validate_placement_shard_key`] to be a non-empty printable-
4890 /// ASCII single-token reference (`tenantId`, `$tenantId`,
4891 /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
4892 /// future M4 Akka-style cluster-sharding reconciler hashes without
4893 /// re-validating at the runtime layer), and every downstream
4894 /// consumer that reads the key keys off this scalar (the
4895 /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
4896 /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
4897 /// declared-but-inert refusal diagnostic, the caixa-mesh
4898 /// per-Aplicacao `placement.shardKey` emit path the substrate
4899 /// operator's per-entity hash-routing reader consumes, the future
4900 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4901 /// per-shard-key resolver).
4902 ///
4903 /// Prior to this lift the `.shard_key` field was accessed inline at
4904 /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
4905 /// `Sharded` arm's `match &self.placement.shard_key { None => …,
4906 /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
4907 /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
4908 /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
4909 /// — two open-coded field-accesses that expressed no compile-time
4910 /// link back to the typed slot. A future extension of the
4911 /// `:placement :shard-key` axis to a richer author surface — a
4912 /// per-cluster override the operator pins through a future
4913 /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
4914 /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
4915 /// alias table the M4 CR materializer resolves per-CR, a
4916 /// per-Aplicacao dynamic `:shard-key` derivation the future
4917 /// adaptive placement engine computes from `:affinity` weights —
4918 /// would have had to be threaded through both open-coded copies in
4919 /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
4920 /// arm refusal would silently disagree on which extractor
4921 /// expression a given Placement resolves to. Lifting the resolution
4922 /// rule to a typed method on the substrate primitive means every
4923 /// downstream consumer of the Aplicacao's per-`:placement`
4924 /// hash-key surface reaches for exactly one typed dispatch — the
4925 /// resolver's accept-set migrates as a unit on any future axis
4926 /// addition.
4927 ///
4928 /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
4929 /// [`WitContract::destination`] / [`WitContract::world_ref`]
4930 /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
4931 /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
4932 /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
4933 /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
4934 /// typed dispatch on the substrate primitive, thin projections at
4935 /// each consumer" discipline extended onto the per-`:placement`
4936 /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
4937 /// First `Option<&str>`-return accessor on the M3 mesh-slot family
4938 /// — opens the "optional per-slot scalar" projection pattern the
4939 /// sibling per-`:placement` `:affinity`, per-`:politicas`
4940 /// `:rate-limit` future lifts fold on. Named `shard_key()` to
4941 /// match the storage field's name; the accessor's identity name
4942 /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
4943 /// slot's docstring already carries.
4944 #[must_use]
4945 pub fn shard_key(&self) -> Option<&str> {
4946 self.shard_key.as_deref()
4947 }
4948
4949 /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
4950 /// compression-hint scalar accessor every weighting-consumer of the
4951 /// Aplicacao's per-hint routing surface keys off — returns the
4952 /// author-declared `:placement :affinity` byte-string verbatim as
4953 /// an `Option<&str>`, borrowed from the typed slot's own
4954 /// `Option<String>` storage; `None` when the slot is absent (the
4955 /// canonical shape of an Aplicacao that leaves the compression
4956 /// weighting up to the placement engine's cluster-default arm — no
4957 /// author-authored `data-locality` / `low-latency` / etc. hint
4958 /// biases the routing).
4959 ///
4960 /// The `:placement :affinity` slot carries the M3 Adaptive-
4961 /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
4962 /// by [`validate_placement_affinity`] to be a DNS-1123 label
4963 /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
4964 /// K8s-conformant label-selector shape every apiserver-side pod-
4965 /// affinity / node-affinity materializer already gates on
4966 /// admission), and every downstream consumer that reads the hint
4967 /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
4968 /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
4969 /// `placement.affinity` overlay emit path the substrate operator's
4970 /// per-hint weighting-consumer reads, the future M4
4971 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
4972 /// pod-affinity / node-affinity selector resolver).
4973 ///
4974 /// Prior to this lift the `.affinity` field was accessed inline at
4975 /// the sole caixa-core site — the
4976 /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
4977 /// `if let Some(a) = &self.placement.affinity { …
4978 /// validate_placement_affinity(a)? … }` cascade — one open-coded
4979 /// field-access that expressed no compile-time link back to the
4980 /// typed slot. A future extension of the `:placement :affinity`
4981 /// axis to a richer author surface — a per-cluster override the
4982 /// operator pins through a future `:placement :affinity-overrides`
4983 /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
4984 /// tenant hint alias table the M4 CR materializer resolves per-CR,
4985 /// a per-Aplicacao dynamic `:affinity` derivation the future
4986 /// adaptive placement engine computes from `:clusters` topology —
4987 /// would have had to be threaded through the open-coded copy in
4988 /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
4989 /// materializer reader that landed on the axis, or the per-hint
4990 /// value-shape gate and its downstream weighting consumers would
4991 /// silently disagree on which hint a given Placement resolves to.
4992 /// Lifting the resolution rule to a typed method on the substrate
4993 /// primitive means every downstream consumer of the Aplicacao's
4994 /// per-`:placement` compression-hint surface reaches for exactly
4995 /// one typed dispatch — the resolver's accept-set migrates as a
4996 /// unit on any future axis addition.
4997 ///
4998 /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
4999 /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5000 /// optional-scalar axis — same "one typed dispatch on the substrate
5001 /// primitive, thin projections at each consumer" discipline extended
5002 /// onto the per-`:placement` M3-Adaptive-compression-hint
5003 /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5004 /// return accessor on the M3 mesh-slot family; closes the last
5005 /// un-lifted per-`:placement` `Option<String>` axis. Named
5006 /// `affinity()` to match the storage field's name; the accessor's
5007 /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5008 /// vocabulary the slot's docstring already carries.
5009 #[must_use]
5010 pub fn affinity(&self) -> Option<&str> {
5011 self.affinity.as_deref()
5012 }
5013
5014 /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5015 /// strategy scalar accessor every consumer that dispatches on the
5016 /// Aplicacao's per-cluster distribution shape keys off — returns the
5017 /// author-declared `:placement :estrategia` variant verbatim as a
5018 /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5019 /// `PlacementStrategy` storage.
5020 ///
5021 /// The `:placement :estrategia` slot carries the closed-set
5022 /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5023 /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5024 /// `Replicated` — active-active across every named cluster; `Sharded`
5025 /// — Akka-style hash-keyed entity distribution across the cluster pool
5026 /// per §II.4) that every downstream consumer of the Aplicacao's
5027 /// per-cluster fan-out shape keys off. Validated by
5028 /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5029 /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5030 /// matches!(estrategia, Sharded)` — the cross-slot partition the
5031 /// [`Placement::shard_key`] accessor's docstring pins), and every
5032 /// downstream consumer that reads the strategy keys off this scalar
5033 /// (the [`AplicacaoSpec::validate_placement`]
5034 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5035 /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5036 /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5037 /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5038 /// declared-but-inert refusal's
5039 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5040 /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5041 /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5042 /// emit path the substrate operator's per-strategy fan-out reader
5043 /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5044 /// materializer's per-strategy admission-webhook resolver).
5045 ///
5046 /// Prior to this lift the `.estrategia` field was accessed inline at
5047 /// four sites — the [`AplicacaoSpec::validate_placement`]
5048 /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5049 /// `estrategia: self.placement.estrategia`, the same method's
5050 /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5051 /// partition dispatch, the non-`Sharded`-arm
5052 /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5053 /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5054 /// per-Aplicacao strategy print line at
5055 /// `println!("… {} …", spec.placement.estrategia, …)`
5056 /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5057 /// expressed no compile-time link back to the typed slot. A future
5058 /// extension of the `:placement :estrategia` axis to a richer author
5059 /// surface (a per-cluster override the operator pins through a future
5060 /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5061 /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5062 /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5063 /// derivation the future adaptive placement engine computes from
5064 /// `:affinity` + `:clusters` topology) would have had to be threaded
5065 /// through every open-coded copy in lockstep — one consumer reading
5066 /// the raw variant while a peer read the operator-resolved variant
5067 /// would silently split the `PlacementWithoutClusters` /
5068 /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5069 /// partition-dispatch input, a two-consumer split at the validator
5070 /// far from the source `caixa.lisp` with no field naming the
5071 /// strategy-drift root cause. Lifting the resolution rule to a typed
5072 /// method on the substrate primitive means every downstream consumer
5073 /// of the Aplicacao's per-`:placement` distribution-strategy surface
5074 /// reaches for exactly one typed dispatch — the resolver's accept-set
5075 /// migrates as a unit on any future axis addition.
5076 ///
5077 /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5078 /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5079 /// same "one typed dispatch on the substrate primitive, thin
5080 /// projections at each consumer" discipline extended onto the
5081 /// per-`:placement` distribution-strategy `Copy`-composite-enum
5082 /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5083 /// family; first `Copy`-return accessor on the M3 mesh-slot
5084 /// `Placement` type — companion to the sibling per-`:placement`
5085 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5086 /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5087 /// optional-scalar axes, closing the last unlifted per-`:placement`
5088 /// scalar-value axis (the closed-set `PlacementStrategy`
5089 /// distribution-strategy discriminator) so every downstream
5090 /// per-`:placement` reader now routes through a typed dispatch on
5091 /// the substrate primitive. Named `estrategia()` to match the storage
5092 /// field's name; the accessor's identity name maps onto the
5093 /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5094 /// already carries.
5095 #[must_use]
5096 pub fn estrategia(&self) -> PlacementStrategy {
5097 self.estrategia
5098 }
5099
5100 /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5101 /// per-cluster distribution-target slice accessor every consumer that
5102 /// walks the Aplicacao's declared cluster-pool keys off — returns the
5103 /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5104 /// `&[String]` slice-view, borrowed from the typed slot's own
5105 /// `Vec<String>` storage (a zero-copy slice-view over the same
5106 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5107 /// through). Non-optional: the empty slice is the load-bearing
5108 /// pre-validation sentinel every downstream consumer of the paired
5109 /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5110 /// off — every strategy in the closed
5111 /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5112 /// requires a non-empty list (`SingleNode` / `Replicated` use the
5113 /// list as hosting / takeover candidates per Erlang/OTP distributed-
5114 /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5115 /// shard pool per Akka cluster-sharding convention, §II.4), so the
5116 /// `.is_empty()` probe is the shared pre-condition every
5117 /// [`AplicacaoSpec::validate_placement`] arm heads on.
5118 ///
5119 /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5120 /// 1123-label per-cluster distribution-target list — the same
5121 /// set-not-multiset shape the sibling `:membros :caixa` /
5122 /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5123 /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5124 /// pins the shape). Every downstream consumer that fans on the list
5125 /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5126 /// pre-flight `.is_empty()` probe that trips
5127 /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5128 /// per-cluster value-shape + duplicate-detection fan-out loop, the
5129 /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5130 /// that materializes the list verbatim onto every
5131 /// programs.yaml entry the substrate operator's per-cluster
5132 /// `placement.clusters | contains .Values.cluster` filter reads,
5133 /// the `feira app graph` per-Aplicacao cluster print line, the
5134 /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5135 /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5136 /// placement engine's cluster-topology reader).
5137 ///
5138 /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5139 /// inline at three production sites — the
5140 /// [`AplicacaoSpec::validate_placement`] pre-flight
5141 /// `self.placement.clusters.is_empty()` refusal probe, the same
5142 /// method's per-cluster validate loop's
5143 /// `for c in &self.placement.clusters` traversal head, and the
5144 /// `feira app graph` per-Aplicacao print line's
5145 /// `spec.placement.clusters` `{:?}` formatter argument
5146 /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5147 /// that expressed no compile-time link back to the typed slot. A
5148 /// future extension of the `:placement :clusters` axis to a richer
5149 /// author surface (a per-tenant cluster-pool overlay the operator
5150 /// pins through a future `:placement :clusters-overrides` slot the
5151 /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5152 /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5153 /// the future M5 adaptive-placement engine computes from
5154 /// `:affinity` weights + live cluster-topology probes, a promotion
5155 /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5156 /// partition once the substrate operator's cluster-membership
5157 /// reconciler comes into typed scope) would have had to be threaded
5158 /// through all three open-coded copies in lockstep or one consumer
5159 /// would silently disagree with the peers on which cluster-pool a
5160 /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5161 /// reading the raw slot while the peer per-cluster validate loop
5162 /// read an operator-resolved slot would silently split the paired
5163 /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5164 /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5165 /// input from the pre-flight input, a three-consumer split at the
5166 /// validator and formatter far from the source `caixa.lisp` with
5167 /// no field naming the cluster-pool-drift root cause. Lifting the
5168 /// resolution rule to a typed method on the substrate primitive
5169 /// means every downstream consumer of the Aplicacao's
5170 /// per-`:placement` cluster-pool surface reaches for exactly one
5171 /// typed dispatch — the resolver's accept-set migrates as a unit
5172 /// on any future axis addition.
5173 ///
5174 /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5175 /// slot — sibling to the seed M2
5176 /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5177 /// slice-return accessor on the peer per-`:supervisor` static-
5178 /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5179 /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5180 /// primitive, thin projections at each consumer" discipline. The
5181 /// three peer `Vec`-carry axes still unlifted at the time of this
5182 /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5183 /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5184 /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5185 /// [`crate::UpgradeFromEntry::instructions`]
5186 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5187 /// — inherit this accessor's discipline as future compounding runs
5188 /// migrate their consumers onto the shared slice-return shape.
5189 /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5190 /// type, sibling to the two `Option<&str>`-return
5191 /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5192 /// (74ec2d3) accessors and the `Copy`-return
5193 /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5194 /// unlifted per-`:placement` field axis (the `Vec<String>`
5195 /// distribution-target-list carrier) so every downstream
5196 /// per-`:placement` reader now routes through a typed dispatch on
5197 /// the substrate primitive. Named `clusters()` to match the storage
5198 /// field's name verbatim and the tatara-lisp author-surface term
5199 /// (`:clusters`) the field's own docstring already carries; the
5200 /// accessor's identity maps onto the canonical MESH-COMPOSITION
5201 /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5202 /// for. Returns `&[String]` (not `&Vec<String>`) because every
5203 /// downstream consumer of the cluster list treats it as a read-only
5204 /// sequence — the slice-view is the narrowest borrow that supports
5205 /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5206 /// `.len()`) without leaking the backing `Vec`'s
5207 /// grow/push/reserve surface that no consumer of the typed view
5208 /// reaches for (the storage-side `Vec` remains reachable through
5209 /// the `pub clusters` field for the mutation-carrying serde
5210 /// round-trip and per-test fixture-mutation paths).
5211 #[must_use]
5212 pub fn clusters(&self) -> &[String] {
5213 self.clusters.as_slice()
5214 }
5215}
5216
5217impl Default for Placement {
5218 fn default() -> Self {
5219 Self {
5220 estrategia: PlacementStrategy::default(),
5221 clusters: Vec::new(),
5222 affinity: None,
5223 shard_key: None,
5224 }
5225 }
5226}
5227
5228// ── external entry point ─────────────────────────────────────────────
5229
5230/// External entry point — what an outside caller sees. Renders to a
5231/// Gateway / Ingress + a route to the named member Servico.
5232#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5233#[serde(rename_all = "camelCase")]
5234pub struct Entrada {
5235 /// Public hostname (e.g. `"checkout.quero.cloud"`).
5236 pub host: String,
5237
5238 /// Member Servico the gateway routes to. Must be in `:membros`.
5239 pub para: String,
5240
5241 /// Optional path filter — if set, only matching paths route to
5242 /// this Aplicacao (the rest fall through to other route rules).
5243 #[serde(default)]
5244 pub paths: Vec<String>,
5245
5246 /// Default port on the destination Servico (the trigger.service.port).
5247 #[serde(default = "default_port")]
5248 pub port: u16,
5249}
5250
5251impl Entrada {
5252 /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5253 /// every HTTPRoute-aware renderer keys off — returns the author-
5254 /// declared `:entrada :paths` list verbatim when non-empty, and the
5255 /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5256 /// all fallback otherwise (so an Aplicacao author who declares an
5257 /// external `:entrada` block but no per-path rule surface still
5258 /// gets a route whose sole `HTTPPathMatch` matches every incoming
5259 /// request under the paired
5260 /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5261 ///
5262 /// Prior to this lift the "if `:entrada :paths` is empty use the
5263 /// substrate catch-all; else return each declared path verbatim"
5264 /// cascade lived inline at
5265 /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5266 /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5267 /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5268 /// substrate ships today, with no typed method on the substrate
5269 /// primitive that named the rule. A future path-resolution axis
5270 /// addition — a per-cluster `:entrada :default-path` override the
5271 /// operator pins through a future `:placement`-scoped slot, an
5272 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5273 /// admission-webhook floor that materializes the catch-all before
5274 /// the CR lands, a future per-`:entrada :paths` overlay from a
5275 /// per-cluster policy the future `feira app deploy` pipeline
5276 /// consumes — would have to be threaded through every renderer's
5277 /// inline copy of the cascade in lockstep or one consumer would
5278 /// silently disagree with the peers on which path list a given
5279 /// `:entrada` block resolves to. Lifting the rule to a typed
5280 /// method on the substrate primitive means every downstream
5281 /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5282 /// per-cluster overlay resolver, every future per-Aplicacao
5283 /// snapshot renderer) reaches for exactly one typed dispatch —
5284 /// the resolver's accept-set moves as a unit on any future axis
5285 /// addition.
5286 ///
5287 /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5288 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5289 /// per-`:entrada` scalar-value axes — extends the "one typed
5290 /// dispatch on the substrate primitive, thin projections at each
5291 /// consumer" discipline onto the per-`:entrada` path-list
5292 /// resolution axis every HTTPRoute-aware renderer consumes. Same
5293 /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5294 /// sibling `:politicas` primitive — one typed method on the
5295 /// substrate primitive that names the cascade every renderer
5296 /// otherwise re-inlines.
5297 #[must_use]
5298 pub fn resolved_paths(&self) -> Vec<&str> {
5299 // Route the internal cascade-head + per-entry projection reads
5300 // through the lifted [`Self::paths`] slice accessor rather than
5301 // the raw `self.paths` field access — the substrate-primitive
5302 // per-`:entrada` path-list resolver's two internal reads now
5303 // key off the canonical raw-slot surface every downstream
5304 // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5305 // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5306 // entrada summary line's `{:?}` Debug print) routes through, so
5307 // any future rebrand on the typed slot's raw-slot reader lands
5308 // at exactly one place. Same two-consumer coherence discipline
5309 // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5310 // the peer M3 mesh-slot `Vec<String>`-carry axis.
5311 if self.paths().is_empty() {
5312 vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5313 } else {
5314 self.paths().iter().map(String::as_str).collect()
5315 }
5316 }
5317
5318 /// Substrate-canonical per-`:entrada` DNS-hostname singular
5319 /// accessor every Gateway-API `Listener.hostname` reader keys off
5320 /// — returns the author-declared `:entrada :host` byte-string
5321 /// verbatim as a `&str`, borrowed from the typed slot's own
5322 /// [`String`] storage.
5323 ///
5324 /// Named the "singular" half of the DNS-hostname resolver pair on
5325 /// the substrate primitive: the parent-Gateway per-listener
5326 /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
5327 /// (`Listener.hostname: Option<PreciseHostname>` — at most one
5328 /// hostname per listener), and this accessor is the typed dispatch
5329 /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
5330 /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
5331 /// the per-HTTPRoute `spec.hostnames[]` list axis the same
5332 /// per-Aplicacao ingress-hostname surface projects onto.
5333 ///
5334 /// Prior to this lift the `entrada.host.clone()` byte-string was
5335 /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
5336 /// per-listener singular `hostname:` axis
5337 /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
5338 /// per-HTTPRoute plural `spec.hostnames[]` axis
5339 /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
5340 /// consumers read the same `entrada.host` field but the two-site
5341 /// duplication expressed no compile-time contract that the singular
5342 /// Gateway-listener filter and the plural `HTTPRoute` filter list
5343 /// stay in lockstep on future extensions of the `:entrada` slot to
5344 /// a multi-hostname author surface (an `:entrada :alt-hosts` list
5345 /// overlay, a per-cluster SNI fan-out the operator pins through a
5346 /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
5347 /// Aplicacao` CR materializer's per-listener virtual-host filter
5348 /// admission-webhook overlay). Any such extension would have to be
5349 /// threaded through every renderer's inline copy of the resolution
5350 /// in lockstep or the Gateway listener's `hostname:` filter would
5351 /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
5352 /// — a Gateway-API-conformance divergence whose apply-time symptom
5353 /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
5354 /// `NoMatchingParent` — the API server rejects the route because
5355 /// its `hostnames[]` filter doesn't intersect the parent listener's
5356 /// `hostname` filter) is far from the source `caixa.lisp` and never
5357 /// surfaces in the emitted YAML. Lifting the singular and plural
5358 /// resolvers to typed methods on the substrate primitive means
5359 /// every consumer of the Aplicacao's ingress-hostname surface
5360 /// reaches for exactly one typed dispatch, and the pair-invariant
5361 /// `hostnames() == vec![hostname()]` pinned by the sibling
5362 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
5363 /// keeps the two axes in lockstep by construction.
5364 ///
5365 /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
5366 /// (1449891) path-list resolver on the per-HTTPRoute per-rule
5367 /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
5368 /// the substrate primitive, thin projections at each consumer"
5369 /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5370 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5371 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5372 /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
5373 /// `:entrada` scalar-value + list-value axes.
5374 #[must_use]
5375 pub fn hostname(&self) -> &str {
5376 self.host.as_str()
5377 }
5378
5379 /// Substrate-canonical per-`:entrada` DNS-hostname plural
5380 /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
5381 /// keys off — returns the singleton `[hostname()]` list under
5382 /// today's single-hostname-per-Aplicacao author surface, and the
5383 /// authoritative multi-hostname list under a future
5384 /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
5385 ///
5386 /// Plural half of the DNS-hostname resolver pair — see the
5387 /// companion [`Entrada::hostname`] docstring for the two-consumer
5388 /// lift + pair-invariant discipline (`hostnames() ==
5389 /// vec![hostname()]`, pinned load-bearing by the sibling
5390 /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
5391 /// test).
5392 ///
5393 /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
5394 /// per-`:entrada` plural-list resolver on the per-HTTPRoute
5395 /// per-rule path-list axis — same `Vec<&str>` shape, same
5396 /// substrate-primitive-owns-the-resolver discipline extended to
5397 /// the per-HTTPRoute virtual-host filter-list axis.
5398 #[must_use]
5399 pub fn hostnames(&self) -> Vec<&str> {
5400 vec![self.hostname()]
5401 }
5402
5403 /// Substrate-canonical per-`:entrada` destination-Servico scalar
5404 /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
5405 /// the author-declared `:entrada :para` byte-string verbatim as a
5406 /// `&str`, borrowed from the typed slot's own [`String`] storage.
5407 ///
5408 /// The `:entrada :para` slot names the single member Servico the
5409 /// external Gateway routes to (validated by
5410 /// [`AplicacaoSpec::validate`] to be a
5411 /// [`Membro::caixa`] the Aplicacao declares — a stray
5412 /// `:para` that doesn't name a member is
5413 /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
5414 /// backend-attachment miss at cluster-apply time). Under today's
5415 /// single-destination author surface `:entrada :para` is the ingress
5416 /// apex Servico's canonical identity; under a hypothetical
5417 /// future multi-backend author surface (a `:entrada
5418 /// :split :backends` weighted-fan-out overlay for canary /
5419 /// blue-green traffic-split rollouts, per-path override for
5420 /// path-based per-Servico routing beyond the single-apex model,
5421 /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5422 /// per-CR admission-webhook that promotes the scalar to a
5423 /// weighted list) this accessor is the substrate primitive's typed
5424 /// dispatch every downstream `HTTPRoute`-aware consumer routes
5425 /// through, so the resolution shape migrates as a unit on one
5426 /// caixa-core edit rather than a coordinated rewrite across every
5427 /// renderer's inline field-access.
5428 ///
5429 /// Prior to this lift the `entrada.para` byte-string was accessed
5430 /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
5431 /// `metadata.name` composer's per-destination discriminator arg
5432 /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
5433 /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
5434 /// per-HTTPRoute per-rule `backendRefs[0].name` axis
5435 /// (`entrada.para.clone()`,
5436 /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
5437 /// consumers read the same `entrada.para` field but the two-site
5438 /// duplication expressed no compile-time contract that the HTTPRoute
5439 /// name-discriminator and the per-rule backend name stay in
5440 /// lockstep on future extensions of the `:entrada` slot to a
5441 /// multi-destination author surface. Any such extension would have
5442 /// to be threaded through every renderer's inline copy of the
5443 /// destination projection in lockstep or the HTTPRoute
5444 /// `metadata.name` would silently reference a different destination
5445 /// than its own `backendRefs[]` — an operator-side
5446 /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
5447 /// grep-by-name lookup would land on a route whose `backendRefs[]`
5448 /// silently point at a peer Servico, dropping every external
5449 /// `:entrada` flow at the gateway with the destination-drift root
5450 /// cause invisible in the emitted YAML.
5451 ///
5452 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
5453 /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
5454 /// the per-listener singular / per-HTTPRoute plural filter axes and
5455 /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
5456 /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
5457 /// typed dispatch on the substrate primitive, thin projections at
5458 /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5459 /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5460 /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5461 /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
5462 /// sibling per-`:entrada` scalar-value + list-value axes — this
5463 /// accessor closes the last unlifted per-`:entrada` scalar axis
5464 /// (the destination-Servico byte-string) so every downstream
5465 /// per-`:entrada` reader now routes through a typed dispatch on
5466 /// the substrate primitive.
5467 #[must_use]
5468 pub fn destination(&self) -> &str {
5469 self.para.as_str()
5470 }
5471
5472 /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
5473 /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
5474 /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
5475 /// reader keys off — returns the author-declared `:entrada :port`
5476 /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
5477 /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
5478 /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
5479 /// [`AplicacaoError::EntradaPortZero`], not a silent
5480 /// admission-webhook rejection at cluster-apply time).
5481 ///
5482 /// The `:entrada :port` slot carries the destination Servico's
5483 /// canonical in-cluster L4 listener port (`trigger.service.port` on
5484 /// the `pleme-computeunit` library chart), and every downstream
5485 /// consumer that reads the port keys off this scalar (the
5486 /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
5487 /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
5488 /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
5489 /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5490 /// CR materializer's per-Aplicacao gateway port resolver).
5491 ///
5492 /// Prior to this lift the `.port` field was accessed inline at two
5493 /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
5494 /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
5495 /// the [`AplicacaoSpec::port_for_destination`] resolver's
5496 /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
5497 /// open-coded field-accesses that expressed no compile-time link
5498 /// back to the typed slot. A future extension of the `:entrada :port`
5499 /// axis to a richer author surface — a per-cluster override the
5500 /// operator pins through a future `:placement :default-port` slot the
5501 /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
5502 /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
5503 /// heterogeneous listener ports, an M4
5504 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5505 /// admission-webhook floor that promotes the scalar to a
5506 /// per-destination map — would have had to be threaded through both
5507 /// open-coded copies in lockstep or the structural-floor validator
5508 /// and the [`AplicacaoSpec::port_for_destination`] resolver would
5509 /// silently disagree on which port a given [`Entrada`] resolves to.
5510 /// Lifting the resolution rule to a typed method on the substrate
5511 /// primitive means every downstream consumer of the Aplicacao's
5512 /// per-`:entrada` L4-port surface reaches for exactly one typed
5513 /// dispatch — the resolver's accept-set migrates as a unit on any
5514 /// future axis addition.
5515 ///
5516 /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
5517 /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
5518 /// accessors on the per-`:entrada` scalar-value axis — same "one
5519 /// typed dispatch on the substrate primitive, thin projections at
5520 /// each consumer" discipline extended onto the per-`:entrada`
5521 /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
5522 /// the M3 mesh-slot `Entrada` type — closes the last unlifted
5523 /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
5524 /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
5525 /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
5526 /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
5527 /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
5528 /// storage field's name; the accessor's identity name maps onto the
5529 /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
5530 /// already carries.
5531 #[must_use]
5532 pub fn port(&self) -> u16 {
5533 self.port
5534 }
5535
5536 /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
5537 /// slice accessor every HTTPRoute-aware renderer keys off when it
5538 /// wants the raw author-declared path-list (not the fallback-
5539 /// applied projection [`Self::resolved_paths`] returns) — returns
5540 /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
5541 /// borrowed from the typed slot's own [`Vec<String>`] storage.
5542 ///
5543 /// Named the "raw slot" half of the per-`:entrada` path-list resolver
5544 /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
5545 /// (1449891) closes the fallback-applying arm every per-Aplicacao
5546 /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
5547 /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
5548 /// catch-all; non-empty slot → per-entry verbatim projection); this
5549 /// accessor closes the raw-slot arm every consumer that must see the
5550 /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
5551 /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
5552 /// not `Err(EntradaPathEmpty)`, so it cannot route through the
5553 /// fallback-applying sibling; the `feira app graph` per-Aplicacao
5554 /// external-gateway summary line's `{:?}` Debug print — which must
5555 /// name the author's declaration, not the substrate's fallback, so
5556 /// an author reading their graph output can grep their caixa.lisp
5557 /// for the exact list they authored) routes through.
5558 ///
5559 /// Prior to this lift the `.paths` field was accessed inline at four
5560 /// production sites: the two internal reads in [`Self::resolved_paths`]
5561 /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
5562 /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
5563 /// value-shape gate's `for p in &e.paths` traversal head, and the
5564 /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
5565 /// Debug print — four open-coded field-accesses that expressed no
5566 /// compile-time link back to the typed slot. A future extension of
5567 /// the `:entrada :paths` axis to a richer author surface — a
5568 /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
5569 /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
5570 /// spec supports through `matches[].method`), a per-path per-header
5571 /// filter overlay (`matches[].headers[]`), a per-cluster override
5572 /// the operator pins through a future `:placement :path-overlay`
5573 /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5574 /// per-CR admission-webhook that normalized the list at admission
5575 /// time — would have had to be threaded through every open-coded
5576 /// copy in lockstep or the validator's per-entry gate would silently
5577 /// disagree with the renderer's per-entry emit on which list a given
5578 /// `:entrada` block resolves to. Lifting the resolution to a typed
5579 /// method on the substrate primitive means every downstream consumer
5580 /// of the Aplicacao's per-`:entrada` path-list surface reaches for
5581 /// exactly one typed dispatch — the resolver's accept-set migrates
5582 /// as a unit on any future axis addition.
5583 ///
5584 /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
5585 /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
5586 /// carry axis — same "one typed dispatch on the substrate primitive,
5587 /// thin projections at each consumer" discipline extended onto the
5588 /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
5589 /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
5590 /// carrier) so every downstream per-`:entrada` reader now routes
5591 /// through a typed dispatch on the substrate primitive. Returns
5592 /// `&[String]` (not `&Vec<String>`) because every downstream consumer
5593 /// treats the list as a read-only sequence — the slice-view is the
5594 /// narrowest borrow that supports every present + roadmapped consumer
5595 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
5596 /// `Vec`'s grow/push/reserve surface that no consumer of the typed
5597 /// view reaches for (the storage-side `Vec` remains reachable through
5598 /// the `pub paths` field for the mutation-carrying serde round-trip
5599 /// and per-test fixture-mutation paths).
5600 #[must_use]
5601 pub fn paths(&self) -> &[String] {
5602 self.paths.as_slice()
5603 }
5604}
5605
5606/// Canonical default L4 port every typed Servico exposes on its
5607/// in-cluster K8s Service (the `trigger.service.port` axis the
5608/// `pleme-computeunit` library chart emits, the `:entrada :port` author
5609/// surface defaults to when the author omits the slot, and the
5610/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
5611/// `:entrada` block matches the per-`:contratos` destination Servico).
5612/// The single source of truth all three typed-port consumers reach for:
5613///
5614/// - [`Entrada::port`]'s serde default (via the
5615/// [`default_port`] helper this constant feeds); the author surface
5616/// `(:entrada (:host … :para …))` without an explicit `:port` slot
5617/// reads back as a typed [`Entrada`] carrying this exact value;
5618/// - the
5619/// [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
5620/// emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
5621/// fallback, fired when the typed `:entrada` block doesn't name
5622/// the per-`:contratos` destination Servico — the typed
5623/// `:contratos` graph carries no per-destination port axis (the
5624/// destination port is the destination Servico's
5625/// `lareira-<nome>` chart's `trigger.service.port`, which the
5626/// Aplicacao-level renderer has no visibility into without a
5627/// resolver round-trip), so the renderer falls back to the
5628/// substrate's canonical Servico-port assumption — by
5629/// construction the same value the destination's own
5630/// `pleme-computeunit` chart emits, the same value the
5631/// destination's own typed `:entrada :port` slot defaults to;
5632/// - every future per-Servico renderer the absorption-roadmap
5633/// acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5634/// CR materializer's per-edge port resolver, the future
5635/// per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
5636/// emitter's per-route bucket key, the future caixa-otel
5637/// collector-pipeline emitter's per-Servico scrape port).
5638///
5639/// Until this lift landed the value `8080` lived at two production-code
5640/// call-sites: the [`default_port`] helper at
5641/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
5642/// and the `.unwrap_or(8080)` literal at
5643/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
5644/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
5645/// resolver). A future Servico-port rebrand — the substrate moving the
5646/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
5647/// gateway grows direct `:80` listeners, to `8443` once the substrate
5648/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
5649/// override the operator pins through a future
5650/// `:placement :default-port` slot — without a coordinated edit on
5651/// both sides would silently emit Servicos listening on one port and
5652/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
5653/// The CNP's apply-time symptom (the policy is admitted but every L4
5654/// flow on the destination Servico's actual port silently drops because
5655/// it doesn't match the whitelisted port) is far from the rebrand
5656/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
5657/// in hubble traces, not in `kubectl describe`. Lifting the literal to
5658/// a shared constant closes the drift footgun structurally — both
5659/// consumers read from the same `u16`, so any rebrand reaches both
5660/// sites by construction.
5661///
5662/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
5663/// per-renderer canonical-K8s-axis constant — the namespace string
5664/// and the canonical Servico port both lived as duplicated literals
5665/// across caixa-core / caixa-mesh / caixa-flux before their respective
5666/// lifts. Same "the typed constant lives in one place" discipline the
5667/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
5668/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
5669/// shared-string axes.
5670///
5671/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
5672pub const DEFAULT_SERVICO_PORT: u16 = 8080;
5673
5674/// Structural floor for the typed `:entrada :port` axis — every
5675/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
5676/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
5677///
5678/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
5679/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
5680/// interprets as "let the kernel pick a free port at bind time", not a
5681/// well-defined destination the substrate's per-`:entrada` Gateway API
5682/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
5683/// carrying `port: 0` degenerates to a nominal-only routing target: the
5684/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
5685/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
5686/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
5687/// at build time rather than at `kubectl apply` time), and the
5688/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
5689/// (caixa-mesh/src/lib.rs:2657 through
5690/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
5691/// [`Entrada::port`] typed value — silently emits a policy whose
5692/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
5693/// actual listener, dropping every L4 flow at the eBPF data plane far
5694/// from the source caixa.lisp with no field naming the port-zero-drift
5695/// root cause.
5696///
5697/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
5698/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
5699/// on the top edge (unlike the peer capped-`u32` `:politicas` /
5700/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
5701/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
5702/// well below `u32::MAX` and therefore need explicit typed caps).
5703///
5704/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
5705/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
5706/// scalar every `(:entrada (:host … :para …))` slot without an explicit
5707/// `:port` inherits through the serde default hook; this constant names
5708/// the accept-set floor every declared port must satisfy. The pair is
5709/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
5710/// substrate's default must satisfy its own accept-set floor by
5711/// construction) — a future rebrand that accidentally moved
5712/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
5713/// negative-cast typo, a per-cluster override the operator pins through
5714/// a future `:placement :default-port` slot that lands out-of-range)
5715/// would silently invalidate the serde-default emission at every
5716/// author-side `(:entrada (:host … :para …))` slot — the compile-time
5717/// invariant pin
5718/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
5719/// closes the drift footgun at caixa-core build time.
5720///
5721/// Lifted as a typed `pub const` (rather than an inline `0` literal at
5722/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
5723/// has exactly one source of truth — the future M4
5724/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
5725/// gateway resolver, the future per-Servico
5726/// `computeunit.trigger.service.port` renderer's per-CR port-value
5727/// validator, and every downstream test-fixture navigator asserting
5728/// the accept-set floor all read from one place. Same shape every
5729/// other typed bracket-floor / bracket-ceiling in this crate carries
5730/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
5731/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
5732/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
5733/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
5734/// [`POLICY_RATE_LIMIT_MAX`]).
5735pub const SERVICO_PORT_MIN: u16 = 1;
5736
5737const fn default_port() -> u16 {
5738 DEFAULT_SERVICO_PORT
5739}
5740
5741// ── the typed view ───────────────────────────────────────────────────
5742
5743/// Typed composition view of the flat Aplicacao slots on
5744/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
5745/// validation + downstream renderer consumption.
5746#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5747#[serde(rename_all = "camelCase")]
5748pub struct AplicacaoSpec {
5749 pub membros: Vec<Membro>,
5750 pub contratos: Vec<WitContract>,
5751 pub politicas: MeshPolicy,
5752 pub placement: Placement,
5753 pub entrada: Option<Entrada>,
5754}
5755
5756impl AplicacaoSpec {
5757 /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
5758 /// per-Aplicacao member-list slice-return accessor every
5759 /// per-Aplicacao member-list reader keys off — returns the author-
5760 /// declared `:membros` list verbatim as a `&[Membro]` slice-view
5761 /// over the same backing buffer the raw `self.membros.as_slice()`
5762 /// field access borrows from.
5763 ///
5764 /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
5765 /// member list — the load-bearing identity of the application graph
5766 /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
5767 /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
5768 /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
5769 /// accessor) with a `:versao` semver-requirement string (through
5770 /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
5771 /// and every downstream consumer that fans on the member-set keys
5772 /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
5773 /// membership-lookup `HashSet<&str>` seed's collect input, the
5774 /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
5775 /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
5776 /// per-member DNS-1123 / semver-requirement / duplicate-detection
5777 /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
5778 /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
5779 /// programs.yaml per-`:membros` fan-out emitter's per-entry
5780 /// mapping-composition loop, the `feira app graph` per-Aplicacao
5781 /// member-count print line and per-member tree traversal,
5782 /// every future wasm-operator (M4) per-Aplicacao CR materializer's
5783 /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
5784 /// placement engine's per-member weight-topology reader).
5785 ///
5786 /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
5787 /// inline at six production sites — the [`AplicacaoSpec::validate`]
5788 /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
5789 /// [`AplicacaoSpec::validate_membros`]'s pre-flight
5790 /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
5791 /// probe, the same method's per-member `for m in &self.membros`
5792 /// validate-loop traversal head, the
5793 /// [`AplicacaoSpec::detect_sync_cycles`]'s
5794 /// `for m in &self.membros` adjacency-list seed, the
5795 /// [`caixa_mesh::programs_for_aplicacao`] emitter's
5796 /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
5797 /// paired with the peer `for m in &spec.membros` per-entry fan-out
5798 /// loop, and the `feira app graph` per-Aplicacao print line's
5799 /// `spec.membros.len()` count formatter argument paired with the
5800 /// peer `for m in &spec.membros` per-member tree traversal — six
5801 /// open-coded field-accesses that expressed no compile-time link
5802 /// back to the typed slot. A future extension of the `:membros`
5803 /// axis to a richer author surface (a per-cluster member-set
5804 /// overlay the operator pins through a future
5805 /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
5806 /// roadmap acknowledges, a per-tenant member-alias table the M4
5807 /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
5808 /// CR at admission time, a per-Aplicacao dynamic member-set
5809 /// derivation the future adaptive-placement engine computes from
5810 /// weighted membership topology, a promotion of the plain
5811 /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
5812 /// Orleans-style virtual-actor dynamic-membership comes into typed
5813 /// scope) would have had to be threaded through all six open-coded
5814 /// copies in lockstep or one consumer would silently disagree with
5815 /// the peers on which member-set a given Aplicacao resolves to —
5816 /// the `HashSet<&str>` name-set seed reading the raw slot while
5817 /// the peer `.is_empty()` refusal probe read an operator-resolved
5818 /// slot would silently split the `:contratos` membership-lookup
5819 /// input from the pre-flight-refusal input, a six-consumer split
5820 /// at the validator + programs.yaml emitter + graph printer far
5821 /// from the source `caixa.lisp` with no field naming the member-
5822 /// set-drift root cause. Lifting the resolution rule to a typed
5823 /// method on the substrate primitive means every downstream
5824 /// consumer of the Aplicacao's per-`:membros` member-list surface
5825 /// reaches for exactly one typed dispatch — the resolver's accept-
5826 /// set migrates as a unit on any future axis addition.
5827 ///
5828 /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
5829 /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5830 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5831 /// static-child-list `Vec`-carry axis, and to the M3
5832 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5833 /// on the peer per-`:placement` distribution-target-list `Vec`-
5834 /// carry axis. Same "one typed dispatch on the substrate primitive,
5835 /// thin projections at each consumer" discipline. The two peer
5836 /// `Vec`-carry axes still unlifted at the time of this lift —
5837 /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
5838 /// WIT-typed edge list) and
5839 /// [`crate::UpgradeFromEntry::instructions`]
5840 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5841 /// — inherit this accessor's discipline as future compounding runs
5842 /// migrate their consumers onto the shared slice-return shape.
5843 /// First `&[T]`-return accessor on the top-level M3 mesh-slot
5844 /// `AplicacaoSpec` type itself, extending the discipline beyond
5845 /// the inner per-slot types ([`crate::Placement`],
5846 /// [`crate::SupervisorSpec`]) onto the outermost typed composition
5847 /// view every renderer consumes. Named `membros()` to match the
5848 /// storage field's name verbatim and the tatara-lisp author-
5849 /// surface term (`:membros`) the field's own docstring already
5850 /// carries; the accessor's identity maps onto the canonical
5851 /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
5852 /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
5853 /// every downstream consumer of the member list treats it as a
5854 /// read-only sequence — the slice-view is the narrowest borrow
5855 /// that supports every present + roadmapped consumer
5856 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5857 /// backing `Vec`'s grow/push/reserve surface that no consumer of
5858 /// the typed view reaches for (the storage-side `Vec` remains
5859 /// reachable through the `pub membros` field for the mutation-
5860 /// carrying serde round-trip and per-test fixture-mutation paths).
5861 #[must_use]
5862 pub fn membros(&self) -> &[Membro] {
5863 self.membros.as_slice()
5864 }
5865
5866 /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
5867 /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
5868 /// accessor every per-Aplicacao contract-list reader keys off —
5869 /// returns the author-declared `:contratos` list verbatim as a
5870 /// `&[WitContract]` slice-view over the same backing buffer the raw
5871 /// `self.contratos.as_slice()` field access borrows from.
5872 ///
5873 /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
5874 /// WIT-typed edge list — the load-bearing set of directed edges
5875 /// on the application graph whose nodes are the `:membros` entries
5876 /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
5877 /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
5878 /// six-tuple is the edge identity every downstream duplicate gate
5879 /// keys off). Every per-`:contratos` entry pairs a `:de` source-
5880 /// Servico caller name + a `:para` destination-Servico callee name
5881 /// (through the lifted [`WitContract::source`] +
5882 /// [`WitContract::destination`] (7f0fd43) accessor pair on the
5883 /// caller/callee-Servico axis) with a `:wit` world-reference
5884 /// (through the lifted [`WitContract::world_ref`] (0804823)
5885 /// accessor) and the target-shape-appropriate payload-carrier
5886 /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
5887 /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
5888 /// (ed22b66) accessor on the per-target-shape payload-carrier
5889 /// axis). Every downstream consumer that fans on the edge-set
5890 /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
5891 /// name-set / self-edge / target-shape / dedup fan-out loop, the
5892 /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
5893 /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
5894 /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
5895 /// grouping loop, the `feira app graph` per-Aplicacao contract-
5896 /// count print line and per-contract tree traversal, every future
5897 /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
5898 /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
5899 /// mesh-policy overlay resolver's per-contract typed-edge weight
5900 /// reader).
5901 ///
5902 /// Prior to this lift the `.contratos` `Vec<WitContract>` was
5903 /// accessed inline at four production sites — the
5904 /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
5905 /// per-edge validate-loop traversal head (which drives every
5906 /// per-edge name-set membership lookup, self-edge check,
5907 /// target-shape dispatch, and dedup `HashSet` insert), the
5908 /// [`AplicacaoSpec::detect_sync_cycles`]'s
5909 /// `for c in &self.contratos` adjacency-list seed head (which
5910 /// drives every per-edge sync-vs-pub-sub partition and per-edge
5911 /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
5912 /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
5913 /// `BTreeMap` grouping loop head (which drives every per-CNP
5914 /// fan-out emit), and the `feira app graph` per-Aplicacao print
5915 /// line's `spec.contratos.len()` count formatter argument paired
5916 /// with the peer `for c in &spec.contratos` per-contract tree
5917 /// traversal — four open-coded field-accesses that expressed no
5918 /// compile-time link back to the typed slot. A future extension
5919 /// of the `:contratos` axis to a richer author surface (a
5920 /// per-cluster contract overlay the operator pins through a
5921 /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
5922 /// federation roadmap acknowledges, a per-tenant edge-policy
5923 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5924 /// materializer resolves per-CR at admission time, a per-edge
5925 /// weight scalar the future adaptive-placement engine reads to
5926 /// bias sync-subgraph routing, a promotion of the plain
5927 /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
5928 /// once virtual-actor-style dynamic-edge composition comes into
5929 /// typed scope) would have had to be threaded through all four
5930 /// open-coded copies in lockstep or one consumer would silently
5931 /// disagree with the peers on which edge-set a given Aplicacao
5932 /// resolves to — the validator's per-edge dedup `HashSet` seed
5933 /// reading the raw slot while the peer sync-cycle adjacency-list
5934 /// seed read an operator-resolved slot would silently split the
5935 /// build-time edge-set gate from the runtime deadlock-detection
5936 /// gate, a four-consumer split at the validator, the cycle
5937 /// detector, the CNP emitter, and the graph printer far from
5938 /// the source `caixa.lisp` with no field naming the edge-set-
5939 /// drift root cause. Lifting the resolution rule to a typed method on the
5940 /// substrate primitive means every downstream consumer of the
5941 /// Aplicacao's per-`:contratos` edge-list surface reaches for
5942 /// exactly one typed dispatch — the resolver's accept-set
5943 /// migrates as a unit on any future axis addition.
5944 ///
5945 /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
5946 /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
5947 /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
5948 /// static-child-list `Vec`-carry axis, to the M3
5949 /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
5950 /// on the peer per-`:placement` distribution-target-list `Vec`-
5951 /// carry axis, and to the immediately-adjacent sibling M3
5952 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
5953 /// the peer per-`:membros` node-list `Vec`-carry axis — the
5954 /// per-`:contratos` edge-list accessor is the natural pair of
5955 /// the per-`:membros` node-list accessor (graph edges over graph
5956 /// nodes; every graph-shaped consumer reads both). Same "one
5957 /// typed dispatch on the substrate primitive, thin projections
5958 /// at each consumer" discipline. The last remaining `Vec`-carry
5959 /// axis still unlifted at the time of this lift —
5960 /// [`crate::UpgradeFromEntry::instructions`]
5961 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
5962 /// list) — inherits this accessor's discipline as future
5963 /// compounding runs migrate its consumers onto the shared slice-
5964 /// return shape. Second `&[T]`-return accessor on the top-level
5965 /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
5966 /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
5967 /// `:contratos` are the two `Vec` fields on the outer typed
5968 /// composition view — `:politicas`, `:placement`, `:entrada` are
5969 /// scalar/option-shaped and already route through their per-slot
5970 /// accessor families). Named `contratos()` to match the storage
5971 /// field's name verbatim and the tatara-lisp author-surface term
5972 /// (`:contratos`) the field's own docstring already carries; the
5973 /// accessor's identity maps onto the canonical MESH-COMPOSITION
5974 /// §III.1 vocabulary the slot's docstring already reaches for.
5975 /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
5976 /// every downstream consumer of the contract list treats it as a
5977 /// read-only sequence — the slice-view is the narrowest borrow
5978 /// that supports every present + roadmapped consumer
5979 /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
5980 /// backing `Vec`'s grow/push/reserve surface that no consumer of
5981 /// the typed view reaches for (the storage-side `Vec` remains
5982 /// reachable through the `pub contratos` field for the mutation-
5983 /// carrying serde round-trip and per-test fixture-mutation paths).
5984 #[must_use]
5985 pub fn contratos(&self) -> &[WitContract] {
5986 self.contratos.as_slice()
5987 }
5988
5989 /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
5990 /// per-Aplicacao mesh-policy composite-reference accessor every
5991 /// per-Aplicacao policy-block reader keys off — returns the author-
5992 /// declared `:politicas` composite verbatim as a `&MeshPolicy`
5993 /// reference over the same backing storage the raw `&self.politicas`
5994 /// field access borrows from.
5995 ///
5996 /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
5997 /// mesh-policy composite — the load-bearing container of every
5998 /// mesh-level operational-policy axis every downstream mesh-artifact
5999 /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6000 /// mesh-policy overlay is the single typed surface a
6001 /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6002 /// from). Every per-`:politicas` axis threads through a lifted
6003 /// per-slot accessor on the [`MeshPolicy`] type: the
6004 /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6005 /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6006 /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6007 /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6008 /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6009 /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6010 /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6011 /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6012 /// accessor. Every downstream consumer that reaches for a policy
6013 /// axis first passes through this outer accessor onto the composite
6014 /// and then dispatches onto the per-axis accessor — the two-level
6015 /// dispatch means every per-`:politicas` reader now routes through
6016 /// a typed dispatch on the substrate primitive at both altitudes.
6017 ///
6018 /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6019 /// accessed inline at four production sites — the
6020 /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6021 /// &self.politicas;` traversal seed (which drives every per-axis
6022 /// zero-floor + upper-cap + canonical-form bracket dispatch through
6023 /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6024 /// `p.rate_limit()` on the axis-level lifted accessors), the
6025 /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6026 /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6027 /// chain (which drives every per-`(:de, :para)` CNP
6028 /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6029 /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6030 /// timeout + retry overlay emitter's paired
6031 /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6032 /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6033 /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6034 /// open-coded outer-field accesses that expressed no compile-time
6035 /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6036 /// future extension of the `:politicas` outer axis to a richer
6037 /// author surface (a per-cluster policy overlay the operator pins
6038 /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6039 /// §V federation roadmap acknowledges, a per-tenant policy-alias
6040 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6041 /// resolves per-CR at admission time, a per-Aplicacao dynamic
6042 /// policy-composite derivation the future adaptive-placement engine
6043 /// computes from a per-cluster load-topology reader, a promotion of
6044 /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6045 /// partition once virtual-actor-style dynamic-mesh-policy
6046 /// composition comes into typed scope) would have had to be threaded
6047 /// through all four open-coded copies in lockstep or one consumer
6048 /// would silently disagree with the peers on which mesh-policy
6049 /// composite a given Aplicacao resolves to — the validator's
6050 /// per-axis bracket-dispatch seed reading the raw slot while the
6051 /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6052 /// would silently split the build-time policy-shape gate from the
6053 /// runtime CNP-emission gate, a four-consumer split at the
6054 /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6055 /// the source `caixa.lisp` with no field naming the policy-drift
6056 /// root cause. Lifting the resolution rule to a typed method on the
6057 /// substrate primitive means every downstream consumer of the
6058 /// Aplicacao's per-`:politicas` mesh-policy composite surface
6059 /// reaches for exactly one typed dispatch — the resolver's accept-
6060 /// set migrates as a unit on any future axis addition.
6061 ///
6062 /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6063 /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6064 /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6065 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6066 /// close the two `Vec`-carry axes on the outer typed composition
6067 /// view; the outer `:politicas` composite-reference axis is the
6068 /// natural pair to the paired outer `Vec`-carry accessors on the
6069 /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6070 /// emitter reads all four axes as one unit (graph nodes + graph
6071 /// edges + mesh policy + placement pool). Peer to the same
6072 /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6073 /// slot: every M2 `SupervisorSpec`-scoped composite reader
6074 /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6075 /// `restart_window`, `children`) already routes through the M2
6076 /// `SupervisorSpec` accessor family — this lift extends the same
6077 /// "one typed dispatch on the substrate primitive at the outer
6078 /// composition altitude" discipline to the M3 mesh-slot
6079 /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6080 /// remaining peer outer-composite axes still unlifted at the time
6081 /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6082 /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6083 /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6084 /// inherit this accessor's discipline as future compounding runs
6085 /// migrate their consumers onto the shared reference-return shape.
6086 /// Named `politicas()` to match the storage field's name verbatim
6087 /// and the tatara-lisp author-surface term (`:politicas`) the
6088 /// field's own docstring already carries; the accessor's identity
6089 /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6090 /// slot's docstring already reaches for. Returns `&MeshPolicy`
6091 /// (not the owning composite by copy or clone) because every
6092 /// downstream consumer of the mesh-policy composite treats it as a
6093 /// read-only per-axis dispatch source — the reference-view is the
6094 /// narrowest borrow that supports every present + roadmapped
6095 /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6096 /// emptiness probe) without cloning the composite through every
6097 /// consumer's fast path.
6098 #[must_use]
6099 pub fn politicas(&self) -> &MeshPolicy {
6100 &self.politicas
6101 }
6102
6103 /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6104 /// per-Aplicacao distribution-composite composite-reference accessor
6105 /// every per-Aplicacao placement-block reader keys off — returns the
6106 /// author-declared `:placement` composite verbatim as a `&Placement`
6107 /// reference over the same backing storage the raw `&self.placement`
6108 /// field access borrows from.
6109 ///
6110 /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6111 /// distribution composite — the load-bearing container of every
6112 /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6113 /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6114 /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6115 /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6116 /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6117 /// `:affinity` hint). Every per-`:placement` axis threads through a
6118 /// lifted per-slot accessor on the [`Placement`] type: the
6119 /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6120 /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6121 /// per-cluster distribution-target slice-return accessor, the
6122 /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6123 /// optional-scalar accessor, and the [`Placement::shard_key`]
6124 /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6125 /// downstream consumer that reaches for a placement axis first passes
6126 /// through this outer accessor onto the composite and then dispatches
6127 /// onto the per-axis accessor — the two-level dispatch means every
6128 /// per-`:placement` reader now routes through a typed dispatch on the
6129 /// substrate primitive at both altitudes.
6130 ///
6131 /// Prior to this lift the `.placement` `Placement` composite was
6132 /// accessed inline at three production sites — the
6133 /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6134 /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6135 /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6136 /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6137 /// cluster `.clusters()` validate-loop traversal head, the per-
6138 /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6139 /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6140 /// paired with the shape-gate cascade's `.shard_key()` /
6141 /// `.estrategia()` diagnostic-carry pair), the
6142 /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6143 /// per-entry placement-block emitter's outer
6144 /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6145 /// seed (which fans onto every per-cluster `programs[]` entry as a
6146 /// self-describing distribution overlay the aggregator filters by),
6147 /// and the `feira app graph` per-Aplicacao print line's paired
6148 /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6149 /// then-inner-accessor chains (which drive the human-readable
6150 /// distribution summary of the typed Aplicacao view) — three open-
6151 /// coded outer-field accesses that expressed no compile-time link
6152 /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6153 /// extension of the `:placement` outer axis to a richer author surface
6154 /// (a per-cluster placement overlay the operator pins through a
6155 /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6156 /// federation roadmap acknowledges, a per-tenant placement-alias
6157 /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6158 /// resolves per-CR at admission time, a per-Aplicacao dynamic
6159 /// placement-composite derivation the future M5 adaptive-placement
6160 /// engine computes from a per-cluster load-topology reader, a
6161 /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6162 /// partition once Orleans-style virtual-actor dynamic-placement comes
6163 /// into typed scope) would have had to be threaded through all three
6164 /// open-coded copies in lockstep or one consumer would silently
6165 /// disagree with the peers on which placement composite a given
6166 /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6167 /// seed reading the raw slot while the peer
6168 /// `programs_for_aplicacao` emitter read an operator-resolved slot
6169 /// would silently split the build-time distribution-shape gate from
6170 /// the runtime programs.yaml distribution-annotation gate, a three-
6171 /// consumer split at the validator, the programs.yaml emitter, and
6172 /// the `feira app graph` printer far from the source `caixa.lisp`
6173 /// with no field naming the placement-drift root cause. Lifting the
6174 /// resolution rule to a typed method on the substrate primitive
6175 /// means every downstream consumer of the Aplicacao's per-
6176 /// `:placement` distribution composite surface reaches for exactly
6177 /// one typed dispatch — the resolver's accept-set migrates as a unit
6178 /// on any future axis addition.
6179 ///
6180 /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6181 /// `AplicacaoSpec` type itself — sibling to the seed
6182 /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6183 /// composite-reference accessor on the peer per-`:politicas` outer-
6184 /// composite axis, and to the paired slice-return accessors
6185 /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6186 /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6187 /// the two `Vec`-carry axes on the outer typed composition view; the
6188 /// outer `:placement` composite-reference axis is the natural pair
6189 /// to the peer `:politicas` composite-reference axis on the two
6190 /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6191 /// how-to-run policy overlay, `:placement` carries the where-to-run
6192 /// distribution composite — every whole-Aplicacao mesh-artifact
6193 /// emitter reads both as one unit). Same "one typed dispatch on the
6194 /// substrate primitive, thin projections at each consumer"
6195 /// discipline the peer per-`:politicas` composite-reference axis
6196 /// already routes through. The one remaining outer-composite axis
6197 /// still unlifted at the time of this lift —
6198 /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6199 /// external-gateway composite) — inherits this accessor's discipline
6200 /// as the next compounding run migrates its consumers onto the shared
6201 /// reference-return shape, closing the outer-composite altitude on
6202 /// every M3 mesh-slot axis. Named `placement()` to match the storage
6203 /// field's name verbatim and the tatara-lisp author-surface term
6204 /// (`:placement`) the field's own docstring already carries; the
6205 /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6206 /// vocabulary the slot's docstring already reaches for. Returns
6207 /// `&Placement` (not the owning composite by copy or clone) because
6208 /// every downstream consumer of the placement composite treats it as
6209 /// a read-only per-axis dispatch source — the reference-view is the
6210 /// narrowest borrow that supports every present + roadmapped consumer
6211 /// (per-axis accessor dispatch, serde composite-serialization) without
6212 /// cloning the composite through every consumer's fast path.
6213 #[must_use]
6214 pub fn placement(&self) -> &Placement {
6215 &self.placement
6216 }
6217
6218 /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6219 /// per-Aplicacao external-gateway composite optional-composite-
6220 /// reference accessor every per-Aplicacao gateway-block reader
6221 /// keys off — returns the author-declared `:entrada` composite
6222 /// verbatim as an `Option<&Entrada>` reference over the same
6223 /// backing storage the raw `self.entrada.as_ref()` field access
6224 /// borrows from, with `None` naming the internal-only mesh shape
6225 /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6226 /// gateway_routes emitter treats as "emit nothing" and the peer
6227 /// `feira app graph` printer treats as "internal-only mesh").
6228 ///
6229 /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6230 /// external-gateway composite — the load-bearing container of
6231 /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6232 /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6233 /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6234 /// hostname axis, §III.4 for the `:para` destination-Servico
6235 /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6236 /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6237 /// axis threads through a lifted per-slot accessor on the
6238 /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6239 /// Gateway-API `Listener.hostname` scalar accessor, the paired
6240 /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6241 /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6242 /// backendRefs destination-Servico scalar accessor, the
6243 /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6244 /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6245 /// scalar accessor. Every downstream consumer that reaches for
6246 /// an entrada axis first passes through this outer accessor onto
6247 /// the composite and then dispatches onto the per-axis accessor
6248 /// — the two-level dispatch means every per-`:entrada` reader
6249 /// now routes through a typed dispatch on the substrate primitive
6250 /// at both altitudes.
6251 ///
6252 /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6253 /// was accessed inline at four production sites — the
6254 /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6255 /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6256 /// (which drives every per-axis refusal on the composite: the
6257 /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6258 /// `EntradaMemberMissing` membership lookup against the
6259 /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6260 /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6261 /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6262 /// per-path shape gate on each entry of `e.paths`), the
6263 /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6264 /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6265 /// composite-projection seed (which drives the destination-
6266 /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6267 /// backendRefs port emitter fans on), the
6268 /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6269 /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6270 /// early-return seed (which drives the "no `:entrada` ⇒ no
6271 /// external artifacts" partition on the whole-Aplicacao Gateway-
6272 /// API emitter's fan-out), and the `feira app graph` per-
6273 /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6274 /// external-gateway summary emitter (which drives the human-
6275 /// readable `entrada: host → para (paths=…, port=…)` /
6276 /// `entrada: (internal-only mesh)` partition on the typed
6277 /// Aplicacao view) — four open-coded outer-field accesses that
6278 /// expressed no compile-time link back to the typed slot at the
6279 /// [`AplicacaoSpec`] altitude. A future extension of the
6280 /// `:entrada` outer axis to a richer author surface (a
6281 /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6282 /// at admission time so an Aplicacao can expose a public-web +
6283 /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6284 /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6285 /// operator can pin a per-cluster hostname override without
6286 /// re-authoring the `caixa.lisp`, a promotion of the plain
6287 /// `Option<Entrada>` to a richer `{single, multi}` partition once
6288 /// the multi-`:entrada` roadmap lands) would have had to be
6289 /// threaded through all four open-coded copies in lockstep or one
6290 /// consumer would silently disagree with the peers on which
6291 /// entrada composite a given Aplicacao resolves to — the
6292 /// validator's per-axis bracket-dispatch seed reading the raw
6293 /// slot while the peer `gateway_routes` emitter read an
6294 /// operator-resolved slot would silently split the build-time
6295 /// gateway-shape gate from the runtime Gateway + HTTPRoute
6296 /// emission gate, a four-consumer split at the validator, the
6297 /// `port_for_destination` L4-port resolver, the `gateway_routes`
6298 /// emitter, and the `feira app graph` printer far from the
6299 /// source `caixa.lisp` with no field naming the entrada-drift
6300 /// root cause. Lifting the resolution rule to a typed method on
6301 /// the substrate primitive means every downstream consumer of
6302 /// the Aplicacao's per-`:entrada` external-gateway composite
6303 /// surface reaches for exactly one typed dispatch — the
6304 /// resolver's accept-set migrates as a unit on any future axis
6305 /// addition.
6306 ///
6307 /// Third and final `&Composite`-return accessor on the top-level
6308 /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
6309 /// unlifted outer-composite axis on the outer typed composition
6310 /// view, sibling to the seed [`AplicacaoSpec::politicas`]
6311 /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
6312 /// accessor on the per-`:politicas` outer-composite axis and to
6313 /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
6314 /// distribution-composite composite-reference accessor on the
6315 /// per-`:placement` outer-composite axis; extends the outer-
6316 /// composite reference-return discipline the two peers already
6317 /// route through onto the last unlifted per-`AplicacaoSpec`
6318 /// outer-composite axis. The `:entrada` outer-composite axis is
6319 /// the natural pair to the two peer outer-composite axes on the
6320 /// three operationally-symmetric M3 mesh-slot outer composites
6321 /// (`:politicas` carries the how-to-run policy overlay,
6322 /// `:placement` carries the where-to-run distribution composite,
6323 /// `:entrada` carries the who-can-reach-it external-gateway
6324 /// composite — every whole-Aplicacao mesh-artifact emitter reads
6325 /// all three as one unit). Same "one typed dispatch on the
6326 /// substrate primitive, thin projections at each consumer"
6327 /// discipline the peer outer-composite axes already route through.
6328 /// Named `entrada()` to match the storage field's name verbatim
6329 /// and the tatara-lisp author-surface term (`:entrada`) the
6330 /// field's own docstring already carries; the accessor's
6331 /// identity maps onto the canonical MESH-COMPOSITION §III.4
6332 /// vocabulary the slot's docstring already reaches for. Returns
6333 /// `Option<&Entrada>` (not the owning composite by copy or
6334 /// clone) because every downstream consumer of the entrada
6335 /// composite treats it as a read-only per-axis dispatch source
6336 /// — the reference-view is the narrowest borrow that supports
6337 /// every present + roadmapped consumer (per-axis accessor
6338 /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
6339 /// port-fallback projection, early-return partition on the
6340 /// `None` arm) without cloning the composite through every
6341 /// consumer's fast path. The `Option` half of the return-type
6342 /// preserves the load-bearing "author-omitted `:entrada` ⇒
6343 /// internal-only mesh" partition (not a default composite the
6344 /// downstream must reject on emptiness) — the accessor projects
6345 /// the raw `Option<Entrada>` slot's presence bit through the
6346 /// reference-return unchanged.
6347 #[must_use]
6348 pub fn entrada(&self) -> Option<&Entrada> {
6349 self.entrada.as_ref()
6350 }
6351
6352 /// Validate the typed shape:
6353 /// - `:membros` is non-empty; every entry has a non-empty `:caixa`
6354 /// and a non-empty `:versao`; no two entries share the same
6355 /// `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
6356 /// not a multiset)
6357 /// - every `:contratos` :de + :para must be in `:membros`
6358 /// - no `:contratos` edge is a self-edge (`:de == :para`) — a
6359 /// contract is an inter-Servico edge, so a Servico contracting
6360 /// with itself is a build error under every WIT shape
6361 /// (MESH-COMPOSITION §III.1)
6362 /// - no two `:contratos` entries agree on
6363 /// `(de, para, wit, endpoint, subject, slot)` — the typed-graph
6364 /// edges are a set, not a multiset (peer of the `:membros` /
6365 /// `:placement :clusters` / `:entrada :paths` duplicate gates)
6366 /// - `:entrada :para` must be in `:membros`
6367 /// - `:placement Sharded` must declare `:shard-key` (non-empty);
6368 /// `:placement Replicated`/`SingleNode` must NOT declare
6369 /// `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
6370 /// consumes it (MESH-COMPOSITION §II.4), and the typed partition
6371 /// between strategy and shard-key is symmetric: every validated
6372 /// `Placement` has `shard_key.is_some()` iff `estrategia ==
6373 /// Sharded`
6374 /// - every `:placement` strategy must declare ≥1 `:clusters` entry —
6375 /// `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
6376 /// the shard pool (MESH-COMPOSITION §III.1)
6377 /// - every `:clusters` entry is non-empty and unique
6378 /// - `:placement :affinity`, when set, is non-empty
6379 /// - the synchronous-`:contratos` subgraph is acyclic
6380 /// (MESH-COMPOSITION §III.3)
6381 /// - every declared `:politicas` value is operationally meaningful
6382 /// (zero timeout, zero retries, zero breaker thresholds, zero rate
6383 /// limit are all build errors — MESH-COMPOSITION §V CSE invariants;
6384 /// omit the field instead to express "no policy on this axis")
6385 pub fn validate(&self) -> Result<(), AplicacaoError> {
6386 self.validate_membros()?;
6387 let names: std::collections::HashSet<&str> =
6388 self.membros().iter().map(Membro::nome).collect();
6389
6390 // Identity key for the typed-edge duplicate gate below: every
6391 // field that distinguishes one contract from another. Two
6392 // entries that agree on all six are *the same edge declared
6393 // twice*, the typed-graph analogue of duplicate `:membros` /
6394 // `:placement :clusters` / `:entrada :paths` entries (which
6395 // are already build errors at this layer). Rejecting it at the
6396 // validate gate closes a renderer-side footgun: caixa-mesh's
6397 // `cilium_network_policies` keys each emitted policy by
6398 // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
6399 // (de, para) and identical payload would land as two K8s
6400 // objects with colliding `metadata.name`, rejected at apply
6401 // time far from the source caixa.lisp.
6402 let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
6403 std::collections::HashSet::new();
6404 for c in self.contratos() {
6405 // Per-axis value-shape gate on every `:contratos` name
6406 // reference, before any graph-membership lookup. Empty +
6407 // DNS-1123-malformed `:de`/`:para` values silently fell
6408 // through to `ContratoMemberMissing` at the lookup arm
6409 // because every `:membros :caixa` is shape-validated
6410 // (3f9d7a0), so the `names` set structurally cannot contain
6411 // an empty / malformed string and the membership-lookup
6412 // diagnostic always misframed the root cause as
6413 // "this caixa is not in `:membros`". The shape gate runs
6414 // ahead of the lookup so structurally-impossible-to-match
6415 // inputs route through the narrower self-locating
6416 // diagnostic, preserving the legitimate "well-shaped
6417 // phantom reference" arm. `:de` runs before `:para` per
6418 // the canonical edge-direction order the existing
6419 // membership lookup, self-edge check, target dispatch,
6420 // and diagnostic strings already use.
6421 // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
6422 // + the paired [`AplicacaoError::ContratoMemberMissing`]
6423 // diagnostic's `caixa:` carrier through the lifted
6424 // [`WitContract::source`] / [`WitContract::destination`]
6425 // scalar accessors rather than the raw `&c.de` / `&c.para`
6426 // `&String`-borrow arg site + the raw `c.de.clone()` /
6427 // `c.para.clone()` field-access `String`-carry sites — the
6428 // last unlifted per-`:contratos` raw-field-access sites in
6429 // the M3 mesh-slot validator's per-edge per-arm shape-gate
6430 // arg + phantom-name diagnostic wrap-envelope emit surface.
6431 // `c.source()` is byte-identical to `&c.de` (pinned by the
6432 // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
6433 // + `wit_contract_source_borrows_from_de_storage` accessor
6434 // tests) and `c.destination()` is byte-identical to `&c.para`
6435 // (pinned by the sibling
6436 // `wit_contract_destination_returns_para_byte_equal_across_permutations`
6437 // + `wit_contract_destination_borrows_from_para_storage`
6438 // accessor tests) — so a future rebrand of either underlying
6439 // storage flows through the accessor's one body without a
6440 // coordinated per-consumer rewrite across the M3 mesh
6441 // validator's per-edge shape-gate + phantom-name refusal
6442 // arms. Peer of the sibling per-`:contratos` self-loop
6443 // arm's `.source().to_string()` / `.world_ref().to_string()`
6444 // `String`-carry sites the earlier convergence lifted onto
6445 // the same accessor pair.
6446 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
6447 validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
6448 if !names.contains(c.source()) {
6449 return Err(AplicacaoError::ContratoMemberMissing {
6450 caixa: c.source().to_string(),
6451 });
6452 }
6453 if !names.contains(c.destination()) {
6454 return Err(AplicacaoError::ContratoMemberMissing {
6455 caixa: c.destination().to_string(),
6456 });
6457 }
6458 // A `:contratos` entry is an *inter*-Servico contract
6459 // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
6460 // typed edge between two distinct graph nodes. An edge whose
6461 // `:de` equals its `:para` is a Servico contracting with
6462 // itself — a degenerate edge under every WIT shape. The
6463 // synchronous shapes were caught only incidentally, and with
6464 // a misleading diagnostic: `detect_sync_cycles` reported
6465 // `cart → cart` as a `ContratoCycle` whose path is
6466 // `["cart", "cart"]` — framing a self-edge as a multi-node
6467 // deadlock. The pub-sub shape slipped through entirely
6468 // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
6469 // `nats:pub-sub` edge from a member to itself silently
6470 // validated, then rendered a `CiliumNetworkPolicy` whose
6471 // endpointSelector and fromEndpoints both name the same
6472 // program — a self-allow rule that is a no-op, since
6473 // intra-pod traffic never traverses the mesh). A self-edge's
6474 // runtime meaning is an in-process call, which doesn't go
6475 // through the mesh at all, so no `:contratos` edge can carry
6476 // it. Firing the gate before the `:wit`/`target()` shape
6477 // checks means the structural "this edge can't exist" error
6478 // precedes the narrower payload-shape diagnostics, and shape-
6479 // agnostically covers all four `WitTarget` arms (HTTP / Store
6480 // / Capability / PubSub) at one point — closing the pub-sub
6481 // hole and replacing the misleading cycle diagnostic in one
6482 // gate. Peer of the duplicate-`:contratos` / duplicate-
6483 // `:membros` set gates: both reject a structurally
6484 // ill-formed graph at the typed surface, before the renderer
6485 // emits a K8s object that fails or no-ops far from the source
6486 // caixa.lisp.
6487 // Route the per-`:contratos` structural self-edge probe
6488 // through the lifted [`WitContract::is_self_loop`] typed
6489 // predicate rather than the raw `c.de == c.para` field-
6490 // equality check — the one production consumer of the per-
6491 // `:contratos` caller-equals-callee endpoint-equality axis
6492 // now keys off exactly one typed dispatch on the substrate
6493 // primitive, so any future rebrand of the axis (an M4-typed-
6494 // caller enum whose identity comparison rule the predicate
6495 // could route through, a per-cluster caller/callee-alias
6496 // table the M4 CR materializer resolves per-CR before the
6497 // equality probe) migrates as a single caixa-core edit
6498 // rather than a coordinated rewrite of the gate + every
6499 // downstream self-edge consumer. Peer of the sibling
6500 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
6501 // [`WitContract::is_store`] shape-predicate routing on the
6502 // `:wit` world-ref axis, extended onto the per-edge
6503 // endpoint-equality axis.
6504 //
6505 // Route the paired [`AplicacaoError::ContratoSelfLoop`]
6506 // diagnostic's `caixa:` / `wit:` carriers through the
6507 // lifted [`WitContract::source`] / [`WitContract::world_ref`]
6508 // scalar accessors rather than the raw `c.de.clone()` /
6509 // `c.wit.clone()` field-access `String`-carry sites — the
6510 // last unlifted per-`:contratos` raw-field-access
6511 // `.clone()` sites in the M3 mesh-slot validator's self-
6512 // edge refusal arm. `.source().to_string()` is byte-
6513 // identical to `.de.clone()` (pinned by the sibling
6514 // `source_returns_de_byte_equal_across_permutations` accessor
6515 // test), and `.world_ref().to_string()` is byte-identical
6516 // to `.wit.clone()` (pinned by the sibling
6517 // `world_ref_returns_wit_byte_equal_across_permutations`
6518 // accessor test) — so a future rebrand of either underlying
6519 // storage flows through the accessor's one body without a
6520 // coordinated per-consumer rewrite across the M3 mesh
6521 // validator.
6522 if c.is_self_loop() {
6523 return Err(AplicacaoError::ContratoSelfLoop {
6524 caixa: c.source().to_string(),
6525 wit: c.world_ref().to_string(),
6526 });
6527 }
6528 if c.world_ref().is_empty() {
6529 let (de, para) = c.edge_pair();
6530 return Err(AplicacaoError::EmptyWit { de, para });
6531 }
6532 // Shape ↔ target consistency — surfaces "HTTP wit without
6533 // :endpoint", "NATS wit with :endpoint set", etc. as named
6534 // build errors instead of silent renderer drops. Threaded
6535 // through the duplicate-edge diagnostic below (via
6536 // [`WitTarget::label`]) so the "which typed target arm did
6537 // the duplicate carry" question is answered by the typed
6538 // enum's variant discriminator, not by re-probing the raw
6539 // `Option<String>` payload fields.
6540 let target_view = c.target()?;
6541 // Contract identity: (de, para, wit, endpoint, subject, slot).
6542 // Two contracts that match on all six are the same typed edge
6543 // declared twice — author error, not a legitimate variant of
6544 // "same caller-callee pair, different payload" (e.g.
6545 // cart→catalog at /products vs /search), which keeps distinct
6546 // identity keys via the differing endpoint payloads.
6547 //
6548 // Route the six-axis dedup key through the lifted
6549 // [`WitContract::identity`] composite-projection accessor
6550 // rather than the inline six-tuple builder — the two
6551 // substrate primitives on the per-`:contratos` identity axis
6552 // (the [`ContratoIdentity`] type alias's six axes, this
6553 // dedup-key's six tuple arms) now migrate as a unit on any
6554 // future axis addition. Peer of the sibling per-`:contratos`
6555 // composite-projection [`WitContract::edge_pair`] /
6556 // [`WitContract::edge_triple`] accessors on the
6557 // caller-callee / caller-callee-wit prefix axes; extends
6558 // the discipline onto the full-identity axis that carries
6559 // the three payload-shape arms too.
6560 let key = c.identity();
6561 crate::render::insert_first_seen(&mut seen_contracts, key, || {
6562 // Route the per-`:contratos` duplicate-gate diagnostic's
6563 // `(de, para, wit)` triple through the lifted
6564 // [`WitContract::edge_triple`] typed accessor rather
6565 // than pairing `edge_pair()` for the `(de, para)` prefix
6566 // with a raw `c.wit.clone()` for the `wit:` tail — the
6567 // paired-with-raw-field-access shape was the last
6568 // per-`:contratos` diagnostic constructor bypassing the
6569 // substrate-primitive composite projection, sibling to
6570 // the eight [`AplicacaoError::Contrato*`] triple-
6571 // carrying constructors [`WitContract::target`]'s edge
6572 // closure feeds through the same accessor.
6573 let (de, para, wit) = c.edge_triple();
6574 AplicacaoError::ContratoDuplicate {
6575 de,
6576 para,
6577 wit,
6578 target: target_view.label(),
6579 }
6580 })?;
6581 }
6582
6583 // Cycles in the synchronous-edge subgraph are build errors
6584 // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
6585 // are "acyclic by construction" because the publisher fires
6586 // and forgets, so no caller blocks on a downstream that loops
6587 // back to it.
6588 self.detect_sync_cycles()?;
6589
6590 if let Some(e) = self.entrada() {
6591 // Route the per-`:entrada` composite-reference read
6592 // through the lifted [`AplicacaoSpec::entrada`] accessor
6593 // rather than the raw `&self.entrada` field access — the
6594 // shape-and-membership gate's traversal head is now the
6595 // canonical read-side surface every per-Aplicacao entrada
6596 // consumer routes through, closing the fourth of four
6597 // open-coded outer-field accesses on the per-`:entrada`
6598 // outer-composite axis.
6599 //
6600 // Shape gate on `:entrada :para` runs ahead of the
6601 // membership lookup. Every `:membros :caixa` past
6602 // `validate_membro_caixa` is a valid DNS-1123 label
6603 // (3f9d7a0), so the `names` set structurally cannot
6604 // contain an empty / malformed string and the membership-
6605 // lookup diagnostic always misframed the root cause as
6606 // "this caixa is not in `:membros`". The shape gate
6607 // routes structurally-impossible-to-match inputs through
6608 // the narrower self-locating diagnostic, preserving the
6609 // legitimate "well-shaped phantom reference" arm — the
6610 // same trajectory the peer `:membros :caixa` (3f9d7a0),
6611 // `:placement :clusters` (6c8c00b), and `:contratos :de`
6612 // / `:para` (8d5af6b) axes already follow. This closes
6613 // the fourth and last Aplicacao-level Servico-name
6614 // reference axis on the canonical DNS-1123 floor.
6615 // Route the per-`:entrada :para` byte-string reads through
6616 // the lifted [`Entrada::destination`] accessor rather than
6617 // the raw `e.para` field access — the three
6618 // per-`AplicacaoSpec::validate` `:entrada :para` consumers
6619 // (shape-gate `validate_entrada_para` arg, membership
6620 // lookup, `EntradaMemberMissing` diagnostic carry) now key
6621 // off exactly one typed dispatch on the substrate
6622 // primitive, closing the last unlifted per-`:entrada :para`
6623 // raw-field-access axis on the M3 mesh-slot validator.
6624 // The `.destination().to_string()` at the diagnostic site
6625 // is byte-identical to `.para.clone()` — pinned by the
6626 // sibling `destination_returns_entrada_para_byte_equal` +
6627 // `destination_borrows_from_entrada_para_storage` accessor
6628 // tests — so a future rebrand of the underlying `:para`
6629 // storage (a lift from `String` to a typed
6630 // `ServicoName(String)` newtype, a per-Aplicacao interning
6631 // arena the M4 CR materializer authors, a
6632 // `smol_str::SmolStr` inline-buffer swap) flows through
6633 // the accessor's one body without a coordinated
6634 // per-consumer rewrite across the M3 mesh validator.
6635 validate_entrada_para(e.destination())?;
6636 if !names.contains(e.destination()) {
6637 return Err(AplicacaoError::EntradaMemberMissing {
6638 para: e.destination().to_string(),
6639 });
6640 }
6641 // Route the per-`:entrada :host` byte-string reads through
6642 // the lifted [`Entrada::hostname`] accessor rather than
6643 // the raw `e.host` field access — the emptiness gate and
6644 // the shape-gate `validate_entrada_host` arg now key off
6645 // exactly one typed dispatch on the substrate primitive,
6646 // closing the last unlifted per-`:entrada :host` raw-
6647 // field-access axis on the M3 mesh-slot validator. Peer
6648 // of the sibling per-`:entrada :para` convergence above
6649 // and pinned by the existing
6650 // `hostname_returns_entrada_host_byte_equal` +
6651 // `hostnames_returns_singleton_of_hostname_accessor`
6652 // accessor tests, so any future
6653 // Gateway-API-shaped host renormalization (a wildcard-
6654 // label lift, a trailing-`.` FQDN substitution, an IDNA
6655 // Punycode round-trip the SNI fan-out overlay authors)
6656 // flows through the accessor's one body without a
6657 // coordinated per-consumer rewrite across the M3 mesh
6658 // validator.
6659 if e.hostname().is_empty() {
6660 return Err(AplicacaoError::EmptyEntradaHost);
6661 }
6662 // The `:host` lands verbatim as a K8s Gateway API v1
6663 // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
6664 // both apiserver-validated against the same restrictive
6665 // pattern: lowercase RFC 1123 DNS subdomain, optional
6666 // single leading wildcard label (`*.`), max length 253,
6667 // per-label max length 63, no IP literals, no scheme,
6668 // no port. Until this gate landed `validate()` only
6669 // refused the empty string (`EmptyEntradaHost`); a
6670 // structurally invalid hostname (`"https://example.com"`,
6671 // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
6672 // `"_underscored.example.com"`, `"FOO.example.com"`,
6673 // `"checkout.quero.cloud."`) silently passed validate
6674 // and the apiserver `field is invalid` error surfaced at
6675 // `kubectl apply` time, far from the source caixa.lisp.
6676 // Lifting the gate to caixa-build time mirrors the
6677 // `:entrada :paths` value-shape trajectory (eb3456d) and
6678 // closes the last unstructured `:entrada` axis.
6679 validate_entrada_host(e.hostname())?;
6680 // Structural-floor gate on `:entrada :port`: every
6681 // validated `Entrada::port` past this gate lies in
6682 // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
6683 // type-inferred ceiling closes the top edge, so no companion
6684 // upper-cap arm is needed here — unlike the peer capped-
6685 // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
6686 // `require_positive_bounded_u32` bracket covers both edges).
6687 // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
6688 // accept-set-floor const rather than the prior inline
6689 // `if e.port == 0` byte-check so a future rebrand of the
6690 // accept-set floor (a hypothetical unprivileged-only
6691 // migration lifting the floor to `1024`, a per-cluster
6692 // scoping the operator pins through a future
6693 // `:placement :port-floor` slot as the M4 typed-slot
6694 // trajectory adds it, the future
6695 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6696 // per-Aplicacao gateway resolver reaching for the same
6697 // floor) is a one-line edit on the canonical
6698 // [`SERVICO_PORT_MIN`] declaration, not a coordinated
6699 // rewrite across the emit site + the pin test + every
6700 // future per-target renderer the substrate adds.
6701 if e.port() < SERVICO_PORT_MIN {
6702 return Err(AplicacaoError::EntradaPortZero);
6703 }
6704 // Each `:entrada :paths` entry becomes a K8s Gateway API
6705 // HTTPRoute `matches[].path.value`. The Gateway API rejects
6706 // values that don't start with `/` for `type: PathPrefix`,
6707 // and an empty value is meaningless. Surface those as build
6708 // errors (MESH-COMPOSITION §III.3) rather than apply-time
6709 // failures. Empty `:paths` itself is fine — caixa-mesh
6710 // falls back to a single `/` catch-all.
6711 let mut seen = std::collections::HashSet::new();
6712 // Route the per-entry value-shape gate's traversal head
6713 // through the lifted [`Entrada::paths`] slice accessor
6714 // rather than the raw `&e.paths` field access — the
6715 // per-Aplicacao `:entrada :paths` validate loop now keys
6716 // off the canonical raw-slot surface every downstream
6717 // per-`:entrada` path-list consumer (the sibling
6718 // [`Entrada::resolved_paths`] fallback-applying resolver
6719 // internal reads, `feira app graph`'s per-Aplicacao entrada
6720 // summary line's `{:?}` Debug print) routes through, so any
6721 // future rebrand on the typed slot's raw-slot reader lands
6722 // at exactly one place. Same convergence discipline as the
6723 // sibling [`Placement::clusters`] (a6e18d7) reader-site
6724 // convergences on the peer M3 mesh-slot `Vec<String>`-carry
6725 // axis.
6726 for p in e.paths() {
6727 if p.is_empty() {
6728 return Err(AplicacaoError::EntradaPathEmpty);
6729 }
6730 if !p.starts_with('/') {
6731 return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
6732 }
6733 // Per-entry value-shape gate: the path lands verbatim
6734 // as a K8s Gateway API HTTPRoute `matches[].path.value`
6735 // (caixa-mesh/src/lib.rs:498), apiserver-validated
6736 // against `maxLength: 1024` + the Gateway API webhook's
6737 // path-grammar rules (no `//`, no `/./`, no `/../`, no
6738 // query/fragment separators, no whitespace, no control
6739 // characters, no non-ASCII bytes). Until this gate
6740 // landed `validate` only refused the empty string and
6741 // missing-leading-slash (eb3456d); a structurally
6742 // invalid path (`"/api?q=1"`, `"/api#frag"`,
6743 // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
6744 // 1025-byte URL-shaped slug) silently passed validate
6745 // and the failure surfaced at `kubectl apply` time as
6746 // a Gateway API webhook rejection, far from the source
6747 // caixa.lisp, with no field naming the offending
6748 // `:paths` entry. Lifting the gate to caixa-build time
6749 // mirrors the `:entrada :host` value-shape trajectory
6750 // (c7d05ec) on the sibling axis — every author surface
6751 // that emits a Gateway API field now matches the
6752 // apiserver's accepted set at validate time.
6753 validate_entrada_path(p)?;
6754 crate::render::insert_first_seen(&mut seen, p.as_str(), || {
6755 AplicacaoError::EntradaPathDuplicate { path: p.clone() }
6756 })?;
6757 }
6758 }
6759
6760 self.validate_placement()?;
6761
6762 self.validate_politicas()?;
6763
6764 Ok(())
6765 }
6766
6767 /// Reject `:membros` values that are operationally meaningless. The
6768 /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
6769 /// every entry names a Servico that participates in the Aplicacao,
6770 /// and the rendered programs.yaml fan-out emits one entry per
6771 /// `:membros`. Three authoring footguns are closed here:
6772 ///
6773 /// - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
6774 /// a `programs:` entry whose `name:` is the empty string, which
6775 /// downstream `lareira-fleet-programs` rejects at template time
6776 /// with a non-localized error;
6777 /// - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
6778 /// an empty semver constraint, so the failure surfaces far from
6779 /// the source caixa.lisp;
6780 /// - duplicate `:caixa` names — two entries with the same name
6781 /// produce duplicate programs.yaml entries (one silently
6782 /// overwrites the other in the cluster's HelmRelease values), and
6783 /// contract membership lookups against `:contratos` collapse the
6784 /// two onto one node, masking authoring mistakes.
6785 ///
6786 /// Same value-shape discipline as `:placement :clusters` (where empty
6787 /// + duplicate cluster names are rejected) and `:entrada :paths`
6788 /// (where empty + duplicate path entries are rejected). Lifting these
6789 /// invariants to the typed surface mirrors the MESH-COMPOSITION
6790 /// §III.3 promise that the `:membros` set — the load-bearing identity
6791 /// of the application graph — is well-formed by construction.
6792 fn validate_membros(&self) -> Result<(), AplicacaoError> {
6793 if self.membros().is_empty() {
6794 return Err(AplicacaoError::NoMembros);
6795 }
6796 let mut seen = std::collections::HashSet::new();
6797 for m in self.membros() {
6798 // Route the `MembroCaixaEmpty` refusal-arm's per-member
6799 // empty-`:caixa` shape-gate through the typed
6800 // [`Membro::nome`] accessor rather than the raw `.caixa`
6801 // field access — the last un-lifted `.caixa` production-
6802 // code read site on the per-`:membros` member-caixa `:nome`
6803 // axis, sibling to the six caixa-core validator read sites
6804 // (member-set collector, per-member value-shape gate,
6805 // duplicate dedup key, cycle-detector adjacency-map seed,
6806 // self-loop gate) the 4a32abf lift already routed through
6807 // the accessor and the peer 54bf2f3 caixa-mesh emit-side
6808 // per-`programs[]` entry-`name:` `String`-carry converge.
6809 // Prior to this converge the `MembroCaixaEmpty` refusal
6810 // arm was the solitary consumer bypassing the typed
6811 // dispatch — the same-loop iteration's very next call
6812 // `validate_membro_caixa(m.nome())` already routed through
6813 // the accessor, so an author landing an empty-`:caixa`
6814 // entry hit the accessor on the shape-gate line but
6815 // bypassed it on the emptiness line one line above. A
6816 // future extension of the `:membros :caixa` axis to a
6817 // richer author surface (a per-cluster alias table pinned
6818 // through a future `:placement`-scoped slot, a namespace-
6819 // qualified rewrite the M4 CR materializer applies per-CR,
6820 // a per-member overlay from the future `:membros
6821 // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
6822 // that lands on the accessor would silently disagree
6823 // between the emptiness gate and every peer consumer —
6824 // an author-declared `:caixa "checkout"` value the
6825 // accessor rewrote to `""` under a future alias arm would
6826 // pass the raw `.is_empty()` gate here while the peer
6827 // `validate_membro_caixa(m.nome())` call one line below
6828 // (and every downstream emit-side consumer routing through
6829 // the accessor) tripped on the empty-value shape far from
6830 // this diagnostic. Pinned by the drift-detection test
6831 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
6832 // below.
6833 if m.nome().is_empty() {
6834 return Err(AplicacaoError::MembroCaixaEmpty);
6835 }
6836 // Every emitted cluster artifact's `metadata.name` derives
6837 // from a `:membros :caixa` value verbatim — the rendered
6838 // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
6839 // the [`crate::LABEL_PROGRAM`] label value on every CNP
6840 // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
6841 // 272), the composed `CiliumNetworkPolicy` `metadata.name`
6842 // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
6843 // `metadata.name` when the member is the `:entrada :para`
6844 // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
6845 // schema enforces the DNS-1123 label rule on admission;
6846 // a structurally invalid member name (`"Cart"`, `"my_cart"`,
6847 // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
6848 // mistaken-identity slug) silently passes the prior empty-/
6849 // duplicate-only gate and the failure surfaces at `kubectl
6850 // apply` time as a `metadata.name: Invalid value` rejection,
6851 // far from the source caixa.lisp, with no field naming the
6852 // offending `:membros` entry. Lifting the gate to caixa-build
6853 // time mirrors the `:entrada :host` value-shape trajectory
6854 // (c7d05ec) on the peer axis — every author surface that
6855 // emits a K8s name now matches the apiserver's accepted set
6856 // at validate time.
6857 validate_membro_caixa(m.nome())?;
6858 // The author surface for `:versao` is the same Cargo-shaped
6859 // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
6860 // `"*"`) every `:deps` entry carries — and the lacre pipeline
6861 // resolves both axes through the same
6862 // [`crate::version::parse_requirement`] entry-point. The
6863 // shared [`crate::render::require_valid_versao_requirement`]
6864 // helper brackets the empty-first + parse cascade both peer
6865 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
6866 // [`crate::SupervisorSpec::validate`] on `:children :versao`)
6867 // route through, so drift between the three axes' accepted
6868 // requirement sets is structurally impossible and the parse-
6869 // side no-op the empty-first arm closes (semver's empty
6870 // parse yields an implicit `*`) lives in exactly one
6871 // predicate.
6872 crate::render::require_valid_versao_requirement(
6873 m.versao_requirement(),
6874 || AplicacaoError::MembroVersaoEmpty {
6875 caixa: m.nome().to_string(),
6876 },
6877 |reason| AplicacaoError::MembroVersaoInvalid {
6878 caixa: m.nome().to_string(),
6879 versao: m.versao_requirement().to_string(),
6880 reason,
6881 },
6882 )?;
6883 crate::render::insert_first_seen(&mut seen, m.nome(), || {
6884 AplicacaoError::MembroDuplicate {
6885 caixa: m.nome().to_string(),
6886 }
6887 })?;
6888 }
6889 Ok(())
6890 }
6891
6892 /// Reject `:placement` values that are operationally meaningless or
6893 /// internally contradictory. Each strategy variant has the same
6894 /// invariants on `:clusters` (non-empty list, non-empty unique
6895 /// entries) — the §III.1 author surface is uniform on this axis,
6896 /// even though the *meaning* of the list differs by strategy
6897 /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
6898 /// shard pool).
6899 ///
6900 /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
6901 /// are the same authoring footgun closed for `:politicas` zero
6902 /// values and `:entrada` empty paths: the field is *declared* but
6903 /// carries no meaning, so downstream renderers either skip it
6904 /// silently (cluster-fanout drops the empty entry, no diagnostic)
6905 /// or apply it literally and fail at admission time. Lifting both
6906 /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
6907 /// violation is a build error" promise.
6908 ///
6909 /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
6910 /// is required exactly when `:estrategia Sharded` (hash-keyed
6911 /// distribution, Akka cluster-sharding convention, §II.4) and
6912 /// refused on `:estrategia Replicated`/`SingleNode` (where no
6913 /// hash-keyed routing axis consumes it). The partition closes the
6914 /// "I think I configured sharding" footgun where an author writes
6915 /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
6916 /// the typed slot's value silently vanishes at the renderer layer
6917 /// — every validated `Placement` past this call satisfies
6918 /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
6919 fn validate_placement(&self) -> Result<(), AplicacaoError> {
6920 // Every strategy needs at least one named cluster: `Replicated`
6921 // and `SingleNode` use the list as hosting/takeover candidates
6922 // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
6923 // §II.1), while `Sharded` uses it as the shard pool
6924 // (Akka cluster-sharding convention — §II.4). An empty list is
6925 // meaningless under any of the three.
6926 //
6927 // Route the paired pre-flight `.is_empty()` refusal probe and
6928 // the per-cluster validate loop's traversal head through the
6929 // lifted [`Placement::clusters`] slice-return accessor rather
6930 // than the raw `self.placement.clusters` field access — the
6931 // two production consumers of the per-`:placement` cluster-
6932 // pool `Vec`-carry now key off exactly one typed dispatch on
6933 // the substrate primitive, so any future rebrand on the axis
6934 // (a per-tenant cluster-pool overlay the operator pins through
6935 // a future `:placement :clusters-overrides` slot, a per-
6936 // Aplicacao dynamic cluster-pool derivation the future M5
6937 // adaptive-placement engine computes from `:affinity` weights)
6938 // migrates as a single caixa-core edit rather than a
6939 // coordinated rewrite of the paired arms — sibling of the
6940 // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
6941 // arm migration on the per-`:supervisor` static-child-list
6942 // `Vec`-carry axis.
6943 //
6944 // Route the per-`:placement` outer-composite reference read
6945 // through the lifted [`AplicacaoSpec::placement`] outer accessor
6946 // rather than the raw `&self.placement` field access — the
6947 // per-axis bracket-dispatch fan-out below (`p.clusters()`,
6948 // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
6949 // axis-level lifted accessor family) now routes through the
6950 // substrate-primitive typed dispatch at the outer composition
6951 // altitude, the same shape the peer caixa-mesh
6952 // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
6953 // and the sibling `feira app graph` per-Aplicacao print line
6954 // now key off after this accessor lift.
6955 let p = self.placement();
6956 if p.clusters().is_empty() {
6957 return Err(AplicacaoError::PlacementWithoutClusters {
6958 estrategia: p.estrategia(),
6959 });
6960 }
6961 let mut seen = std::collections::HashSet::new();
6962 for c in p.clusters() {
6963 // Per-entry value-shape gate: the cluster name lands in
6964 // every K8s context / `lareira-fleet-programs` aggregator
6965 // filter / future M4 CR materializer's per-cluster axis
6966 // a validated `:clusters` entry passes through, each
6967 // enforcing the DNS-1123 label rule on admission. Same
6968 // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
6969 // on the peer name axis — both axes' validated values
6970 // are guaranteed-accepted by the apiserver without
6971 // re-validation at any downstream renderer or admission
6972 // layer.
6973 validate_placement_cluster(c)?;
6974 crate::render::insert_first_seen(&mut seen, c.as_str(), || {
6975 AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
6976 })?;
6977 }
6978 // Route the per-`:placement :affinity` per-hint value-shape
6979 // gate through the typed [`Placement::affinity`] accessor rather
6980 // than the raw `&self.placement.affinity` field access — the
6981 // sole open-coded field-access site on the per-`:placement`
6982 // M3-Adaptive-compression-hint axis the accessor lift now owns.
6983 // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
6984 // the accessor's `Option<&str>` return type;
6985 // [`validate_placement_affinity`]'s `&str` parameter accepts
6986 // the narrower borrow without a re-allocation, so the routing
6987 // change is byte-for-byte in the pass arm and remains
6988 // byte-for-byte in every failure diagnostic
6989 // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
6990 // String` field is populated inside
6991 // [`validate_placement_affinity`] via the peer `.to_string()`
6992 // path on the same borrowed slice). Peer of the sibling
6993 // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
6994 // routing through [`Placement::shard_key`] at the caixa-core
6995 // site above — extends the "read `:placement` optional-scalars
6996 // through the typed accessor" discipline to the second
6997 // `Option<String>`-shape slot on the M3 mesh-slot family.
6998 //
6999 // Per-hint value-shape gate: the `:affinity` value lands
7000 // verbatim in the M3 Adaptive compression overlay
7001 // (caixa-mesh's `placement.affinity` emission) and every
7002 // future M4 placement-engine routing axis keying off the
7003 // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7004 // selector — each enforces the DNS-1123 label rule on
7005 // admission. Same typed-shape trajectory as `:placement
7006 // :clusters` (6c8c00b) on the sibling slot and the four
7007 // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7008 // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7009 // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7010 // on the Aplicacao surface to land on the canonical
7011 // [`crate::render::is_dns_1123_label`] floor.
7012 if let Some(a) = p.affinity() {
7013 validate_placement_affinity(a)?;
7014 }
7015 match p.estrategia() {
7016 // Route the `Sharded`-arm shape-gate cascade through the
7017 // typed [`Placement::shard_key`] accessor rather than the
7018 // raw `&self.placement.shard_key` field access — one of the
7019 // two open-coded field-access sites on the per-`:placement`
7020 // Akka-cluster-sharding-key axis the accessor lift now
7021 // owns. The `Some(k)`-bound `k` narrows from `&String` to
7022 // `&str` under the accessor's `Option<&str>` return type;
7023 // `str::is_empty` and [`validate_placement_shard_key`]'s
7024 // `&str` parameter both accept the narrower borrow without
7025 // a re-allocation.
7026 PlacementStrategy::Sharded => match p.shard_key() {
7027 None => return Err(AplicacaoError::ShardedWithoutKey),
7028 Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7029 // Per-axis value-shape gate on the Akka-cluster-sharding
7030 // `:shard-key` extractor expression. The shape gate runs
7031 // after the more self-locating `ShardedKeyEmpty` arm so
7032 // a `:shard-key ""` surfaces the narrower empty
7033 // diagnostic first; every non-empty `:shard-key` past
7034 // this call is guaranteed to be a printable-ASCII
7035 // single-token reference the future M4 Akka-style
7036 // cluster-sharding reconciler can hash without
7037 // re-validating at the runtime layer. Mirrors the
7038 // payload-axis shape gates on the peer `:contratos`
7039 // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7040 // 63e18a0 / c4213a4) — each lifts the runtime parser's
7041 // intersection-floor to a caixa-build-time gate.
7042 Some(k) => validate_placement_shard_key(k)?,
7043 },
7044 // `:shard-key` is the Akka-cluster-sharding axis
7045 // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7046 // across the cluster pool. `Replicated` (active-active across
7047 // every named cluster) and `SingleNode` (Erlang/OTP
7048 // distributed-app takeover/failover, §II.1) have no hash-keyed
7049 // routing axis to consume the slot; downstream renderers
7050 // (caixa-mesh's `placement.shardKey` overlay at
7051 // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7052 // sharding reconciler) ignore `:shard-key` outside the
7053 // `Sharded` arm by construction. Until this gate landed an
7054 // author who wrote `:placement (:estrategia Replicated
7055 // :shard-key "tenantId")` (an off-by-one strategy typo, a
7056 // copy-paste from a Sharded sibling caixa, the "I think I
7057 // configured sharding" footgun) silently passed validate and
7058 // the typed slot's value vanished at the renderer layer with
7059 // no diagnostic — the canonical "declared-but-inert" footgun
7060 // the empty-:affinity / empty-shard-key / zero-:politicas /
7061 // empty-:contratos-target gates already close on every other
7062 // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7063 // Lifting the rejection to a build-time gate closes the
7064 // Sharded ↔ non-Sharded partition over the typed
7065 // `:placement` slot: every validated `Placement` past this
7066 // call has `shard_key.is_some()` iff `estrategia ==
7067 // Sharded`, structurally — the future Akka reconciler can
7068 // reach for `placement.shard_key` knowing it's `Some` exactly
7069 // when the strategy consumes it, without re-deriving the
7070 // partition from inline strategy probes.
7071 PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7072 // Route the non-`Sharded`-arm declared-but-inert refusal
7073 // through the typed [`Placement::shard_key`] accessor —
7074 // the second of the two open-coded field-access sites the
7075 // accessor lift now owns. The `Some(k)`-bound `k` narrows
7076 // from `&String` to `&str`; the `AplicacaoError::
7077 // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7078 // materializes the owned `String` via `k.to_string()`
7079 // (peer to the sibling per-Membro `String`-carry sites
7080 // 4127bb6 routed through `m.nome().to_string()` /
7081 // `m.versao_requirement().to_string()`), so the whole
7082 // `Sharded` ↔ non-`Sharded` partition on the
7083 // `:shard-key` axis now flows through the same typed
7084 // dispatch as the sibling `Sharded`-arm shape gate.
7085 if let Some(k) = p.shard_key() {
7086 return Err(AplicacaoError::ShardKeyOnNonSharded {
7087 estrategia: p.estrategia(),
7088 shard_key: k.to_string(),
7089 });
7090 }
7091 }
7092 }
7093 Ok(())
7094 }
7095
7096 /// Reject `:politicas` values that are operationally meaningless.
7097 /// Each axis is optional — omitting it expresses "no policy on this
7098 /// axis". Carrying a *zero* value for a declared axis is the bug
7099 /// this function rejects: zero is either
7100 ///
7101 /// - re-interpreted as "infinite" by downstream proxies (Envoy's
7102 /// `RouteAction.timeout = 0s` disables the timeout entirely),
7103 /// directly contradicting MESH-COMPOSITION §V CSE invariant
7104 /// "every Aplicacao declares :politicas :timeout (no infinite
7105 /// blocking)", or
7106 /// - a renderer footgun (a 0-failure circuit breaker trips on the
7107 /// first call; a 0-rate rate-limit denies every request).
7108 ///
7109 /// Lifting these "0 means the opposite of what you think" idioms to
7110 /// the typed Aplicacao surface as build errors mirrors the §III.3
7111 /// promise that contract drift, capability leaks, and cycles are all
7112 /// build errors — not runtime surprises.
7113 fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7114 // Route the per-`:politicas` composite-reference read through
7115 // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7116 // than the raw `&self.politicas` field access — the per-axis
7117 // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7118 // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7119 // the substrate-primitive typed dispatch at the outer
7120 // composition altitude AND at every per-axis altitude, matching
7121 // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7122 // timeout/retry-overlay emitters that already key off the same
7123 // per-axis accessor family. The four-axis fan-out is now
7124 // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7125 // `p.retries` field-access sites (co-resident with the peer
7126 // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7127 // b0e741a / 21a6c3b already lifted) now route through
7128 // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7129 // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7130 // access axis on the M3 mesh-slot family.
7131 let p = self.politicas();
7132 if let Some(t) = p.timeout() {
7133 // Zero-floor + integer-millisecond canonical-form +
7134 // upper-cap bracket on the typed `:timeout` axis. See
7135 // [`crate::render::require_positive_canonical_bounded_duration`]
7136 // for the full three-arm ordering discipline (zero-floor
7137 // strictly precedes the canonical-form arm so
7138 // `Duration::ZERO` surfaces the self-locating
7139 // `PolicyTimeoutZero` diagnostic naming the omit-axis
7140 // remediation; canonical-form strictly precedes the cap
7141 // arm so a sub-millisecond above-cap `Duration` surfaces
7142 // the more fundamental round-trip-shape diagnostic first)
7143 // and the four peer typed-`Duration` sites that now share
7144 // this canonical bracket. Every validated value lies in
7145 // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7146 // granularity — the same top-and-bottom-edge discipline
7147 // [`POLICY_RETRIES_MAX`] and
7148 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7149 // capped-`u32` `:politicas` axes.
7150 crate::render::require_positive_canonical_bounded_duration(
7151 t,
7152 POLICY_TIMEOUT_MAX,
7153 || AplicacaoError::PolicyTimeoutZero,
7154 |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7155 |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7156 )?;
7157 }
7158 if let Some(r) = p.retries() {
7159 // Zero-floor + upper-cap bracket on the typed `:retries`
7160 // axis. See [`crate::render::require_positive_bounded_u32`]
7161 // for the ordering discipline (zero-floor arm strictly
7162 // precedes cap arm so `Some(0)` surfaces the self-locating
7163 // `PolicyRetriesZero` diagnostic with its omit-axis
7164 // remediation directly named, not the misleading
7165 // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7166 // this bracket landed the top edge ran all the way to
7167 // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7168 // Some(100_000), .. }` (or the equivalent author-surface
7169 // `(:retries 100000)` / `(:retries 4294967295)` typo
7170 // landing in the slot) silently passed validate. The
7171 // runtime substrate consuming the value (Envoy's
7172 // `retry_policy.num_retries`, the future
7173 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7174 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7175 // policy into a thundering-herd amplification vector —
7176 // the caller's one request fans out to `retries`
7177 // server-side calls per edge per traversal, multiplying
7178 // load by `(retries+1)^depth` across the
7179 // synchronous-`:contratos` subgraph at the precise moment
7180 // the substrate is already failing (transient failure is
7181 // the trigger), exactly the failure mode AWS App Mesh's
7182 // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7183 // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7184 // the sibling capped-`u32` `:politicas` axes
7185 // (`max_failures`, `rate_limit.rate`) and the peer capped-
7186 // `u32` axes in `:supervisor :max-restarts` +
7187 // `:limits :cpu`; all five now route through the same
7188 // canonical bracket helper.
7189 crate::render::require_positive_bounded_u32(
7190 r,
7191 POLICY_RETRIES_MAX,
7192 || AplicacaoError::PolicyRetriesZero,
7193 |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7194 )?;
7195 }
7196 if let Some(cb) = p.circuit_breaker() {
7197 // Zero-floor + upper-cap bracket on the typed
7198 // `:max-failures` axis. See
7199 // [`crate::render::require_positive_bounded_u32`] for the
7200 // ordering discipline (zero-floor arm strictly precedes
7201 // cap arm so `max_failures == 0` surfaces the
7202 // self-locating `PolicyBreakerZeroFailures` diagnostic
7203 // with its omit-axis remediation directly named, not the
7204 // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7205 // false` cap-arm miss). Until this bracket landed the top
7206 // edge ran all the way to `u32::MAX` and a struct-literal
7207 // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7208 // equivalent author-surface `(:max-failures 100000)` /
7209 // `(:max-failures 4294967295)` typo landing in the slot)
7210 // silently passed validate. The runtime substrate
7211 // consuming the value (Envoy's
7212 // `outlier_detection.consecutive_5xx`, the future
7213 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7214 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7215 // breaker policy into a no-op — the trip threshold is
7216 // structurally so high that no realistic
7217 // failures-per-`:window` traffic shape can reach it, the
7218 // breaker never trips, and every typed-slot consumer
7219 // emits an Envoy / Cilium L7 overlay carrying a
7220 // protection that is structurally never enforced. The
7221 // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7222 // peer with `retries` and `rate_limit.rate` on the same
7223 // helper.
7224 crate::render::require_positive_bounded_u32(
7225 cb.max_failures(),
7226 POLICY_BREAKER_MAX_FAILURES_MAX,
7227 || AplicacaoError::PolicyBreakerZeroFailures,
7228 |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7229 )?;
7230 // Zero-floor + integer-millisecond canonical-form +
7231 // upper-cap bracket on the typed `:window` axis. See
7232 // [`crate::render::require_positive_canonical_bounded_duration`]
7233 // for the full three-arm ordering discipline (peer to the
7234 // `:timeout` site immediately above); every validated
7235 // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7236 // (1ms..=1h), integer-millisecond granularity — the same
7237 // top-and-bottom-edge discipline
7238 // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7239 // duration-typed `:politicas :timeout` axis.
7240 crate::render::require_positive_canonical_bounded_duration(
7241 cb.window(),
7242 POLICY_BREAKER_WINDOW_MAX,
7243 || AplicacaoError::PolicyBreakerZeroWindow,
7244 |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7245 |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7246 )?;
7247 }
7248 if let Some(rl) = p.rate_limit() {
7249 // Zero-floor + upper-cap bracket on the typed
7250 // `:rate-limit` rate axis. See
7251 // [`crate::render::require_positive_bounded_u32`] for the
7252 // ordering discipline (zero-floor arm strictly precedes
7253 // cap arm so `rl.rate == 0` surfaces the self-locating
7254 // `PolicyRateLimitZero` diagnostic with its omit-axis
7255 // remediation directly named, not the misleading
7256 // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7257 // Until this bracket landed the top edge ran all the way
7258 // to `u32::MAX` and a struct-literal
7259 // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7260 // author-surface `(:rate-limit "4294967295/s")` /
7261 // `(:rate-limit "100000000/m")` typo landing in the slot)
7262 // silently passed validate. The runtime substrate
7263 // consuming the value (Envoy's
7264 // `local_rate_limit.token_bucket.max_tokens`, the future
7265 // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7266 // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7267 // rate-limit policy into a no-op limiter: the bucket
7268 // capacity is structurally so high that no realistic
7269 // per-edge traffic shape can drain it, the limiter never
7270 // trips, and every typed-slot consumer emits a "rate
7271 // declared" L7 overlay carrying enforcement that is
7272 // structurally never reached — the canonical
7273 // declared-but-inert footgun the sibling
7274 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7275 // the peer no-op-breaker shape. The bracket set is
7276 // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7277 // `max_failures` on the same helper. The rate bracket
7278 // strictly precedes the window-canonical gate so a
7279 // structurally absurd rate magnitude surfaces the more
7280 // fundamental amplification-shape diagnostic before the
7281 // narrower codec-round-trip-shape diagnostic on `:window`.
7282 crate::render::require_positive_bounded_u32(
7283 rl.rate(),
7284 POLICY_RATE_LIMIT_MAX,
7285 || AplicacaoError::PolicyRateLimitZero,
7286 |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7287 )?;
7288 // The `:rate-limit` author surface is the canonical
7289 // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7290 // accepts exactly the three-unit set (1s/60s/3600s) the
7291 // [`rate_limit_codec::render`] formatter emits the canonical
7292 // unit suffix for. A `RateLimit` whose `:window` is anything
7293 // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7294 // programmatically (struct literals in Rust + the typed
7295 // `Duration` field) but renders to a `<n>/<k>s` fragment
7296 // (the codec's fall-through) the parser then rejects on
7297 // round-trip — silently breaking the THEORY.md §V.2.7
7298 // render-determinism contract for any consumer that
7299 // serializes-then-deserializes the typed slot. Lifting the
7300 // canonical-window invariant to a build-time gate at
7301 // `validate_politicas` makes the codec's round-trip property
7302 // a structural property of the validated typed value:
7303 // every `RateLimit` past `AplicacaoSpec::validate` has a
7304 // window the codec round-trips losslessly, so the next
7305 // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
7306 // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
7307 // §III.2 #3) reaches for `rate_limit.window` knowing the
7308 // value is in the codec's accepted set without re-validating
7309 // at the renderer layer. Same trajectory as c4213a4 (typed
7310 // WitContract endpoint/subject/slot value-shape gates) and
7311 // the b0c8389 :behavior + :upgrade-from script-path lifts:
7312 // the typed slot's valid set matches its codec's accepted
7313 // set, structurally.
7314 // Route the canonical-window shape-gate through the substrate
7315 // primitive [`RateLimit::canonical_unit`] rather than the free
7316 // module-private [`is_canonical_rate_limit_window`] predicate:
7317 // both projections resolve `Duration → Option<RateLimitUnit>`
7318 // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
7319 // arm on the closed-set typed enum), but the accessor is the
7320 // typed method every downstream consumer of the validated slot
7321 // ([`rate_limit_codec::render`]'s canonical arm above, the
7322 // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7323 // per-`:politicas :rate-limit` admission webhook, the future
7324 // per-`:contratos`-edge rate-limit-override overlay
7325 // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
7326 // production consumers of the canonical-unit axis (the codec
7327 // render and this validate gate) now key off exactly one typed
7328 // dispatch on the substrate primitive, so any future extension
7329 // to `canonical_unit` (a per-cluster canonical-window overlay
7330 // the operator pins through a future `:contratos :rate-limit
7331 // -unit-overrides` slot, a per-tenant unit-alias table the M4
7332 // CR materializer resolves per-CR) reaches both consumers by
7333 // construction rather than a coordinated rewrite of every
7334 // free-helper call site.
7335 if rl.canonical_unit().is_none() {
7336 return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
7337 window: rl.window(),
7338 });
7339 }
7340 }
7341 Ok(())
7342 }
7343
7344 /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
7345 /// A synchronous edge is any contract whose typed [`WitTarget`] is
7346 /// `Http`, `Store`, or `Capability` — the caller blocks on the
7347 /// callee, so a cycle would deadlock at runtime. Pub-sub edges
7348 /// (`WitTarget::PubSub`) are skipped: an event publisher does not
7349 /// block on its subscribers, so they can never close a sync loop.
7350 ///
7351 /// Iterative DFS with three-coloring; the reported cycle is the
7352 /// path of caixa names traversed from the back-edge target around
7353 /// to itself, in declaration order. Adjacency lists and DFS roots
7354 /// are visited in `BTreeMap` key order so the diagnostic is
7355 /// deterministic across runs.
7356 fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
7357 use std::collections::{BTreeMap, BTreeSet};
7358
7359 #[derive(Clone, Copy, PartialEq, Eq)]
7360 enum Mark {
7361 White,
7362 Gray,
7363 Black,
7364 }
7365
7366 let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
7367 for m in self.membros() {
7368 adj.entry(m.nome()).or_default();
7369 }
7370 for c in self.contratos() {
7371 // target() was already called by validate(); re-running here
7372 // keeps detect_sync_cycles self-contained for callers that
7373 // reuse it (M4 per-edge policy resolver) without revalidating.
7374 //
7375 // The pub-sub-arm check routes through the lifted
7376 // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
7377 // arm-discriminator predicate rather than a raw `matches!(…,
7378 // WitTarget::PubSub { .. })` on the variant so a future
7379 // rebrand on the axis (an M4 per-edge WIT registry split of
7380 // [`WitTarget::PubSub`] into shape-specific peers, a
7381 // per-consumer rename that the accept-set already carries)
7382 // reaches this call site through the derive rather than a
7383 // scattered per-arm `matches!` rewrite — same
7384 // `IsVariant`-derived-arm-discriminator discipline the
7385 // peer closed-set typed enums ([`crate::CaixaKind`] via
7386 // f5bba80, [`PlacementStrategy`] via 766ec63,
7387 // [`crate::supervisor::RestartStrategy`] +
7388 // [`crate::supervisor::RestartPolicy`],
7389 // [`crate::upgrade::UpgradeInstruction`] via 915a934)
7390 // already route through on the substrate's other typed-enum
7391 // arm-discriminator axes.
7392 if c.target()?.is_pubsub() {
7393 continue;
7394 }
7395 adj.entry(c.source()).or_default().insert(c.destination());
7396 }
7397
7398 let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
7399 let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
7400
7401 // Stable DFS root order — BTreeMap iteration is sorted by key.
7402 let roots: Vec<&str> = adj.keys().copied().collect();
7403
7404 // Frame: (node, sorted-neighbours snapshot, next-edge index).
7405 for root in roots {
7406 if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
7407 continue;
7408 }
7409 let root_neighbors: Vec<&str> = adj
7410 .get(root)
7411 .map(|s| s.iter().copied().collect())
7412 .unwrap_or_default();
7413 let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
7414 color.insert(root, Mark::Gray);
7415
7416 loop {
7417 // Read+advance the top frame in one borrow scope so we
7418 // can later mutate the stack (push/pop) without holding
7419 // a borrow across.
7420 let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
7421 let node = top.0;
7422 if top.2 >= top.1.len() {
7423 (node, None)
7424 } else {
7425 let nxt = top.1[top.2];
7426 top.2 += 1;
7427 (node, Some(nxt))
7428 }
7429 });
7430 let Some((node, nxt_opt)) = step else { break };
7431 let Some(nxt) = nxt_opt else {
7432 color.insert(node, Mark::Black);
7433 stack.pop();
7434 continue;
7435 };
7436 let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
7437 match nxt_color {
7438 Mark::Gray => {
7439 // Reconstruct the cycle from `node` back through
7440 // the parent chain to `nxt`, then close.
7441 let mut cycle = Vec::new();
7442 let mut cur = node;
7443 cycle.push(cur.to_string());
7444 while cur != nxt {
7445 match parent.get(cur).copied() {
7446 Some(p) => {
7447 cur = p;
7448 cycle.push(cur.to_string());
7449 }
7450 None => break,
7451 }
7452 }
7453 cycle.reverse();
7454 cycle.push(nxt.to_string());
7455 return Err(AplicacaoError::ContratoCycle { cycle });
7456 }
7457 Mark::White => {
7458 parent.insert(nxt, node);
7459 color.insert(nxt, Mark::Gray);
7460 let nxt_neighbors: Vec<&str> = adj
7461 .get(nxt)
7462 .map(|s| s.iter().copied().collect())
7463 .unwrap_or_default();
7464 stack.push((nxt, nxt_neighbors, 0));
7465 }
7466 Mark::Black => {}
7467 }
7468 }
7469 }
7470 Ok(())
7471 }
7472
7473 /// Substrate-canonical destination-facing TCP port every emitted
7474 /// per-Aplicacao artifact must key `destination`-shaped port axes
7475 /// off. Returns the typed `:entrada :port` scalar when this
7476 /// Aplicacao's `:entrada` block names `destination` under its
7477 /// `:para` axis (the destination Servico *is* the ingress apex, so
7478 /// the substrate honors the author-declared listener port
7479 /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
7480 /// fallback otherwise (every non-apex destination — the internal
7481 /// mesh Servicos `:contratos` reach across, the future per-edge
7482 /// policy resolver's per-destination probe targets, the
7483 /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
7484 /// L4 port resolver — reads the same substrate-canonical port floor
7485 /// by construction).
7486 ///
7487 /// Prior to this lift the "if :entrada matches this destination use
7488 /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
7489 /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
7490 /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
7491 /// prior to this lift), with no typed method on the substrate primitive
7492 /// that named the rule. A future per-destination port axis addition
7493 /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
7494 /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
7495 /// per-Servico listener ports land, a per-cluster override the operator
7496 /// pins through a future `:placement :default-port` slot — would have
7497 /// to be threaded through every renderer's inline cascade in lockstep
7498 /// or one consumer would silently disagree on which port a given
7499 /// destination Servico's ingress lands at. Lifting the rule to a
7500 /// typed method on the substrate primitive means the M4 CR
7501 /// materializer, the future per-edge policy resolver, and every
7502 /// downstream test-fixture navigator reach for exactly one typed
7503 /// dispatch — the resolver's accept-set moves as a unit on any
7504 /// future axis addition.
7505 ///
7506 /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
7507 /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
7508 /// the typed primitive, thin projections at each consumer"
7509 /// discipline lifts on the sibling `:contratos` payload / `:politicas
7510 /// :rate-limit` unit-suffix axes; extends the discipline onto the
7511 /// destination-facing port-resolution axis every per-Aplicacao
7512 /// L4-fallback renderer consumes.
7513 #[must_use]
7514 pub fn port_for_destination(&self, destination: &str) -> u16 {
7515 // Route the per-`:entrada` composite-reference read through
7516 // the lifted [`AplicacaoSpec::entrada`] accessor rather than
7517 // the raw `self.entrada.as_ref()` field access — the
7518 // per-destination L4-port fallback resolver's composite-
7519 // projection seed is now the canonical read-side surface
7520 // every per-Aplicacao entrada consumer routes through, peer
7521 // of the sibling `validate` per-`:entrada` shape-and-
7522 // membership gate migration on the same outer-composite
7523 // axis.
7524 // Route the per-`:entrada` apex-destination membership probe
7525 // through the lifted [`Entrada::destination`] accessor rather
7526 // than the raw `e.para == destination` field access — the last
7527 // un-lifted `.para` production-code read site on the per-
7528 // `:entrada` `:para` axis, sibling to the four caixa-core
7529 // consumer sites the peer 15ddd8c converge already routed
7530 // through the accessor (the three
7531 // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
7532 // membership gate sites: the `validate_entrada_para` DNS-1123
7533 // shape gate, the per-`:membros` membership lookup, and the
7534 // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
7535 // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
7536 // `entrada.para`-projection converge at
7537 // caixa-core/src/render.rs (the `gateway_api_http_route_name`
7538 // route-name projection site). Prior to this converge the
7539 // `port_for_destination` resolver was the solitary consumer
7540 // bypassing the typed dispatch on the `.para` axis — the two
7541 // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
7542 // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
7543 // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
7544 // reach through the same accessor family compose with this
7545 // resolver at the emit boundary via the apex-identity
7546 // invariant `spec.port_for_destination(entrada.destination())
7547 // == entrada.port` the sibling
7548 // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
7549 // pin pins across four permutations. A future extension of the
7550 // `:entrada :para` axis to a richer author surface (a per-
7551 // cluster alias overlay the operator pins through a future
7552 // `:placement`-scoped slot, a namespace-qualified rewrite the
7553 // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
7554 // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
7555 // §III.2 acknowledges) that lands on the accessor would silently
7556 // disagree between this resolver and the two `caixa-mesh` emit
7557 // sites — an author-declared `:para "cart"` value the accessor
7558 // rewrote to `"cart-v2"` under a future canary arm would leave
7559 // the resolver's membership arm falling through to
7560 // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
7561 // `.para`) while the peer emit-site consumers landed on the
7562 // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
7563 // silently disagreed on which destination port a given typed
7564 // `:entrada` resolves to at cluster-apply time. Pinned by the
7565 // drift-detection test
7566 // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
7567 // below.
7568 self.entrada()
7569 .filter(|e| e.destination() == destination)
7570 .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
7571 }
7572}
7573
7574/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
7575/// entry may name the Aplicacao's own `:nome`.
7576///
7577/// An Aplicacao that lists itself as a member is a degenerate self-edge in
7578/// the typed graph — the application graph is a DAG rooted at the Aplicacao
7579/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
7580/// Servicos that compose the app; an Aplicacao is never its own constituent),
7581/// and the lacre pipeline's closure-resolution would otherwise be handed a
7582/// node that is its own parent: a one-node cycle it either rejects far from
7583/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
7584/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
7585/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
7586/// label + lacre closure root), a member whose `:caixa` equals the
7587/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
7588/// peer.
7589///
7590/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
7591/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
7592/// gate `validate_upgrade_from_against_versao` and the supervision-tree
7593/// self-parent gate `crate::supervisor::validate_no_self_supervision`
7594/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
7595/// not a tree/mesh edge" discipline, here on the second typed-graph axis
7596/// (the Aplicacao :membros set; the supervision-tree :children list was the
7597/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
7598/// every validated Supervisor's children are distinct from its `:nome`,
7599/// every validated Aplicacao's membros are distinct from its `:nome`. The
7600/// transitive consequence is that `:entrada :para` and `:contratos`
7601/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
7602/// name the Aplicacao itself, without re-deriving the partition.
7603pub fn validate_no_self_membership(
7604 membros: &[Membro],
7605 parent_nome: &str,
7606) -> Result<(), AplicacaoError> {
7607 for m in membros {
7608 if m.nome() == parent_nome {
7609 return Err(AplicacaoError::MembroIsSelfAplicacao {
7610 caixa: parent_nome.to_string(),
7611 });
7612 }
7613 }
7614 Ok(())
7615}
7616
7617#[derive(Debug, Error, PartialEq, Eq)]
7618pub enum AplicacaoError {
7619 #[error("Aplicacao must declare at least one :membros entry")]
7620 NoMembros,
7621 #[error(
7622 ":membros entry has empty :caixa (every member must name a Servico; \
7623 omit the entry instead of carrying an empty name)"
7624 )]
7625 MembroCaixaEmpty,
7626 #[error(
7627 ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
7628 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
7629 name / label value the member name lands in; use a lowercase \
7630 alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
7631 )]
7632 MembroCaixaInvalid { caixa: String, reason: String },
7633 #[error(
7634 ":membros entry {caixa:?} has empty :versao (every member must pin a \
7635 semver constraint that resolves through the lacre pipeline)"
7636 )]
7637 MembroVersaoEmpty { caixa: String },
7638 #[error(
7639 ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
7640 requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
7641 `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
7642 carries; the lacre pipeline resolves both through the same parser)"
7643 )]
7644 MembroVersaoInvalid {
7645 caixa: String,
7646 versao: String,
7647 reason: String,
7648 },
7649 #[error(
7650 ":membros entry {caixa:?} appears more than once (the graph node set \
7651 is a set, not a multiset; duplicate members produce duplicate \
7652 programs.yaml entries and ambiguous :contratos membership lookups)"
7653 )]
7654 MembroDuplicate { caixa: String },
7655 #[error(
7656 "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
7657 never its own constituent Servico (the application graph is a DAG rooted \
7658 at the Aplicacao; :membros names the *other* caixas that compose the \
7659 app, not the app itself). Since every :nome is a globally-unique \
7660 substrate identity, a member naming the Aplicacao's own :nome is a \
7661 one-node lacre-closure recursion, not a coincidentally-named peer; \
7662 drop the self-referential :membros entry or rename it to the actual \
7663 constituent caixa."
7664 )]
7665 MembroIsSelfAplicacao { caixa: String },
7666 #[error(
7667 "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
7668 caixa declared in :membros; omit the contract or fill the {slot} field with a \
7669 member name)"
7670 )]
7671 ContratoCaixaEmpty { slot: &'static str },
7672 #[error(
7673 "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
7674 :contratos {slot} value names a member of :membros, which is itself a \
7675 DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
7676 object the member name lands in — Service, Pod, identity-based Cilium \
7677 selector; use a lowercase alphanumeric + hyphen identifier like \
7678 `\"checkout\"` or `\"cart-v2\"`)"
7679 )]
7680 ContratoCaixaInvalid {
7681 slot: &'static str,
7682 caixa: String,
7683 reason: String,
7684 },
7685 #[error("contrato references caixa {caixa:?} not declared in :membros")]
7686 ContratoMemberMissing { caixa: String },
7687 #[error(
7688 "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
7689 entry is an inter-Servico contract whose :de and :para must name distinct \
7690 :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
7691 the contract, or point :para at the member it actually calls)"
7692 )]
7693 ContratoSelfLoop { caixa: String, wit: String },
7694 #[error("contrato {de:?} → {para:?} has empty :wit")]
7695 EmptyWit { de: String, para: String },
7696 #[error(
7697 "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
7698 {reason} (the substrate dispatches `:wit` values on the canonical \
7699 lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
7700 `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
7701 demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
7702 kebab-case identifier per segment)"
7703 )]
7704 ContratoWitInvalid {
7705 de: String,
7706 para: String,
7707 wit: String,
7708 reason: String,
7709 },
7710 #[error(
7711 ":entrada :para is empty (every :entrada must route to a caixa declared in \
7712 :membros; fill the :para field with a member name)"
7713 )]
7714 EntradaParaEmpty,
7715 #[error(
7716 ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
7717 :entrada :para value names a member of :membros, which is itself a DNS-1123 \
7718 label per the K8s apiserver's `metadata.name` rule on every object the \
7719 member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
7720 Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
7721 `\"checkout\"` or `\"cart-v2\"`)"
7722 )]
7723 EntradaParaInvalid { para: String, reason: String },
7724 #[error(":entrada routes to caixa {para:?} not declared in :membros")]
7725 EntradaMemberMissing { para: String },
7726 #[error(":entrada must declare a non-empty :host")]
7727 EmptyEntradaHost,
7728 #[error(
7729 ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
7730 (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
7731 `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
7732 like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
7733 )]
7734 EntradaHostInvalid { host: String, reason: String },
7735 #[error(":entrada :port must be in 1..=65535, got 0")]
7736 EntradaPortZero,
7737 #[error(":entrada :paths entry is empty (use the empty list to match all)")]
7738 EntradaPathEmpty,
7739 #[error(
7740 ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
7741 )]
7742 EntradaPathNotAbsolute { path: String },
7743 #[error(
7744 ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
7745 value: {reason} (the K8s apiserver enforces the same shape on \
7746 `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
7747 single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
7748 requires percent-encoding `%XX` for non-ASCII and whitespace)"
7749 )]
7750 EntradaPathInvalid { path: String, reason: String },
7751 #[error(":entrada :paths entry {path:?} appears more than once")]
7752 EntradaPathDuplicate { path: String },
7753 #[error(
7754 ":placement {estrategia} requires at least one :clusters entry \
7755 (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
7756 )]
7757 PlacementWithoutClusters { estrategia: PlacementStrategy },
7758 #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
7759 PlacementClusterEmpty,
7760 #[error(
7761 ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
7762 (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
7763 in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
7764 future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
7765 — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
7766 identifier like `\"rio\"` or `\"mar-east\"`)"
7767 )]
7768 PlacementClusterInvalid { cluster: String, reason: String },
7769 #[error(":placement :clusters entry {cluster:?} appears more than once")]
7770 PlacementClusterDuplicate { cluster: String },
7771 #[error(
7772 ":placement :affinity must be non-empty when set (omit :affinity to express \
7773 `no placement hint`)"
7774 )]
7775 PlacementAffinityEmpty,
7776 #[error(
7777 ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
7778 (placement hints land verbatim in the M3 Adaptive compression overlay's \
7779 `placement.affinity` field and in every future M4 placement-engine routing \
7780 axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
7781 selector — both enforce the DNS-1123 label rule on admission; use a \
7782 lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
7783 `\"low-latency\"`, or `\"anti-affinity\"`)"
7784 )]
7785 PlacementAffinityInvalid { affinity: String, reason: String },
7786 #[error(":placement Sharded requires :shard-key")]
7787 ShardedWithoutKey,
7788 #[error(
7789 ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
7790 hashes every entity onto the same shard, defeating sharding entirely)"
7791 )]
7792 ShardedKeyEmpty,
7793 #[error(
7794 ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
7795 entity-id extractor expression: {reason} (the future M4 Akka-style \
7796 cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
7797 as a single-token property reference and hashes the extracted entity ID \
7798 to compute shard placement; use a printable-ASCII extractor expression \
7799 like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
7800 `\"${{tenant}}\"`)"
7801 )]
7802 ShardKeyInvalid { shard_key: String, reason: String },
7803 #[error(
7804 ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
7805 Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
7806 convention); :estrategia Replicated runs every cluster active-active and \
7807 :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
7808 distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
7809 to :estrategia Sharded if hash-keyed routing is the intent"
7810 )]
7811 ShardKeyOnNonSharded {
7812 estrategia: PlacementStrategy,
7813 shard_key: String,
7814 },
7815 #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
7816 ContratoMissingTarget {
7817 de: String,
7818 para: String,
7819 wit: String,
7820 expected: &'static str,
7821 },
7822 #[error(
7823 "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
7824 expected `:{expected}` only"
7825 )]
7826 ContratoWrongTarget {
7827 de: String,
7828 para: String,
7829 wit: String,
7830 expected: &'static str,
7831 },
7832 #[error(
7833 "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
7834 like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
7835 that matches no traffic and silently drops every request)"
7836 )]
7837 ContratoEndpointEmpty { de: String, para: String },
7838 #[error(
7839 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
7840 (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
7841 :entrada :paths)"
7842 )]
7843 ContratoEndpointNotAbsolute {
7844 de: String,
7845 para: String,
7846 endpoint: String,
7847 },
7848 #[error(
7849 "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
7850 Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
7851 emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
7852 caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
7853 shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
7854 like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
7855 and whitespace)"
7856 )]
7857 ContratoEndpointInvalid {
7858 de: String,
7859 para: String,
7860 endpoint: String,
7861 reason: String,
7862 },
7863 #[error(
7864 "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
7865 subject is a no-op subscribe; omit :subject only if the WIT world is not \
7866 pub-sub-shaped)"
7867 )]
7868 ContratoSubjectEmpty { de: String, para: String },
7869 #[error(
7870 "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
7871 NATS subject: {reason} (the NATS server's subject parser enforces the \
7872 same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
7873 single-token and `>` multi-token wildcards — at publish/subscribe time; \
7874 use a token-by-token form like `\"checkout.events.charge.failed\"` or \
7875 `\"orders.*.completed\"` — a malformed subject silently drops every \
7876 message at runtime far from the source caixa.lisp)"
7877 )]
7878 ContratoSubjectInvalid {
7879 de: String,
7880 para: String,
7881 subject: String,
7882 reason: String,
7883 },
7884 #[error(
7885 "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
7886 addresses the bucket root, defeating the per-key isolation the slot exists \
7887 for; omit :slot only if the WIT world is not store-shaped)"
7888 )]
7889 ContratoSlotEmpty { de: String, para: String },
7890 #[error(
7891 "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
7892 WASI keyvalue store slot template: {reason} (the substrate enforces \
7893 the printable-ASCII intersection-floor every kv backend admits — \
7894 use a single-token path / template expression like `\"checkout/$orderId\"`, \
7895 `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
7896 percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
7897 slot either gets rejected on write by strict backends or silently \
7898 corrupts the next read on permissive ones, far from the source caixa.lisp)"
7899 )]
7900 ContratoSlotInvalid {
7901 de: String,
7902 para: String,
7903 slot: String,
7904 reason: String,
7905 },
7906 #[error(
7907 "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
7908 or an event-sourced indirection (MESH-COMPOSITION §III.3)",
7909 cycle.join(" → ")
7910 )]
7911 ContratoCycle { cycle: Vec<String> },
7912 #[error(
7913 ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
7914 than once (the typed graph edges are a set, not a multiset; duplicate \
7915 contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
7916 values that K8s admission rejects far from the source caixa.lisp)"
7917 )]
7918 ContratoDuplicate {
7919 de: String,
7920 para: String,
7921 wit: String,
7922 target: String,
7923 },
7924 #[error(
7925 ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
7926 contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
7927 express `no per-call deadline on this axis`"
7928 )]
7929 PolicyTimeoutZero,
7930 #[error(
7931 ":politicas :retries must be > 0 when set; omit :retries to express \
7932 `no retries on transient failure`"
7933 )]
7934 PolicyRetriesZero,
7935 #[error(
7936 ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
7937 (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
7938 retry policy into a thundering-herd amplification vector on transient \
7939 failure (one caller request fans out to `(retries+1)^depth` server-side \
7940 calls across the synchronous-:contratos subgraph), exactly the failure \
7941 mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
7942 Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
7943 or omit :retries to disable retries entirely"
7944 )]
7945 PolicyRetriesExceedsCap { retries: u32 },
7946 #[error(
7947 ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
7948 breaker trips on the first call); omit :circuit-breaker to disable it"
7949 )]
7950 PolicyBreakerZeroFailures,
7951 #[error(
7952 ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
7953 mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
7954 above this cap turns the typed breaker policy into a no-op: the trip \
7955 threshold is structurally so high that no realistic failures-per-:window \
7956 traffic shape can reach it, so the breaker never trips and every typed-slot \
7957 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
7958 Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
7959 structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
7960 Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
7961 omit :circuit-breaker to disable the breaker entirely"
7962 )]
7963 PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
7964 #[error(
7965 ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
7966 tracks no failures); omit :circuit-breaker to disable it"
7967 )]
7968 PolicyBreakerZeroWindow,
7969 #[error(
7970 ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
7971 request); omit :rate-limit to disable rate limiting"
7972 )]
7973 PolicyRateLimitZero,
7974 #[error(
7975 ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
7976 (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
7977 rate-limit policy into a no-op limiter: the token-bucket capacity is \
7978 structurally so high that no realistic per-edge traffic shape can drain it, \
7979 so the limiter never trips and every typed-slot consumer (the future \
7980 CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
7981 local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
7982 that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
7983 Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
7984 Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
7985 Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
7986 to disable rate limiting entirely"
7987 )]
7988 PolicyRateLimitExceedsCap { rate: u32 },
7989 #[error(
7990 ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
7991 the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
7992 rate-limit codec round-trips losslessly; got {window:?} which renders to a \
7993 non-round-trippable form (omit :rate-limit to disable, or pick one of the \
7994 three canonical windows)"
7995 )]
7996 PolicyRateLimitWindowNotCanonical { window: Duration },
7997 #[error(
7998 ":politicas :timeout must be an integer number of milliseconds — the canonical \
7999 authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8000 duration codec round-trips losslessly; got {timeout:?} which carries a \
8001 sub-millisecond residue that either truncates to a different `Duration` on \
8002 re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8003 to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8004 zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8005 (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8006 )]
8007 PolicyTimeoutNotCanonical { timeout: Duration },
8008 #[error(
8009 ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8010 (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8011 per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8012 overlays carry a deadline so long no realistic synchronous-:contratos \
8013 traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8014 CSE invariant degenerates to enforcement only at the per-Servico \
8015 `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8016 `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8017 (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8018 ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8019 maxes out at the same `3600s` ceiling) or omit :timeout to express \
8020 `no per-call deadline on this axis` (the synchronous-call deadline then \
8021 relies entirely on the per-Servico `:limits :wall-clock` axis)"
8022 )]
8023 PolicyTimeoutExceedsCap { timeout: Duration },
8024 #[error(
8025 ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8026 the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8027 the shared duration codec round-trips losslessly; got {window:?} which carries a \
8028 sub-millisecond residue that either truncates to a different `Duration` on \
8029 re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8030 Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8031 )]
8032 PolicyBreakerWindowNotCanonical { window: Duration },
8033 #[error(
8034 ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8035 (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8036 rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8037 is structurally so long that transient failures are never forgotten, the breaker \
8038 trips once and stays tripped for the lifetime of the component, and every typed-slot \
8039 consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8040 outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8041 Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8042 default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8043 the breaker entirely"
8044 )]
8045 PolicyBreakerWindowExceedsCap { window: Duration },
8046}
8047
8048#[cfg(test)]
8049mod tests {
8050 use super::*;
8051
8052 fn membro(name: &str, ver: &str) -> Membro {
8053 Membro {
8054 caixa: name.into(),
8055 versao: ver.into(),
8056 }
8057 }
8058
8059 fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8060 WitContract {
8061 de: de.into(),
8062 para: para.into(),
8063 wit: "wasi:http/proxy".into(),
8064 endpoint: Some(ep.into()),
8065 subject: None,
8066 slot: None,
8067 }
8068 }
8069
8070 fn three_member_spec() -> AplicacaoSpec {
8071 AplicacaoSpec {
8072 membros: vec![
8073 membro("catalog", "^0.1"),
8074 membro("cart", "^0.1"),
8075 membro("payment", "^0.2"),
8076 ],
8077 contratos: vec![
8078 contract_http("cart", "catalog", "/products/:id"),
8079 contract_http("cart", "payment", "/charge"),
8080 ],
8081 politicas: MeshPolicy {
8082 timeout: Some(Duration::from_secs(30)),
8083 retries: Some(3),
8084 mtls_required: Some(true),
8085 ..Default::default()
8086 },
8087 placement: Placement {
8088 estrategia: PlacementStrategy::Replicated,
8089 clusters: vec!["rio".into(), "mar".into()],
8090 affinity: Some("data-locality".into()),
8091 shard_key: None,
8092 },
8093 entrada: Some(Entrada {
8094 host: "checkout.quero.cloud".into(),
8095 para: "cart".into(),
8096 paths: vec!["/api/cart".into(), "/api/products".into()],
8097 port: 8080,
8098 }),
8099 }
8100 }
8101
8102 #[test]
8103 fn happy_path_validates() {
8104 three_member_spec().validate().unwrap();
8105 }
8106
8107 #[test]
8108 fn rejects_empty_membros() {
8109 let mut s = three_member_spec();
8110 s.membros = vec![];
8111 assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8112 }
8113
8114 #[test]
8115 fn rejects_empty_membro_caixa() {
8116 // A `:caixa ""` entry has no name to render into programs.yaml
8117 // and no caixa.lisp to resolve at lacre time.
8118 let mut s = three_member_spec();
8119 s.membros[1].caixa = String::new();
8120 assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8121 }
8122
8123 #[test]
8124 fn rejects_empty_membro_versao() {
8125 // A `:versao ""` entry can't pin a semver constraint, so the
8126 // lacre pipeline fails far from the source.
8127 let mut s = three_member_spec();
8128 s.membros[2].versao = String::new();
8129 let err = s.validate().unwrap_err();
8130 assert!(
8131 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8132 "got {err:?}"
8133 );
8134 }
8135
8136 #[test]
8137 fn rejects_duplicate_membro_caixa() {
8138 // Two `:membros` entries with the same `:caixa` collapse to one
8139 // node in the membership HashSet, which masks `:contratos`
8140 // membership errors and produces duplicate programs.yaml entries.
8141 let mut s = three_member_spec();
8142 s.membros.push(membro("cart", "^0.2"));
8143 let err = s.validate().unwrap_err();
8144 assert!(
8145 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8146 "got {err:?}"
8147 );
8148 }
8149
8150 #[test]
8151 fn rejects_invalid_membro_versao_requirement() {
8152 // The fail-before-pass-after pin: a non-empty but malformed
8153 // semver requirement (`"^bad-version"`) silently passed
8154 // `validate()` on every pre-gate codebase because the prior
8155 // shape only refused the empty string. The parse failure
8156 // surfaced far downstream at lacre-resolve time with a
8157 // `semver::Error` that didn't name which `:membros` entry
8158 // carried the typo. The new gate moves the check to caixa-build
8159 // time at the source caixa.lisp.
8160 let mut s = three_member_spec();
8161 s.membros[2].versao = "^bad-version".into();
8162 let err = s.validate().unwrap_err();
8163 assert!(
8164 matches!(
8165 err,
8166 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8167 if caixa == "payment" && versao == "^bad-version"
8168 ),
8169 "got {err:?}"
8170 );
8171 }
8172
8173 #[test]
8174 fn rejects_membro_versao_with_double_caret_typo() {
8175 // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8176 // Cargo-shaped requirement on first glance but fails the parser
8177 // because semver doesn't accept stacked operators. Pin this
8178 // adjacent-shape footgun explicitly so a future relaxation that
8179 // accepts "looks-canonical-but-isn't" forms surfaces here.
8180 let mut s = three_member_spec();
8181 s.membros[0].versao = "^^0.1".into();
8182 let err = s.validate().unwrap_err();
8183 assert!(
8184 matches!(
8185 err,
8186 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8187 if caixa == "catalog" && versao == "^^0.1"
8188 ),
8189 "got {err:?}"
8190 );
8191 }
8192
8193 #[test]
8194 fn rejects_membro_versao_with_v_prefixed_tag() {
8195 // `"v0.1"` is the canonical "git-tag-shape leaking into the
8196 // semver requirement slot" typo — an author copies the
8197 // publish-side git-tag string verbatim into `:versao`, but
8198 // Cargo's semver parser rejects the leading `v` (only digits +
8199 // canonical operators are valid in the major-version
8200 // position). The gate's diagnostic names which member entry
8201 // carried the v-prefix so the fix is one edit, not a grep
8202 // through every member's `:versao`. (Note: bare `x`-glob
8203 // shorthands like `^0.1.x` are *accepted* by the semver crate
8204 // as an `*` wildcard on the patch axis — they're a Cargo-side
8205 // valid shape, not a typo, so the gate intentionally lets them
8206 // through.)
8207 let mut s = three_member_spec();
8208 s.membros[1].versao = "v0.1".into();
8209 let err = s.validate().unwrap_err();
8210 assert!(
8211 matches!(
8212 err,
8213 AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8214 if caixa == "cart" && versao == "v0.1"
8215 ),
8216 "got {err:?}"
8217 );
8218 }
8219
8220 #[test]
8221 fn accepts_canonical_membro_versao_forms() {
8222 // The four Cargo-shaped requirement forms `:deps :versao`
8223 // already accepts via `crate::parse_requirement` must pass the
8224 // membros gate without re-validating at the resolver layer.
8225 // Pin every leg so a future tightening of the canonical set
8226 // surfaces here as a test failure.
8227 for form in [
8228 "^0.1", // caret — minor-range pin (the most common shape)
8229 "~0.1.2", // tilde — patch-range pin
8230 "0.1.0", // exact — single-version pin
8231 "*", // wildcard — explicitly any-version (semver::VersionReq::STAR)
8232 ">=0.1, <2", // multi-range — comma-separated comparators
8233 ] {
8234 let mut s = three_member_spec();
8235 for m in &mut s.membros {
8236 m.versao = form.into();
8237 }
8238 s.validate()
8239 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8240 }
8241 }
8242
8243 #[test]
8244 fn membro_versao_empty_takes_precedence_over_invalid() {
8245 // Order pin: the existing `MembroVersaoEmpty` diagnostic
8246 // (which doesn't try to parse) fires before the new
8247 // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8248 // `:versao` keeps its narrower error message — `parse_requirement`
8249 // would also reject `""`, but the empty-string arm is the more
8250 // self-locating diagnostic for the author.
8251 let mut s = three_member_spec();
8252 s.membros[1].versao = String::new();
8253 let err = s.validate().unwrap_err();
8254 assert!(
8255 matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8256 "got {err:?}"
8257 );
8258 }
8259
8260 #[test]
8261 fn membro_versao_invalid_fires_before_duplicate_check() {
8262 // Order pin: a malformed requirement on a non-duplicate entry
8263 // surfaces *its own* diagnostic (which names the offending
8264 // `:versao` string), even when a later entry would otherwise
8265 // collapse onto an earlier name. The per-entry shape gate runs
8266 // inline before the duplicate-key insert, parallel to
8267 // `membros_validation_runs_before_contratos_membership_check`
8268 // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8269 let mut s = three_member_spec();
8270 s.membros[0].versao = "^bad".into();
8271 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8272 let err = s.validate().unwrap_err();
8273 assert!(
8274 matches!(
8275 err,
8276 AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8277 ),
8278 "got {err:?}"
8279 );
8280 }
8281
8282 #[test]
8283 fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8284 // The diagnostic-shape pin: the error names the offending
8285 // `:versao` value verbatim so the author can grep their
8286 // caixa.lisp without re-running the build, and carries a
8287 // non-empty `reason` from `semver::VersionReq::parse` so the
8288 // parser's own wording flows through to the diagnostic.
8289 let mut s = three_member_spec();
8290 s.membros[2].versao = "not-a-req".into();
8291 let err = s.validate().unwrap_err();
8292 let AplicacaoError::MembroVersaoInvalid {
8293 caixa,
8294 versao,
8295 reason,
8296 } = err
8297 else {
8298 panic!("expected MembroVersaoInvalid, got other variant");
8299 };
8300 assert_eq!(caixa, "payment");
8301 assert_eq!(versao, "not-a-req");
8302 assert!(
8303 !reason.is_empty(),
8304 "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
8305 );
8306 }
8307
8308 #[test]
8309 fn membro_versao_invalid_runs_before_contratos_check() {
8310 // A malformed `:versao` on any member must surface its own
8311 // diagnostic (which names *which* member to fix) before any
8312 // `:contratos` membership lookup raises `ContratoMemberMissing`.
8313 // The `:contratos` gate runs after `validate_membros`, so this
8314 // is structurally guaranteed — pin it explicitly so a future
8315 // refactor that reorders the gates surfaces here.
8316 let mut s = three_member_spec();
8317 s.membros[1].versao = "^^0.1".into();
8318 // Add a contrato whose `:para` doesn't exist — would normally
8319 // raise ContratoMemberMissing at the membership lookup, but
8320 // the membros gate must fire first.
8321 s.contratos
8322 .push(contract_http("cart", "phantom", "/never-reached"));
8323 let err = s.validate().unwrap_err();
8324 assert!(
8325 matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
8326 "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
8327 );
8328 }
8329
8330 #[test]
8331 fn membros_validation_runs_before_contratos_membership_check() {
8332 // If `:membros` carries a duplicate, the membership-collapse
8333 // would silently accept a `:contratos :para "phantom"` so long
8334 // as some entry hashes to "phantom". Pinning order: the
8335 // duplicate-membros error fires first, regardless of whether
8336 // contratos reference real members.
8337 let mut s = three_member_spec();
8338 s.membros = vec![
8339 membro("cart", "^0.1"),
8340 membro("cart", "^0.2"),
8341 membro("catalog", "^0.1"),
8342 membro("payment", "^0.1"),
8343 ];
8344 let err = s.validate().unwrap_err();
8345 assert!(
8346 matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8347 "got {err:?}"
8348 );
8349 }
8350
8351 #[test]
8352 fn distinct_membros_validate() {
8353 // Pin the happy-path: every `:membros` entry has a non-empty
8354 // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
8355 // The fixture already satisfies this; this test makes the
8356 // invariant explicit so a future refactor of the fixture can't
8357 // silently break the guarantee.
8358 three_member_spec().validate().unwrap();
8359 }
8360
8361 // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
8362
8363 #[test]
8364 fn rejects_membro_caixa_with_uppercase() {
8365 // The canonical "I copied the Servico's display name verbatim"
8366 // typo — caixa names are lowercase per K8s DNS-1123 label rule,
8367 // but author tools often round-trip a TitleCase or CamelCase
8368 // identifier from an ADR or a sketch. Pin the diagnostic names
8369 // the offending name and suggests the lower-cased fix in one
8370 // edit, mirroring the `rejects_entrada_host_with_uppercase`
8371 // gate's shape (c7d05ec).
8372 let mut s = three_member_spec();
8373 s.membros[1].caixa = "Cart".into();
8374 let err = s.validate().unwrap_err();
8375 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8376 panic!("expected MembroCaixaInvalid, got other variant");
8377 };
8378 assert_eq!(caixa, "Cart");
8379 assert!(
8380 reason.contains("uppercase"),
8381 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8382 );
8383 assert!(
8384 reason.contains("\"cart\""),
8385 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
8386 );
8387 }
8388
8389 #[test]
8390 fn rejects_membro_caixa_with_underscore() {
8391 // The canonical "I'm thinking of a Python module / Postgres
8392 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
8393 // label schema. K8s rejects `metadata.name: my_cart` at admission
8394 // time with an opaque `field is invalid` (no source-citing
8395 // diagnostic). The gate moves it to caixa-build time.
8396 let mut s = three_member_spec();
8397 s.membros[0].caixa = "my_cart".into();
8398 let err = s.validate().unwrap_err();
8399 assert!(
8400 matches!(
8401 err,
8402 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8403 if caixa == "my_cart" && reason.contains('_')
8404 ),
8405 "got {err:?}"
8406 );
8407 }
8408
8409 #[test]
8410 fn rejects_membro_caixa_with_dot() {
8411 // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
8412 // subdomain — even though K8s `metadata.name` itself accepts
8413 // dots (DNS-1123 subdomain rule), this string also lands as a
8414 // K8s Service name (DNS-1035 label — no dots) and as a label
8415 // value on identity-based Cilium selectors. The strictest floor
8416 // among the use sites wins. The "I want to namespace my member
8417 // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
8418 let mut s = three_member_spec();
8419 s.membros[2].caixa = "team.cart".into();
8420 let err = s.validate().unwrap_err();
8421 assert!(
8422 matches!(
8423 err,
8424 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8425 if caixa == "team.cart" && reason.contains('.')
8426 ),
8427 "got {err:?}"
8428 );
8429 }
8430
8431 #[test]
8432 fn rejects_membro_caixa_with_leading_hyphen() {
8433 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
8434 // with an alphanumeric. The K8s apiserver rejects `-cart`
8435 // outright; the renderer would emit a `metadata.name: "-cart"`
8436 // that fails admission far from the source caixa.lisp.
8437 let mut s = three_member_spec();
8438 s.membros[0].caixa = "-cart".into();
8439 let err = s.validate().unwrap_err();
8440 assert!(
8441 matches!(
8442 err,
8443 AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8444 if caixa == "-cart" && reason.contains("start and end")
8445 ),
8446 "got {err:?}"
8447 );
8448 }
8449
8450 #[test]
8451 fn rejects_membro_caixa_with_trailing_hyphen() {
8452 // The symmetric arm of the boundary rule. Pin separately so
8453 // both ends of the label are covered against a future relaxation
8454 // that only checks one boundary.
8455 let mut s = three_member_spec();
8456 s.membros[1].caixa = "cart-".into();
8457 let err = s.validate().unwrap_err();
8458 assert!(
8459 matches!(
8460 err,
8461 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8462 if caixa == "cart-"
8463 ),
8464 "got {err:?}"
8465 );
8466 }
8467
8468 #[test]
8469 fn rejects_membro_caixa_with_unicode() {
8470 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8471 // (`xn--…`) by the author before it reaches K8s. The byte-by-
8472 // byte ASCII validity check rejects multi-byte UTF-8 sequences
8473 // by the first byte that fails the `[a-z0-9-]` predicate.
8474 let mut s = three_member_spec();
8475 s.membros[2].caixa = "café".into();
8476 let err = s.validate().unwrap_err();
8477 assert!(
8478 matches!(
8479 err,
8480 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8481 if caixa == "café"
8482 ),
8483 "got {err:?}"
8484 );
8485 }
8486
8487 #[test]
8488 fn rejects_membro_caixa_with_whitespace() {
8489 // Whitespace is the canonical "I pasted from a sketch / doc"
8490 // footgun. The apiserver rejects every `metadata.name` value
8491 // carrying whitespace; pin the gate fires at the right boundary.
8492 let mut s = three_member_spec();
8493 s.membros[0].caixa = "my cart".into();
8494 let err = s.validate().unwrap_err();
8495 assert!(
8496 matches!(
8497 err,
8498 AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
8499 if caixa == "my cart"
8500 ),
8501 "got {err:?}"
8502 );
8503 }
8504
8505 #[test]
8506 fn rejects_membro_caixa_too_long() {
8507 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
8508 // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
8509 // exactly. The gate's reason names both the cap and the actual
8510 // length so the author can shorten in one edit.
8511 let mut s = three_member_spec();
8512 let too_long = "a".repeat(64);
8513 s.membros[1].caixa = too_long.clone();
8514 let err = s.validate().unwrap_err();
8515 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8516 panic!("expected MembroCaixaInvalid");
8517 };
8518 assert_eq!(caixa, too_long);
8519 assert!(
8520 reason.contains("63") && reason.contains("64"),
8521 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
8522 );
8523 }
8524
8525 #[test]
8526 fn membro_caixa_max_length_validates() {
8527 // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
8528 // so a future tightening (e.g. dropping to 62) surfaces here as
8529 // a regression, mirroring `entrada_host_max_length_validates`
8530 // (c7d05ec).
8531 let mut s = three_member_spec();
8532 s.membros[2].caixa = "a".repeat(63);
8533 s.entrada.as_mut().unwrap().para = "a".repeat(63);
8534 // remove contratos referencing the renamed member; they'd
8535 // raise ContratoMemberMissing otherwise
8536 s.contratos
8537 .retain(|c| c.de != "payment" && c.para != "payment");
8538 s.validate().unwrap();
8539 }
8540
8541 #[test]
8542 fn accepts_canonical_membro_caixa_forms() {
8543 // The DNS-1123 label shapes a caixa author is realistically
8544 // going to write: single-word lowercase, hyphen-joined, ending
8545 // in a digit-suffixed version (`cart-v2`), starting with a
8546 // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
8547 // DNS-1035 which requires a letter at position 0), single-
8548 // character (`a` — boundary). Pin every leg so a future
8549 // tightening that bans (e.g.) digit-start identifiers surfaces
8550 // here.
8551 for form in [
8552 "checkout",
8553 "cart",
8554 "cart-v2",
8555 "a",
8556 "c0",
8557 "3rd-party-shim",
8558 "x-1-2-3-4",
8559 ] {
8560 let mut s = three_member_spec();
8561 // Renaming a member also requires updating downstream refs;
8562 // drop everything else and rebuild a minimal spec around
8563 // just the one renamed member.
8564 s.membros = vec![membro(form, "^0.1")];
8565 s.contratos = vec![];
8566 s.entrada = None;
8567 s.validate()
8568 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8569 }
8570 }
8571
8572 #[test]
8573 fn membro_caixa_empty_takes_precedence_over_invalid() {
8574 // Order pin: the existing `MembroCaixaEmpty` diagnostic
8575 // (which doesn't try to parse) fires before the new
8576 // `MembroCaixaInvalid` parse-side diagnostic, so an empty
8577 // `:caixa` keeps its narrower error message — the new gate
8578 // would also reject `""`, but the empty-string arm is the more
8579 // self-locating diagnostic for the author. Mirrors the
8580 // `entrada_host_empty_takes_precedence_over_invalid` pin
8581 // (c7d05ec).
8582 let mut s = three_member_spec();
8583 s.membros[1].caixa = String::new();
8584 let err = s.validate().unwrap_err();
8585 assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
8586 }
8587
8588 #[test]
8589 fn membro_caixa_invalid_fires_before_versao_check() {
8590 // Order pin: an invalid-shape `:caixa` surfaces *its own*
8591 // diagnostic (which names the offending caixa name), even when
8592 // the same entry's `:versao` is also empty/invalid. The shape
8593 // gate runs first because the diagnostic is more self-locating —
8594 // an empty/invalid `:versao` on an invalid-shape caixa name is
8595 // a downstream-fix-after-the-caixa-rename concern.
8596 let mut s = three_member_spec();
8597 s.membros[1].caixa = "Cart".into();
8598 s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
8599 let err = s.validate().unwrap_err();
8600 assert!(
8601 matches!(
8602 err,
8603 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
8604 ),
8605 "got {err:?}"
8606 );
8607 }
8608
8609 #[test]
8610 fn membro_caixa_invalid_fires_before_duplicate_check() {
8611 // Order pin: a malformed-shape `:caixa` on an earlier entry
8612 // surfaces *its own* diagnostic, even when a later entry would
8613 // otherwise collapse onto a duplicate name. The per-entry shape
8614 // gate runs inline before the duplicate-key insert, parallel
8615 // to `membro_versao_invalid_fires_before_duplicate_check`.
8616 let mut s = three_member_spec();
8617 s.membros[0].caixa = "Catalog".into();
8618 s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8619 let err = s.validate().unwrap_err();
8620 assert!(
8621 matches!(
8622 err,
8623 AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
8624 ),
8625 "got {err:?}"
8626 );
8627 }
8628
8629 #[test]
8630 fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
8631 // The diagnostic-shape pin: the error names the offending
8632 // `:caixa` value verbatim so the author can grep their
8633 // caixa.lisp without re-running the build, and carries a
8634 // non-empty `reason` naming the specific violation. Same
8635 // shape every typed-shape gate enshrines (c7d05ec's
8636 // `entrada_host_diagnostic_carries_offending_host`,
8637 // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
8638 let mut s = three_member_spec();
8639 s.membros[2].caixa = "BAD_NAME".into();
8640 let err = s.validate().unwrap_err();
8641 let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8642 panic!("expected MembroCaixaInvalid");
8643 };
8644 assert_eq!(caixa, "BAD_NAME");
8645 assert!(
8646 !reason.is_empty(),
8647 "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
8648 );
8649 }
8650
8651 #[test]
8652 fn rejects_contrato_with_unknown_de() {
8653 let mut s = three_member_spec();
8654 s.contratos.push(contract_http("phantom", "catalog", "/x"));
8655 let err = s.validate().unwrap_err();
8656 assert!(
8657 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8658 );
8659 }
8660
8661 #[test]
8662 fn rejects_contrato_with_unknown_para() {
8663 let mut s = three_member_spec();
8664 s.contratos.push(contract_http("cart", "phantom", "/x"));
8665 let err = s.validate().unwrap_err();
8666 assert!(
8667 matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
8668 );
8669 }
8670
8671 #[test]
8672 fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
8673 // The read-path pin: the phantom-`:de` refusal arm's
8674 // `ContratoMemberMissing.caixa` carrier must be observed through
8675 // the lifted [`WitContract::source`] accessor, not the raw
8676 // `.de.clone()` field-access `String`-carry. Peer of the sibling
8677 // per-`:contratos` self-loop arm's `.source().to_string()` /
8678 // `.world_ref().to_string()` `String`-carry sites the earlier
8679 // convergence lifted onto the same accessor pair. A future
8680 // silent detour that reintroduced the raw `.de.clone()` at the
8681 // wrap envelope while the shape-gate and membership lookup
8682 // routed through the accessor would surface here as a byte-equal
8683 // miss between the fired diagnostic's `caixa:` field and the
8684 // offending edge's `.source()` — pinning the accessor as the
8685 // sole read path across the phantom-name refusal arm's arg +
8686 // wrap-envelope emit surface.
8687 let mut s = three_member_spec();
8688 let phantom = contract_http("phantom", "catalog", "/x");
8689 s.contratos.push(phantom.clone());
8690 let err = s.validate().unwrap_err();
8691 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8692 panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
8693 };
8694 assert_eq!(
8695 caixa,
8696 phantom.source(),
8697 "ContratoMemberMissing.caixa on the phantom-:de arm must \
8698 byte-equal WitContract::source — the wrap envelope must \
8699 route through the lifted accessor rather than the raw \
8700 .de.clone() field-access String-carry"
8701 );
8702 }
8703
8704 #[test]
8705 fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8706 // The symmetric read-path pin on the `:para` phantom-name
8707 // refusal arm — same shape as the sibling `:de` pin above but
8708 // on the callee-Servico axis. Pins the wrap envelope's
8709 // `caixa:` field is observed through the lifted
8710 // [`WitContract::destination`] accessor, not the raw
8711 // `.para.clone()` field-access `String`-carry.
8712 let mut s = three_member_spec();
8713 let phantom = contract_http("cart", "phantom", "/x");
8714 s.contratos.push(phantom.clone());
8715 let err = s.validate().unwrap_err();
8716 let AplicacaoError::ContratoMemberMissing { caixa } = err else {
8717 panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
8718 };
8719 assert_eq!(
8720 caixa,
8721 phantom.destination(),
8722 "ContratoMemberMissing.caixa on the phantom-:para arm must \
8723 byte-equal WitContract::destination — the wrap envelope \
8724 must route through the lifted accessor rather than the raw \
8725 .para.clone() field-access String-carry"
8726 );
8727 }
8728
8729 #[test]
8730 fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
8731 // The read-path pin on the `:de` DNS-1123-malformed shape-gate
8732 // refusal arm — the `validate_contrato_caixa` arg must be
8733 // observed through the lifted [`WitContract::source`] accessor,
8734 // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
8735 // value routes through the shared
8736 // [`crate::render::require_valid_dns_1123_label`] floor with the
8737 // accessor-projected value; the fired
8738 // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
8739 // the offending edge's `.source()`, pinning that the arg + the
8740 // downstream `caixa: caixa.to_string()` wrap route through the
8741 // same accessor's read path.
8742 let mut s = three_member_spec();
8743 let malformed = contract_http("BAD_NAME", "catalog", "/x");
8744 s.contratos.push(malformed.clone());
8745 let err = s.validate().unwrap_err();
8746 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8747 panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
8748 };
8749 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8750 assert_eq!(
8751 caixa,
8752 malformed.source(),
8753 "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
8754 byte-equal WitContract::source — the shape-gate arg + wrap \
8755 envelope must route through the lifted accessor rather \
8756 than the raw &c.de &String-borrow"
8757 );
8758 }
8759
8760 #[test]
8761 fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
8762 // Symmetric arm to the sibling `:de` malformed-shape pin above,
8763 // on the `:para` axis. Pins the shape-gate arg + wrap envelope
8764 // route through the lifted [`WitContract::destination`]
8765 // accessor. `:para` runs after the `:de` shape gate in the
8766 // canonical edge-direction order, so the `:de` value must be
8767 // well-shaped for the `:para` gate to fire — the `cart` :de is
8768 // canonical.
8769 let mut s = three_member_spec();
8770 let malformed = contract_http("cart", "BAD_NAME", "/x");
8771 s.contratos.push(malformed.clone());
8772 let err = s.validate().unwrap_err();
8773 let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
8774 panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
8775 };
8776 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
8777 assert_eq!(
8778 caixa,
8779 malformed.destination(),
8780 "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
8781 byte-equal WitContract::destination — the shape-gate arg + \
8782 wrap envelope must route through the lifted accessor \
8783 rather than the raw &c.para &String-borrow"
8784 );
8785 }
8786
8787 // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
8788
8789 #[test]
8790 fn rejects_contrato_de_empty() {
8791 // `:de ""` previously fell through to `ContratoMemberMissing`
8792 // (with `caixa: ""`) because the validated `:membros :caixa`
8793 // set never contains the empty string. The narrower
8794 // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
8795 // the offending slot.
8796 let mut s = three_member_spec();
8797 s.contratos.push(contract_http("", "catalog", "/x"));
8798 let err = s.validate().unwrap_err();
8799 assert_eq!(
8800 err,
8801 AplicacaoError::ContratoCaixaEmpty {
8802 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8803 },
8804 "got {err:?}"
8805 );
8806 }
8807
8808 #[test]
8809 fn rejects_contrato_para_empty() {
8810 // Symmetric arm to `:de ""` — `:para ""` previously fell
8811 // through to `ContratoMemberMissing { caixa: "" }`.
8812 let mut s = three_member_spec();
8813 s.contratos.push(contract_http("cart", "", "/x"));
8814 let err = s.validate().unwrap_err();
8815 assert_eq!(
8816 err,
8817 AplicacaoError::ContratoCaixaEmpty {
8818 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
8819 },
8820 "got {err:?}"
8821 );
8822 }
8823
8824 #[test]
8825 fn rejects_contrato_de_with_uppercase() {
8826 // The canonical "I copied the Servico's TitleCase display
8827 // name from an ADR" typo. Until this gate landed `:de "Cart"`
8828 // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
8829 // as "this caixa isn't in `:membros`" when the root cause is
8830 // "this `:de` value's shape can never legitimately match a
8831 // validated member (DNS-1123 labels are lowercase)". The
8832 // narrower diagnostic names the offending slot, the value
8833 // verbatim, and the parser-shaped reason.
8834 let mut s = three_member_spec();
8835 s.contratos.push(contract_http("Cart", "catalog", "/x"));
8836 let err = s.validate().unwrap_err();
8837 let AplicacaoError::ContratoCaixaInvalid {
8838 slot,
8839 caixa,
8840 reason,
8841 } = err
8842 else {
8843 panic!("expected ContratoCaixaInvalid, got other variant");
8844 };
8845 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
8846 assert_eq!(caixa, "Cart");
8847 assert!(
8848 reason.contains("uppercase"),
8849 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8850 );
8851 }
8852
8853 #[test]
8854 fn rejects_contrato_para_with_underscore() {
8855 // The canonical "I'm thinking of a Python module" leak —
8856 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
8857 // Pin the `:para` axis surfaces the same diagnostic shape as
8858 // the `:de` axis on the underscore violation.
8859 let mut s = three_member_spec();
8860 s.contratos.push(contract_http("cart", "my_catalog", "/x"));
8861 let err = s.validate().unwrap_err();
8862 assert!(
8863 matches!(
8864 err,
8865 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8866 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
8867 ),
8868 "got {err:?}"
8869 );
8870 }
8871
8872 #[test]
8873 fn rejects_contrato_de_with_dot() {
8874 // A `:contratos :de` value is a single DNS-1123 *label*, not
8875 // a subdomain — mirroring the `:membros :caixa` floor. The
8876 // strictest floor among the use sites wins.
8877 let mut s = three_member_spec();
8878 s.contratos
8879 .push(contract_http("team.cart", "catalog", "/x"));
8880 let err = s.validate().unwrap_err();
8881 assert!(
8882 matches!(
8883 err,
8884 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8885 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
8886 ),
8887 "got {err:?}"
8888 );
8889 }
8890
8891 #[test]
8892 fn rejects_contrato_para_with_unicode() {
8893 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
8894 // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
8895 // validity check rejects multi-byte UTF-8 by the first
8896 // non-`[a-z0-9-]` byte.
8897 let mut s = three_member_spec();
8898 s.contratos.push(contract_http("cart", "café", "/x"));
8899 let err = s.validate().unwrap_err();
8900 assert!(
8901 matches!(
8902 err,
8903 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8904 if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
8905 ),
8906 "got {err:?}"
8907 );
8908 }
8909
8910 #[test]
8911 fn rejects_contrato_de_with_leading_hyphen() {
8912 // DNS-1123 boundary rule: labels must start and end with an
8913 // alphanumeric. K8s rejects `-cart` outright; the narrower
8914 // shape diagnostic now names the violation at caixa-build
8915 // time rather than the misframed membership-lookup arm.
8916 let mut s = three_member_spec();
8917 s.contratos.push(contract_http("-cart", "catalog", "/x"));
8918 let err = s.validate().unwrap_err();
8919 assert!(
8920 matches!(
8921 err,
8922 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
8923 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
8924 ),
8925 "got {err:?}"
8926 );
8927 }
8928
8929 #[test]
8930 fn contrato_de_empty_takes_precedence_over_invalid() {
8931 // Order pin: the `ContratoCaixaEmpty` arm fires before the
8932 // `ContratoCaixaInvalid` parse-side arm — same empty-first
8933 // cascade `validate_membro_caixa` / `validate_placement_cluster`
8934 // / `validate_entrada_host` already establish on their peer
8935 // name axes. The empty string is a structurally distinct
8936 // authoring footgun (the author left the field blank, vs.
8937 // typed a malformed value), so it gets its own diagnostic.
8938 let mut s = three_member_spec();
8939 s.contratos.push(contract_http("", "catalog", "/x"));
8940 let err = s.validate().unwrap_err();
8941 assert_eq!(
8942 err,
8943 AplicacaoError::ContratoCaixaEmpty {
8944 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
8945 }
8946 );
8947 }
8948
8949 #[test]
8950 fn contrato_de_shape_fires_before_para_shape() {
8951 // Per-axis order pin: within one `:contratos` entry, the `:de`
8952 // shape gate fires before the `:para` shape gate — same
8953 // edge-direction order the existing `ContratoMemberMissing` /
8954 // `ContratoSelfLoop` / target-dispatch checks use, so the
8955 // diagnostic for a contract with both `:de` and `:para`
8956 // malformed is stable. Authors fixing the surfaced `:de`
8957 // first will see `:para`'s diagnostic on re-run.
8958 let mut s = three_member_spec();
8959 s.contratos.push(contract_http("Cart", "Catalog", "/x"));
8960 let err = s.validate().unwrap_err();
8961 assert!(
8962 matches!(
8963 err,
8964 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
8965 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
8966 ),
8967 "got {err:?}"
8968 );
8969 }
8970
8971 #[test]
8972 fn contrato_shape_fires_before_membership_lookup() {
8973 // The load-bearing pin: an invalid-shape `:de` surfaces its
8974 // *own* diagnostic, not the misframed `ContratoMemberMissing`.
8975 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
8976 // an invalid-shape `:de` could never legitimately match any
8977 // member — the prior `ContratoMemberMissing` diagnostic was
8978 // a structural impossibility framed as a graph-membership
8979 // failure. The shape gate now routes every such input through
8980 // the narrower self-locating diagnostic.
8981 let mut s = three_member_spec();
8982 s.contratos.push(contract_http("Cart", "catalog", "/x"));
8983 let err = s.validate().unwrap_err();
8984 assert!(
8985 matches!(
8986 err,
8987 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
8988 ),
8989 "got {err:?}"
8990 );
8991 // And the symmetric case: an invalid-shape `:para` surfaces
8992 // its own diagnostic too, even when `:de` is well-shaped.
8993 let mut s = three_member_spec();
8994 s.contratos.push(contract_http("cart", "Catalog", "/x"));
8995 let err = s.validate().unwrap_err();
8996 assert!(
8997 matches!(
8998 err,
8999 AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9000 ),
9001 "got {err:?}"
9002 );
9003 }
9004
9005 #[test]
9006 fn contrato_shape_fires_before_self_edge_check() {
9007 // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9008 // bugs: the shape violation (uppercase) and the self-edge
9009 // violation. The narrower per-axis shape diagnostic surfaces
9010 // first because fixing the shape may reveal that the author
9011 // also meant to point `:para` at a different member — the
9012 // self-edge framing is only useful once both endpoints have
9013 // valid shape.
9014 let mut s = three_member_spec();
9015 s.contratos.push(contract_http("Cart", "Cart", "/x"));
9016 let err = s.validate().unwrap_err();
9017 assert!(
9018 matches!(
9019 err,
9020 AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9021 if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9022 ),
9023 "got {err:?}"
9024 );
9025 }
9026
9027 #[test]
9028 fn contrato_well_shaped_phantom_still_raises_member_missing() {
9029 // Strict-improvement pin: a well-shaped `:de` that simply
9030 // isn't in `:membros` (a phantom reference — author meant
9031 // to add the member but didn't, or renamed and missed an
9032 // update) still surfaces `ContratoMemberMissing`, unchanged.
9033 // The shape gate only intercepts inputs that could never
9034 // legitimately match a validated member; legitimately-shaped
9035 // phantom references remain on the graph-membership axis.
9036 let mut s = three_member_spec();
9037 s.contratos
9038 .push(contract_http("phantom-shim", "catalog", "/x"));
9039 let err = s.validate().unwrap_err();
9040 assert!(
9041 matches!(
9042 err,
9043 AplicacaoError::ContratoMemberMissing { ref caixa }
9044 if caixa == "phantom-shim"
9045 ),
9046 "got {err:?}"
9047 );
9048 }
9049
9050 #[test]
9051 fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9052 // The diagnostic-shape pin: the error names the offending
9053 // slot (`:de` or `:para`) verbatim and the offending value
9054 // verbatim plus a non-empty parser-shaped reason, so the
9055 // author can grep their caixa.lisp for `:de "<name>"` /
9056 // `:para "<name>"` and fix it in one edit. Same diagnostic
9057 // shape as `MembroCaixaInvalid` (3f9d7a0) and
9058 // `PlacementClusterInvalid` (6c8c00b).
9059 let mut s = three_member_spec();
9060 s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9061 let err = s.validate().unwrap_err();
9062 let AplicacaoError::ContratoCaixaInvalid {
9063 slot,
9064 caixa,
9065 reason,
9066 } = err
9067 else {
9068 panic!("expected ContratoCaixaInvalid, got {err:?}");
9069 };
9070 assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9071 assert_eq!(caixa, "BAD_NAME");
9072 assert!(
9073 !reason.is_empty(),
9074 "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9075 );
9076 }
9077
9078 #[test]
9079 fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9080 // Scalar-value pin: the two author-facing kebab-case labels the
9081 // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9082 // admits on the `:contratos` per-entry endpoint-shape axis,
9083 // one arm per typed sub-slot. Mirrors the peer scalar-value
9084 // pin the sibling top-level M2 / M3 / Supervisor
9085 // author-facing-label consts carry
9086 // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9087 // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9088 // slot itself), so every altitude of the typed-slot algebra
9089 // shares the same "one canonical byte-string per arm"
9090 // discipline. A future rebrand (`:de` → `:from` matching the
9091 // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9092 // sibling, `:para` → `:to` matching the same, or
9093 // `:de`/`:para` → `:source`/`:target` matching the WIT
9094 // world's `import`/`export` half-vocabulary) lands as an
9095 // edit to exactly one const, and every consumer that reaches
9096 // for the label picks it up at build time rather than at
9097 // runtime as a downstream `ContratoCaixaEmpty` /
9098 // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9099 // diagnostic mismatch far from the rename's commit.
9100 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9101 assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9102 }
9103
9104 #[test]
9105 fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9106 // Production-through-const pin: the two per-axis labels the
9107 // per-`:contratos` entry endpoint-shape gate at
9108 // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9109 // argument to [`validate_contrato_caixa`] route through the
9110 // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9111 // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9112 // future rebrand that reaches the const but not the gate (or
9113 // vice versa) surfaces here at build time rather than at
9114 // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9115 // `slot: <stale-kebab-case>` diagnostic far from the rename's
9116 // commit. Mirror of the peer
9117 // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9118 // pin (882f498) on the sibling M3 top-level slot axis.
9119 let mut s = three_member_spec();
9120 s.contratos.push(contract_http("", "catalog", "/x"));
9121 assert_eq!(
9122 s.validate().unwrap_err(),
9123 AplicacaoError::ContratoCaixaEmpty {
9124 slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9125 }
9126 );
9127 let mut s = three_member_spec();
9128 s.contratos.push(contract_http("cart", "", "/x"));
9129 assert_eq!(
9130 s.validate().unwrap_err(),
9131 AplicacaoError::ContratoCaixaEmpty {
9132 slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9133 }
9134 );
9135 }
9136
9137 #[test]
9138 fn accepts_canonical_contrato_caixa_forms() {
9139 // The DNS-1123 label shapes a caixa author is realistically
9140 // going to write on a `:contratos :de` / `:para`. Pin every
9141 // leg so a future tightening that bans (e.g.) digit-start
9142 // identifiers surfaces here, mirroring
9143 // `accepts_canonical_membro_caixa_forms` on the peer name
9144 // axis.
9145 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9146 let mut s = three_member_spec();
9147 s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9148 s.contratos = vec![contract_http("checkout", form, "/x")];
9149 s.entrada = None;
9150 s.validate().unwrap_or_else(|e| {
9151 panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9152 });
9153
9154 let mut s = three_member_spec();
9155 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9156 s.contratos = vec![contract_http(form, "catalog", "/x")];
9157 s.entrada = None;
9158 s.validate().unwrap_or_else(|e| {
9159 panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9160 });
9161 }
9162 }
9163
9164 #[test]
9165 fn rejects_empty_wit() {
9166 let mut s = three_member_spec();
9167 s.contratos.push(WitContract {
9168 de: "cart".into(),
9169 para: "catalog".into(),
9170 wit: "".into(),
9171 endpoint: None,
9172 subject: None,
9173 slot: None,
9174 });
9175 let err = s.validate().unwrap_err();
9176 assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9177 }
9178
9179 #[test]
9180 fn rejects_entrada_to_unknown_member() {
9181 let mut s = three_member_spec();
9182 s.entrada.as_mut().unwrap().para = "phantom".into();
9183 assert!(matches!(
9184 s.validate().unwrap_err(),
9185 AplicacaoError::EntradaMemberMissing { .. }
9186 ));
9187 }
9188
9189 // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9190
9191 #[test]
9192 fn rejects_entrada_para_empty() {
9193 // `:para ""` previously fell through to
9194 // `EntradaMemberMissing { para: "" }` because the validated
9195 // `:membros :caixa` set never contains the empty string. The
9196 // narrower `EntradaParaEmpty` diagnostic now names the
9197 // offending slot directly — same empty-first cascade
9198 // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9199 // `ContratoCaixaEmpty` establish on the peer name axes.
9200 let mut s = three_member_spec();
9201 s.entrada.as_mut().unwrap().para = String::new();
9202 let err = s.validate().unwrap_err();
9203 assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9204 }
9205
9206 #[test]
9207 fn rejects_entrada_para_with_uppercase() {
9208 // The canonical "I copied the Servico's TitleCase display
9209 // name from an ADR" typo. Until this gate landed `:para "Cart"`
9210 // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9211 // as "this caixa isn't in `:membros`" when the root cause is
9212 // "this `:para` value's shape can never legitimately match a
9213 // validated member (DNS-1123 labels are lowercase)". The
9214 // narrower diagnostic names the value verbatim plus the
9215 // parser-shaped reason.
9216 let mut s = three_member_spec();
9217 s.entrada.as_mut().unwrap().para = "Cart".into();
9218 let err = s.validate().unwrap_err();
9219 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9220 panic!("expected EntradaParaInvalid, got other variant");
9221 };
9222 assert_eq!(para, "Cart");
9223 assert!(
9224 reason.contains("uppercase"),
9225 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9226 );
9227 }
9228
9229 #[test]
9230 fn rejects_entrada_para_with_underscore() {
9231 // The canonical "I'm thinking of a Python module" leak —
9232 // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9233 let mut s = three_member_spec();
9234 s.entrada.as_mut().unwrap().para = "my_cart".into();
9235 let err = s.validate().unwrap_err();
9236 assert!(
9237 matches!(
9238 err,
9239 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9240 if para == "my_cart" && reason.contains('_')
9241 ),
9242 "got {err:?}"
9243 );
9244 }
9245
9246 #[test]
9247 fn rejects_entrada_para_with_dot() {
9248 // An `:entrada :para` value is a single DNS-1123 *label*, not
9249 // a subdomain — mirroring the `:membros :caixa` floor. The
9250 // strictest floor among the use sites wins.
9251 let mut s = three_member_spec();
9252 s.entrada.as_mut().unwrap().para = "team.cart".into();
9253 let err = s.validate().unwrap_err();
9254 assert!(
9255 matches!(
9256 err,
9257 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9258 if para == "team.cart" && reason.contains('.')
9259 ),
9260 "got {err:?}"
9261 );
9262 }
9263
9264 #[test]
9265 fn rejects_entrada_para_with_unicode() {
9266 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9267 // (`xn--…`) before it reaches K8s.
9268 let mut s = three_member_spec();
9269 s.entrada.as_mut().unwrap().para = "café".into();
9270 let err = s.validate().unwrap_err();
9271 assert!(
9272 matches!(
9273 err,
9274 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9275 ),
9276 "got {err:?}"
9277 );
9278 }
9279
9280 #[test]
9281 fn rejects_entrada_para_with_leading_hyphen() {
9282 // DNS-1123 boundary rule: labels must start and end with an
9283 // alphanumeric. K8s rejects `-cart` outright.
9284 let mut s = three_member_spec();
9285 s.entrada.as_mut().unwrap().para = "-cart".into();
9286 let err = s.validate().unwrap_err();
9287 assert!(
9288 matches!(
9289 err,
9290 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9291 if para == "-cart" && reason.contains("start and end")
9292 ),
9293 "got {err:?}"
9294 );
9295 }
9296
9297 #[test]
9298 fn rejects_entrada_para_with_trailing_hyphen() {
9299 // Symmetric boundary arm.
9300 let mut s = three_member_spec();
9301 s.entrada.as_mut().unwrap().para = "cart-".into();
9302 let err = s.validate().unwrap_err();
9303 assert!(
9304 matches!(
9305 err,
9306 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9307 if para == "cart-" && reason.contains("start and end")
9308 ),
9309 "got {err:?}"
9310 );
9311 }
9312
9313 #[test]
9314 fn rejects_entrada_para_too_long() {
9315 // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
9316 // bytes per label. K8s rejects longer names at admission on
9317 // every `metadata.name` axis.
9318 let mut s = three_member_spec();
9319 s.entrada.as_mut().unwrap().para = "a".repeat(64);
9320 let err = s.validate().unwrap_err();
9321 assert!(
9322 matches!(
9323 err,
9324 AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9325 if para.len() == 64 && reason.contains("max length")
9326 ),
9327 "got {err:?}"
9328 );
9329 }
9330
9331 #[test]
9332 fn entrada_para_empty_takes_precedence_over_invalid() {
9333 // Order pin: the `EntradaParaEmpty` arm fires before the
9334 // `EntradaParaInvalid` parse-side arm — same empty-first
9335 // cascade `validate_membro_caixa` / `validate_placement_cluster`
9336 // / `validate_contrato_caixa` already establish.
9337 let mut s = three_member_spec();
9338 s.entrada.as_mut().unwrap().para = String::new();
9339 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
9340 }
9341
9342 #[test]
9343 fn entrada_para_shape_fires_before_membership_lookup() {
9344 // The load-bearing pin: an invalid-shape `:para` surfaces its
9345 // *own* diagnostic, not the misframed `EntradaMemberMissing`.
9346 // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9347 // an invalid-shape `:para` could never legitimately match any
9348 // member — the prior `EntradaMemberMissing` diagnostic framed
9349 // a structural impossibility as a graph-membership failure.
9350 let mut s = three_member_spec();
9351 s.entrada.as_mut().unwrap().para = "Cart".into();
9352 let err = s.validate().unwrap_err();
9353 assert!(
9354 matches!(
9355 err,
9356 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9357 ),
9358 "got {err:?}"
9359 );
9360 }
9361
9362 #[test]
9363 fn entrada_para_shape_fires_before_host_gate() {
9364 // Per-`:entrada` order pin: the `:para` shape gate fires
9365 // before the `:host` gate, mirroring the existing
9366 // `entrada_host_member_missing_takes_precedence_over_host_invalid`
9367 // ordering where the member-lookup arm preceded the host gate.
9368 // The shape gate slots ahead of that, so a malformed `:para`
9369 // surfaces its own diagnostic even when `:host` is also wrong.
9370 let mut s = three_member_spec();
9371 let e = s.entrada.as_mut().unwrap();
9372 e.para = "Cart".into();
9373 e.host = "BAD HOST".into();
9374 let err = s.validate().unwrap_err();
9375 assert!(
9376 matches!(
9377 err,
9378 AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9379 ),
9380 "got {err:?}"
9381 );
9382 }
9383
9384 #[test]
9385 fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
9386 // Strict-improvement pin: a well-shaped `:para` that simply
9387 // isn't in `:membros` (a phantom reference — author meant to
9388 // add the member but didn't, or renamed and missed an
9389 // update) still surfaces `EntradaMemberMissing`, unchanged.
9390 // The shape gate only intercepts inputs that could never
9391 // legitimately match a validated member.
9392 let mut s = three_member_spec();
9393 s.entrada.as_mut().unwrap().para = "phantom-shim".into();
9394 let err = s.validate().unwrap_err();
9395 assert!(
9396 matches!(
9397 err,
9398 AplicacaoError::EntradaMemberMissing { ref para }
9399 if para == "phantom-shim"
9400 ),
9401 "got {err:?}"
9402 );
9403 }
9404
9405 #[test]
9406 fn entrada_para_invalid_diagnostic_carries_offending_para() {
9407 // The diagnostic-shape pin: the error names the offending
9408 // `:para` value verbatim plus a non-empty parser-shaped
9409 // reason, so the author can grep their caixa.lisp for
9410 // `:para "<name>"` and fix it in one edit. Same diagnostic
9411 // shape as `MembroCaixaInvalid` (3f9d7a0),
9412 // `PlacementClusterInvalid` (6c8c00b), and
9413 // `ContratoCaixaInvalid` (8d5af6b).
9414 let mut s = three_member_spec();
9415 s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
9416 let err = s.validate().unwrap_err();
9417 let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9418 panic!("expected EntradaParaInvalid, got {err:?}");
9419 };
9420 assert_eq!(para, "BAD_NAME");
9421 assert!(
9422 !reason.is_empty(),
9423 "EntradaParaInvalid `reason` must carry a parser-shaped wording"
9424 );
9425 }
9426
9427 #[test]
9428 fn accepts_canonical_entrada_para_forms() {
9429 // Positive-control sweep covering the DNS-1123 label shapes a
9430 // caixa author is realistically going to write on `:entrada
9431 // :para`. Pin every leg so a future tightening that bans
9432 // (e.g.) digit-start identifiers surfaces here, mirroring
9433 // `accepts_canonical_membro_caixa_forms` and
9434 // `accepts_canonical_contrato_caixa_forms` on the peer name
9435 // axes.
9436 for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9437 let mut s = three_member_spec();
9438 s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9439 s.contratos = vec![contract_http(form, "catalog", "/x")];
9440 s.entrada = Some(Entrada {
9441 host: "checkout.quero.cloud".into(),
9442 para: form.into(),
9443 paths: vec!["/api".into()],
9444 port: 8080,
9445 });
9446 s.validate().unwrap_or_else(|e| {
9447 panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
9448 });
9449 }
9450 }
9451
9452 #[test]
9453 fn rejects_replicated_without_clusters() {
9454 let mut s = three_member_spec();
9455 s.placement.clusters = vec![];
9456 assert!(matches!(
9457 s.validate().unwrap_err(),
9458 AplicacaoError::PlacementWithoutClusters { .. }
9459 ));
9460 }
9461
9462 #[test]
9463 fn rejects_sharded_without_key() {
9464 let mut s = three_member_spec();
9465 s.placement.estrategia = PlacementStrategy::Sharded;
9466 s.placement.shard_key = None;
9467 s.placement.clusters = vec!["rio".into()];
9468 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
9469 }
9470
9471 #[test]
9472 fn sharded_with_key_validates() {
9473 let mut s = three_member_spec();
9474 s.placement.estrategia = PlacementStrategy::Sharded;
9475 s.placement.shard_key = Some("$tenantId".into());
9476 s.validate().unwrap();
9477 }
9478
9479 #[test]
9480 fn round_trip_via_json_preserves_shape() {
9481 let s = three_member_spec();
9482 let json = serde_json::to_string(&s.membros).unwrap();
9483 let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
9484 assert_eq!(back, s.membros);
9485
9486 let json = serde_json::to_string(&s.contratos).unwrap();
9487 let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
9488 assert_eq!(back, s.contratos);
9489
9490 let json = serde_json::to_string(&s.placement).unwrap();
9491 let back: Placement = serde_json::from_str(&json).unwrap();
9492 assert_eq!(back, s.placement);
9493
9494 let json = serde_json::to_string(&s.entrada).unwrap();
9495 let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
9496 assert_eq!(back, s.entrada);
9497 }
9498
9499 #[test]
9500 fn rate_limit_round_trip_seconds() {
9501 let policy = MeshPolicy {
9502 rate_limit: Some(RateLimit {
9503 rate: 100,
9504 window: Duration::from_secs(1),
9505 }),
9506 ..Default::default()
9507 };
9508 let json = serde_json::to_string(&policy).unwrap();
9509 assert!(json.contains("\"100/s\""));
9510 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9511 assert_eq!(back.rate_limit.unwrap().rate, 100);
9512 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
9513 }
9514
9515 #[test]
9516 fn rate_limit_round_trip_minutes() {
9517 let policy = MeshPolicy {
9518 rate_limit: Some(RateLimit {
9519 rate: 5000,
9520 window: Duration::from_secs(60),
9521 }),
9522 ..Default::default()
9523 };
9524 let json = serde_json::to_string(&policy).unwrap();
9525 assert!(json.contains("\"5000/m\""));
9526 }
9527
9528 #[test]
9529 fn circuit_breaker_round_trip() {
9530 let policy = MeshPolicy {
9531 circuit_breaker: Some(CircuitBreaker {
9532 max_failures: 5,
9533 window: Duration::from_secs(60),
9534 }),
9535 ..Default::default()
9536 };
9537 let json = serde_json::to_string(&policy).unwrap();
9538 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
9539 assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
9540 assert_eq!(
9541 back.circuit_breaker.unwrap().window,
9542 Duration::from_secs(60)
9543 );
9544 }
9545
9546 #[test]
9547 fn rejects_http_contrato_without_endpoint() {
9548 let mut s = three_member_spec();
9549 s.contratos.push(WitContract {
9550 de: "cart".into(),
9551 para: "catalog".into(),
9552 wit: "wasi:http/proxy".into(),
9553 endpoint: None,
9554 subject: None,
9555 slot: None,
9556 });
9557 let err = s.validate().unwrap_err();
9558 assert!(matches!(
9559 err,
9560 AplicacaoError::ContratoMissingTarget {
9561 expected: WitTarget::HTTP_FIELD_NAME,
9562 ..
9563 }
9564 ));
9565 }
9566
9567 #[test]
9568 fn rejects_http_contrato_with_subject() {
9569 let mut s = three_member_spec();
9570 s.contratos.push(WitContract {
9571 de: "cart".into(),
9572 para: "catalog".into(),
9573 wit: "wasi:http/proxy".into(),
9574 endpoint: Some("/x".into()),
9575 subject: Some("not.allowed.here".into()),
9576 slot: None,
9577 });
9578 let err = s.validate().unwrap_err();
9579 assert!(matches!(
9580 err,
9581 AplicacaoError::ContratoWrongTarget {
9582 expected: WitTarget::HTTP_FIELD_NAME,
9583 ..
9584 }
9585 ));
9586 }
9587
9588 #[test]
9589 fn rejects_pubsub_contrato_without_subject() {
9590 let mut s = three_member_spec();
9591 s.contratos.push(WitContract {
9592 de: "cart".into(),
9593 para: "catalog".into(),
9594 wit: "nats:pub-sub".into(),
9595 endpoint: None,
9596 subject: None,
9597 slot: None,
9598 });
9599 let err = s.validate().unwrap_err();
9600 assert!(matches!(
9601 err,
9602 AplicacaoError::ContratoMissingTarget {
9603 expected: WitTarget::PUBSUB_FIELD_NAME,
9604 ..
9605 }
9606 ));
9607 }
9608
9609 #[test]
9610 fn rejects_pubsub_contrato_with_endpoint() {
9611 let mut s = three_member_spec();
9612 s.contratos.push(WitContract {
9613 de: "cart".into(),
9614 para: "catalog".into(),
9615 wit: "kafka:topic".into(),
9616 endpoint: Some("/wrong".into()),
9617 subject: Some("topic.x".into()),
9618 slot: None,
9619 });
9620 let err = s.validate().unwrap_err();
9621 assert!(matches!(
9622 err,
9623 AplicacaoError::ContratoWrongTarget {
9624 expected: WitTarget::PUBSUB_FIELD_NAME,
9625 ..
9626 }
9627 ));
9628 }
9629
9630 #[test]
9631 fn rejects_store_contrato_without_slot() {
9632 let mut s = three_member_spec();
9633 s.contratos.push(WitContract {
9634 de: "cart".into(),
9635 para: "catalog".into(),
9636 wit: "wasi:keyvalue/store".into(),
9637 endpoint: None,
9638 subject: None,
9639 slot: None,
9640 });
9641 let err = s.validate().unwrap_err();
9642 assert!(matches!(
9643 err,
9644 AplicacaoError::ContratoMissingTarget {
9645 expected: WitTarget::STORE_FIELD_NAME,
9646 ..
9647 }
9648 ));
9649 }
9650
9651 // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
9652
9653 #[test]
9654 fn rejects_http_contrato_with_empty_endpoint() {
9655 // `Some("")` for an HTTP endpoint passes the presence check
9656 // (target() previously returned WitTarget::Http { endpoint: "" })
9657 // but renders as a `path: ""` Cilium L7 rule that matches no
9658 // traffic. Same value-shape footgun closed for :entrada :paths
9659 // entries (eb3456d).
9660 let mut s = three_member_spec();
9661 s.contratos.push(WitContract {
9662 de: "cart".into(),
9663 para: "catalog".into(),
9664 wit: "wasi:http/proxy".into(),
9665 endpoint: Some(String::new()),
9666 subject: None,
9667 slot: None,
9668 });
9669 let err = s.validate().unwrap_err();
9670 assert!(
9671 matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
9672 if de == "cart" && para == "catalog"),
9673 "got {err:?}"
9674 );
9675 }
9676
9677 #[test]
9678 fn rejects_http_contrato_with_relative_endpoint() {
9679 // Cilium L7 :path + Gateway API PathPrefix both require a
9680 // leading `/`. Same shape required of :entrada :paths
9681 // (eb3456d). Lifted into target() so every consumer of the
9682 // typed WitTarget view inherits the guarantee.
9683 let mut s = three_member_spec();
9684 s.contratos.push(WitContract {
9685 de: "cart".into(),
9686 para: "catalog".into(),
9687 wit: "wasi:http/proxy".into(),
9688 endpoint: Some("products/:id".into()),
9689 subject: None,
9690 slot: None,
9691 });
9692 let err = s.validate().unwrap_err();
9693 assert!(
9694 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9695 if endpoint == "products/:id"),
9696 "got {err:?}"
9697 );
9698 }
9699
9700 #[test]
9701 fn rejects_pubsub_contrato_with_empty_subject() {
9702 // NATS / Kafka publish without a subject is a no-op subscribe;
9703 // never the author's intent. Same empty-string rejection as
9704 // :membros :caixa, :placement :clusters entries, :entrada
9705 // :paths entries — every value carried by every typed slot is
9706 // value-shape-checked at validate().
9707 let mut s = three_member_spec();
9708 s.contratos.push(WitContract {
9709 de: "cart".into(),
9710 para: "catalog".into(),
9711 wit: "nats:pub-sub".into(),
9712 endpoint: None,
9713 subject: Some(String::new()),
9714 slot: None,
9715 });
9716 let err = s.validate().unwrap_err();
9717 assert!(
9718 matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
9719 if de == "cart" && para == "catalog"),
9720 "got {err:?}"
9721 );
9722 }
9723
9724 #[test]
9725 fn rejects_store_contrato_with_empty_slot() {
9726 // An empty slot template addresses the bucket root, defeating
9727 // the per-key isolation the slot exists for — a footgun on
9728 // `wasi:keyvalue/store` whose closest analog is the empty
9729 // shard-key rejected on :placement Sharded (c7c7799).
9730 let mut s = three_member_spec();
9731 s.contratos.push(WitContract {
9732 de: "cart".into(),
9733 para: "catalog".into(),
9734 wit: "wasi:keyvalue/store".into(),
9735 endpoint: None,
9736 subject: None,
9737 slot: Some(String::new()),
9738 });
9739 let err = s.validate().unwrap_err();
9740 assert!(
9741 matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
9742 if de == "cart" && para == "catalog"),
9743 "got {err:?}"
9744 );
9745 }
9746
9747 #[test]
9748 fn http_contrato_root_endpoint_validates() {
9749 // Pin the boundary case: a single-`/` endpoint is the catch-all
9750 // form the Gateway HTTPRoute renderer falls back to when
9751 // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
9752 // must remain a valid contrato endpoint too.
9753 let mut s = three_member_spec();
9754 s.contratos.push(contract_http("cart", "catalog", "/"));
9755 s.validate().unwrap();
9756 }
9757
9758 // ── :contratos :endpoint value-shape gate ────────────────────────────
9759 //
9760 // Mirrors the `:entrada :paths` value-shape suite on the peer
9761 // HTTP-path axis. Until this gate landed `WitContract::target()`
9762 // only refused the empty string + the missing-leading-`/` form
9763 // (c4213a4); a structurally invalid endpoint passed validate and
9764 // landed verbatim as a Cilium L7 `path:` rule
9765 // (caixa-mesh/src/lib.rs:311) that either silently dropped all
9766 // traffic or was rejected at apply time by Cilium policy admission.
9767 // Every authoring footgun the K8s Gateway API webhook / Cilium
9768 // policy validator would catch on admission now becomes a caixa-
9769 // build-time `ContratoEndpointInvalid` with the offending
9770 // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
9771 // shape as `EntradaPathInvalid` on the sibling axis; same shared
9772 // predicate (`crate::render::is_gateway_api_http_path`) ensures
9773 // drift between the two axes' rule enforcement is a build error
9774 // at the predicate.
9775
9776 fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
9777 // Fresh spec per call so the would-be-duplicate edge
9778 // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
9779 // `three_member_spec`'s pre-existing
9780 // `(cart, catalog, …, /products/:id)` entry — only the
9781 // endpoint payload differs.
9782 let mut s = three_member_spec();
9783 s.contratos.push(contract_http("cart", "catalog", ep));
9784 s.validate().unwrap_err()
9785 }
9786
9787 #[test]
9788 fn rejects_http_contrato_endpoint_with_query() {
9789 // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
9790 // silently rendered as a Cilium L7 `path: "/charge?token=X"`
9791 // rule the L7 matcher would never satisfy.
9792 let err = contrato_endpoint_err("/charge?token=X");
9793 assert!(
9794 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9795 if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
9796 "got {err:?}"
9797 );
9798 }
9799
9800 #[test]
9801 fn rejects_http_contrato_endpoint_with_fragment() {
9802 let err = contrato_endpoint_err("/charge#frag");
9803 assert!(
9804 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9805 if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
9806 "got {err:?}"
9807 );
9808 }
9809
9810 #[test]
9811 fn rejects_http_contrato_endpoint_with_whitespace() {
9812 let err = contrato_endpoint_err("/foo bar");
9813 assert!(
9814 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9815 if endpoint == "/foo bar" && reason.contains("whitespace")),
9816 "got {err:?}"
9817 );
9818 }
9819
9820 #[test]
9821 fn rejects_http_contrato_endpoint_with_control_char() {
9822 let err = contrato_endpoint_err("/api/\x01bar");
9823 assert!(
9824 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9825 if endpoint == "/api/\x01bar" && reason.contains("control character")),
9826 "got {err:?}"
9827 );
9828 }
9829
9830 #[test]
9831 fn rejects_http_contrato_endpoint_with_non_ascii() {
9832 let err = contrato_endpoint_err("/api/café");
9833 assert!(
9834 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9835 if endpoint == "/api/café" && reason.contains("non-ASCII")),
9836 "got {err:?}"
9837 );
9838 }
9839
9840 #[test]
9841 fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
9842 let err = contrato_endpoint_err("/api//cart");
9843 assert!(
9844 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9845 if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
9846 "got {err:?}"
9847 );
9848 }
9849
9850 #[test]
9851 fn rejects_http_contrato_endpoint_with_dot_segment() {
9852 let err = contrato_endpoint_err("/api/./cart");
9853 assert!(
9854 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9855 if endpoint == "/api/./cart" && reason.contains("`.` segment")),
9856 "got {err:?}"
9857 );
9858 }
9859
9860 #[test]
9861 fn rejects_http_contrato_endpoint_with_parent_segment() {
9862 // Path-traversal in a contrato endpoint is the canonical
9863 // "L7 rule that the workload's HTTP server's path-resolution
9864 // logic interprets differently than the policy enforcer"
9865 // footgun. Rejected outright at validate time.
9866 let err = contrato_endpoint_err("/api/../etc");
9867 assert!(
9868 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9869 if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
9870 "got {err:?}"
9871 );
9872 }
9873
9874 #[test]
9875 fn rejects_http_contrato_endpoint_too_long() {
9876 // 1025-byte endpoint — one over the Gateway API
9877 // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
9878 // path matcher has no inherent length limit but the policy
9879 // CR itself rides through the K8s apiserver, which enforces
9880 // ConfigMap-shaped limits; sharing the Gateway API cap is the
9881 // conservative floor.
9882 let big = format!("/api/{}", "a".repeat(1020));
9883 assert_eq!(big.len(), 1025);
9884 let err = contrato_endpoint_err(&big);
9885 assert!(
9886 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
9887 if endpoint == &big && reason.contains("max length of 1024")),
9888 "got {err:?}"
9889 );
9890 }
9891
9892 #[test]
9893 fn http_contrato_endpoint_max_length_validates() {
9894 // 1024-byte endpoint — exactly the cap. Boundary pin: drift
9895 // in the cap surfaces here and at
9896 // `rejects_http_contrato_endpoint_too_long` simultaneously,
9897 // mirroring `entrada_path_max_length_validates` on the peer
9898 // axis.
9899 let big = format!("/api/{}", "a".repeat(1019));
9900 assert_eq!(big.len(), 1024);
9901 let mut s = three_member_spec();
9902 s.contratos.push(contract_http("cart", "catalog", &big));
9903 s.validate().unwrap();
9904 }
9905
9906 #[test]
9907 fn http_contrato_endpoint_accepts_canonical_forms() {
9908 // Positive-set sweep: every canonical HTTP-path shape the
9909 // sibling `:entrada :paths` axis accepts (the bare-root `/`,
9910 // plain paths, hidden-file-style `.config` segments distinct
9911 // from the `.` segment, digit-bearing segments, the canonical
9912 // route-template `:param` form, trailing-slash form,
9913 // percent-encoded segments, the `/foo..bar` interior-`..`-
9914 // substring forms that are NOT `..` segments) must remain a
9915 // valid contrato endpoint too. Drift between this list and
9916 // the entrada path positive sweep surfaces at the shared
9917 // `is_gateway_api_http_path` substrate-side suite — one
9918 // source of truth. Uses a fresh `(payment, catalog)` edge so
9919 // none of the swept endpoints collide with the pre-existing
9920 // `(cart, catalog, /products/:id)` / `(cart, payment,
9921 // /charge)` entries in `three_member_spec`.
9922 for ep in [
9923 "/",
9924 "/charge",
9925 "/v1/charge",
9926 "/api/.config",
9927 "/products/:id",
9928 "/api/cart/",
9929 "/api/caf%C3%A9",
9930 "/foo..bar",
9931 "/...",
9932 ] {
9933 let mut s = three_member_spec();
9934 s.contratos.push(contract_http("payment", "catalog", ep));
9935 s.validate()
9936 .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
9937 }
9938 }
9939
9940 #[test]
9941 fn contrato_endpoint_empty_takes_precedence_over_invalid() {
9942 // Ordering pin: `ContratoEndpointEmpty` is the more self-
9943 // locating diagnostic on `""` and must lead — the value-
9944 // shape gate is only reached after the empty-check fires.
9945 // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
9946 // on the peer axis.
9947 let mut s = three_member_spec();
9948 s.contratos.push(WitContract {
9949 de: "cart".into(),
9950 para: "catalog".into(),
9951 wit: "wasi:http/proxy".into(),
9952 endpoint: Some(String::new()),
9953 subject: None,
9954 slot: None,
9955 });
9956 let err = s.validate().unwrap_err();
9957 assert!(
9958 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
9959 "got {err:?}"
9960 );
9961 }
9962
9963 #[test]
9964 fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
9965 // Ordering pin: an endpoint without a leading `/` surfaces the
9966 // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
9967 // value-shape gate is only consulted on endpoints that already
9968 // satisfy the absolute-prefix invariant. Mirrors
9969 // `entrada_path_not_absolute_takes_precedence_over_invalid`.
9970 let err = contrato_endpoint_err("bad path");
9971 assert!(
9972 matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
9973 if endpoint == "bad path"),
9974 "got {err:?}"
9975 );
9976 }
9977
9978 #[test]
9979 fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
9980 // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
9981 // `:para` + a non-empty reason flow through verbatim so the
9982 // author can grep their caixa.lisp for the offending contrato
9983 // block and fix it in one edit. Same shape as
9984 // `entrada_path_diagnostic_carries_offending_path`.
9985 let err = contrato_endpoint_err("/api?q=1");
9986 match err {
9987 AplicacaoError::ContratoEndpointInvalid {
9988 de,
9989 para,
9990 endpoint,
9991 reason,
9992 } => {
9993 assert_eq!(de, "cart");
9994 assert_eq!(para, "catalog");
9995 assert_eq!(endpoint, "/api?q=1");
9996 assert!(!reason.is_empty(), "reason field must be non-empty");
9997 }
9998 other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
9999 }
10000 }
10001
10002 #[test]
10003 fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10004 // The compounding theorem: every &str inside a WitTarget
10005 // returned by target() is non-empty (and absolute, for Http).
10006 // Renderers downstream of typed_view() can rely on this
10007 // without re-checking — the type system carries the proof.
10008 let http = contract_http("cart", "catalog", "/x");
10009 match http.target().unwrap() {
10010 WitTarget::Http { endpoint } => {
10011 assert!(!endpoint.is_empty());
10012 assert!(endpoint.starts_with('/'));
10013 }
10014 other => panic!("expected Http, got {other:?}"),
10015 }
10016 let nats = WitContract {
10017 de: "a".into(),
10018 para: "b".into(),
10019 wit: "nats:pub-sub".into(),
10020 endpoint: None,
10021 subject: Some("topic.x".into()),
10022 slot: None,
10023 };
10024 match nats.target().unwrap() {
10025 WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10026 other => panic!("expected PubSub, got {other:?}"),
10027 }
10028 let kv = WitContract {
10029 de: "a".into(),
10030 para: "b".into(),
10031 wit: "wasi:keyvalue/store".into(),
10032 endpoint: None,
10033 subject: None,
10034 slot: Some("checkout/$orderId".into()),
10035 };
10036 match kv.target().unwrap() {
10037 WitTarget::Store { slot } => assert!(!slot.is_empty()),
10038 other => panic!("expected Store, got {other:?}"),
10039 }
10040 }
10041
10042 #[test]
10043 fn target_diagnostic_names_offending_endpoint_value() {
10044 // When the malformed endpoint string is non-trivial, the
10045 // diagnostic carries the actual value back to the author —
10046 // not a generic "endpoint malformed" error.
10047 let bad = WitContract {
10048 de: "src".into(),
10049 para: "dst".into(),
10050 wit: "wasi:http/proxy".into(),
10051 endpoint: Some("api/v1/charge".into()),
10052 subject: None,
10053 slot: None,
10054 };
10055 match bad.target().unwrap_err() {
10056 AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10057 assert_eq!(de, "src");
10058 assert_eq!(para, "dst");
10059 assert_eq!(endpoint, "api/v1/charge");
10060 }
10061 other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10062 }
10063 }
10064
10065 #[test]
10066 fn rejects_unknown_wit_with_target_set() {
10067 let mut s = three_member_spec();
10068 s.contratos.push(WitContract {
10069 de: "cart".into(),
10070 para: "catalog".into(),
10071 wit: "custom:exchange".into(),
10072 endpoint: Some("/leaked".into()),
10073 subject: None,
10074 slot: None,
10075 });
10076 let err = s.validate().unwrap_err();
10077 assert!(matches!(
10078 err,
10079 AplicacaoError::ContratoWrongTarget {
10080 expected: WitTarget::CAPABILITY_EXPECTED,
10081 ..
10082 }
10083 ));
10084 }
10085
10086 #[test]
10087 fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10088 // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10089 // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10090 // fourth arm of the same "which payload field name goes in the
10091 // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10092 // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10093 // consts cover on the peer HTTP / PubSub / Store arms
10094 // (`wit_target_field_name_pins_per_variant`). Until this lift
10095 // landed the byte-string sat twice — once inline in the
10096 // [`WitContract::target`] Capability-arm rejection at the
10097 // production dispatch, once in `rejects_unknown_wit_with_target_set`
10098 // pinning against the same literal — with no compile-time link
10099 // between them. Same "one canonical declaration, next to the
10100 // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10101 // lift established for the payload-less arm's human-readable
10102 // label axis; this test is the shape peer of
10103 // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10104 // pair (routes-through-const + scalar-value pin) on the
10105 // wrong-target diagnostic-scalar axis.
10106 //
10107 // Fail-before-pass-after was verified locally by mutating the
10108 // const declaration to `"capability"` — the scalar-value pin
10109 // below fires (`"capability" != "none"`) and the routes-through
10110 // assertion below still holds (production and const walk in
10111 // lockstep), which is the correct behavior: a rename on the
10112 // const drifts here first, not at a downstream consumer.
10113 assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10114
10115 let mut s = three_member_spec();
10116 s.contratos.push(WitContract {
10117 de: "cart".into(),
10118 para: "catalog".into(),
10119 wit: "custom:exchange".into(),
10120 endpoint: Some("/leaked".into()),
10121 subject: None,
10122 slot: None,
10123 });
10124 match s.validate().unwrap_err() {
10125 AplicacaoError::ContratoWrongTarget { expected, .. } => {
10126 assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10127 }
10128 other => panic!("expected ContratoWrongTarget, got {other:?}"),
10129 }
10130 }
10131
10132 #[test]
10133 fn unknown_wit_capability_only_validates() {
10134 let mut s = three_member_spec();
10135 s.contratos.push(WitContract {
10136 de: "cart".into(),
10137 para: "catalog".into(),
10138 // A WIT world we haven't yet shaped — accept it as a typed
10139 // capability edge so authors aren't blocked while the WIT
10140 // registry catches up. No payload field may be carried.
10141 wit: "custom:exchange".into(),
10142 endpoint: None,
10143 subject: None,
10144 slot: None,
10145 });
10146 s.validate().unwrap();
10147 let added = s.contratos.last().unwrap();
10148 assert_eq!(added.target().unwrap(), WitTarget::Capability);
10149 }
10150
10151 #[test]
10152 fn target_typed_view_round_trips_each_shape() {
10153 let http = contract_http("cart", "catalog", "/products/:id");
10154 assert_eq!(
10155 http.target().unwrap(),
10156 WitTarget::Http {
10157 endpoint: "/products/:id"
10158 }
10159 );
10160 let nats = WitContract {
10161 de: "a".into(),
10162 para: "b".into(),
10163 wit: "nats:pub-sub".into(),
10164 endpoint: None,
10165 subject: Some("topic.x".into()),
10166 slot: None,
10167 };
10168 assert_eq!(
10169 nats.target().unwrap(),
10170 WitTarget::PubSub { subject: "topic.x" }
10171 );
10172 let kv = WitContract {
10173 de: "a".into(),
10174 para: "b".into(),
10175 wit: "wasi:keyvalue/store".into(),
10176 endpoint: None,
10177 subject: None,
10178 slot: Some("checkout/$orderId".into()),
10179 };
10180 assert_eq!(
10181 kv.target().unwrap(),
10182 WitTarget::Store {
10183 slot: "checkout/$orderId"
10184 }
10185 );
10186 }
10187
10188 #[test]
10189 fn wit_contract_kind_predicates() {
10190 let http = contract_http("a", "b", "/x");
10191 assert!(http.is_http());
10192 assert!(!http.is_pubsub());
10193 assert!(!http.is_store());
10194 assert!(!http.is_capability());
10195
10196 let nats = WitContract {
10197 de: "a".into(),
10198 para: "b".into(),
10199 wit: "nats:pub-sub".into(),
10200 endpoint: None,
10201 subject: Some("topic.x".into()),
10202 slot: None,
10203 };
10204 assert!(nats.is_pubsub());
10205 assert!(!nats.is_http());
10206 assert!(!nats.is_capability());
10207
10208 let kv = WitContract {
10209 de: "a".into(),
10210 para: "b".into(),
10211 wit: "wasi:keyvalue/store".into(),
10212 endpoint: None,
10213 subject: None,
10214 slot: Some("checkout/$orderId".into()),
10215 };
10216 assert!(kv.is_store());
10217 assert!(!kv.is_http());
10218 assert!(!kv.is_capability());
10219
10220 // Fourth arm on the paired closed-set predicate family: the
10221 // payload-less capability edge that projects to the payload-
10222 // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10223 // Extends the 3-arm predicate sweep this test opened to cover
10224 // the closed 4-way partition [`WitContract::is_capability`]
10225 // closes on the pre-projection WIT-shape axis, matched with the
10226 // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10227 // 4-arm predicate set.
10228 let cap = WitContract {
10229 de: "a".into(),
10230 para: "b".into(),
10231 wit: "custom:capability-only".into(),
10232 endpoint: None,
10233 subject: None,
10234 slot: None,
10235 };
10236 assert!(cap.is_capability());
10237 assert!(!cap.is_http());
10238 assert!(!cap.is_pubsub());
10239 assert!(!cap.is_store());
10240 }
10241
10242 // ── :contratos :wit value-shape gate ─────────────────────────────────
10243 //
10244 // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10245 // dispatch-discriminator axis. Until this gate landed
10246 // `WitContract::target()` accepted any non-empty string and
10247 // silently demoted unrecognized shapes to a capability-only L4
10248 // edge — the canonical "I thought I had L7 HTTP routing, got
10249 // L4-only" footgun. Every authoring footgun the WIT registry's
10250 // own grammar rejects (uppercase, hyphen-for-colon typo,
10251 // whitespace, empty package, doubled `@`, …) now becomes a
10252 // caixa-build-time `ContratoWitInvalid` with the offending
10253 // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10254 // as `ContratoEndpointInvalid` on the sibling axis; same shared
10255 // predicate (`crate::render::is_wit_world_ref`) ensures drift
10256 // between any two axes' rule enforcement is a build error at the
10257 // predicate, not piecemeal across renderers.
10258
10259 fn contrato_wit_err(wit: &str) -> AplicacaoError {
10260 // Fresh spec per call so the new contract doesn't collide on
10261 // identity with `three_member_spec`'s pre-existing entries.
10262 // The new edge uses `(payment, catalog)` — a pair the fixture
10263 // doesn't already declare — with no payload field set, so the
10264 // wit-shape gate fires before any payload-shape arm.
10265 let mut s = three_member_spec();
10266 s.contratos.push(WitContract {
10267 de: "payment".into(),
10268 para: "catalog".into(),
10269 wit: wit.into(),
10270 endpoint: None,
10271 subject: None,
10272 slot: None,
10273 });
10274 s.validate().unwrap_err()
10275 }
10276
10277 #[test]
10278 fn rejects_wit_with_uppercase_namespace() {
10279 // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10280 // didn't match the lowercase `wasi:http/` prefix is_http() keys
10281 // off, so the dispatch fell through to the capability arm and
10282 // the contract silently rendered as an L4-only Cilium edge.
10283 // The new gate surfaces the uppercase typo at validate time
10284 // with the offending `:wit` named.
10285 let err = contrato_wit_err("WASI:http/proxy");
10286 assert!(
10287 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10288 if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10289 "got {err:?}"
10290 );
10291 }
10292
10293 #[test]
10294 fn rejects_wit_with_hyphen_for_colon_typo() {
10295 // The canonical "I forgot the `:` separator" typo — pre-gate
10296 // this passed as Capability silently, so the renderer emitted
10297 // an L4-only policy where the author expected L7 HTTP rules.
10298 let err = contrato_wit_err("wasi-http/proxy");
10299 assert!(
10300 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10301 if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
10302 "got {err:?}"
10303 );
10304 }
10305
10306 #[test]
10307 fn rejects_wit_with_multiple_colons() {
10308 // Doubled `:` — the namespace/package split has nowhere to
10309 // anchor, so the dispatch silently demotes to Capability.
10310 let err = contrato_wit_err("wasi:http:proxy");
10311 assert!(
10312 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10313 if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
10314 "got {err:?}"
10315 );
10316 }
10317
10318 #[test]
10319 fn rejects_wit_with_empty_package() {
10320 // `wasi:` — namespace alone with no package. Pre-gate this
10321 // failed neither the is_http nor is_pubsub nor is_store
10322 // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
10323 // a bare `wasi:`), so it silently demoted to Capability.
10324 let err = contrato_wit_err("wasi:");
10325 assert!(
10326 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10327 if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
10328 "got {err:?}"
10329 );
10330 }
10331
10332 #[test]
10333 fn rejects_wit_with_underscore() {
10334 // Underscore — WIT identifiers are kebab-case, same rule
10335 // DNS-1123 enforces on its peer axes. The diagnostic carries
10336 // the explicit "use `-` instead" remediation.
10337 let err = contrato_wit_err("wasi:http_proxy");
10338 assert!(
10339 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10340 if wit == "wasi:http_proxy" && reason.contains('_')),
10341 "got {err:?}"
10342 );
10343 }
10344
10345 #[test]
10346 fn rejects_wit_with_whitespace() {
10347 // Whitespace mid-token — the prefix check matches but the
10348 // package-and-onward parse silently demoted to Capability.
10349 let err = contrato_wit_err("wasi:http proxy");
10350 assert!(
10351 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10352 if wit == "wasi:http proxy" && reason.contains("whitespace")),
10353 "got {err:?}"
10354 );
10355 }
10356
10357 #[test]
10358 fn rejects_wit_with_non_ascii() {
10359 // Un-percent-encoded non-ASCII byte — the canonical "I copied
10360 // the package name from a doc with smart quotes / accented
10361 // characters" footgun.
10362 let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
10363 assert!(
10364 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10365 if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
10366 "got {err:?}"
10367 );
10368 }
10369
10370 #[test]
10371 fn rejects_wit_with_consecutive_hyphens() {
10372 // `pub--sub` — WIT identifiers join words with single hyphens.
10373 let err = contrato_wit_err("nats:pub--sub");
10374 assert!(
10375 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10376 if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
10377 "got {err:?}"
10378 );
10379 }
10380
10381 #[test]
10382 fn rejects_wit_with_trailing_at_no_version() {
10383 // `wasi:http/proxy@` — the version-suffix author started to
10384 // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
10385 // parser would reject this; surface it at validate time.
10386 let err = contrato_wit_err("wasi:http/proxy@");
10387 assert!(
10388 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10389 if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
10390 "got {err:?}"
10391 );
10392 }
10393
10394 #[test]
10395 fn rejects_wit_too_long() {
10396 // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
10397 // The legitimate-shape arms all pass (lowercase, single `:`,
10398 // kebab-case identifiers); only the cap arm fires. Surfaces
10399 // the paste-from-binary / accidental-multi-line-blob landing
10400 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10401 // on the peer axis.
10402 let big = format!("wasi:{}", "a".repeat(124));
10403 assert_eq!(big.len(), 129);
10404 let err = contrato_wit_err(&big);
10405 assert!(
10406 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10407 if wit == &big && reason.contains("max length of 128")),
10408 "got {err:?}"
10409 );
10410 }
10411
10412 #[test]
10413 fn wit_max_length_validates() {
10414 // 128-byte WIT reference — exactly the cap. Boundary pin:
10415 // drift in the cap surfaces here and at `rejects_wit_too_long`
10416 // simultaneously, mirroring
10417 // `http_contrato_endpoint_max_length_validates` on the peer
10418 // axis.
10419 let big = format!("wasi:{}", "a".repeat(123));
10420 assert_eq!(big.len(), 128);
10421 let mut s = three_member_spec();
10422 s.contratos.push(WitContract {
10423 de: "payment".into(),
10424 para: "catalog".into(),
10425 wit: big,
10426 endpoint: None,
10427 subject: None,
10428 slot: None,
10429 });
10430 s.validate().unwrap();
10431 }
10432
10433 #[test]
10434 fn wit_accepts_canonical_forms_at_aplicacao_layer() {
10435 // Positive-set sweep through the AplicacaoSpec::validate
10436 // surface (rather than the substrate-side predicate directly)
10437 // — pins every shape the existing test fixtures + the
10438 // checkout-aplicacao example carry, so the gate's accept-set
10439 // matches the substrate's emit-set. Drift between this list
10440 // and `render::tests::wit_world_ref_accepts_canonical_forms`
10441 // surfaces at the substrate layer's positive sweep — one
10442 // source of truth for the rule.
10443 for wit in [
10444 "wasi:http/proxy",
10445 "wasi:keyvalue/store",
10446 "nats:pub-sub",
10447 "kafka:topic",
10448 "custom:exchange",
10449 "pleme:cap/audit",
10450 "wasi:http/proxy@0.2.0",
10451 ] {
10452 // Payload field paired to the dispatched WIT shape so the
10453 // shape-↔-target arm doesn't fire instead of the wit-shape
10454 // arm we're exercising. Routes off the same
10455 // `wit_shape_is_http` / `wit_shape_is_pubsub` /
10456 // `wit_shape_is_store` free functions the production
10457 // `WitContract::is_http` / `is_pubsub` / `is_store`
10458 // methods delegate to (both consult the lifted
10459 // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
10460 // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
10461 // future prefix addition to the routing accept-set
10462 // reaches this test's payload-dispatch arm by
10463 // construction — no per-test-site drift can hide a
10464 // shape-→-target-slot mismatch that would silently
10465 // demote a canonical `:wit` value to the
10466 // `(None, None, None)` capability-only arm and let the
10467 // `AplicacaoSpec::validate` positive sweep pass on a
10468 // shape it should exercise as HTTP / pub-sub / store.
10469 let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
10470 (Some("/x".into()), None, None)
10471 } else if wit_shape_is_pubsub(wit) {
10472 (None, Some("topic.x".into()), None)
10473 } else if wit_shape_is_store(wit) {
10474 (None, None, Some("bucket/$key".into()))
10475 } else {
10476 (None, None, None)
10477 };
10478 let mut s = three_member_spec();
10479 s.contratos.push(WitContract {
10480 de: "payment".into(),
10481 para: "catalog".into(),
10482 wit: wit.into(),
10483 endpoint,
10484 subject,
10485 slot,
10486 });
10487 s.validate()
10488 .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
10489 }
10490 }
10491
10492 #[test]
10493 fn wit_shape_predicates_accept_canonical_prefix_set() {
10494 // Positive-set sweep pinning every prefix in
10495 // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
10496 // WIT_STORE_SHAPE_PREFIXES against the three free-function
10497 // dispatch predicates. The six prefixes are the load-bearing
10498 // routing keys the substrate's WIT-shape dispatch consults
10499 // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
10500 // key/value-store-slot admission); any drift between the
10501 // free-function accept-set and this list surfaces here
10502 // rather than at apply time as a silent
10503 // shape-→-capability-only demotion.
10504 assert!(wit_shape_is_http("wasi:http/proxy"));
10505 assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
10506 assert!(wit_shape_is_http("http:incoming"));
10507
10508 assert!(wit_shape_is_pubsub("nats:pub-sub"));
10509 assert!(wit_shape_is_pubsub("kafka:topic"));
10510
10511 assert!(wit_shape_is_store("wasi:keyvalue/store"));
10512 assert!(wit_shape_is_store("kv:cache/session"));
10513 }
10514
10515 #[test]
10516 fn wit_shape_predicates_reject_uncanonical_forms() {
10517 // Negative-set pin: the six canonical prefixes are
10518 // lowercase-only (mirrors the `is_wit_world_ref` substrate
10519 // predicate's lowercase invariant — see its docstring on the
10520 // "I thought I had L7 HTTP routing, got L4-only" footgun).
10521 // The empty string, an uppercase-prefixed form, a hyphen-
10522 // instead-of-colon typo, and a bare kebab identifier all miss
10523 // every shape arm — reachable-by-construction only via the
10524 // `is_wit_world_ref` gate that admission-checks the `:wit`
10525 // value first, but pinned here so any future
10526 // free-function change (e.g. a case-insensitive
10527 // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
10528 // this unit level.
10529 for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
10530 assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
10531 assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
10532 assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
10533 }
10534 }
10535
10536 #[test]
10537 fn wit_shape_predicates_partition_canonical_set() {
10538 // Every canonical prefix routes to exactly one shape arm —
10539 // the three prefix sets are pairwise disjoint. Pins the
10540 // routing property [`WitContract::target`] relies on: an
10541 // `is_http()` return of `true` guarantees `is_pubsub()` and
10542 // `is_store()` return `false`, so the shape-→-target-slot
10543 // dispatch (endpoint vs subject vs slot) is unambiguous.
10544 // Drift (e.g. a future `"kv:"` moved into the HTTP set
10545 // without removal from the store set) would silently route
10546 // one prefix to two arms and the first-matching-arm order
10547 // becomes load-bearing — this pin surfaces it as a build
10548 // error instead.
10549 for prefix in WIT_HTTP_SHAPE_PREFIXES {
10550 let sample = format!("{prefix}x");
10551 assert!(wit_shape_is_http(&sample));
10552 assert!(!wit_shape_is_pubsub(&sample));
10553 assert!(!wit_shape_is_store(&sample));
10554 }
10555 for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
10556 let sample = format!("{prefix}x");
10557 assert!(!wit_shape_is_http(&sample));
10558 assert!(wit_shape_is_pubsub(&sample));
10559 assert!(!wit_shape_is_store(&sample));
10560 }
10561 for prefix in WIT_STORE_SHAPE_PREFIXES {
10562 let sample = format!("{prefix}x");
10563 assert!(!wit_shape_is_http(&sample));
10564 assert!(!wit_shape_is_pubsub(&sample));
10565 assert!(wit_shape_is_store(&sample));
10566 }
10567 }
10568
10569 #[test]
10570 fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
10571 // Positive pin: [`wit_shape_matches`] is exactly the
10572 // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
10573 // parameterized on the accept-set. Two-prefix accept-set,
10574 // one-prefix accept-set, and empty accept-set (which must
10575 // reject everything, including the empty string — an empty
10576 // `any()` fold returns `false`) all pinned so a future
10577 // reimplementation that swaps `starts_with` for `contains`,
10578 // `==`, or a case-folded comparator surfaces at unit-test
10579 // time.
10580 let two = &["wasi:http/", "http:"];
10581 assert!(wit_shape_matches("wasi:http/proxy", two));
10582 assert!(wit_shape_matches("http:incoming", two));
10583 assert!(!wit_shape_matches("wasi:keyvalue/store", two));
10584
10585 let one = &["nats:"];
10586 assert!(wit_shape_matches("nats:pub-sub", one));
10587 assert!(!wit_shape_matches("kafka:topic", one));
10588
10589 // Empty accept-set matches nothing — the identity element
10590 // for the disjunctive `any()` fold across the prefix set.
10591 // Reachable via a future `wit_shape_is_<name>` const paired
10592 // to a still-empty prefix table on a nascent shape-arm draft.
10593 let empty: &[&str] = &[];
10594 assert!(!wit_shape_matches("wasi:http/proxy", empty));
10595 assert!(!wit_shape_matches("", empty));
10596
10597 // starts_with, not contains: a prefix embedded mid-string
10598 // never matches. Pins the routing invariant [`WitContract::target`]
10599 // relies on (an authored `:wit "custom:wasi:http/"` string
10600 // does not silently route through the HTTP arm just because
10601 // it happens to contain the canonical HTTP prefix).
10602 assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
10603 }
10604
10605 #[test]
10606 fn wit_shape_predicates_delegate_to_wit_shape_matches() {
10607 // Equivalence pin: each per-shape predicate is exactly
10608 // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
10609 // every canonical prefix + the empty string + one negative
10610 // sample against every peer so a future predicate that grew
10611 // its own inline `iter().any(starts_with)` (rather than
10612 // delegating through the lifted combinator) drifts loudly here
10613 // — the peer-const table's contents must agree with the
10614 // predicate's accept-set by construction.
10615 let samples = [
10616 String::new(),
10617 "wasi:http/proxy".to_string(),
10618 "http:incoming".to_string(),
10619 "nats:pub-sub".to_string(),
10620 "kafka:topic".to_string(),
10621 "wasi:keyvalue/store".to_string(),
10622 "kv:cache/session".to_string(),
10623 "custom-shape".to_string(),
10624 "WASI:HTTP/proxy".to_string(),
10625 ];
10626 for wit in &samples {
10627 assert_eq!(
10628 wit_shape_is_http(wit),
10629 wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
10630 "wit_shape_is_http drifted from combinator on {wit:?}",
10631 );
10632 assert_eq!(
10633 wit_shape_is_pubsub(wit),
10634 wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
10635 "wit_shape_is_pubsub drifted from combinator on {wit:?}",
10636 );
10637 assert_eq!(
10638 wit_shape_is_store(wit),
10639 wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
10640 "wit_shape_is_store drifted from combinator on {wit:?}",
10641 );
10642 }
10643 }
10644
10645 #[test]
10646 fn wit_contract_shape_methods_delegate_to_free_functions() {
10647 // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
10648 // `is_store` are `&self` conveniences on top of the free
10649 // functions — for every canonical prefix the method's return
10650 // matches its free-function peer. Sweeps the union of the
10651 // three prefix sets so a future method that grew its own
10652 // inline prefix logic (rather than delegating) drifts loudly
10653 // here on the first prefix the free function accepts and the
10654 // method doesn't.
10655 for shape_set in [
10656 WIT_HTTP_SHAPE_PREFIXES,
10657 WIT_PUBSUB_SHAPE_PREFIXES,
10658 WIT_STORE_SHAPE_PREFIXES,
10659 ] {
10660 for prefix in shape_set {
10661 let c = WitContract {
10662 de: "cart".into(),
10663 para: "catalog".into(),
10664 wit: format!("{prefix}x"),
10665 endpoint: None,
10666 subject: None,
10667 slot: None,
10668 };
10669 assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
10670 assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
10671 assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
10672 }
10673 }
10674 }
10675
10676 #[test]
10677 fn wit_contract_is_capability_partitions_the_wit_shape_space() {
10678 // 4-way partition-witness pin: for every canonical prefix in
10679 // the payload-arm accept-sets, exactly one of the four
10680 // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
10681 // [`WitContract::is_store`] / [`WitContract::is_capability`]
10682 // predicates returns `true` and the other three return `false`
10683 // — the four-arm partition witness that locks the substrate's
10684 // WIT-shape-space closure on the pre-projection axis load-
10685 // bearing. A future arm addition (a hypothetical fourth
10686 // payload-shape prefix set, a `wasi:sockets/*` transport-layer
10687 // shape) that landed on one of the payload-arm predicates
10688 // without shrinking [`WitContract::is_capability`]'s accept-set
10689 // would surface here as two arms returning `true` simultaneously
10690 // — a partition-witness break the pin catches at caixa-core
10691 // build time rather than a silent per-consumer misclassification
10692 // at renderer emit time. Peer of the sibling `WitTarget`-side
10693 // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
10694 // partition-witness pin on the post-projection payload-scalar
10695 // arm-set — extends the discipline onto the pre-projection
10696 // 4-arm shape-space.
10697 for shape_set in [
10698 WIT_HTTP_SHAPE_PREFIXES,
10699 WIT_PUBSUB_SHAPE_PREFIXES,
10700 WIT_STORE_SHAPE_PREFIXES,
10701 ] {
10702 for prefix in shape_set {
10703 let c = WitContract {
10704 de: "cart".into(),
10705 para: "catalog".into(),
10706 wit: format!("{prefix}x"),
10707 endpoint: None,
10708 subject: None,
10709 slot: None,
10710 };
10711 let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
10712 .iter()
10713 .filter(|&&b| b)
10714 .count();
10715 assert_eq!(
10716 hits,
10717 1,
10718 "WitContract WIT-shape 4-way predicate partition must \
10719 admit exactly one arm per canonical prefix; got {hits} \
10720 hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
10721 is_capability={})",
10722 c.wit,
10723 c.is_http(),
10724 c.is_pubsub(),
10725 c.is_store(),
10726 c.is_capability(),
10727 );
10728 }
10729 }
10730 // Capability-arm sweep: two representative capability shapes
10731 // (a bare WIT world outside the three payload-arm prefix sets,
10732 // and the deliberately-shaped empty string that
10733 // [`crate::render::is_wit_world_ref`] rejects at
10734 // [`WitContract::target`] time but which the pure classifier
10735 // still admits — see the method docstring's "purely syntactic
10736 // classification" note). Both must land on the fourth arm
10737 // exclusively, so the partition witness holds across the full
10738 // 4-arm closure.
10739 for wit in ["custom:capability-only", ""] {
10740 let c = WitContract {
10741 de: "cart".into(),
10742 para: "catalog".into(),
10743 wit: wit.into(),
10744 endpoint: None,
10745 subject: None,
10746 slot: None,
10747 };
10748 let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
10749 .iter()
10750 .filter(|&&b| b)
10751 .count();
10752 assert_eq!(
10753 hits, 1,
10754 "WitContract WIT-shape 4-way predicate partition must \
10755 admit exactly one arm on Capability-shaped wit={wit:?}"
10756 );
10757 assert!(
10758 c.is_capability(),
10759 "wit={wit:?} must project onto the Capability arm"
10760 );
10761 }
10762 }
10763
10764 #[test]
10765 fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
10766 // Composition-witness pin: [`WitContract::is_capability`] is the
10767 // exact-inverse disjunction of the sibling payload-arm predicate
10768 // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
10769 // [`WitContract::is_store`]. A future reimplementation that
10770 // grew its own prefix-set scan (e.g. inlining a fourth
10771 // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
10772 // own today) rather than delegating to the sibling trio would
10773 // drift loudly here — the composition contract binds the
10774 // fourth-arm predicate to the exact-inverse of the three
10775 // payload-arm predicates, so any rebrand of any prefix-set const
10776 // flows through this method by construction without a
10777 // coordinated per-consumer rewrite. Sweeps the union of the
10778 // three payload-arm prefix sets plus two Capability-shaped
10779 // shapes (a bare non-prefix-matching WIT world, the deliberately-
10780 // empty string the pure classifier still admits per the method
10781 // docstring's "purely syntactic classification" note).
10782 let mut cases: Vec<String> = Vec::new();
10783 for shape_set in [
10784 WIT_HTTP_SHAPE_PREFIXES,
10785 WIT_PUBSUB_SHAPE_PREFIXES,
10786 WIT_STORE_SHAPE_PREFIXES,
10787 ] {
10788 for prefix in shape_set {
10789 cases.push(format!("{prefix}x"));
10790 }
10791 }
10792 cases.push("custom:capability-only".to_string());
10793 cases.push(String::new());
10794 for wit in cases {
10795 let c = WitContract {
10796 de: "cart".into(),
10797 para: "catalog".into(),
10798 wit: wit.clone(),
10799 endpoint: None,
10800 subject: None,
10801 slot: None,
10802 };
10803 assert_eq!(
10804 c.is_capability(),
10805 !c.is_http() && !c.is_pubsub() && !c.is_store(),
10806 "WitContract::is_capability must equal \
10807 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
10808 );
10809 }
10810 }
10811
10812 #[test]
10813 fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
10814 // Cross-projection-witness pin: whenever [`WitContract::target`]
10815 // succeeds, the pre-projection [`WitContract::is_capability`]
10816 // classification agrees with the post-projection
10817 // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
10818 // predicate — the 4-arm typed partition on the substrate's
10819 // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
10820 // partition on the pre-projection axis line up by construction.
10821 // A future divergence between the two axes (a peer
10822 // [`WitTarget`] variant addition that landed on the typed-view
10823 // surface without a peer prefix-set + [`WitContract`] predicate
10824 // extension, or vice versa) would surface here at caixa-core
10825 // build time rather than a silent per-consumer split at renderer
10826 // emit time. Peer of the sibling pre-/post-projection
10827 // agreement pins the payload-carrier trio
10828 // ([`WitContract::endpoint`] / [`WitContract::subject`] /
10829 // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
10830 // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
10831 // post-projection — b11bb49 trio lift) already carry across the
10832 // three payload arms — this pin closes the pair on the fourth
10833 // payload-less arm.
10834 let http = WitContract {
10835 de: "cart".into(),
10836 para: "catalog".into(),
10837 wit: "wasi:http/proxy".into(),
10838 endpoint: Some("/x".into()),
10839 subject: None,
10840 slot: None,
10841 };
10842 assert!(!http.is_capability());
10843 assert!(!http.target().unwrap().is_capability());
10844
10845 let nats = WitContract {
10846 de: "cart".into(),
10847 para: "catalog".into(),
10848 wit: "nats:pub-sub".into(),
10849 endpoint: None,
10850 subject: Some("events.x".into()),
10851 slot: None,
10852 };
10853 assert!(!nats.is_capability());
10854 assert!(!nats.target().unwrap().is_capability());
10855
10856 let kv = WitContract {
10857 de: "cart".into(),
10858 para: "catalog".into(),
10859 wit: "wasi:keyvalue/store".into(),
10860 endpoint: None,
10861 subject: None,
10862 slot: Some("checkout/$orderId".into()),
10863 };
10864 assert!(!kv.is_capability());
10865 assert!(!kv.target().unwrap().is_capability());
10866
10867 let cap = WitContract {
10868 de: "cart".into(),
10869 para: "catalog".into(),
10870 wit: "custom:capability-only".into(),
10871 endpoint: None,
10872 subject: None,
10873 slot: None,
10874 };
10875 assert!(cap.is_capability());
10876 assert!(cap.target().unwrap().is_capability());
10877 }
10878
10879 #[test]
10880 fn empty_wit_takes_precedence_over_invalid() {
10881 // Ordering pin: `EmptyWit` is the more self-locating
10882 // diagnostic on `""` and must lead — the value-shape gate is
10883 // only reached after the empty-check fires. Mirrors
10884 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
10885 // the peer payload axis.
10886 let mut s = three_member_spec();
10887 s.contratos.push(WitContract {
10888 de: "payment".into(),
10889 para: "catalog".into(),
10890 wit: String::new(),
10891 endpoint: None,
10892 subject: None,
10893 slot: None,
10894 });
10895 let err = s.validate().unwrap_err();
10896 assert!(
10897 matches!(err, AplicacaoError::EmptyWit { .. }),
10898 "got {err:?}"
10899 );
10900 }
10901
10902 #[test]
10903 fn wit_invalid_fires_before_payload_shape_arm() {
10904 // Ordering pin: a malformed `:wit` surfaces *its own*
10905 // diagnostic (which names the offending wit verbatim) before
10906 // any payload-field check — a contrato whose wit is
10907 // structurally invalid AND carries a wrong target field
10908 // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
10909 // because the dispatch on the wit is what decides which
10910 // payload field is "right" in the first place. Without this
10911 // ordering, the author would see "wrong target field" for a
10912 // wit that hasn't even been parsed, which doesn't name the
10913 // root cause.
10914 let mut s = three_member_spec();
10915 s.contratos.push(WitContract {
10916 de: "payment".into(),
10917 para: "catalog".into(),
10918 // Hyphen-for-colon typo + endpoint set: pre-gate this
10919 // raised `ContratoWrongTarget { expected: "none" }` (the
10920 // Capability arm rejecting the endpoint), masking the
10921 // real authoring mistake (the wit isn't `wasi:http/proxy`).
10922 wit: "wasi-http/proxy".into(),
10923 endpoint: Some("/x".into()),
10924 subject: None,
10925 slot: None,
10926 });
10927 let err = s.validate().unwrap_err();
10928 assert!(
10929 matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
10930 if wit == "wasi-http/proxy"),
10931 "got {err:?}"
10932 );
10933 }
10934
10935 #[test]
10936 fn wit_invalid_diagnostic_carries_offending_wit() {
10937 // Diagnostic-shape pin — the offending `:wit` + `:de` +
10938 // `:para` + a non-empty reason flow through verbatim so the
10939 // author can grep their caixa.lisp for the offending contrato
10940 // block and fix it in one edit. Same shape as
10941 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
10942 let err = contrato_wit_err("WASI:HTTP/proxy");
10943 match err {
10944 AplicacaoError::ContratoWitInvalid {
10945 de,
10946 para,
10947 wit,
10948 reason,
10949 } => {
10950 assert_eq!(de, "payment");
10951 assert_eq!(para, "catalog");
10952 assert_eq!(wit, "WASI:HTTP/proxy");
10953 assert!(!reason.is_empty(), "reason field must be non-empty");
10954 }
10955 other => panic!("expected ContratoWitInvalid, got {other:?}"),
10956 }
10957 }
10958
10959 // ── :contratos :subject value-shape gate ─────────────────────────────
10960 //
10961 // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
10962 // suites on the peer payload axes. Until this gate landed
10963 // `WitContract::target()` only refused the empty string; a
10964 // structurally invalid subject silently passed validate and the
10965 // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
10966 // Subject'` on publish / subscribe, or as a silent message drop,
10967 // far from the source caixa.lisp. Every authoring footgun the
10968 // NATS server's subject parser would catch on admission now
10969 // becomes a caixa-build-time `ContratoSubjectInvalid` with the
10970 // offending `:subject` + `:de` + `:para` named verbatim. Same
10971 // diagnostic shape as `ContratoEndpointInvalid` /
10972 // `ContratoWitInvalid` on the peer payload axes; same shared
10973 // predicate (`crate::render::is_nats_subject`) ensures drift
10974 // between any two axes' rule enforcement is a build error at the
10975 // predicate, not piecemeal across renderers.
10976
10977 fn contrato_subject_err(subject: &str) -> AplicacaoError {
10978 // Fresh spec per call so the new contract doesn't collide on
10979 // identity with `three_member_spec`'s pre-existing entries.
10980 // The new edge uses `(payment, catalog)` — a pair the fixture
10981 // doesn't already declare — with `:wit "nats:pub-sub"` and the
10982 // varying `:subject`, so the subject-shape gate fires cleanly
10983 // after the wit-shape gate (which `"nats:pub-sub"` passes).
10984 let mut s = three_member_spec();
10985 s.contratos.push(WitContract {
10986 de: "payment".into(),
10987 para: "catalog".into(),
10988 wit: "nats:pub-sub".into(),
10989 endpoint: None,
10990 subject: Some(subject.into()),
10991 slot: None,
10992 });
10993 s.validate().unwrap_err()
10994 }
10995
10996 #[test]
10997 fn rejects_pubsub_contrato_subject_with_whitespace() {
10998 // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
10999 // landed at the NATS server as a malformed subject the parser
11000 // rejects with `-ERR 'Invalid Subject'`. Now caught at the
11001 // source caixa.lisp.
11002 let err = contrato_subject_err("foo bar");
11003 assert!(
11004 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11005 if subject == "foo bar" && reason.contains("whitespace")),
11006 "got {err:?}"
11007 );
11008 }
11009
11010 #[test]
11011 fn rejects_pubsub_contrato_subject_with_control_char() {
11012 let err = contrato_subject_err("foo\x01bar");
11013 assert!(
11014 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11015 if subject == "foo\x01bar" && reason.contains("control character")),
11016 "got {err:?}"
11017 );
11018 }
11019
11020 #[test]
11021 fn rejects_pubsub_contrato_subject_with_non_ascii() {
11022 // Un-percent-encoded non-ASCII byte — the canonical "I copied
11023 // the subject from a doc with smart quotes / accented
11024 // characters" footgun.
11025 let err = contrato_subject_err("foo.caf\u{e9}");
11026 assert!(
11027 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11028 if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
11029 "got {err:?}"
11030 );
11031 }
11032
11033 #[test]
11034 fn rejects_pubsub_contrato_subject_with_leading_dot() {
11035 // Empty leading token — NATS rejects.
11036 let err = contrato_subject_err(".foo");
11037 assert!(
11038 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11039 if subject == ".foo" && reason.contains("must not start with `.`")),
11040 "got {err:?}"
11041 );
11042 }
11043
11044 #[test]
11045 fn rejects_pubsub_contrato_subject_with_trailing_dot() {
11046 // Empty trailing token — NATS rejects. The remediation
11047 // (use `>` instead) is in the reason string.
11048 let err = contrato_subject_err("foo.");
11049 assert!(
11050 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11051 if subject == "foo." && reason.contains("must not end with `.`")),
11052 "got {err:?}"
11053 );
11054 }
11055
11056 #[test]
11057 fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
11058 // The canonical "I forgot to fill in the middle segment"
11059 // typo — `"foo..bar"`. NATS rejects empty tokens.
11060 let err = contrato_subject_err("foo..bar");
11061 assert!(
11062 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11063 if subject == "foo..bar" && reason.contains("consecutive `.`")),
11064 "got {err:?}"
11065 );
11066 }
11067
11068 #[test]
11069 fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
11070 // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
11071 // as the final segment. Pre-gate this passed as a typed edge
11072 // and surfaced at runtime as a NATS subscribe rejection.
11073 let err = contrato_subject_err("foo.>.bar");
11074 assert!(
11075 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11076 if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
11077 "got {err:?}"
11078 );
11079 }
11080
11081 #[test]
11082 fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
11083 // `foo*.bar` — NATS wildcards are standalone tokens. The
11084 // remediation is in the reason string.
11085 let err = contrato_subject_err("foo*.bar");
11086 assert!(
11087 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11088 if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
11089 "got {err:?}"
11090 );
11091 }
11092
11093 #[test]
11094 fn rejects_pubsub_contrato_subject_with_invalid_char() {
11095 // `foo,bar` — comma is not a valid NATS subject character.
11096 // Pinned separately from the wildcard arms so the invalid-
11097 // character diagnostic is in force.
11098 let err = contrato_subject_err("foo,bar");
11099 assert!(
11100 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11101 if subject == "foo,bar" && reason.contains("invalid character")),
11102 "got {err:?}"
11103 );
11104 }
11105
11106 #[test]
11107 fn rejects_pubsub_contrato_subject_too_long() {
11108 // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
11109 // The legitimate-shape arms all pass (one all-`a` token, no
11110 // `.`, no wildcards); only the cap arm fires. Surfaces the
11111 // paste-from-binary / accidental-multi-line-blob landing
11112 // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
11113 // on the peer axis.
11114 let big = "a".repeat(257);
11115 assert_eq!(big.len(), 257);
11116 let err = contrato_subject_err(&big);
11117 assert!(
11118 matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
11119 if subject == &big && reason.contains("max length of 256")),
11120 "got {err:?}"
11121 );
11122 }
11123
11124 #[test]
11125 fn pubsub_contrato_subject_max_length_validates() {
11126 // 256-byte subject — exactly the cap. Boundary pin: drift in
11127 // the cap surfaces here and at
11128 // `rejects_pubsub_contrato_subject_too_long` simultaneously,
11129 // mirroring `http_contrato_endpoint_max_length_validates` and
11130 // `wit_max_length_validates` on the peer axes.
11131 let big = "a".repeat(256);
11132 assert_eq!(big.len(), 256);
11133 let mut s = three_member_spec();
11134 s.contratos.push(WitContract {
11135 de: "payment".into(),
11136 para: "catalog".into(),
11137 wit: "nats:pub-sub".into(),
11138 endpoint: None,
11139 subject: Some(big),
11140 slot: None,
11141 });
11142 s.validate().unwrap();
11143 }
11144
11145 #[test]
11146 fn pubsub_contrato_subject_accepts_canonical_forms() {
11147 // Positive-set sweep: every canonical NATS subject shape the
11148 // substrate-side `is_nats_subject` predicate accepts (the
11149 // multi-dot `events.order.charged`, the snake_case / kebab-
11150 // case / mixed-case tokens, the digit-bearing tokens, the
11151 // single-token wildcard `*` at every segment position, and
11152 // the trailing `>` multi-token wildcard) must remain a valid
11153 // contrato subject too. Drift between this list and the
11154 // substrate-side `nats_subject_accepts_canonical_forms` sweep
11155 // surfaces at the shared predicate — one source of truth.
11156 // Uses a fresh `(payment, catalog)` edge so none of the swept
11157 // subjects collide with the pre-existing entries in
11158 // `three_member_spec`.
11159 for subject in [
11160 "checkout.events.charge.failed",
11161 "rio.events.order.charged",
11162 "orders",
11163 "orders.123",
11164 "snake_case.token",
11165 "kebab-case.token",
11166 "MixedCase.Token",
11167 "orders.*.charged",
11168 "*.events.*",
11169 "orders.>",
11170 ] {
11171 let mut s = three_member_spec();
11172 s.contratos.push(WitContract {
11173 de: "payment".into(),
11174 para: "catalog".into(),
11175 wit: "nats:pub-sub".into(),
11176 endpoint: None,
11177 subject: Some(subject.into()),
11178 slot: None,
11179 });
11180 s.validate()
11181 .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
11182 }
11183 }
11184
11185 #[test]
11186 fn contrato_subject_empty_takes_precedence_over_invalid() {
11187 // Ordering pin: `ContratoSubjectEmpty` is the more self-
11188 // locating diagnostic on `""` and must lead — the value-shape
11189 // gate is only reached after the empty-check fires. Mirrors
11190 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11191 // the peer payload axis.
11192 let mut s = three_member_spec();
11193 s.contratos.push(WitContract {
11194 de: "payment".into(),
11195 para: "catalog".into(),
11196 wit: "nats:pub-sub".into(),
11197 endpoint: None,
11198 subject: Some(String::new()),
11199 slot: None,
11200 });
11201 let err = s.validate().unwrap_err();
11202 assert!(
11203 matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
11204 "got {err:?}"
11205 );
11206 }
11207
11208 #[test]
11209 fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
11210 // Diagnostic-shape pin — the offending `:subject` + `:de` +
11211 // `:para` + a non-empty reason flow through verbatim so the
11212 // author can grep their caixa.lisp for the offending contrato
11213 // block and fix it in one edit. Same shape as
11214 // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
11215 // and `wit_invalid_diagnostic_carries_offending_wit`.
11216 let err = contrato_subject_err("foo..bar");
11217 match err {
11218 AplicacaoError::ContratoSubjectInvalid {
11219 de,
11220 para,
11221 subject,
11222 reason,
11223 } => {
11224 assert_eq!(de, "payment");
11225 assert_eq!(para, "catalog");
11226 assert_eq!(subject, "foo..bar");
11227 assert!(!reason.is_empty(), "reason field must be non-empty");
11228 }
11229 other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
11230 }
11231 }
11232
11233 #[test]
11234 fn target_view_pubsub_subject_passes_through_to_typed_view() {
11235 // The compounding theorem on the pub-sub axis: every
11236 // `WitTarget::PubSub { subject }` returned by `target()` carries
11237 // a NATS-server-accepted subject. Renderers downstream of
11238 // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
11239 // NATS Stream/Consumer CR emitter, the future `feira app graph`
11240 // view's subject labeller) can rely on this without re-checking
11241 // — the type system carries the proof. Mirrors
11242 // `target_view_payload_is_guaranteed_nonempty_after_target_call`
11243 // on the peer axes.
11244 let nats = WitContract {
11245 de: "a".into(),
11246 para: "b".into(),
11247 wit: "nats:pub-sub".into(),
11248 endpoint: None,
11249 subject: Some("orders.events.*.charged".into()),
11250 slot: None,
11251 };
11252 match nats.target().unwrap() {
11253 WitTarget::PubSub { subject } => {
11254 assert_eq!(subject, "orders.events.*.charged");
11255 }
11256 other => panic!("expected PubSub, got {other:?}"),
11257 }
11258 }
11259
11260 // ── :contratos :slot value-shape gate ────────────────────────────────
11261 //
11262 // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
11263 // (63e18a0) value-shape suites on the peer payload axes. Until this
11264 // gate landed `WitContract::target()` only refused the empty string
11265 // for the Store arm; a structurally invalid slot (raw whitespace,
11266 // control character, non-ASCII byte, paste-from-binary multi-line
11267 // blob) silently passed validate and surfaced at runtime as a
11268 // per-backend kv write rejection or a silent next-read corruption,
11269 // far from the source caixa.lisp with no field naming which
11270 // `:contratos` edge carried the typo. Every authoring footgun the
11271 // kv backend intersection-floor would catch on write now becomes a
11272 // caixa-build-time `ContratoSlotInvalid` with the offending
11273 // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
11274 // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
11275 // peer payload axes; same shared predicate
11276 // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
11277 // any two axes' rule enforcement is a build error at the
11278 // predicate, not piecemeal across renderers. Closes the typed
11279 // payload-axis value-shape trajectory across all three legs of the
11280 // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
11281
11282 fn contrato_slot_err(slot: &str) -> AplicacaoError {
11283 // Fresh spec per call so the new contract doesn't collide on
11284 // identity with `three_member_spec`'s pre-existing entries
11285 // and doesn't close a synchronous cycle the cycle detector
11286 // would reject before the slot-shape gate fires. The new edge
11287 // uses `(payment, catalog)` — a pair the fixture doesn't
11288 // already declare in either direction (the fixture carries
11289 // `cart -> catalog` and `cart -> payment`, so `payment ->
11290 // catalog` doesn't form a cycle on the sync subgraph) — with
11291 // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
11292 // slot-shape gate fires cleanly after the wit-shape gate
11293 // (which `"wasi:keyvalue/store"` passes). Same edge pair the
11294 // peer `contrato_subject_err` helper uses (63e18a0).
11295 let mut s = three_member_spec();
11296 s.contratos.push(WitContract {
11297 de: "payment".into(),
11298 para: "catalog".into(),
11299 wit: "wasi:keyvalue/store".into(),
11300 endpoint: None,
11301 subject: None,
11302 slot: Some(slot.into()),
11303 });
11304 s.validate().unwrap_err()
11305 }
11306
11307 #[test]
11308 fn rejects_store_contrato_slot_with_whitespace() {
11309 // Fail-before-pass-after pin — pre-gate `"check out/$order"`
11310 // silently landed at the kv backend with whitespace whose
11311 // runtime behavior varies unpredictably across backends (etcd
11312 // accepts, Redis accepts then breaks on next CLI op, DynamoDB
11313 // rejects on write). Now caught at the source caixa.lisp.
11314 let err = contrato_slot_err("check out/$order");
11315 assert!(
11316 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11317 if slot == "check out/$order" && reason.contains("whitespace")),
11318 "got {err:?}"
11319 );
11320 }
11321
11322 #[test]
11323 fn rejects_store_contrato_slot_with_tab() {
11324 // Tab byte arm-pinned separately from the space arm so a
11325 // future relaxation that admits one but not the other surfaces
11326 // here.
11327 let err = contrato_slot_err("check\tout");
11328 assert!(
11329 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11330 if slot == "check\tout" && reason.contains("whitespace")),
11331 "got {err:?}"
11332 );
11333 }
11334
11335 #[test]
11336 fn rejects_store_contrato_slot_with_control_char() {
11337 // SOH (0x01) — distinct from the whitespace arm. Redis admits
11338 // and corrupts on RESP protocol framing; DynamoDB rejects on
11339 // write.
11340 let err = contrato_slot_err("checkout/\x01order");
11341 assert!(
11342 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11343 if slot == "checkout/\x01order" && reason.contains("control character")),
11344 "got {err:?}"
11345 );
11346 }
11347
11348 #[test]
11349 fn rejects_store_contrato_slot_with_newline() {
11350 // Embedded newline — the canonical "the paste-from-binary slug
11351 // spans multiple lines" footgun. Distinct from the whitespace
11352 // arm because `\n` is a control character (0x0A).
11353 let err = contrato_slot_err("checkout\norder");
11354 assert!(
11355 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11356 if slot == "checkout\norder" && reason.contains("control character")),
11357 "got {err:?}"
11358 );
11359 }
11360
11361 #[test]
11362 fn rejects_store_contrato_slot_with_non_ascii() {
11363 // Un-percent-encoded non-ASCII byte — the canonical "I copied
11364 // the slot from a doc with accented characters" footgun. Each
11365 // kv backend re-encodes non-ASCII differently (etcd preserves
11366 // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
11367 // rejects), so the typed slot's value set is the intersection-
11368 // floor every backend admits identically (printable ASCII).
11369 let err = contrato_slot_err("ch\u{e9}ckout/$order");
11370 assert!(
11371 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11372 if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
11373 "got {err:?}"
11374 );
11375 }
11376
11377 #[test]
11378 fn rejects_store_contrato_slot_too_long() {
11379 // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
11380 // legitimate-shape arms all pass (a single all-`a` token, no
11381 // separators); only the cap arm fires. Surfaces the paste-
11382 // from-binary / accidental-multi-line-blob landing footgun.
11383 // Mirrors `rejects_pubsub_contrato_subject_too_long` and
11384 // `rejects_http_contrato_endpoint_too_long` on the peer
11385 // payload axes.
11386 let big = "a".repeat(513);
11387 assert_eq!(big.len(), 513);
11388 let err = contrato_slot_err(&big);
11389 assert!(
11390 matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
11391 if slot == &big && reason.contains("max length of 512")),
11392 "got {err:?}"
11393 );
11394 }
11395
11396 #[test]
11397 fn store_contrato_slot_max_length_validates() {
11398 // 512-byte slot — exactly the cap. Boundary pin: drift in the
11399 // cap surfaces here and at `rejects_store_contrato_slot_too_long`
11400 // simultaneously, mirroring
11401 // `pubsub_contrato_subject_max_length_validates` and
11402 // `http_contrato_endpoint_max_length_validates` on the peer
11403 // payload axes.
11404 let big = "a".repeat(512);
11405 assert_eq!(big.len(), 512);
11406 let mut s = three_member_spec();
11407 s.contratos.push(WitContract {
11408 de: "payment".into(),
11409 para: "catalog".into(),
11410 wit: "wasi:keyvalue/store".into(),
11411 endpoint: None,
11412 subject: None,
11413 slot: Some(big),
11414 });
11415 s.validate().unwrap();
11416 }
11417
11418 #[test]
11419 fn store_contrato_slot_accepts_canonical_forms() {
11420 // Positive-set sweep: every canonical kv slot template the
11421 // substrate-side `is_wasi_keyvalue_slot` predicate accepts
11422 // (single-token identifiers, path-namespaced `$`-templates,
11423 // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
11424 // snake_case / kebab-case / MixedCase tokens, digit-bearing
11425 // tokens, percent-encoded fragments) must remain valid
11426 // contrato slots too. Drift between this list and the
11427 // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
11428 // surfaces at the shared predicate — one source of truth.
11429 // Uses a fresh `(payment, catalog)` edge so none of the swept
11430 // slots collide with the pre-existing entries in
11431 // `three_member_spec`.
11432 for slot in [
11433 "checkout",
11434 "checkout/$orderId",
11435 "users:{tenant}/{id}",
11436 "session.<sid>",
11437 "session.tokens.<sid>",
11438 "snake_case_key",
11439 "kebab-case-key",
11440 "MixedCase",
11441 "shard0",
11442 "v2/key",
11443 "users/caf%C3%A9",
11444 ] {
11445 let mut s = three_member_spec();
11446 s.contratos.push(WitContract {
11447 de: "payment".into(),
11448 para: "catalog".into(),
11449 wit: "wasi:keyvalue/store".into(),
11450 endpoint: None,
11451 subject: None,
11452 slot: Some(slot.into()),
11453 });
11454 s.validate()
11455 .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
11456 }
11457 }
11458
11459 #[test]
11460 fn contrato_slot_empty_takes_precedence_over_invalid() {
11461 // Ordering pin: `ContratoSlotEmpty` is the more self-locating
11462 // diagnostic on `""` and must lead — the value-shape gate is
11463 // only reached after the empty-check fires. Mirrors
11464 // `contrato_subject_empty_takes_precedence_over_invalid` and
11465 // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11466 // the peer payload axes.
11467 let mut s = three_member_spec();
11468 s.contratos.push(WitContract {
11469 de: "payment".into(),
11470 para: "catalog".into(),
11471 wit: "wasi:keyvalue/store".into(),
11472 endpoint: None,
11473 subject: None,
11474 slot: Some(String::new()),
11475 });
11476 let err = s.validate().unwrap_err();
11477 assert!(
11478 matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
11479 "got {err:?}"
11480 );
11481 }
11482
11483 #[test]
11484 fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
11485 // Diagnostic-shape pin — the offending `:slot` + `:de` +
11486 // `:para` + a non-empty reason flow through verbatim so the
11487 // author can grep their caixa.lisp for the offending contrato
11488 // block and fix it in one edit. Same shape as
11489 // `contrato_subject_invalid_diagnostic_carries_offending_subject`
11490 // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
11491 // on the peer payload axes.
11492 let err = contrato_slot_err("check out/$order");
11493 match err {
11494 AplicacaoError::ContratoSlotInvalid {
11495 de,
11496 para,
11497 slot,
11498 reason,
11499 } => {
11500 assert_eq!(de, "payment");
11501 assert_eq!(para, "catalog");
11502 assert_eq!(slot, "check out/$order");
11503 assert!(!reason.is_empty(), "reason field must be non-empty");
11504 }
11505 other => panic!("expected ContratoSlotInvalid, got {other:?}"),
11506 }
11507 }
11508
11509 #[test]
11510 fn target_view_store_slot_passes_through_to_typed_view() {
11511 // The compounding theorem on the store axis: every
11512 // `WitTarget::Store { slot }` returned by `target()` carries a
11513 // kv-backend-accepted slot template. Renderers downstream of
11514 // `typed_view()` (the future per-Servico `:capabilities
11515 // wasi:keyvalue/store` axis emitter, the future `feira app
11516 // graph` view's slot labeller, the future kv-provider CR
11517 // materializer) can rely on this without re-checking — the
11518 // type system carries the proof. Mirrors
11519 // `target_view_pubsub_subject_passes_through_to_typed_view` on
11520 // the peer payload axis.
11521 let store = WitContract {
11522 de: "a".into(),
11523 para: "b".into(),
11524 wit: "wasi:keyvalue/store".into(),
11525 endpoint: None,
11526 subject: None,
11527 slot: Some("checkout/$orderId".into()),
11528 };
11529 match store.target().unwrap() {
11530 WitTarget::Store { slot } => {
11531 assert_eq!(slot, "checkout/$orderId");
11532 }
11533 other => panic!("expected Store, got {other:?}"),
11534 }
11535 }
11536
11537 #[test]
11538 fn rejects_self_loop_in_synchronous_contratos() {
11539 // A synchronous self-edge (`cart → cart` over HTTP) is now
11540 // rejected by the dedicated `ContratoSelfLoop` gate — a precise
11541 // "this edge is degenerate" diagnostic — rather than incidentally
11542 // by the cycle detector framing it as a `["cart", "cart"]`
11543 // multi-node deadlock.
11544 let mut s = three_member_spec();
11545 s.contratos.push(contract_http("cart", "cart", "/loop"));
11546 let err = s.validate().unwrap_err();
11547 match err {
11548 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
11549 assert_eq!(caixa, "cart");
11550 assert_eq!(wit, "wasi:http/proxy");
11551 }
11552 other => panic!("expected ContratoSelfLoop, got {other:?}"),
11553 }
11554 }
11555
11556 #[test]
11557 fn rejects_self_loop_in_pubsub_contratos() {
11558 // The cycle detector excludes pub-sub edges (acyclic by
11559 // construction), so before the explicit gate a `nats:pub-sub`
11560 // self-edge silently validated and rendered a self-allow CNP.
11561 // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
11562 let mut s = three_member_spec();
11563 s.contratos.push(WitContract {
11564 de: "payment".into(),
11565 para: "payment".into(),
11566 wit: "nats:pub-sub".into(),
11567 endpoint: None,
11568 subject: Some("rio.events.payment".into()),
11569 slot: None,
11570 });
11571 let err = s.validate().unwrap_err();
11572 match err {
11573 AplicacaoError::ContratoSelfLoop { caixa, wit } => {
11574 assert_eq!(caixa, "payment");
11575 assert_eq!(wit, "nats:pub-sub");
11576 }
11577 other => panic!("expected ContratoSelfLoop, got {other:?}"),
11578 }
11579 }
11580
11581 #[test]
11582 fn self_loop_fires_before_payload_shape_check() {
11583 // The structural "this edge can't exist" error precedes the
11584 // narrower payload-shape diagnostics: a self-edge carrying an
11585 // otherwise-malformed endpoint still reports ContratoSelfLoop,
11586 // not ContratoEndpointInvalid.
11587 let mut s = three_member_spec();
11588 s.contratos.push(WitContract {
11589 de: "cart".into(),
11590 para: "cart".into(),
11591 wit: "wasi:http/proxy".into(),
11592 endpoint: Some("not-absolute".into()),
11593 subject: None,
11594 slot: None,
11595 });
11596 match s.validate().unwrap_err() {
11597 AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
11598 other => panic!("expected ContratoSelfLoop, got {other:?}"),
11599 }
11600 }
11601
11602 #[test]
11603 fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
11604 // A self-edge naming a non-member reports the more fundamental
11605 // ContratoMemberMissing first (the member doesn't exist), so the
11606 // self-loop gate is reached only once both endpoints resolve.
11607 let mut s = three_member_spec();
11608 s.contratos.push(contract_http("ghost", "ghost", "/loop"));
11609 match s.validate().unwrap_err() {
11610 AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
11611 other => panic!("expected ContratoMemberMissing, got {other:?}"),
11612 }
11613 }
11614
11615 #[test]
11616 fn rejects_two_node_synchronous_cycle() {
11617 let mut s = three_member_spec();
11618 // existing edges: cart → catalog, cart → payment
11619 // adding catalog → cart closes a 2-cycle on the HTTP subgraph
11620 s.contratos
11621 .push(contract_http("catalog", "cart", "/refresh"));
11622 let err = s.validate().unwrap_err();
11623 match err {
11624 AplicacaoError::ContratoCycle { cycle } => {
11625 // Cycle traversal should mention both endpoints, with
11626 // the back-edge target appearing as both first and last
11627 // element to close the loop.
11628 assert!(cycle.len() >= 3);
11629 assert_eq!(cycle.first(), cycle.last());
11630 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
11631 assert!(body.contains("cart"));
11632 assert!(body.contains("catalog"));
11633 }
11634 other => panic!("expected ContratoCycle, got {other:?}"),
11635 }
11636 }
11637
11638 #[test]
11639 fn rejects_three_node_synchronous_cycle() {
11640 let mut s = three_member_spec();
11641 // Reset to a clean 3-cycle: catalog → cart → payment → catalog
11642 s.contratos = vec![
11643 contract_http("catalog", "cart", "/x"),
11644 contract_http("cart", "payment", "/y"),
11645 contract_http("payment", "catalog", "/z"),
11646 ];
11647 let err = s.validate().unwrap_err();
11648 match err {
11649 AplicacaoError::ContratoCycle { cycle } => {
11650 assert_eq!(cycle.first(), cycle.last());
11651 let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
11652 assert_eq!(body.len(), 3);
11653 assert!(body.contains("cart"));
11654 assert!(body.contains("catalog"));
11655 assert!(body.contains("payment"));
11656 }
11657 other => panic!("expected ContratoCycle, got {other:?}"),
11658 }
11659 }
11660
11661 #[test]
11662 fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
11663 // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
11664 // "acyclic by construction" — so a cycle whose closing edge
11665 // is pub-sub should NOT raise ContratoCycle.
11666 let mut s = three_member_spec();
11667 s.contratos = vec![
11668 contract_http("catalog", "cart", "/x"),
11669 contract_http("cart", "payment", "/y"),
11670 // Closing edge is pub-sub — async; not a sync deadlock.
11671 WitContract {
11672 de: "payment".into(),
11673 para: "catalog".into(),
11674 wit: "nats:pub-sub".into(),
11675 endpoint: None,
11676 subject: Some("checkout.events.charge.completed".into()),
11677 slot: None,
11678 },
11679 ];
11680 s.validate().expect("pub-sub edge breaks the sync cycle");
11681 }
11682
11683 #[test]
11684 fn store_edge_counts_as_synchronous_for_cycle_detection() {
11685 // wasi:keyvalue/store is request/response; a cycle through one
11686 // *is* a sync deadlock, just like HTTP.
11687 let mut s = three_member_spec();
11688 s.contratos = vec![
11689 contract_http("catalog", "cart", "/x"),
11690 WitContract {
11691 de: "cart".into(),
11692 para: "catalog".into(),
11693 wit: "wasi:keyvalue/store".into(),
11694 endpoint: None,
11695 subject: None,
11696 slot: Some("session/$id".into()),
11697 },
11698 ];
11699 let err = s.validate().unwrap_err();
11700 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
11701 }
11702
11703 #[test]
11704 fn capability_edge_counts_as_synchronous_for_cycle_detection() {
11705 // Capability-only edges (unknown WIT shape, no payload) default
11706 // to synchronous — safer; authors with truly async capability
11707 // semantics can model them as pub-sub explicitly.
11708 let mut s = three_member_spec();
11709 s.contratos = vec![
11710 contract_http("catalog", "cart", "/x"),
11711 WitContract {
11712 de: "cart".into(),
11713 para: "catalog".into(),
11714 wit: "custom:exchange".into(),
11715 endpoint: None,
11716 subject: None,
11717 slot: None,
11718 },
11719 ];
11720 let err = s.validate().unwrap_err();
11721 assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
11722 }
11723
11724 #[test]
11725 fn long_acyclic_chain_validates() {
11726 // A long sync chain (no back-edges) must validate even when
11727 // every node is reachable from the first.
11728 let mut s = three_member_spec();
11729 s.membros = vec![
11730 membro("a", "^0.1"),
11731 membro("b", "^0.1"),
11732 membro("c", "^0.1"),
11733 membro("d", "^0.1"),
11734 membro("e", "^0.1"),
11735 ];
11736 s.contratos = vec![
11737 contract_http("a", "b", "/1"),
11738 contract_http("b", "c", "/2"),
11739 contract_http("c", "d", "/3"),
11740 contract_http("d", "e", "/4"),
11741 ];
11742 s.entrada.as_mut().unwrap().para = "a".into();
11743 s.validate().unwrap();
11744 }
11745
11746 #[test]
11747 fn diamond_acyclic_validates() {
11748 // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
11749 let mut s = three_member_spec();
11750 s.membros = vec![
11751 membro("a", "^0.1"),
11752 membro("b", "^0.1"),
11753 membro("c", "^0.1"),
11754 membro("d", "^0.1"),
11755 ];
11756 s.contratos = vec![
11757 contract_http("a", "b", "/1"),
11758 contract_http("a", "c", "/2"),
11759 contract_http("b", "d", "/3"),
11760 contract_http("c", "d", "/4"),
11761 ];
11762 s.entrada.as_mut().unwrap().para = "a".into();
11763 s.validate().unwrap();
11764 }
11765
11766 // ── duplicate-`:contratos` build-error gate ──────────────────────────
11767
11768 #[test]
11769 fn rejects_duplicate_http_contrato() {
11770 // Fail-before-pass-after pin: the fixture's `cart → catalog`
11771 // HTTP edge appears once. Push an identical entry — same
11772 // (de, para, wit, endpoint) — and validate() must reject it.
11773 // Until this gate landed the typed surface accepted the
11774 // duplicate silently and caixa-mesh's `cilium_network_policies`
11775 // emitted two ``CiliumNetworkPolicy`` objects with identical
11776 // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
11777 // admission rejects on `kubectl apply` far from the source.
11778 let mut s = three_member_spec();
11779 s.contratos
11780 .push(contract_http("cart", "catalog", "/products/:id"));
11781 let err = s.validate().unwrap_err();
11782 assert!(
11783 matches!(
11784 err,
11785 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11786 if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
11787 ),
11788 "got {err:?}"
11789 );
11790 }
11791
11792 #[test]
11793 fn rejects_duplicate_pubsub_contrato() {
11794 // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
11795 // edges with identical (de, para, subject) are degenerate;
11796 // pin that the typed surface refuses both at validate time.
11797 let mut s = three_member_spec();
11798 let pubsub = WitContract {
11799 de: "payment".into(),
11800 para: "cart".into(),
11801 wit: "nats:pub-sub".into(),
11802 endpoint: None,
11803 subject: Some("checkout.events.charge.failed".into()),
11804 slot: None,
11805 };
11806 s.contratos.push(pubsub.clone());
11807 s.contratos.push(pubsub);
11808 let err = s.validate().unwrap_err();
11809 assert!(
11810 matches!(
11811 err,
11812 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11813 if de == "payment" && para == "cart" && wit == "nats:pub-sub"
11814 ),
11815 "got {err:?}"
11816 );
11817 }
11818
11819 #[test]
11820 fn rejects_duplicate_store_contrato() {
11821 // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
11822 // edges with identical (de, para, slot) collapse to one mesh-
11823 // policy edge; pin the build error.
11824 let mut s = three_member_spec();
11825 let store = WitContract {
11826 de: "cart".into(),
11827 para: "payment".into(),
11828 wit: "wasi:keyvalue/store".into(),
11829 endpoint: None,
11830 subject: None,
11831 slot: Some("checkout/$orderId".into()),
11832 };
11833 // Drop the conflicting HTTP `cart → payment` edge from the
11834 // fixture so the duplicate-store pair is the only one
11835 // distinguishable on this pair.
11836 s.contratos
11837 .retain(|c| !(c.de == "cart" && c.para == "payment"));
11838 s.contratos.push(store.clone());
11839 s.contratos.push(store);
11840 let err = s.validate().unwrap_err();
11841 assert!(
11842 matches!(
11843 err,
11844 AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
11845 if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
11846 ),
11847 "got {err:?}"
11848 );
11849 }
11850
11851 #[test]
11852 fn rejects_duplicate_capability_contrato() {
11853 // Same gate on the pure-capability axis (no payload selector).
11854 // Two contracts with identical (de, para, wit) and no
11855 // endpoint/subject/slot are duplicate edges; pin so a future
11856 // `target_label` change can't accidentally collapse the
11857 // capability arm into a None-shaped key that compares equal
11858 // to a populated one.
11859 let mut s = three_member_spec();
11860 let capability = WitContract {
11861 de: "cart".into(),
11862 para: "catalog".into(),
11863 wit: "pleme:cap/audit".into(),
11864 endpoint: None,
11865 subject: None,
11866 slot: None,
11867 };
11868 s.contratos.push(capability.clone());
11869 s.contratos.push(capability);
11870 let err = s.validate().unwrap_err();
11871 match err {
11872 AplicacaoError::ContratoDuplicate {
11873 de,
11874 para,
11875 wit,
11876 target,
11877 } => {
11878 assert_eq!(de, "cart");
11879 assert_eq!(para, "catalog");
11880 assert_eq!(wit, "pleme:cap/audit");
11881 assert!(
11882 target.contains("capability"),
11883 "capability-edge duplicate diagnostic must surface the \
11884 no-payload shape (got target = {target:?})"
11885 );
11886 }
11887 other => panic!("expected ContratoDuplicate, got {other:?}"),
11888 }
11889 }
11890
11891 #[test]
11892 fn accepts_distinct_http_paths_between_same_pair() {
11893 // Negative pin: two HTTP contracts cart → catalog at distinct
11894 // endpoints (`/products/:id` and `/search`) are *not*
11895 // duplicates — they're distinct typed edges differing on the
11896 // payload axis. The duplicate-gate must not over-match here,
11897 // since the cart-calls-catalog-on-multiple-paths shape is the
11898 // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
11899 // example: cart calls catalog at /products/:id, payment at
11900 // /charge — same shape extends to two paths on one para).
11901 let mut s = three_member_spec();
11902 s.contratos
11903 .push(contract_http("cart", "catalog", "/search"));
11904 s.validate()
11905 .expect("distinct endpoints between same (de, para) must validate");
11906 }
11907
11908 #[test]
11909 fn accepts_same_endpoint_on_different_pairs() {
11910 // Negative pin: the same `/charge` endpoint reused on two
11911 // different (de, para) pairs is two distinct edges, not a
11912 // duplicate. Pinning this shape so the gate's identity key
11913 // includes both `de` and `para` (not just `(wit, endpoint)`).
11914 let mut s = three_member_spec();
11915 s.contratos
11916 .push(contract_http("payment", "catalog", "/charge"));
11917 s.validate()
11918 .expect("same endpoint reused on distinct (de, para) must validate");
11919 }
11920
11921 #[test]
11922 fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
11923 // Pin the diagnostic shape: the duplicate-edge error names
11924 // *which* target field carried the conflict, so the author
11925 // doesn't have to re-grep the source caixa.lisp to find it.
11926 // Same self-locating diagnostic discipline as
11927 // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
11928 let mut s = three_member_spec();
11929 s.contratos
11930 .push(contract_http("cart", "catalog", "/products/:id"));
11931 let err = s.validate().unwrap_err();
11932 let msg = format!("{err}");
11933 assert!(
11934 msg.contains("\"/products/:id\""),
11935 "duplicate-contrato diagnostic must name the offending \
11936 :endpoint payload (got: {msg:?})"
11937 );
11938 assert!(
11939 msg.contains("cart") && msg.contains("catalog"),
11940 "diagnostic must name both endpoints of the duplicate edge \
11941 (got: {msg:?})"
11942 );
11943 }
11944
11945 #[test]
11946 fn duplicate_contrato_gate_runs_after_membership_check() {
11947 // Order pin: a duplicate contract whose `:de` is *also* not in
11948 // `:membros` surfaces the membership error first — the
11949 // missing-member diagnostic is more locating than the
11950 // duplicate-edge one (the author has to fix the membership
11951 // before the duplicate is meaningful). Same ordering
11952 // discipline as `membros_validation_runs_before_contratos_membership_check`.
11953 let mut s = three_member_spec();
11954 s.contratos.push(contract_http("phantom", "catalog", "/x"));
11955 s.contratos.push(contract_http("phantom", "catalog", "/x"));
11956 let err = s.validate().unwrap_err();
11957 assert!(
11958 matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
11959 "membership-missing must fire before duplicate-edge (got {err:?})"
11960 );
11961 }
11962
11963 #[test]
11964 fn duplicate_contrato_gate_runs_after_target_shape_check() {
11965 // Order pin: a contract with a malformed target (e.g. an HTTP
11966 // wit world with an empty :endpoint) surfaces the target-shape
11967 // error first, not the duplicate one. Even when two such
11968 // malformed entries are identical, the per-contract `target()`
11969 // check fires inside the loop *before* the duplicate-key
11970 // insert, so the diagnostic remains the most-locating one.
11971 let mut s = three_member_spec();
11972 let malformed = WitContract {
11973 de: "cart".into(),
11974 para: "catalog".into(),
11975 wit: "wasi:http/proxy".into(),
11976 endpoint: Some(String::new()),
11977 subject: None,
11978 slot: None,
11979 };
11980 s.contratos.push(malformed.clone());
11981 s.contratos.push(malformed);
11982 let err = s.validate().unwrap_err();
11983 assert!(
11984 matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
11985 "endpoint-empty must fire before duplicate-edge (got {err:?})"
11986 );
11987 }
11988
11989 #[test]
11990 fn wit_target_label_pins_per_variant_format() {
11991 // Label format is the single source of truth every duplicate-
11992 // `:contratos` diagnostic + every future `feira app graph`
11993 // consumer routes through. Pin the shape per variant so a
11994 // future edit to `WitTarget::label` (e.g. a JSON emitter that
11995 // strips the leading `:`, or a rename from `endpoint` →
11996 // `path`) surfaces as a red-red test rather than as a silent
11997 // downstream diagnostic drift. Together with the exhaustive
11998 // `match` on `WitTarget` inside `label()`, adding a future
11999 // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
12000 // peer, per-edge WIT registry variants) is a compile error at
12001 // the label site — not a fall-through into the `Capability`
12002 // "no payload" default the prior raw-field-probe helper
12003 // silently landed on.
12004 assert_eq!(
12005 WitTarget::Http {
12006 endpoint: "/charge",
12007 }
12008 .label(),
12009 "\
12010:endpoint \"/charge\""
12011 );
12012 assert_eq!(
12013 WitTarget::PubSub {
12014 subject: "events.checkout.paid",
12015 }
12016 .label(),
12017 "\
12018:subject \"events.checkout.paid\""
12019 );
12020 assert_eq!(
12021 WitTarget::Store {
12022 slot: "checkout/$order",
12023 }
12024 .label(),
12025 "\
12026:slot \"checkout/$order\""
12027 );
12028 assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
12029 // Capability-arm label routes through the lifted
12030 // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
12031 // declaration per arm, next to the variant" discipline the
12032 // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
12033 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12034 // consts already carry extends to the payload-less arm; the
12035 // byte-string equality pin below plus this label-routes-
12036 // through-the-const pin make a future rebrand on either the
12037 // const declaration or the `label()` template a build error
12038 // here rather than a downstream consumer surprise.
12039 assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
12040 assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
12041 }
12042
12043 #[test]
12044 fn wit_target_display_routes_through_label_helper() {
12045 // Fail-before-pass-after pin on the fourth (and only remaining)
12046 // typed-shape-discriminator axis to converge onto the
12047 // three-path-convergence discipline the sibling M3
12048 // [`PlacementStrategy`] (0a2f653) and M2
12049 // [`crate::supervisor::RestartStrategy`] /
12050 // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
12051 // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
12052 // through [`WitTarget::label`], so every consumer reaching for
12053 // `format!("{v}")` on a typed payload target lands on the same
12054 // stable author-facing byte-string [`WitTarget::label`] returns
12055 // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
12056 // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
12057 // `:contratos` gate seeds via [`WitTarget::label`] at
12058 // aplicacao.rs:5491 already threads through.
12059 //
12060 // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
12061 // through to the `Debug` derive's structural output
12062 // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
12063 // rather than the [`WitTarget::label`] helper's stable byte-
12064 // string (`:endpoint "/charge"` — the author-facing `:contratos`
12065 // keyword form). Every future consumer that reaches for
12066 // `format!("{target}")` — the canonical shape every user-facing
12067 // pretty-print site on the sibling typed-enum axes
12068 // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
12069 // [`crate::supervisor::RestartPolicy`]) already uses — would
12070 // silently land under a different byte-string than the
12071 // [`WitTarget::label`] callers that the duplicate-`:contratos`
12072 // diagnostic already threads through, with the mismatch
12073 // surfacing as a downstream diagnostic / graph / audit line
12074 // reading one spelling while the substrate's own gate emitted
12075 // another.
12076 //
12077 // Pin the routing here so a future
12078 // `impl std::fmt::Display for WitTarget<'_>` reimplementation
12079 // that hand-rolls the per-arm formatting instead of delegating
12080 // to [`WitTarget::label`] fails at caixa-core build time.
12081 for variant in [
12082 WitTarget::Http {
12083 endpoint: "/charge",
12084 },
12085 WitTarget::PubSub {
12086 subject: "events.checkout.paid",
12087 },
12088 WitTarget::Store {
12089 slot: "checkout/$order",
12090 },
12091 WitTarget::Capability,
12092 ] {
12093 assert_eq!(
12094 variant.to_string(),
12095 variant.label(),
12096 "WitTarget::{variant:?} Display must route through \
12097 WitTarget::label (single source of truth: the lifted \
12098 payload_pair 4-arm dispatch the label helper already \
12099 threads through)"
12100 );
12101 }
12102 }
12103
12104 #[test]
12105 fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
12106 // Consumer-side pin on the three-path convergence:
12107 // [`std::fmt::Display`] agrees byte-for-byte with the
12108 // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
12109 // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
12110 // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
12111 // Pre-lift the two paths were structurally independent — the
12112 // substrate-side gate reached for `target_view.label()` while a
12113 // future downstream diagnostic / graph / audit line reaching
12114 // for `format!("{target}")` would silently land on the `Debug`
12115 // derive's structural output. Pin the two paths byte-for-byte
12116 // here so any future variant addition (M4 `Rest`/`Grpc` split
12117 // of [`WitTarget::Http`], `Queue`-shaped peer of
12118 // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
12119 // match error at [`WitTarget::payload_pair`] rather than a
12120 // silent per-consumer dispatch miss.
12121 for variant in [
12122 WitTarget::Http {
12123 endpoint: "/charge",
12124 },
12125 WitTarget::PubSub {
12126 subject: "events.checkout.paid",
12127 },
12128 WitTarget::Store {
12129 slot: "checkout/$order",
12130 },
12131 WitTarget::Capability,
12132 ] {
12133 assert_eq!(
12134 format!("{variant}"),
12135 variant.label(),
12136 "WitTarget::{variant:?} Display byte-string must match \
12137 the AplicacaoError::ContratoDuplicate `target:` carrier \
12138 the AplicacaoSpec::validate duplicate-`:contratos` gate \
12139 seeds via WitTarget::label — three-path convergence: \
12140 Display + label + payload_pair all resolve to the same \
12141 per-arm byte-string"
12142 );
12143 }
12144 }
12145
12146 #[test]
12147 fn wit_target_payload_pair_pins_per_variant() {
12148 // Pin the per-arm `(field-name, payload)` pair single-sourced
12149 // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
12150 // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
12151 // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
12152 // and [`WitTarget::field_name`] (returns the first component)
12153 // route through. Until this lift landed [`WitTarget::label`]
12154 // dispatched on the same three arms with a per-arm
12155 // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
12156 // paired [`WitTarget::HTTP_FIELD_NAME`] /
12157 // [`WitTarget::PUBSUB_FIELD_NAME`] /
12158 // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
12159 // canonical "same shape, written N times" duplication
12160 // THEORY.md §I.3.5 promotes to a build-time concern. A future
12161 // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
12162 // [`WitTarget::Http`], `Queue`-shaped peer of
12163 // [`WitTarget::Store`]) is one match-arm edit at
12164 // [`WitTarget::payload_pair`], visible here as a compile-time
12165 // exhaustiveness error on both this pin and the label-format
12166 // pin above.
12167 assert_eq!(
12168 WitTarget::Http {
12169 endpoint: "/charge"
12170 }
12171 .payload_pair(),
12172 Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
12173 );
12174 assert_eq!(
12175 WitTarget::PubSub {
12176 subject: "events.x",
12177 }
12178 .payload_pair(),
12179 Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
12180 );
12181 assert_eq!(
12182 WitTarget::Store {
12183 slot: "checkout/$order",
12184 }
12185 .payload_pair(),
12186 Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
12187 );
12188 assert_eq!(WitTarget::Capability.payload_pair(), None);
12189 }
12190
12191 #[test]
12192 fn wit_target_field_name_pins_per_variant() {
12193 // Pin the per-arm author-facing `:contratos` payload field
12194 // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
12195 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12196 // + returned by [`WitTarget::field_name`]. Every downstream
12197 // consumer (the [`WitContract::target`] gate's `expected:`
12198 // scalar, the [`WitTarget::label`] template's keyword prefix,
12199 // the `feira app graph` verb's `endpoint=…` prefix) routes
12200 // through the same three peer consts, so a rename on the
12201 // author-surface `(defcaixa … :contratos ((:de … :para …
12202 // :wit … :endpoint …)))` field lands in exactly one place.
12203 assert_eq!(
12204 WitTarget::Http {
12205 endpoint: "/charge"
12206 }
12207 .field_name(),
12208 Some(WitTarget::HTTP_FIELD_NAME),
12209 );
12210 assert_eq!(
12211 WitTarget::PubSub {
12212 subject: "events.x",
12213 }
12214 .field_name(),
12215 Some(WitTarget::PUBSUB_FIELD_NAME),
12216 );
12217 assert_eq!(
12218 WitTarget::Store {
12219 slot: "checkout/$order",
12220 }
12221 .field_name(),
12222 Some(WitTarget::STORE_FIELD_NAME),
12223 );
12224 // Capability arm carries no payload field — the diagnostic
12225 // never reports `expected: "capability"` because the gate's
12226 // Capability arm accepts no payload at all (it fires the
12227 // "expected: none" WrongTarget error instead), so the field-
12228 // name method returns None here rather than a placeholder.
12229 assert_eq!(WitTarget::Capability.field_name(), None);
12230
12231 // Peer const scalar values pinned so a rename on either side
12232 // (author-surface field name in the `(defcaixa …)` DSL, or
12233 // the diagnostic's `expected:` scalar) can't drift without
12234 // failing here first.
12235 assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
12236 assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
12237 assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
12238 }
12239
12240 #[test]
12241 fn wit_target_payload_pins_per_variant() {
12242 // Pin the per-arm payload scalar single-sourced onto the
12243 // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
12244 // [`WitTarget::payload`] — the peer per-half projection to
12245 // [`WitTarget::field_name`] on the paired sub-selector axis. The
12246 // three payload-carrying arms round-trip their author-declared
12247 // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
12248 // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
12249 // the payload-less [`WitTarget::Capability`] arm returns `None`.
12250 // Same shape as the sibling `wit_target_field_name_pins_per_variant`
12251 // (c6ec2af) pin on the Component-0 projection axis, extended
12252 // onto the Component-1 projection axis so both per-half readers
12253 // on the paired dispatch carry their own byte-shape pin.
12254 assert_eq!(
12255 WitTarget::Http {
12256 endpoint: "/charge",
12257 }
12258 .payload(),
12259 Some("/charge"),
12260 );
12261 assert_eq!(
12262 WitTarget::PubSub {
12263 subject: "events.x",
12264 }
12265 .payload(),
12266 Some("events.x"),
12267 );
12268 assert_eq!(
12269 WitTarget::Store {
12270 slot: "checkout/$order",
12271 }
12272 .payload(),
12273 Some("checkout/$order"),
12274 );
12275 assert_eq!(WitTarget::Capability.payload(), None);
12276 }
12277
12278 #[test]
12279 fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
12280 // Per-variant equivalence pin: for every arm of [`WitTarget`],
12281 // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
12282 // byte-for-byte. Guards the drift surface where a future refactor
12283 // that split one accessor off the shared match onto its own
12284 // dispatch — a well-meaning "inline the pair back into per-half
12285 // fields for one crate-internal caller who only wanted one half"
12286 // or a scratch `impl` shadowing the derived projection — would
12287 // silently desynchronize [`WitTarget::payload`] from the
12288 // authoritative [`WitTarget::payload_pair`] dispatch, and every
12289 // downstream consumer that thinks "the payload half of the pair"
12290 // would drift from the diagnostic / graph consumers reading the
12291 // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
12292 // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
12293 // per-half projection pin (`gitrefspec_ref_pair_projects_
12294 // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
12295 // FluxCD source-controller `spec.ref.<field>` axis — same "one
12296 // paired dispatch, both per-half projections agree byte-for-
12297 // byte" discipline extended onto the M3 `:contratos` payload-
12298 // arm surface.
12299 for variant in [
12300 WitTarget::Http {
12301 endpoint: "/charge",
12302 },
12303 WitTarget::PubSub {
12304 subject: "events.checkout.paid",
12305 },
12306 WitTarget::Store {
12307 slot: "checkout/$order",
12308 },
12309 WitTarget::Capability,
12310 ] {
12311 let via_projection = variant.payload();
12312 let via_pair = variant.payload_pair().map(|(_, p)| p);
12313 assert_eq!(
12314 via_projection, via_pair,
12315 "WitTarget::{variant:?} payload() must equal \
12316 payload_pair().map(|(_, p)| p) byte-for-byte — a \
12317 regression that splits the two per-half projections off \
12318 their shared match would silently desynchronize the \
12319 payload accessor from the paired dispatch every \
12320 diagnostic / graph consumer reads through",
12321 );
12322 }
12323 }
12324
12325 #[test]
12326 fn wit_target_http_endpoint_pins_per_variant() {
12327 // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
12328 // [`WitTarget::http_endpoint`] 2-arm dispatch — the
12329 // substrate-primitive per-arm post-projection accessor every
12330 // L7-HTTP-facing consumer routes through, sibling to the peer
12331 // WitContract pre-projection [`WitContract::endpoint`] (7020470)
12332 // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
12333 // arm round-trips its author-declared endpoint verbatim as
12334 // `Some("/charge")`; the three sibling arms
12335 // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
12336 // [`WitTarget::Capability`]) each return `None` because they
12337 // carry no HTTP endpoint by definition. Same fail-before-pass-
12338 // after per-variant discipline as the sibling
12339 // `wit_target_payload_pins_per_variant` (5d6dc92) /
12340 // `wit_target_field_name_pins_per_variant` (c6ec2af) /
12341 // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
12342 // the peer pan-arm / per-half projection axes — extended onto
12343 // the per-arm HTTP-shape post-projection axis so a future
12344 // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
12345 // [`WitTarget::Http`], a `Queue`-shaped peer of
12346 // [`WitTarget::Store`]) trips a compile-time exhaustiveness
12347 // error on the sibling [`WitTarget::http_endpoint`] match arms
12348 // whose payload the L7-HTTP-shape accept-set is meant to bound.
12349 assert_eq!(
12350 WitTarget::Http {
12351 endpoint: "/charge",
12352 }
12353 .http_endpoint(),
12354 Some("/charge"),
12355 );
12356 assert_eq!(
12357 WitTarget::PubSub {
12358 subject: "events.checkout.paid",
12359 }
12360 .http_endpoint(),
12361 None,
12362 );
12363 assert_eq!(
12364 WitTarget::Store {
12365 slot: "checkout/$order",
12366 }
12367 .http_endpoint(),
12368 None,
12369 );
12370 assert_eq!(WitTarget::Capability.http_endpoint(), None);
12371 }
12372
12373 #[test]
12374 fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
12375 // Per-variant coherence pin: for every arm of [`WitTarget`],
12376 // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
12377 // arm (both project the same author-declared request-path
12378 // scalar), and returns `None` on every sibling arm regardless of
12379 // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
12380 // Store carry their own payload the pan-arm accessor surfaces,
12381 // but that payload is not an HTTP endpoint — the per-arm
12382 // accessor must not leak it through the HTTP-shape channel).
12383 // Guards the drift surface where a future refactor that
12384 // conflated the per-arm HTTP projection with the pan-arm
12385 // [`WitTarget::payload`] projection — a well-meaning "one
12386 // accessor for the L7 branch, one for the graph" collapse that
12387 // routes both through the same 4-arm dispatch — would silently
12388 // widen the L7-HTTP-shape accept-set onto pub-sub / store
12389 // payloads at the caixa-mesh L7 emit branch, admitting a
12390 // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
12391 // rule with the operator-side apply-time symptom (Cilium's
12392 // eBPF data-plane rejects every ingress edge whose L7 filter
12393 // doesn't match the wire-format HTTP request line) far from
12394 // the source refactor. Sibling to the peer
12395 // `wit_target_payload_matches_payload_pair_second_component_
12396 // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
12397 // extended onto the per-arm HTTP specialization axis so both
12398 // the pan-arm and the per-arm projections carry their own
12399 // byte-shape coherence witness against the substrate's typed
12400 // arm-family accept-set.
12401 for variant in [
12402 WitTarget::Http {
12403 endpoint: "/charge",
12404 },
12405 WitTarget::PubSub {
12406 subject: "events.checkout.paid",
12407 },
12408 WitTarget::Store {
12409 slot: "checkout/$order",
12410 },
12411 WitTarget::Capability,
12412 ] {
12413 let per_arm = variant.http_endpoint();
12414 let pan_arm = variant.payload();
12415 if variant.is_http() {
12416 assert_eq!(
12417 per_arm, pan_arm,
12418 "WitTarget::{variant:?} http_endpoint() must equal \
12419 payload() on the Http arm — a per-arm-vs-pan-arm \
12420 split would silently drift the L7 emit branch's \
12421 path-scalar source from the graph verb's payload \
12422 scalar source",
12423 );
12424 } else {
12425 assert_eq!(
12426 per_arm, None,
12427 "WitTarget::{variant:?} http_endpoint() must return \
12428 None on non-Http arms — a leak that surfaced a \
12429 pub-sub :subject or a key/value :slot through the \
12430 HTTP-endpoint accessor would silently widen the \
12431 Cilium L7 HTTP `path:` rule accept-set onto \
12432 protocol shapes Cilium's eBPF data-plane can't \
12433 introspect",
12434 );
12435 }
12436 }
12437 }
12438
12439 #[test]
12440 fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
12441 // Per-variant coherence pin: for every arm of [`WitTarget`],
12442 // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
12443 // drift surface where a future extension of the
12444 // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
12445 // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
12446 // accessor to cover both peers) landed without a paired
12447 // extension of the [`gen_platform::IsVariant`]-derived
12448 // `is_http()` predicate's accept-set, or vice versa — a
12449 // regression that split the "which arms count as HTTP-shaped
12450 // for L7-path emission?" answer between two dispatch surfaces
12451 // the substrate ships. Sibling to the peer
12452 // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
12453 // on the paired dispatch axis — extended onto the per-arm
12454 // predicate-vs-accessor coherence axis so the gen-platform
12455 // IsVariant predicate and the substrate-lifted per-arm
12456 // accessor carry one shared answer to "is this the HTTP arm?".
12457 for variant in [
12458 WitTarget::Http {
12459 endpoint: "/charge",
12460 },
12461 WitTarget::PubSub {
12462 subject: "events.checkout.paid",
12463 },
12464 WitTarget::Store {
12465 slot: "checkout/$order",
12466 },
12467 WitTarget::Capability,
12468 ] {
12469 assert_eq!(
12470 variant.http_endpoint().is_some(),
12471 variant.is_http(),
12472 "WitTarget::{variant:?} http_endpoint().is_some() must \
12473 equal is_http() — a drift would split the L7 emit \
12474 branch's arm-set gate from the substrate-derived \
12475 shape-discrimination predicate on the same axis",
12476 );
12477 }
12478 }
12479
12480 #[test]
12481 fn wit_target_pubsub_subject_pins_per_variant() {
12482 // Fail-before-pass-after pin: the substrate-canonical per-arm
12483 // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
12484 // is the single dispatch every future pub-sub-facing consumer
12485 // routes through, sibling to the peer [`WitContract::subject`]
12486 // (63e18a0) pre-projection scalar accessor on the raw-field
12487 // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
12488 // post-projection per-arm accessor on the sibling HTTP-shape
12489 // axis. The [`WitTarget::PubSub`] arm round-trips its
12490 // author-declared subject verbatim as
12491 // `Some("events.checkout.paid")`; the three sibling arms each
12492 // return `None` because they carry no NATS-shaped subject by
12493 // definition. Same fail-before-pass-after per-variant discipline
12494 // as the sibling `wit_target_http_endpoint_pins_per_variant`
12495 // pin on the peer per-arm axis — extended onto the per-arm
12496 // pub-sub-shape post-projection axis so a future [`WitTarget`]
12497 // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
12498 // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
12499 // compile-time exhaustiveness error on the sibling
12500 // [`WitTarget::pubsub_subject`] match arms whose payload the
12501 // pub-sub-shape accept-set is meant to bound.
12502 assert_eq!(
12503 WitTarget::PubSub {
12504 subject: "events.checkout.paid",
12505 }
12506 .pubsub_subject(),
12507 Some("events.checkout.paid"),
12508 );
12509 assert_eq!(
12510 WitTarget::Http {
12511 endpoint: "/charge",
12512 }
12513 .pubsub_subject(),
12514 None,
12515 );
12516 assert_eq!(
12517 WitTarget::Store {
12518 slot: "checkout/$order",
12519 }
12520 .pubsub_subject(),
12521 None,
12522 );
12523 assert_eq!(WitTarget::Capability.pubsub_subject(), None);
12524 }
12525
12526 #[test]
12527 fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
12528 // Per-variant coherence pin: for every arm of [`WitTarget`],
12529 // `.pubsub_subject()` equals `.payload()` on the
12530 // [`WitTarget::PubSub`] arm (both project the same
12531 // author-declared subject scalar), and returns `None` on every
12532 // sibling arm regardless of whether [`WitTarget::payload`]
12533 // itself returns `Some` (Http / Store carry their own payload
12534 // the pan-arm accessor surfaces, but that payload is not a
12535 // pub-sub subject — the per-arm accessor must not leak it
12536 // through the pub-sub-shape channel). Sibling to the peer
12537 // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
12538 // coherence pin on the per-arm HTTP-shape axis — extended onto
12539 // the per-arm pub-sub specialization axis so both per-arm
12540 // projections carry their own byte-shape coherence witness
12541 // against the substrate's typed arm-family accept-set.
12542 for variant in [
12543 WitTarget::Http {
12544 endpoint: "/charge",
12545 },
12546 WitTarget::PubSub {
12547 subject: "events.checkout.paid",
12548 },
12549 WitTarget::Store {
12550 slot: "checkout/$order",
12551 },
12552 WitTarget::Capability,
12553 ] {
12554 let per_arm = variant.pubsub_subject();
12555 let pan_arm = variant.payload();
12556 if variant.is_pubsub() {
12557 assert_eq!(
12558 per_arm, pan_arm,
12559 "WitTarget::{variant:?} pubsub_subject() must equal \
12560 payload() on the PubSub arm — a per-arm-vs-pan-arm \
12561 split would silently drift the pub-sub-shape emit \
12562 branch's subject-scalar source from the graph verb's \
12563 payload scalar source",
12564 );
12565 } else {
12566 assert_eq!(
12567 per_arm, None,
12568 "WitTarget::{variant:?} pubsub_subject() must return \
12569 None on non-PubSub arms — a leak that surfaced an \
12570 HTTP :endpoint or a key/value :slot through the \
12571 pub-sub-subject accessor would silently widen the \
12572 downstream NATS-shape accept-set onto protocol \
12573 shapes NATS servers can't route",
12574 );
12575 }
12576 }
12577 }
12578
12579 #[test]
12580 fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
12581 // Per-variant coherence pin: for every arm of [`WitTarget`],
12582 // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
12583 // drift surface where a future extension of the
12584 // [`WitTarget::pubsub_subject`] accessor's accept-set landed
12585 // without a paired extension of the [`gen_platform::IsVariant`]-
12586 // derived `is_pubsub()` predicate's accept-set, or vice versa
12587 // — a regression that split the "which arms count as pub-sub-
12588 // shaped for subject emission?" answer between two dispatch
12589 // surfaces the substrate ships. Sibling to the peer
12590 // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
12591 // pin on the per-arm HTTP-shape axis — extended onto the
12592 // per-arm pub-sub predicate-vs-accessor coherence axis so the
12593 // gen-platform IsVariant predicate and the substrate-lifted
12594 // per-arm accessor carry one shared answer to "is this the
12595 // PubSub arm?".
12596 for variant in [
12597 WitTarget::Http {
12598 endpoint: "/charge",
12599 },
12600 WitTarget::PubSub {
12601 subject: "events.checkout.paid",
12602 },
12603 WitTarget::Store {
12604 slot: "checkout/$order",
12605 },
12606 WitTarget::Capability,
12607 ] {
12608 assert_eq!(
12609 variant.pubsub_subject().is_some(),
12610 variant.is_pubsub(),
12611 "WitTarget::{variant:?} pubsub_subject().is_some() must \
12612 equal is_pubsub() — a drift would split the pub-sub \
12613 emit branch's arm-set gate from the substrate-derived \
12614 shape-discrimination predicate on the same axis",
12615 );
12616 }
12617 }
12618
12619 #[test]
12620 fn wit_target_store_slot_pins_per_variant() {
12621 // Fail-before-pass-after pin: the substrate-canonical per-arm
12622 // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
12623 // is the single dispatch every future store-facing consumer
12624 // routes through, sibling to the peer [`WitContract::slot`]
12625 // pre-projection scalar accessor on the raw-field axis and to
12626 // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
12627 // [`WitTarget::pubsub_subject`] post-projection per-arm
12628 // accessors on the sibling per-payload-arm axes. The
12629 // [`WitTarget::Store`] arm round-trips its author-declared
12630 // slot verbatim as `Some("checkout/$order")`; the three
12631 // sibling arms each return `None` because they carry no
12632 // WASI-key/value slot by definition. Same fail-before-pass-
12633 // after per-variant discipline as the sibling
12634 // `wit_target_http_endpoint_pins_per_variant` +
12635 // `wit_target_pubsub_subject_pins_per_variant` pins on the
12636 // peer per-arm axes — extended onto the per-arm store-shape
12637 // post-projection axis so a future [`WitTarget`] variant
12638 // addition trips a compile-time exhaustiveness error on the
12639 // sibling [`WitTarget::store_slot`] match arms whose payload
12640 // the store-shape accept-set is meant to bound.
12641 assert_eq!(
12642 WitTarget::Store {
12643 slot: "checkout/$order",
12644 }
12645 .store_slot(),
12646 Some("checkout/$order"),
12647 );
12648 assert_eq!(
12649 WitTarget::Http {
12650 endpoint: "/charge",
12651 }
12652 .store_slot(),
12653 None,
12654 );
12655 assert_eq!(
12656 WitTarget::PubSub {
12657 subject: "events.checkout.paid",
12658 }
12659 .store_slot(),
12660 None,
12661 );
12662 assert_eq!(WitTarget::Capability.store_slot(), None);
12663 }
12664
12665 #[test]
12666 fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
12667 // Per-variant coherence pin: for every arm of [`WitTarget`],
12668 // `.store_slot()` equals `.payload()` on the
12669 // [`WitTarget::Store`] arm (both project the same
12670 // author-declared slot scalar), and returns `None` on every
12671 // sibling arm regardless of whether [`WitTarget::payload`]
12672 // itself returns `Some`. Sibling to the peer
12673 // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
12674 // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
12675 // pins on the per-arm HTTP and PubSub axes — closes the
12676 // per-arm-vs-pan-arm byte-shape coherence trio across all
12677 // three payload arms.
12678 for variant in [
12679 WitTarget::Http {
12680 endpoint: "/charge",
12681 },
12682 WitTarget::PubSub {
12683 subject: "events.checkout.paid",
12684 },
12685 WitTarget::Store {
12686 slot: "checkout/$order",
12687 },
12688 WitTarget::Capability,
12689 ] {
12690 let per_arm = variant.store_slot();
12691 let pan_arm = variant.payload();
12692 if variant.is_store() {
12693 assert_eq!(
12694 per_arm, pan_arm,
12695 "WitTarget::{variant:?} store_slot() must equal \
12696 payload() on the Store arm — a per-arm-vs-pan-arm \
12697 split would silently drift the store-shape emit \
12698 branch's slot-scalar source from the graph verb's \
12699 payload scalar source",
12700 );
12701 } else {
12702 assert_eq!(
12703 per_arm, None,
12704 "WitTarget::{variant:?} store_slot() must return \
12705 None on non-Store arms — a leak that surfaced an \
12706 HTTP :endpoint or a NATS :subject through the \
12707 key/value-slot accessor would silently widen the \
12708 downstream WASI-key/value slot accept-set onto \
12709 protocol shapes the kv backends can't route",
12710 );
12711 }
12712 }
12713 }
12714
12715 #[test]
12716 fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
12717 // Per-variant coherence pin: for every arm of [`WitTarget`],
12718 // `.store_slot().is_some()` iff `.is_store()`. Guards the
12719 // drift surface where a future extension of the
12720 // [`WitTarget::store_slot`] accessor's accept-set landed
12721 // without a paired extension of the [`gen_platform::IsVariant`]-
12722 // derived `is_store()` predicate's accept-set. Sibling to the
12723 // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
12724 // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
12725 // pins — closes the per-arm predicate-vs-accessor coherence
12726 // trio across all three payload arms so the gen-platform
12727 // IsVariant predicate and the substrate-lifted per-arm
12728 // accessor carry one shared answer to "is this the Store arm?".
12729 for variant in [
12730 WitTarget::Http {
12731 endpoint: "/charge",
12732 },
12733 WitTarget::PubSub {
12734 subject: "events.checkout.paid",
12735 },
12736 WitTarget::Store {
12737 slot: "checkout/$order",
12738 },
12739 WitTarget::Capability,
12740 ] {
12741 assert_eq!(
12742 variant.store_slot().is_some(),
12743 variant.is_store(),
12744 "WitTarget::{variant:?} store_slot().is_some() must \
12745 equal is_store() — a drift would split the store-shape \
12746 emit branch's arm-set gate from the substrate-derived \
12747 shape-discrimination predicate on the same axis",
12748 );
12749 }
12750 }
12751
12752 #[test]
12753 fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
12754 // Fail-before-pass-after cross-axis pin on the trio
12755 // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
12756 // payload-carrying arm of [`WitTarget`], exactly one per-arm
12757 // accessor returns `Some(payload)` and the two peers return
12758 // `None`; and on the payload-less [`WitTarget::Capability`]
12759 // arm, all three return `None`. Guards the drift surface where
12760 // a future extension of one per-arm accessor's accept-set (e.g.
12761 // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
12762 // that widened `http_endpoint` to cover both peers without
12763 // narrowing the peer `pubsub_subject` / `store_slot` accept-
12764 // sets to keep the partition mutually exclusive) landed without
12765 // threading through the peer per-arm accessors — the resulting
12766 // silent overlap would land the same edge's payload on two
12767 // downstream per-shape emit branches at once, or leak a
12768 // pub-sub subject through the store-slot channel, at renderer
12769 // emit time far from the substrate primitive's arm-widening
12770 // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
12771 // 3-way pin on the payload-field-name axis — extended onto the
12772 // per-arm-accessor payload-projection axis so the substrate-
12773 // owned partition invariant is load-bearing at every per-arm
12774 // consumer's read site.
12775 let payload_variants = [
12776 (
12777 WitTarget::Http {
12778 endpoint: "/charge",
12779 },
12780 "http",
12781 ),
12782 (
12783 WitTarget::PubSub {
12784 subject: "events.checkout.paid",
12785 },
12786 "pubsub",
12787 ),
12788 (
12789 WitTarget::Store {
12790 slot: "checkout/$order",
12791 },
12792 "store",
12793 ),
12794 ];
12795 for (variant, own_arm_label) in payload_variants {
12796 let own_arm_hit = match own_arm_label {
12797 "http" => variant.is_http(),
12798 "pubsub" => variant.is_pubsub(),
12799 "store" => variant.is_store(),
12800 other => panic!("unknown own-arm label {other:?}"),
12801 };
12802 let per_arm_results = [
12803 ("http_endpoint", variant.http_endpoint()),
12804 ("pubsub_subject", variant.pubsub_subject()),
12805 ("store_slot", variant.store_slot()),
12806 ];
12807 let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
12808 assert_eq!(
12809 some_count, 1,
12810 "WitTarget::{variant:?} must land exactly one per-arm \
12811 post-projection accessor's Some result — the trio \
12812 (http_endpoint, pubsub_subject, store_slot) must \
12813 partition the payload arm-set; got {per_arm_results:?}",
12814 );
12815 assert!(
12816 own_arm_hit,
12817 "WitTarget::{variant:?} own-arm gen-platform predicate \
12818 must return true on its own arm — a partition failure \
12819 upstream of this pin",
12820 );
12821 assert!(
12822 variant.payload().is_some(),
12823 "WitTarget::{variant:?} pan-arm payload() must return \
12824 Some on every payload-carrying arm the trio partitions",
12825 );
12826 }
12827 // The payload-less Capability arm must return None on every
12828 // per-arm accessor — the partition's terminal-fallback shape.
12829 let cap = WitTarget::Capability;
12830 assert_eq!(cap.http_endpoint(), None);
12831 assert_eq!(cap.pubsub_subject(), None);
12832 assert_eq!(cap.store_slot(), None);
12833 assert_eq!(
12834 cap.payload(),
12835 None,
12836 "WitTarget::Capability pan-arm payload() must return None — \
12837 the trio's payload-less-arm coherence witness",
12838 );
12839 }
12840
12841 #[test]
12842 fn wit_target_field_names_are_pairwise_distinct() {
12843 // Distinctness pin: if any two of the three payload-field-name
12844 // scalars ever collapse (e.g. an accidental `endpoint` copy-
12845 // paste over the `subject` const), the [`WitContract::target`]
12846 // gate's diagnostic would point authors at the wrong field —
12847 // an "expected `:endpoint`" error on a pub-sub edge would
12848 // silently misroute the fix. Same cross-axis-distinctness
12849 // discipline as the peer M3 `:placement :estrategia` variant-
12850 // discriminator scalar-value pins (cc8f749) applied to the
12851 // payload-field-name axis.
12852 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
12853 assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
12854 assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
12855 }
12856
12857 #[test]
12858 fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
12859 // Fail-before-pass-after pin: the graph-verb payload column's
12860 // per-arm `{field}={payload}` byte-string is derived through the
12861 // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
12862 // payload-carrying arms, not through a hand-rolled per-arm match
12863 // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
12864 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12865 // inline. A future variant addition — the M4-and-later per-edge
12866 // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
12867 // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
12868 // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
12869 // and both [`WitTarget::label`] (duplicate-`:contratos`
12870 // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
12871 // payload column) pick up the new arm from the same dispatch.
12872 // Prior to this lift the graph verb open-coded the 4-arm match
12873 // in caixa-feira, so a variant addition would have to be threaded
12874 // through both projections in lockstep or the graph verb would
12875 // silently drop the new arm to `(capability-only)`.
12876 for variant in [
12877 WitTarget::Http {
12878 endpoint: "/charge",
12879 },
12880 WitTarget::PubSub {
12881 subject: "events.checkout.paid",
12882 },
12883 WitTarget::Store {
12884 slot: "checkout/$order",
12885 },
12886 ] {
12887 let (field, payload) = variant
12888 .payload_pair()
12889 .expect("payload arm must expose (field, payload)");
12890 assert_eq!(
12891 variant.graph_label(),
12892 format!("{field}={payload}"),
12893 "WitTarget::{variant:?} graph_label must route the \
12894 `{{field}}={{payload}}` template through payload_pair — \
12895 a regression to a hand-rolled per-arm match at the graph \
12896 verb would silently disagree with a future variant \
12897 addition landed only at payload_pair"
12898 );
12899 }
12900 }
12901
12902 #[test]
12903 fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
12904 // Fail-before-pass-after pin on the payload-less arm: the graph
12905 // verb's `(capability-only)` byte-string routes through the
12906 // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
12907 // [`WitTarget::Capability`] arm, not through an inline
12908 // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
12909 // per-`:contratos` payload column. Peer of the sibling
12910 // [`wit_target_label_pins_per_variant_format`] Capability-arm
12911 // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
12912 // extended here onto the third payload-less-arm consumer axis
12913 // (graph verb, sibling to the duplicate-`:contratos` diagnostic
12914 // axis and the wrong-target diagnostic axis).
12915 assert_eq!(
12916 WitTarget::Capability.graph_label(),
12917 WitTarget::CAPABILITY_GRAPH_LABEL,
12918 );
12919 assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
12920 }
12921
12922 #[test]
12923 fn wit_target_capability_graph_label_distinct_from_capability_label() {
12924 // Cross-consumer-axis distinctness pin: the graph-verb
12925 // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
12926 // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
12927 // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
12928 // payload)`) surface the payload-less arm on two distinct
12929 // consumer axes; a collapse (an accidental rebrand that lands
12930 // one spelling on both consts, a copy-paste that unifies them
12931 // "for consistency") would silently merge the two byte-strings
12932 // and lose the vocabulary distinction the graph verb's
12933 // compact-column form and the diagnostic's descriptive-clause
12934 // form each carry on purpose. Peer of the sibling 4-way
12935 // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
12936 // pin on the `ContratoWrongTarget::expected` scalar-value axis —
12937 // extended here onto the cross-consumer-axis distinctness of the
12938 // two payload-less-arm consts.
12939 assert_ne!(
12940 WitTarget::CAPABILITY_GRAPH_LABEL,
12941 WitTarget::CAPABILITY_LABEL,
12942 "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
12943 and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
12944 diagnostic) must remain distinct — a collapse would silently \
12945 merge two consumer axes onto one spelling"
12946 );
12947 }
12948
12949 #[test]
12950 fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
12951 // 4-way distinctness pin extending the sibling
12952 // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
12953 // (which covers only the HTTP / PubSub / Store payload arms)
12954 // onto the fourth scalar the shared
12955 // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
12956 // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
12957 // (`"none"`), the payload-less Capability-arm rejection scalar.
12958 //
12959 // All four [`WitTarget::HTTP_FIELD_NAME`] /
12960 // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12961 // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
12962 // dispatch surface [`WitContract::target`] writes onto the
12963 // `ContratoWrongTarget::expected` field — the same `&'static
12964 // str` axis authors read as "this WIT world's shape admits
12965 // (only|not) `:<field>`". Pairwise-distinctness is the invariant
12966 // downstream consumers rely on: an `expected: "endpoint"`
12967 // diagnostic on a Capability-shaped edge tells the author to
12968 // add a `:endpoint "…"` slot to a WIT world that admits none,
12969 // silently misrouting the fix. Until this pin landed the three
12970 // payload-arm consts were distinctness-guarded by the sibling
12971 // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
12972 // scalar (d4f54f2) sat unguarded — a rebrand collision (the
12973 // author-facing vocabulary shift from `"none"` to `"endpoint"`
12974 // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
12975 // into per-shape peers) would have silently landed one
12976 // Capability-arm rejection on a payload-arm's `expected:` byte-
12977 // string and desynchronized the diagnostic from the author's
12978 // typed shape.
12979 //
12980 // Same 4-way pairwise-distinctness pin discipline as the peer
12981 // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
12982 // (cc8f749) applies on the sibling M3 closed-set typed-enum
12983 // scalar-value dispatch axis; extends the pin trajectory the
12984 // sibling `wit_target_field_names_are_pairwise_distinct`
12985 // 3-way pin opened to cover the last unguarded corner on the
12986 // `ContratoWrongTarget::expected` scalar-value axis.
12987 //
12988 // Fail-before-pass-after locally verified by mutating
12989 // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
12990 // — this pin fires as expected; restoring passes.
12991 let all = [
12992 WitTarget::HTTP_FIELD_NAME,
12993 WitTarget::PUBSUB_FIELD_NAME,
12994 WitTarget::STORE_FIELD_NAME,
12995 WitTarget::CAPABILITY_EXPECTED,
12996 ];
12997 for (i, a) in all.iter().enumerate() {
12998 for (j, b) in all.iter().enumerate() {
12999 if i != j {
13000 assert_ne!(
13001 a, b,
13002 "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
13003 STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
13004 pairwise distinct — got duplicate {a:?} at indices \
13005 {i} and {j}; all four scalars thread through the \
13006 shared `AplicacaoError::ContratoWrongTarget::expected` \
13007 &'static str axis, so a collapse silently misdirects \
13008 the diagnostic on which typed shape the WIT world admits",
13009 );
13010 }
13011 }
13012 }
13013 }
13014
13015 #[test]
13016 fn wit_target_is_variant_predicates_partition_the_arm_set() {
13017 // Fail-before-pass-after pin on the
13018 // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
13019 // each of the four variants exactly one of the generated
13020 // `is_http` / `is_pubsub` / `is_store` / `is_capability`
13021 // predicates returns `true` and the other three return
13022 // `false`. Prior to this derive the only production
13023 // arm-discriminator on [`WitTarget`] — the sync-cycle
13024 // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
13025 // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
13026 // the variant that expressed no compile-time link back to
13027 // the closed-set typed dispatch a future fifth
13028 // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
13029 // split of [`WitTarget::PubSub`] into shape-specific peers,
13030 // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
13031 // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
13032 // to thread through in lockstep or the DFS exclusion would
13033 // silently disagree with the peer diagnostic templates on
13034 // which arms carry sync-versus-async semantics. Peer of the
13035 // sibling [`crate::CaixaKind`] (f5bba80),
13036 // [`PlacementStrategy`] (766ec63),
13037 // [`crate::supervisor::RestartStrategy`],
13038 // [`crate::supervisor::RestartPolicy`], and
13039 // [`crate::upgrade::UpgradeInstruction`] (915a934)
13040 // `IsVariant` derives on the sibling closed-set typed-enum
13041 // discriminator axes — extends the same one-typed-dispatch-
13042 // per-variant discipline onto the last unlifted closed-set
13043 // typed-enum discriminator on the caixa surface (the M3
13044 // mesh-slot per-`:contratos` target-arm axis), closing the
13045 // arm-discriminator convergence trajectory across every
13046 // closed-set typed enum in caixa-core.
13047 let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
13048 (
13049 WitTarget::Http { endpoint: "/x" },
13050 [true, false, false, false],
13051 ),
13052 (
13053 WitTarget::PubSub {
13054 subject: "events.x",
13055 },
13056 [false, true, false, false],
13057 ),
13058 (
13059 WitTarget::Store { slot: "kv/x" },
13060 [false, false, true, false],
13061 ),
13062 (WitTarget::Capability, [false, false, false, true]),
13063 ];
13064 for (variant, expected) in rows {
13065 let observed = [
13066 variant.is_http(),
13067 variant.is_pubsub(),
13068 variant.is_store(),
13069 variant.is_capability(),
13070 ];
13071 assert_eq!(
13072 observed, expected,
13073 "WitTarget::{variant:?} is_* predicates must partition \
13074 the arm set (http, pubsub, store, capability); got {observed:?}"
13075 );
13076 }
13077 }
13078
13079 #[test]
13080 fn wit_target_is_variant_predicates_are_const_fn() {
13081 // The [`gen_platform::IsVariant`] derive emits `const fn`
13082 // predicates on the peer [`crate::CaixaKind`] +
13083 // [`crate::upgrade::UpgradeInstruction`] +
13084 // [`crate::supervisor::RestartStrategy`] +
13085 // [`crate::supervisor::RestartPolicy`] +
13086 // [`PlacementStrategy`] closed-set typed enums — pin the
13087 // same posture on [`WitTarget`] so a future accidental
13088 // downgrade to non-`const` (an added runtime helper reachable
13089 // only from a non-`const` context, a manual hand-rolled
13090 // `impl` that shadows the derive-generated method) trips at
13091 // caixa-core build time rather than surfacing as a downstream
13092 // `const`-context regression far from the derive declaration.
13093 //
13094 // Unlike the peer unit-variant enums (`CaixaKind` /
13095 // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
13096 // whose `const` constructors need no arguments, the three
13097 // payload-carrying [`WitTarget`] arms are const-constructed
13098 // through `&'static str` payloads — the same `'static`
13099 // lifetime the closed-set typed enum's four-arm partition
13100 // pin above already threads through.
13101 const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
13102 const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
13103 const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
13104 const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
13105 const IS_HTTP: bool = HTTP.is_http();
13106 const IS_PUBSUB: bool = PUBSUB.is_pubsub();
13107 const IS_STORE: bool = STORE.is_store();
13108 const IS_CAPABILITY: bool = CAPABILITY.is_capability();
13109 assert!(IS_HTTP);
13110 assert!(IS_PUBSUB);
13111 assert!(IS_STORE);
13112 assert!(IS_CAPABILITY);
13113 }
13114
13115 #[test]
13116 fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
13117 // Consumer-side pin on the sole production converge site:
13118 // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
13119 // edges from the synchronous-subgraph DFS via the lifted
13120 // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
13121 // predicate (rebound from the prior raw
13122 // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
13123 // variant). Byte-equivalent today (`is_pubsub` is the
13124 // derive-generated `matches!(self, Self::PubSub { .. })` by
13125 // construction, the `#[is_variant(name = "pubsub")]` override
13126 // aliasing the auto-derived `is_pub_sub` back to the sibling
13127 // [`WitContract::is_pubsub`] name); pin the behavior so a
13128 // future accidental drift (a rebind onto a peer arm
13129 // predicate, a manual hand-rolled `impl` that shadows the
13130 // derive-generated method with different semantics, a peer
13131 // arm rename that shifts which variant carries sync-versus-
13132 // async semantics) trips at caixa-core test time rather than
13133 // at some downstream operator's runtime dispatch far from the
13134 // rebind commit.
13135 //
13136 // The fixture constructs a two-Servico Aplicacao with one
13137 // pub-sub edge that would close a sync-cycle if the DFS did
13138 // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
13139 // pub-sub exclusion means the DFS sees only the `b → a` HTTP
13140 // edge, which is not a cycle. A regression in the converge
13141 // (a rebind that reads the pub-sub arm as sync) would report
13142 // `AplicacaoError::ContratoCycle`.
13143 let s = AplicacaoSpec {
13144 membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
13145 contratos: vec![
13146 // Pub-sub edge: DFS must skip via is_pubsub().
13147 WitContract {
13148 de: "a".into(),
13149 para: "b".into(),
13150 wit: "nats:pub-sub".into(),
13151 endpoint: None,
13152 subject: Some("events.x".into()),
13153 slot: None,
13154 },
13155 // HTTP edge: DFS must include.
13156 WitContract {
13157 de: "b".into(),
13158 para: "a".into(),
13159 wit: "wasi:http/proxy".into(),
13160 endpoint: Some("/x".into()),
13161 subject: None,
13162 slot: None,
13163 },
13164 ],
13165 politicas: MeshPolicy::default(),
13166 placement: Placement {
13167 estrategia: PlacementStrategy::Replicated,
13168 clusters: vec!["rio".into()],
13169 affinity: None,
13170 shard_key: None,
13171 },
13172 entrada: None,
13173 };
13174 s.validate()
13175 .expect("pub-sub edge must be excluded from sync-cycle DFS");
13176 }
13177
13178 #[test]
13179 fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
13180 // Consumer-side pin: the same three peer consts thread through
13181 // both the [`WitTarget::label`] template (leading-`:` keyword
13182 // prefix in the duplicate-`:contratos` diagnostic) and the
13183 // [`WitContract::target`] gate's [`AplicacaoError::
13184 // ContratoMissingTarget`] `expected:` scalar (the field the
13185 // author needs to add). Pin both routes at once so a future
13186 // refactor can't accidentally split them onto separate string
13187 // literals — the "one place, everywhere reaches for it"
13188 // invariant the peer const set carries.
13189 let http_label = WitTarget::Http { endpoint: "/x" }.label();
13190 assert!(
13191 http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
13192 "label must lead with :{} keyword (got {http_label:?})",
13193 WitTarget::HTTP_FIELD_NAME,
13194 );
13195
13196 let mut s = three_member_spec();
13197 s.contratos.push(WitContract {
13198 de: "cart".into(),
13199 para: "catalog".into(),
13200 wit: "kafka:topic".into(),
13201 endpoint: None,
13202 subject: None,
13203 slot: None,
13204 });
13205 match s.validate().unwrap_err() {
13206 AplicacaoError::ContratoMissingTarget { expected, .. } => {
13207 assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
13208 }
13209 other => panic!("expected ContratoMissingTarget, got {other:?}"),
13210 }
13211 }
13212
13213 #[test]
13214 fn duplicate_pubsub_diagnostic_names_offending_subject() {
13215 // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
13216 // on the pub-sub target axis: the duplicate-edge diagnostic
13217 // must name the `:subject` payload verbatim (not just the
13218 // `(de, para, wit)` triple). Prior to lifting the label onto
13219 // [`WitTarget::label`] the diagnostic derived the label from
13220 // raw [`WitContract`] `Option<String>` probes — a future
13221 // `WitTarget` variant addition (M4 per-edge WIT registry)
13222 // would silently fall through to the `Capability` "no
13223 // payload" default without a compiler warning. Pinning the
13224 // pub-sub arm's format closes the second of three
13225 // payload-carrying `WitTarget` arms this diagnostic threads
13226 // through.
13227 let mut s = three_member_spec();
13228 let pubsub = WitContract {
13229 de: "payment".into(),
13230 para: "cart".into(),
13231 wit: "nats:pub-sub".into(),
13232 endpoint: None,
13233 subject: Some("events.checkout.paid".into()),
13234 slot: None,
13235 };
13236 s.contratos.push(pubsub.clone());
13237 s.contratos.push(pubsub);
13238 let err = s.validate().unwrap_err();
13239 let msg = format!("{err}");
13240 assert!(
13241 msg.contains(":subject \"events.checkout.paid\""),
13242 "duplicate-pubsub diagnostic must name the offending \
13243 :subject payload (got: {msg:?})"
13244 );
13245 }
13246
13247 #[test]
13248 fn duplicate_store_diagnostic_names_offending_slot() {
13249 // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
13250 // key-value target axis: the diagnostic must name the `:slot`
13251 // payload verbatim. Third of three payload-carrying
13252 // `WitTarget` arms this diagnostic threads through, closing
13253 // the per-arm label pin trilogy (`Http` — 6841,
13254 // `PubSub` + `Store` — this test + peer above).
13255 let mut s = three_member_spec();
13256 let store = WitContract {
13257 de: "cart".into(),
13258 para: "payment".into(),
13259 wit: "wasi:keyvalue/store".into(),
13260 endpoint: None,
13261 subject: None,
13262 slot: Some("checkout/$orderId".into()),
13263 };
13264 s.contratos
13265 .retain(|c| !(c.de == "cart" && c.para == "payment"));
13266 s.contratos.push(store.clone());
13267 s.contratos.push(store);
13268 let err = s.validate().unwrap_err();
13269 let msg = format!("{err}");
13270 assert!(
13271 msg.contains(":slot \"checkout/$orderId\""),
13272 "duplicate-store diagnostic must name the offending :slot \
13273 payload (got: {msg:?})"
13274 );
13275 }
13276
13277 #[test]
13278 fn rejects_entrada_path_without_leading_slash() {
13279 let mut s = three_member_spec();
13280 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
13281 let err = s.validate().unwrap_err();
13282 assert!(
13283 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
13284 "got {err:?}"
13285 );
13286 }
13287
13288 #[test]
13289 fn rejects_empty_entrada_path() {
13290 let mut s = three_member_spec();
13291 s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
13292 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
13293 }
13294
13295 #[test]
13296 fn rejects_duplicate_entrada_paths() {
13297 let mut s = three_member_spec();
13298 s.entrada.as_mut().unwrap().paths = vec![
13299 "/api/cart".into(),
13300 "/api/products".into(),
13301 "/api/cart".into(),
13302 ];
13303 let err = s.validate().unwrap_err();
13304 assert!(
13305 matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
13306 "got {err:?}"
13307 );
13308 }
13309
13310 #[test]
13311 fn rejects_zero_entrada_port() {
13312 let mut s = three_member_spec();
13313 s.entrada.as_mut().unwrap().port = 0;
13314 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
13315 }
13316
13317 // ── :entrada :paths value-shape gate ─────────────────────────────
13318 //
13319 // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
13320 // sibling `:paths` axis. Every authoring footgun the K8s Gateway
13321 // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
13322 // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
13323 // time now becomes a caixa-build-time `EntradaPathInvalid` with
13324 // the offending `:paths` entry named verbatim.
13325
13326 #[test]
13327 fn rejects_entrada_path_with_query() {
13328 // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
13329 // silently passed validate and the Gateway API webhook
13330 // rejected it at apply time with no source citation.
13331 let mut s = three_member_spec();
13332 s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
13333 let err = s.validate().unwrap_err();
13334 assert!(
13335 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13336 if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
13337 "got {err:?}"
13338 );
13339 }
13340
13341 #[test]
13342 fn rejects_entrada_path_with_fragment() {
13343 let mut s = three_member_spec();
13344 s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
13345 let err = s.validate().unwrap_err();
13346 assert!(
13347 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13348 if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
13349 "got {err:?}"
13350 );
13351 }
13352
13353 #[test]
13354 fn rejects_entrada_path_with_space() {
13355 let mut s = three_member_spec();
13356 s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
13357 let err = s.validate().unwrap_err();
13358 assert!(
13359 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13360 if path == "/api/my cart" && reason.contains("whitespace")),
13361 "got {err:?}"
13362 );
13363 }
13364
13365 #[test]
13366 fn rejects_entrada_path_with_tab() {
13367 let mut s = three_member_spec();
13368 s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
13369 let err = s.validate().unwrap_err();
13370 assert!(
13371 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13372 if path == "/api/\tcart" && reason.contains("whitespace")),
13373 "got {err:?}"
13374 );
13375 }
13376
13377 #[test]
13378 fn rejects_entrada_path_with_control_char() {
13379 // 0x01 (SOH) — a non-whitespace control char surfaces the
13380 // distinct "control character" reason arm, separate from
13381 // the whitespace arm. Pinned so a future refactor that
13382 // collapses the two arms can't accidentally drop the more
13383 // self-locating diagnostic.
13384 let mut s = three_member_spec();
13385 s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
13386 let err = s.validate().unwrap_err();
13387 assert!(
13388 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13389 if path == "/api/\x01cart" && reason.contains("control character")),
13390 "got {err:?}"
13391 );
13392 }
13393
13394 #[test]
13395 fn rejects_entrada_path_with_non_ascii() {
13396 // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
13397 // unreserved-set rule rejects. The Gateway API webhook
13398 // rejects literal non-ASCII bytes; percent-encoding is the
13399 // only way to author non-ASCII in a path.
13400 let mut s = three_member_spec();
13401 s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
13402 let err = s.validate().unwrap_err();
13403 assert!(
13404 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13405 if path == "/api/café" && reason.contains("non-ASCII")),
13406 "got {err:?}"
13407 );
13408 }
13409
13410 #[test]
13411 fn rejects_entrada_path_with_consecutive_slashes() {
13412 let mut s = three_member_spec();
13413 s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
13414 let err = s.validate().unwrap_err();
13415 assert!(
13416 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13417 if path == "/api//cart" && reason.contains("consecutive `/`")),
13418 "got {err:?}"
13419 );
13420 }
13421
13422 #[test]
13423 fn rejects_entrada_path_with_dot_segment() {
13424 let mut s = three_member_spec();
13425 s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
13426 let err = s.validate().unwrap_err();
13427 assert!(
13428 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13429 if path == "/api/./cart" && reason.contains("`.` segment")),
13430 "got {err:?}"
13431 );
13432 }
13433
13434 #[test]
13435 fn rejects_entrada_path_with_trailing_dot_segment() {
13436 // The bare `/.` and the trailing `/foo/.` are both rejected
13437 // by the Gateway API webhook; pinned separately so a future
13438 // narrowing that catches only the inner form surfaces here.
13439 let mut s = three_member_spec();
13440 s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
13441 let err = s.validate().unwrap_err();
13442 assert!(
13443 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13444 if path == "/api/." && reason.contains("`.` segment")),
13445 "got {err:?}"
13446 );
13447 }
13448
13449 #[test]
13450 fn rejects_entrada_path_with_parent_segment() {
13451 let mut s = three_member_spec();
13452 s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
13453 let err = s.validate().unwrap_err();
13454 assert!(
13455 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13456 if path == "/api/../etc" && reason.contains("`..` parent-segment")),
13457 "got {err:?}"
13458 );
13459 }
13460
13461 #[test]
13462 fn rejects_entrada_path_with_trailing_parent_segment() {
13463 // Trailing `/..` — symmetric arm of the parent-segment rule,
13464 // pinned separately so a future relaxation that only checks
13465 // the inner form (`/../`) surfaces here.
13466 let mut s = three_member_spec();
13467 s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
13468 let err = s.validate().unwrap_err();
13469 assert!(
13470 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13471 if path == "/api/.." && reason.contains("`..` parent-segment")),
13472 "got {err:?}"
13473 );
13474 }
13475
13476 #[test]
13477 fn rejects_entrada_path_too_long() {
13478 // 1025-byte path — one over the Gateway API HTTPPathMatch.value
13479 // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
13480 // ASCII-alphanumeric body so only the length rule fires.
13481 let mut s = three_member_spec();
13482 let big = format!("/api/{}", "a".repeat(1020));
13483 assert_eq!(big.len(), 1025);
13484 s.entrada.as_mut().unwrap().paths = vec![big.clone()];
13485 let err = s.validate().unwrap_err();
13486 assert!(
13487 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13488 if path == &big && reason.contains("max length of 1024")),
13489 "got {err:?}"
13490 );
13491 }
13492
13493 #[test]
13494 fn entrada_path_max_length_validates() {
13495 // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
13496 // maxLength cap. Boundary pin: drift in the cap surfaces here
13497 // and at `rejects_entrada_path_too_long` simultaneously.
13498 let mut s = three_member_spec();
13499 let big = format!("/api/{}", "a".repeat(1019));
13500 assert_eq!(big.len(), 1024);
13501 s.entrada.as_mut().unwrap().paths = vec![big];
13502 s.validate().unwrap();
13503 }
13504
13505 #[test]
13506 fn entrada_accepts_canonical_paths() {
13507 // Positive-control sweep — every form the Gateway API
13508 // apiserver accepts must round-trip through validate. Covers
13509 // the root catch-all, plain paths, dot-prefixed segments
13510 // (hidden-file-style, distinct from `.` and `..` segments
13511 // which are rejected), digit-bearing segments, the canonical
13512 // route-template `:param` form (`:` is RFC 3986 reserved-set
13513 // valid in paths), trailing-slash form, percent-encoded
13514 // segments, and an interior `..` *substring* (`/foo..bar` is
13515 // not the `..` segment and is allowed).
13516 for path in [
13517 "/",
13518 "/api/cart",
13519 "/healthz",
13520 "/api/.config",
13521 "/v1/products",
13522 "/products/:id",
13523 "/api/cart/",
13524 "/api/caf%C3%A9",
13525 "/foo..bar",
13526 "/...",
13527 ] {
13528 let mut s = three_member_spec();
13529 s.entrada.as_mut().unwrap().paths = vec![path.into()];
13530 s.validate()
13531 .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
13532 }
13533 }
13534
13535 #[test]
13536 fn entrada_path_empty_takes_precedence_over_invalid() {
13537 // Ordering pin: `EntradaPathEmpty` is the more self-locating
13538 // diagnostic on `""` and must lead — `validate_entrada_path`
13539 // is only reached after the empty-check fires at the call
13540 // site. (The predicate itself defends against direct
13541 // invocation by returning the same error on `""`.)
13542 let mut s = three_member_spec();
13543 s.entrada.as_mut().unwrap().paths = vec!["".into()];
13544 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
13545 }
13546
13547 #[test]
13548 fn entrada_path_not_absolute_takes_precedence_over_invalid() {
13549 // Ordering pin: a path without a leading `/` surfaces the
13550 // narrower `EntradaPathNotAbsolute` diagnostic first; the
13551 // value-shape gate is only consulted on paths that already
13552 // satisfy the absolute-prefix invariant.
13553 let mut s = three_member_spec();
13554 // `bad path` would fire the whitespace rule under the
13555 // value-shape gate, but missing-leading-`/` is the more
13556 // self-locating diagnostic.
13557 s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
13558 let err = s.validate().unwrap_err();
13559 assert!(
13560 matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
13561 "got {err:?}"
13562 );
13563 }
13564
13565 #[test]
13566 fn entrada_path_invalid_fires_before_duplicate_check() {
13567 // Ordering pin: a malformed path on the *first* entry of a
13568 // would-be duplicate pair fires the value-shape gate before
13569 // the duplicate gate, mirroring the
13570 // `placement_cluster_invalid_fires_before_duplicate_check`
13571 // (6cbb900) pattern on the peer axis.
13572 let mut s = three_member_spec();
13573 s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
13574 let err = s.validate().unwrap_err();
13575 assert!(
13576 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
13577 "got {err:?}"
13578 );
13579 }
13580
13581 #[test]
13582 fn entrada_path_diagnostic_carries_offending_path() {
13583 // Diagnostic-shape pin — the offending path + a non-empty
13584 // reason flow through verbatim so the author can grep their
13585 // caixa.lisp for `:paths` and fix it in one edit. Same shape
13586 // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
13587 let mut s = three_member_spec();
13588 s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
13589 let err = s.validate().unwrap_err();
13590 match err {
13591 AplicacaoError::EntradaPathInvalid { path, reason } => {
13592 assert_eq!(path, "/api?q=1");
13593 assert!(!reason.is_empty(), "reason field must be non-empty");
13594 }
13595 other => panic!("expected EntradaPathInvalid, got {other:?}"),
13596 }
13597 }
13598
13599 #[test]
13600 fn rejects_entrada_path_with_curly_brace_template_form() {
13601 // Per-axis pin on the shared `is_gateway_api_http_path`
13602 // reserved-byte arm: the canonical "I wrote an OpenAPI
13603 // path-template `{id}` instead of the Gateway API `:id` form"
13604 // footgun the K8s apiserver would otherwise catch at admission
13605 // time on every `HTTPRoute.spec.rules[].matches[].path.value`
13606 // landing site, far from the caixa.lisp. Surfaces as
13607 // `EntradaPathInvalid` carrying the offending path verbatim
13608 // plus the canonical `%7B`/`%7D` percent-encoding remediation
13609 // — the substrate-side `gateway_api_http_path_rejects_every_
13610 // reserved_printable_ascii_byte` predicate-level sweep pins the
13611 // full eleven-byte set; this per-axis pin confirms the
13612 // diagnostic flows through to the `EntradaPathInvalid` variant.
13613 let mut s = three_member_spec();
13614 s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
13615 let err = s.validate().unwrap_err();
13616 assert!(
13617 matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
13618 if path == "/api/cart/{id}"
13619 && reason.contains("reserved character")
13620 && reason.contains("'{'")
13621 && reason.contains("%7B")),
13622 "got {err:?}"
13623 );
13624 }
13625
13626 #[test]
13627 fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
13628 // Per-axis peer of `rejects_entrada_path_with_curly_brace_
13629 // template_form` on the sibling `:contratos :endpoint` axis.
13630 // Same shared `is_gateway_api_http_path` reserved-byte arm
13631 // fires through `ContratoEndpointInvalid`, with the offending
13632 // endpoint + `:de` + `:para` + reason flowing through verbatim.
13633 // Pins that the lifted predicate's tightening lands on both
13634 // caller axes simultaneously — one source of truth for the
13635 // Gateway API HTTPPathMatch.value accepted set.
13636 let err = contrato_endpoint_err("/api/cart/{id}");
13637 assert!(
13638 matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13639 if endpoint == "/api/cart/{id}"
13640 && reason.contains("reserved character")
13641 && reason.contains("'{'")
13642 && reason.contains("%7B")),
13643 "got {err:?}"
13644 );
13645 }
13646
13647 // ── :entrada :host value-shape gate ──────────────────────────────
13648 //
13649 // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
13650 // the sibling `:host` axis. Every authoring footgun the K8s
13651 // Gateway API v1 apiserver would catch at admission time becomes
13652 // a caixa-build-time `EntradaHostInvalid` with the offending
13653 // `:host` named verbatim. Same diagnostic shape as
13654 // `MembroVersaoInvalid` (9888b13).
13655
13656 #[test]
13657 fn rejects_entrada_host_with_scheme() {
13658 // Fail-before-pass-after pin — pre-gate codebases silently
13659 // accepted `https://…` and the apiserver rejected it at apply
13660 // time with no source citation.
13661 let mut s = three_member_spec();
13662 s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
13663 let err = s.validate().unwrap_err();
13664 assert!(
13665 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
13666 if host == "https://checkout.quero.cloud"),
13667 "got {err:?}"
13668 );
13669 }
13670
13671 #[test]
13672 fn rejects_entrada_host_with_port() {
13673 // The `:8080` port suffix is the canonical "I forgot the port
13674 // belongs in `:entrada :port`" footgun. The top-level `:` arm
13675 // (introduced after the per-label loop-only impl silently
13676 // surfaced a deep "label \"cloud:8080\" contains invalid
13677 // character ':'" leak) names the canonical fix verbatim — the
13678 // `:entrada :port` slot.
13679 let mut s = three_member_spec();
13680 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
13681 let err = s.validate().unwrap_err();
13682 assert!(
13683 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
13684 if host == "checkout.quero.cloud:8080"
13685 && reason.contains(":entrada :port")),
13686 "got {err:?}"
13687 );
13688 }
13689
13690 #[test]
13691 fn rejects_entrada_host_with_trailing_colon() {
13692 // Trailing `:` (e.g. an in-progress `:host "example.com:"`
13693 // edit) — the per-label loop would land it as a deep
13694 // "label \"com:\" must start and end with an alphanumeric"
13695 // / "contains invalid character ':'" leak. The top-level
13696 // `:` arm pre-empts with the canonical `:port` slot
13697 // diagnostic.
13698 let mut s = three_member_spec();
13699 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
13700 let err = s.validate().unwrap_err();
13701 assert!(
13702 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
13703 if host == "checkout.quero.cloud:"
13704 && reason.contains(":entrada :port")),
13705 "got {err:?}"
13706 );
13707 }
13708
13709 #[test]
13710 fn rejects_entrada_host_unbracketed_ipv6_literal() {
13711 // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
13712 // literals across the board (peer with `rejects_entrada_host_
13713 // ipv4_literal` above for the four-label-all-digit IPv4 arm).
13714 // Before this top-level `:` arm landed the per-label loop
13715 // surfaced a single-label byte-class diagnostic that named the
13716 // `:` byte but not the IP-literal prohibition. The top-level
13717 // `:` arm names both the `:port` slot and the IP-literal
13718 // prohibition verbatim, so an author whose `:host "2001:..."`
13719 // value lands here gets a self-locating fix either way.
13720 let mut s = three_member_spec();
13721 s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
13722 let err = s.validate().unwrap_err();
13723 assert!(
13724 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
13725 if host == "2001:db8::1"
13726 && reason.contains("IPv6")),
13727 "got {err:?}"
13728 );
13729 }
13730
13731 #[test]
13732 fn rejects_entrada_host_wildcard_with_port() {
13733 // Wildcard host with port suffix — the `*.` strip and the
13734 // per-label loop on `["foo", "quero", "cloud:8080"]` would
13735 // surface the deep byte-class leak. The top-level `:` arm sits
13736 // upstream of the `*.` strip, so it names the canonical `:port`
13737 // fix verbatim regardless of whether the host is wildcard-led.
13738 let mut s = three_member_spec();
13739 s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
13740 let err = s.validate().unwrap_err();
13741 assert!(
13742 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
13743 if host == "*.quero.cloud:8080"
13744 && reason.contains(":entrada :port")),
13745 "got {err:?}"
13746 );
13747 }
13748
13749 #[test]
13750 fn rejects_entrada_host_with_path() {
13751 let mut s = three_member_spec();
13752 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
13753 let err = s.validate().unwrap_err();
13754 assert!(
13755 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
13756 if host == "checkout.quero.cloud/api"),
13757 "got {err:?}"
13758 );
13759 }
13760
13761 #[test]
13762 fn rejects_entrada_host_with_uppercase() {
13763 // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
13764 // rejected, not silently lower-cased.
13765 let mut s = three_member_spec();
13766 s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
13767 let err = s.validate().unwrap_err();
13768 assert!(
13769 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13770 if reason.contains("uppercase")),
13771 "got {err:?}"
13772 );
13773 }
13774
13775 #[test]
13776 fn rejects_entrada_host_with_underscore() {
13777 // RFC 1123 allows `[a-z0-9-]` only; underscore is the
13778 // canonical "I'm thinking of HTTP cookies / SRV records" leak.
13779 let mut s = three_member_spec();
13780 s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
13781 let err = s.validate().unwrap_err();
13782 assert!(
13783 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13784 if reason.contains('_')),
13785 "got {err:?}"
13786 );
13787 }
13788
13789 #[test]
13790 fn rejects_entrada_host_ipv4_literal() {
13791 // Gateway API v1 explicitly forbids IP literals as Hostnames.
13792 let mut s = three_member_spec();
13793 s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
13794 let err = s.validate().unwrap_err();
13795 assert!(
13796 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13797 if reason.contains("IPv4")),
13798 "got {err:?}"
13799 );
13800 }
13801
13802 #[test]
13803 fn rejects_entrada_host_with_trailing_dot() {
13804 // The Gateway API regex anchors at end-of-string with no
13805 // trailing `.` allowance — the FQDN root-dot form is rejected.
13806 let mut s = three_member_spec();
13807 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
13808 let err = s.validate().unwrap_err();
13809 assert!(
13810 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
13811 if host == "checkout.quero.cloud."),
13812 "got {err:?}"
13813 );
13814 }
13815
13816 #[test]
13817 fn rejects_entrada_host_with_leading_dot() {
13818 let mut s = three_member_spec();
13819 s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
13820 let err = s.validate().unwrap_err();
13821 assert!(
13822 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13823 if reason.contains("empty label")),
13824 "got {err:?}"
13825 );
13826 }
13827
13828 #[test]
13829 fn rejects_entrada_host_with_consecutive_dots() {
13830 let mut s = three_member_spec();
13831 s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
13832 let err = s.validate().unwrap_err();
13833 assert!(
13834 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13835 if reason.contains("empty label")),
13836 "got {err:?}"
13837 );
13838 }
13839
13840 #[test]
13841 fn rejects_entrada_host_with_leading_hyphen_label() {
13842 let mut s = three_member_spec();
13843 s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
13844 let err = s.validate().unwrap_err();
13845 assert!(
13846 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13847 if reason.contains("alphanumeric")),
13848 "got {err:?}"
13849 );
13850 }
13851
13852 #[test]
13853 fn rejects_entrada_host_with_trailing_hyphen_label() {
13854 let mut s = three_member_spec();
13855 s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
13856 let err = s.validate().unwrap_err();
13857 assert!(
13858 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13859 if reason.contains("alphanumeric")),
13860 "got {err:?}"
13861 );
13862 }
13863
13864 #[test]
13865 fn rejects_entrada_host_with_inner_wildcard() {
13866 // Gateway API allows `*` only as the first label (`*.foo`);
13867 // any inner or trailing `*` is rejected.
13868 let mut s = three_member_spec();
13869 s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
13870 let err = s.validate().unwrap_err();
13871 assert!(
13872 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13873 if reason.contains("wildcard")),
13874 "got {err:?}"
13875 );
13876 }
13877
13878 #[test]
13879 fn rejects_entrada_host_bare_wildcard() {
13880 // `*.` with no domain is meaningless; Gateway API rejects it.
13881 let mut s = three_member_spec();
13882 s.entrada.as_mut().unwrap().host = "*.".into();
13883 let err = s.validate().unwrap_err();
13884 assert!(
13885 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13886 if reason.contains("wildcard")),
13887 "got {err:?}"
13888 );
13889 }
13890
13891 #[test]
13892 fn rejects_entrada_host_with_whitespace() {
13893 let mut s = three_member_spec();
13894 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
13895 let err = s.validate().unwrap_err();
13896 assert!(
13897 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
13898 if reason.contains("whitespace")),
13899 "got {err:?}"
13900 );
13901 }
13902
13903 #[test]
13904 fn rejects_entrada_host_space_names_offending_byte() {
13905 // Embedded space in the `:entrada :host` axis surfaces the
13906 // byte-naming diagnostic through the lifted
13907 // `find_ascii_whitespace_byte` predicate. Peer with the
13908 // sibling `parse_rejects_leading_whitespace` pins on
13909 // `supervisor::duration_codec` (a7ae622) — same "the
13910 // diagnostic carries the offending byte's `0x{b:02x}` shape"
13911 // discipline extended from the shared duration codec to the
13912 // Gateway API v1 Hostname axis.
13913 let mut s = three_member_spec();
13914 s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
13915 let err = s.validate().unwrap_err();
13916 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
13917 panic!("expected EntradaHostInvalid, got {err:?}");
13918 };
13919 assert!(
13920 reason.contains("ASCII whitespace byte"),
13921 "expected byte-naming diagnostic, got {reason:?}"
13922 );
13923 assert!(
13924 reason.contains("0x20"),
13925 "expected offending space byte 0x20, got {reason:?}"
13926 );
13927 }
13928
13929 #[test]
13930 fn rejects_entrada_host_tab_names_offending_byte() {
13931 // Embedded tab byte in the `:entrada :host` axis — the
13932 // canonical paste-from-YAML-block-scalar / paste-from-
13933 // indented-doc footgun. Pins that the lifted predicate covers
13934 // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
13935 // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
13936 // not just the leading-space case the pre-lift `.bytes().any`
13937 // arm's opaque "must not contain whitespace" reason already
13938 // covered. Peer with `parse_rejects_tab_byte` on
13939 // `supervisor::duration_codec` (a7ae622).
13940 let mut s = three_member_spec();
13941 s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
13942 let err = s.validate().unwrap_err();
13943 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
13944 panic!("expected EntradaHostInvalid, got {err:?}");
13945 };
13946 assert!(
13947 reason.contains("ASCII whitespace byte"),
13948 "expected byte-naming diagnostic, got {reason:?}"
13949 );
13950 assert!(
13951 reason.contains("0x09"),
13952 "expected offending tab byte 0x09, got {reason:?}"
13953 );
13954 }
13955
13956 #[test]
13957 fn rejects_entrada_host_lf_names_offending_byte() {
13958 // Embedded LF byte in the `:entrada :host` axis — the
13959 // canonical paste-from-shell-heredoc / paste-from-multiline-
13960 // doc footgun the caixa-mesh YAML emitter would silently
13961 // reinterpret at the Gateway API v1 HTTPRoute admission
13962 // layer (an embedded LF byte in a YAML plain scalar either
13963 // truncates the value at the emitter or crashes the parser
13964 // on the k8s-apiserver side). Pins the third representative
13965 // of the full ASCII-whitespace set through the shared
13966 // predicate.
13967 let mut s = three_member_spec();
13968 s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
13969 let err = s.validate().unwrap_err();
13970 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
13971 panic!("expected EntradaHostInvalid, got {err:?}");
13972 };
13973 assert!(
13974 reason.contains("ASCII whitespace byte"),
13975 "expected byte-naming diagnostic, got {reason:?}"
13976 );
13977 assert!(
13978 reason.contains("0x0a"),
13979 "expected offending LF byte 0x0a, got {reason:?}"
13980 );
13981 }
13982
13983 #[test]
13984 fn rejects_entrada_host_nbsp_names_offending_codepoint() {
13985 // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
13986 // axis — the canonical paste-from-typography /
13987 // paste-from-word-processor footgun. Before the non-ASCII
13988 // Unicode `White_Space` scan lifted through the shared
13989 // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
13990 // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
13991 // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
13992 // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
13993 // with the far-from-source `label "…" must start and end
13994 // with an alphanumeric` diagnostic — burying the
13995 // paste-from-typography origin under a label-shape leak.
13996 // Peer with the sibling non-ASCII-whitespace pins at
13997 // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
13998 // — 1b75b38), `limits::parse_duration`,
13999 // `limits::parse_millicores`, and the shared duration codec
14000 // — same "the diagnostic carries the offending Unicode
14001 // codepoint's `U+XXXX` shape" discipline extended from every
14002 // typed-magnitude codec to the Gateway API v1 Hostname axis.
14003 let mut s = three_member_spec();
14004 s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
14005 let err = s.validate().unwrap_err();
14006 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14007 panic!("expected EntradaHostInvalid, got {err:?}");
14008 };
14009 assert!(
14010 reason.contains("non-ASCII Unicode whitespace character"),
14011 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14012 );
14013 assert!(
14014 reason.contains("U+00A0"),
14015 "expected offending NBSP codepoint U+00A0, got {reason:?}"
14016 );
14017 }
14018
14019 #[test]
14020 fn rejects_entrada_host_line_separator_names_offending_codepoint() {
14021 // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
14022 // `:entrada :host` axis — the canonical paste-from-web-doc /
14023 // paste-from-published-HTML footgun. `char::is_whitespace`
14024 // returns true for `U+2028` per the Unicode `White_Space`
14025 // property, so `str::trim` at any downstream site would
14026 // silently strip it — same drift class as NBSP but on a
14027 // different codepoint region. Pins the second representative
14028 // (non-Latin-1 `char::is_whitespace` member) through the
14029 // shared predicate. Peer with
14030 // `parse_byte_size_rejects_internal_line_separator` on
14031 // `limits::parse_byte_size` (1b75b38).
14032 let mut s = three_member_spec();
14033 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
14034 let err = s.validate().unwrap_err();
14035 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14036 panic!("expected EntradaHostInvalid, got {err:?}");
14037 };
14038 assert!(
14039 reason.contains("non-ASCII Unicode whitespace character"),
14040 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14041 );
14042 assert!(
14043 reason.contains("U+2028"),
14044 "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
14045 );
14046 }
14047
14048 #[test]
14049 fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
14050 // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
14051 // labels in the `:entrada :host` axis — the canonical
14052 // paste-from-CJK-typography footgun (CJK IMEs default to
14053 // full-width whitespace when the space bar is pressed in
14054 // Japanese / Chinese input modes). Pins the third
14055 // representative of the non-ASCII Unicode `White_Space` set
14056 // through the shared predicate: the CJK block, distinct from
14057 // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
14058 // SEPARATOR `U+2028` — covering the same axis breadth the
14059 // sibling `parse_byte_size_rejects_trailing_ideographic_space`
14060 // (1b75b38) pins on `limits::parse_byte_size`.
14061 let mut s = three_member_spec();
14062 s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
14063 let err = s.validate().unwrap_err();
14064 let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14065 panic!("expected EntradaHostInvalid, got {err:?}");
14066 };
14067 assert!(
14068 reason.contains("non-ASCII Unicode whitespace character"),
14069 "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
14070 );
14071 assert!(
14072 reason.contains("U+3000"),
14073 "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
14074 );
14075 }
14076
14077 #[test]
14078 fn rejects_entrada_host_too_long() {
14079 // Total length cap = 253; build a 254-byte host out of two
14080 // 63-byte labels + one 62-byte label + dots.
14081 let mut s = three_member_spec();
14082 let big = format!(
14083 "{}.{}.{}.{}",
14084 "a".repeat(63),
14085 "b".repeat(63),
14086 "c".repeat(63),
14087 "d".repeat(254 - 63 * 3 - 3)
14088 );
14089 assert_eq!(big.len(), 254);
14090 s.entrada.as_mut().unwrap().host = big;
14091 let err = s.validate().unwrap_err();
14092 assert!(
14093 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14094 if reason.contains("max length of 253")),
14095 "got {err:?}"
14096 );
14097 }
14098
14099 #[test]
14100 fn rejects_entrada_host_label_too_long() {
14101 let mut s = three_member_spec();
14102 // 64-byte label — one over the per-label cap.
14103 s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
14104 let err = s.validate().unwrap_err();
14105 assert!(
14106 matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14107 if reason.contains("label max length of 63")),
14108 "got {err:?}"
14109 );
14110 }
14111
14112 #[test]
14113 fn entrada_host_diagnostic_carries_offending_host() {
14114 // Diagnostic-shape pin — the offending host + a non-empty
14115 // reason flow through verbatim so the author can grep their
14116 // caixa.lisp for `:host "<host>"` and fix it in one edit.
14117 let mut s = three_member_spec();
14118 s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
14119 let err = s.validate().unwrap_err();
14120 match err {
14121 AplicacaoError::EntradaHostInvalid { host, reason } => {
14122 assert_eq!(host, "checkout.quero.cloud:8080");
14123 assert!(!reason.is_empty(), "reason field must be non-empty");
14124 }
14125 other => panic!("expected EntradaHostInvalid, got {other:?}"),
14126 }
14127 }
14128
14129 #[test]
14130 fn entrada_host_empty_takes_precedence_over_invalid() {
14131 // Ordering pin: `EmptyEntradaHost` is the more self-locating
14132 // diagnostic on `""` and must lead — `validate_entrada_host`
14133 // is only reached after the empty-check fires at the call
14134 // site. (The predicate itself defends against direct
14135 // invocation by returning the same error on `""`.)
14136 let mut s = three_member_spec();
14137 s.entrada.as_mut().unwrap().host = String::new();
14138 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
14139 }
14140
14141 #[test]
14142 fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
14143 // Ordering pin: a missing :para member is the more
14144 // self-locating diagnostic and fires before the host gate.
14145 let mut s = three_member_spec();
14146 let e = s.entrada.as_mut().unwrap();
14147 e.para = "ghost".into();
14148 e.host = "BAD HOST".into();
14149 let err = s.validate().unwrap_err();
14150 assert!(
14151 matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
14152 "got {err:?}"
14153 );
14154 }
14155
14156 #[test]
14157 fn entrada_host_invalid_fires_before_port_zero() {
14158 // Ordering pin: the host gate fires before the port gate so
14159 // a malformed host is named even when the port is also wrong.
14160 let mut s = three_member_spec();
14161 let e = s.entrada.as_mut().unwrap();
14162 e.host = "Checkout.quero.cloud".into();
14163 e.port = 0;
14164 let err = s.validate().unwrap_err();
14165 assert!(
14166 matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14167 if host == "Checkout.quero.cloud"),
14168 "got {err:?}"
14169 );
14170 }
14171
14172 #[test]
14173 fn entrada_accepts_canonical_hosts() {
14174 // Positive-control sweep — every form the Gateway API
14175 // apiserver accepts must round-trip through validate. Covers
14176 // a plain DNS subdomain, a leading wildcard, a single-label
14177 // host (cluster-internal), a max-length-edge label, a
14178 // hyphen-bearing label, and a Punycode IDN label.
14179 for host in [
14180 "checkout.quero.cloud",
14181 "*.quero.cloud",
14182 "checkout",
14183 // 63-byte label — exactly the per-label cap.
14184 "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
14185 "foo-bar.quero.cloud",
14186 // Punycode IDN — valid because the author pre-encoded.
14187 "xn--bcher-kva.example.com",
14188 ] {
14189 let mut s = three_member_spec();
14190 s.entrada.as_mut().unwrap().host = host.into();
14191 s.validate()
14192 .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
14193 }
14194 }
14195
14196 #[test]
14197 fn entrada_host_max_length_validates() {
14198 // 253-byte host is the cap exactly — must validate. Build a
14199 // 253-byte host out of three 63-byte labels + one 61-byte
14200 // label + 3 dots = 252 bytes, then pad one byte to 253.
14201 let mut s = three_member_spec();
14202 let host = format!(
14203 "{}.{}.{}.{}",
14204 "a".repeat(63),
14205 "b".repeat(63),
14206 "c".repeat(63),
14207 "d".repeat(253 - 63 * 3 - 3)
14208 );
14209 assert_eq!(host.len(), 253);
14210 s.entrada.as_mut().unwrap().host = host;
14211 s.validate().unwrap();
14212 }
14213
14214 #[test]
14215 fn entrada_host_total_length_cap_threads_lifted_render_const() {
14216 // Cross-crate-side pin: the aplicacao-side `:entrada :host`
14217 // total-length gate now reads the K8s Gateway API v1 Hostname
14218 // `maxLength: 253` cap from the lifted
14219 // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
14220 // of truth — the same constant every future Gateway-API-Hostname
14221 // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
14222 // materializer's per-host validator, the future per-`Certificate`
14223 // SAN emitter for cert-manager, the multi-`:entrada`
14224 // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
14225 // from. Before the lift, the aplicacao-side reader consumed a
14226 // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
14227 // 253-byte value as the peer render-side canonical bounds
14228 // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
14229 // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
14230 // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
14231 // module boundary — a future 253-byte drift on either side would
14232 // silently split into two axes' worth of admission-schema mismatch
14233 // without a build-time signal. Pin the cap through a fresh 254-
14234 // byte host that hits the total-length arm, then read the reason
14235 // for the exact byte count the shared constant carries: any future
14236 // regression on the lift (a private alias reintroduced, a hard-
14237 // coded literal at the arm, a mismatch between the aplicacao-side
14238 // and render-side canonicals) surfaces as this pin's diagnostic
14239 // failing to match, not as a per-cluster admission rejection far
14240 // from the caixa.lisp source line.
14241 let mut s = three_member_spec();
14242 let over_cap = format!(
14243 "{}.{}.{}.{}",
14244 "a".repeat(63),
14245 "b".repeat(63),
14246 "c".repeat(63),
14247 "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
14248 );
14249 assert_eq!(
14250 over_cap.len(),
14251 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
14252 );
14253 s.entrada.as_mut().unwrap().host = over_cap;
14254 let err = s.validate().unwrap_err();
14255 match err {
14256 AplicacaoError::EntradaHostInvalid { reason, .. } => {
14257 let needle = format!(
14258 "max length of {} bytes",
14259 crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
14260 );
14261 assert!(
14262 reason.contains(&needle),
14263 "diagnostic must name the lifted \
14264 GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
14265 );
14266 }
14267 other => panic!("expected EntradaHostInvalid, got {other:?}"),
14268 }
14269 }
14270
14271 #[test]
14272 fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
14273 // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
14274 // on the per-label-cap axis. Before the lift, the aplicacao-side
14275 // per-label arm consumed a private const alias
14276 // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
14277 // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
14278 // split from it at the module boundary — every `.`-separated
14279 // label in a Gateway API v1 Hostname is a DNS-1123 label under
14280 // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
14281 // so the private alias's 63 and the canonical const's 63 were
14282 // pinning the same underlying rule twice. Pin the cap through a
14283 // 64-byte label that hits the per-label arm, then read the reason
14284 // for the exact byte count the shared constant carries: any
14285 // future drift on either side (a private alias reintroduced, a
14286 // hard-coded literal at the arm, a mismatch between the two
14287 // 63-byte pins) surfaces at this pin's diagnostic rather than at
14288 // a per-cluster admission rejection whose "field is invalid"
14289 // opacity misframes the root cause.
14290 let mut s = three_member_spec();
14291 let over_cap_label = format!(
14292 "{}.quero.cloud",
14293 "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
14294 );
14295 s.entrada.as_mut().unwrap().host = over_cap_label;
14296 let err = s.validate().unwrap_err();
14297 match err {
14298 AplicacaoError::EntradaHostInvalid { reason, .. } => {
14299 let needle = format!(
14300 "label max length of {} bytes",
14301 crate::render::DNS_1123_LABEL_MAX_LEN,
14302 );
14303 assert!(
14304 reason.contains(&needle),
14305 "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
14306 cap verbatim on the per-label arm, got: {reason:?}",
14307 );
14308 }
14309 other => panic!("expected EntradaHostInvalid, got {other:?}"),
14310 }
14311 }
14312
14313 #[test]
14314 fn entrada_with_empty_paths_validates() {
14315 // Empty `:paths` is the documented "match every path" form;
14316 // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
14317 let mut s = three_member_spec();
14318 s.entrada.as_mut().unwrap().paths = vec![];
14319 s.validate().unwrap();
14320 }
14321
14322 #[test]
14323 fn entrada_root_path_validates() {
14324 // The author-supplied bare-root `:entrada :paths` entry is the
14325 // same byte-shape the peer emit-side catch-all constant
14326 // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
14327 // the author's `:paths` list is empty — sweeping the test-side
14328 // probe literal onto the lifted const closes the two-axis pin
14329 // (author-side admit + emit-side canonical fallback) around
14330 // one `&'static str`, so a future rebrand of the catch-all
14331 // reaches both consumers by construction. Peer to
14332 // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
14333 // on the canonical-literal pin surface.
14334 let mut s = three_member_spec();
14335 s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
14336 s.validate().unwrap();
14337 }
14338
14339 #[test]
14340 fn placement_strategy_variants_round_trip() {
14341 for s in [
14342 PlacementStrategy::SingleNode,
14343 PlacementStrategy::Replicated,
14344 PlacementStrategy::Sharded,
14345 ] {
14346 let p = Placement {
14347 estrategia: s,
14348 clusters: vec!["rio".into()],
14349 affinity: None,
14350 // Route the paired `:shard-key` fixture-builder through the
14351 // typed cross-slot invariant predicate
14352 // [`PlacementStrategy::requires_shard_key`] rather than the
14353 // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
14354 // arm-identity predicate — the two answer the same
14355 // question under today's closed accept-set but a future
14356 // arm addition that consumed `:shard-key` under a
14357 // non-`Sharded` name would silently mis-attach the
14358 // fixture's `:shard-key` if the builder read through the
14359 // arm-identity predicate. The cross-slot-invariant
14360 // predicate migrates through one caixa-core edit on any
14361 // future arm addition; the fixture keeps producing a
14362 // `validate()`-passing round-trip by construction.
14363 shard_key: if s.requires_shard_key() {
14364 Some("$key".into())
14365 } else {
14366 None
14367 },
14368 };
14369 let json = serde_json::to_string(&p).unwrap();
14370 let back: Placement = serde_json::from_str(&json).unwrap();
14371 assert_eq!(back, p);
14372 }
14373 }
14374
14375 #[test]
14376 fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
14377 // The fail-before-pass-after pin: pre-lift there was no
14378 // single-source binding between the [`PlacementStrategy`]
14379 // variant name the `Serialize` derive emits and the byte-
14380 // string every downstream cluster-side dispatcher (the
14381 // `lareira-fleet-programs` aggregator's per-entry strategy
14382 // branch, the future `app-operator` reconciler, the M3
14383 // Adaptive compression pass's per-strategy weighting) probes
14384 // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
14385 // future `#[serde(rename_all = "kebab-case")]` attribute on
14386 // the enum — or a variant rename in the source — would
14387 // silently rebrand the emitted scalar under one spelling
14388 // while every downstream dispatcher still probed the other,
14389 // with the failure surfacing at the aggregator's dispatch
14390 // step or the operator's reconcile posture (workloads coming
14391 // up under the `default()` `Replicated` arm rather than the
14392 // typed slot's declared strategy) far from the source
14393 // rebrand commit and with no field naming the drift. Pinning
14394 // the two paths (the `Serialize` derive's serialized string
14395 // AND the [`PlacementStrategy::as_str`] helper) to the same
14396 // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
14397 // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
14398 // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
14399 // makes any future drift on either endpoint fail here at
14400 // caixa-core build time.
14401 for (variant, expected) in [
14402 (
14403 PlacementStrategy::SingleNode,
14404 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
14405 ),
14406 (
14407 PlacementStrategy::Replicated,
14408 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
14409 ),
14410 (
14411 PlacementStrategy::Sharded,
14412 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
14413 ),
14414 ] {
14415 let json = serde_json::to_string(&variant).unwrap();
14416 assert_eq!(
14417 json,
14418 format!("\"{expected}\""),
14419 "PlacementStrategy::{variant:?} must serialize to {expected:?}"
14420 );
14421 assert_eq!(
14422 variant.as_str(),
14423 expected,
14424 "PlacementStrategy::{variant:?}.as_str() must return the lifted \
14425 M3_PLACEMENT_ESTRATEGIA_* constant"
14426 );
14427 }
14428 }
14429
14430 #[test]
14431 fn m3_placement_estrategia_consts_are_pairwise_distinct() {
14432 // Cross-arm drift-detection pin on the M3
14433 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
14434 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
14435 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
14436 // scalar-value pentad: a future collapse of two canonical
14437 // variant byte-strings onto the same value (an accidental
14438 // copy-paste flip of
14439 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
14440 // read `"SingleNode"`, a per-arm rebrand that lands one const
14441 // without touching its paired peer) would silently reroute
14442 // every downstream operator's per-strategy dispatch onto the
14443 // sibling arm's reconcile branch and pass every
14444 // propagation-probe test that expected only the stale arm's
14445 // value — a `Replicated`-declared Aplicacao would come up
14446 // under the `SingleNode` primary-and-standby reconcile
14447 // posture, so every-cluster active-active workload would
14448 // silently collapse onto one-cluster-runs-at-a-time takeover
14449 // semantics against its declared strategy, with no field
14450 // naming the strategy-value drift root cause. Peer of the
14451 // sibling
14452 // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
14453 // (09ffb2d) /
14454 // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
14455 // (ccdf955) /
14456 // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
14457 // (d739850) distinctness pins on the sibling OTP-shape /
14458 // caixa-kind closed-set typed-enum discriminator axes — the
14459 // fourth (and structurally the M3 mesh-primitive-defining)
14460 // closed-set typed-enum axis to converge on the same
14461 // "pairwise-distinct-by-construction" discipline.
14462 //
14463 // Fail-before-pass-after locally verified by mutating
14464 // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
14465 // also read `"SingleNode"` — this pin fires as expected;
14466 // restoring passes.
14467 let all = [
14468 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
14469 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
14470 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
14471 ];
14472 for (i, a) in all.iter().enumerate() {
14473 for (j, b) in all.iter().enumerate() {
14474 if i != j {
14475 assert_ne!(
14476 a, b,
14477 "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
14478 distinct — got duplicate {a:?} at indices {i} and {j}",
14479 );
14480 }
14481 }
14482 }
14483 }
14484
14485 #[test]
14486 fn placement_strategy_display_routes_through_as_str_helper() {
14487 // The fail-before-pass-after pin: pre-lift the sibling
14488 // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
14489 // / [`crate::supervisor::RestartPolicy`] both carried a stable
14490 // [`std::fmt::Display`] surface via their
14491 // `#[discriminant(also_display)]` gen-platform derive, but
14492 // [`PlacementStrategy`] did not — every consumer reaching for
14493 // a strategy byte-string past the wire format had to pick
14494 // between three paths ([`PlacementStrategy::as_str`], the
14495 // `Serialize` derive's serialized string, or `format!("{v:?}")`
14496 // on the `Debug` derive), any two of which a future variant
14497 // rename or `#[serde(rename_all = "kebab-case")]` attribute
14498 // would silently desynchronize. Wiring [`std::fmt::Display`]
14499 // through [`PlacementStrategy::as_str`] closes the third path:
14500 // every `format!("{v}")` call reaches the same lifted
14501 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
14502 // and the [`PlacementStrategy::as_str`] helper already route
14503 // through, so a future variant rename lands at exactly one
14504 // place. Pin the routing here so a future
14505 // `impl std::fmt::Display for PlacementStrategy` reimplementation
14506 // that hand-rolls the arms instead of delegating to
14507 // [`PlacementStrategy::as_str`] fails at caixa-core build time.
14508 for variant in [
14509 PlacementStrategy::SingleNode,
14510 PlacementStrategy::Replicated,
14511 PlacementStrategy::Sharded,
14512 ] {
14513 assert_eq!(
14514 variant.to_string(),
14515 variant.as_str(),
14516 "PlacementStrategy::{variant:?} Display must route through \
14517 PlacementStrategy::as_str (single source of truth: the lifted \
14518 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
14519 );
14520 }
14521 }
14522
14523 #[test]
14524 fn placement_strategy_display_matches_serialized_wire_byte_string() {
14525 // The fail-before-pass-after pin on the second half of the
14526 // three-path convergence: `Display` (user-facing text) agrees
14527 // byte-for-byte with the `Serialize` derive's wire format
14528 // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
14529 // scalar) on every variant. Pre-lift the two paths were
14530 // structurally independent — a future
14531 // `#[serde(rename_all = "kebab-case")]` attribute on the enum
14532 // would silently rebrand the emitted wire scalar
14533 // (`single-node`, `replicated`, `sharded`) while every consumer
14534 // that pretty-prints the strategy (the M3 diagnostic templates,
14535 // the future `feira app graph` per-Aplicacao strategy line,
14536 // the future M4 CR materializer's admission-webhook rejection
14537 // body) would still emit the TitleCase form the `as_str` /
14538 // `Display` route returns, with the mismatch surfacing at
14539 // consumer parse time / operator dispatch time far from the
14540 // source rebrand commit. Pin the two paths byte-for-byte here
14541 // so any future serde-attribute or variant-rename drift is a
14542 // caixa-core-build-time test failure at this call, not a
14543 // silent per-consumer dispatch miss.
14544 for variant in [
14545 PlacementStrategy::SingleNode,
14546 PlacementStrategy::Replicated,
14547 PlacementStrategy::Sharded,
14548 ] {
14549 let wire = serde_json::to_string(&variant).unwrap();
14550 // Strip the outer `"…"` the JSON string form carries — the
14551 // wire scalar the K8s / YAML apiserver consumes is the
14552 // enclosed byte-string, not the quote wrapper.
14553 let unquoted = wire
14554 .strip_prefix('"')
14555 .and_then(|s| s.strip_suffix('"'))
14556 .expect("serialized PlacementStrategy is a JSON string");
14557 assert_eq!(
14558 variant.to_string(),
14559 unquoted,
14560 "PlacementStrategy::{variant:?} Display byte-string must match the \
14561 Serialize derive's wire byte-string (three-path convergence: \
14562 Display + as_str + Serialize all resolve to the same \
14563 M3_PLACEMENT_ESTRATEGIA_* const)"
14564 );
14565 }
14566 }
14567
14568 #[test]
14569 fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
14570 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
14571 // derive on [`PlacementStrategy`]: for each of the three variants
14572 // exactly one of the generated `is_single_node` / `is_replicated`
14573 // / `is_sharded` predicates returns `true` and the other two
14574 // return `false`. Prior to this derive the three per-arm
14575 // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
14576 // (the `placement_strategy_variants_round_trip` fixture, the
14577 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
14578 // fixture, and the
14579 // `validate_placement_reads_through_lifted_estrategia_accessor`
14580 // fixture) each open-coded a per-arm PartialEq compare against
14581 // the enum variant — three sites that expressed no compile-time
14582 // link back to the closed-set typed dispatch a future fourth
14583 // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
14584 // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
14585 // would have to thread through in lockstep or one fixture would
14586 // silently disagree with the others on which arms consume the
14587 // `:shard-key` axis. Peer of the sibling
14588 // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
14589 // / [`crate::supervisor::RestartPolicy`] /
14590 // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
14591 // the sibling closed-set typed-enum discriminator axes — extends
14592 // the same one-typed-dispatch-per-variant discipline onto the
14593 // fifth (and only remaining) closed-set typed-enum discriminator
14594 // on the caixa surface, closing the axis on the M3 mesh-slot
14595 // family.
14596 let rows: [(PlacementStrategy, [bool; 3]); 3] = [
14597 (PlacementStrategy::SingleNode, [true, false, false]),
14598 (PlacementStrategy::Replicated, [false, true, false]),
14599 (PlacementStrategy::Sharded, [false, false, true]),
14600 ];
14601 for (variant, expected) in rows {
14602 let observed = [
14603 variant.is_single_node(),
14604 variant.is_replicated(),
14605 variant.is_sharded(),
14606 ];
14607 assert_eq!(
14608 observed, expected,
14609 "PlacementStrategy::{variant:?} is_* predicates must partition \
14610 the arm set (single_node, replicated, sharded); got {observed:?}"
14611 );
14612 }
14613 }
14614
14615 #[test]
14616 fn placement_strategy_is_variant_predicates_are_const_fn() {
14617 // The [`gen_platform::IsVariant`] derive emits `const fn`
14618 // predicates on the peer [`crate::CaixaKind`] +
14619 // [`crate::upgrade::UpgradeInstruction`] +
14620 // [`crate::supervisor::RestartStrategy`] +
14621 // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
14622 // pin the same posture on [`PlacementStrategy`] so a future
14623 // accidental downgrade to non-`const` (an added runtime helper
14624 // reachable only from a non-`const` context, a manual hand-rolled
14625 // `impl` that shadows the derive-generated method) trips at
14626 // caixa-core build time rather than surfacing as a downstream
14627 // `const`-context regression far from the derive declaration.
14628 const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
14629 const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
14630 const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
14631 assert!(IS_SINGLE_NODE);
14632 assert!(IS_REPLICATED);
14633 assert!(IS_SHARDED);
14634 }
14635
14636 #[test]
14637 fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
14638 // Fail-before-pass-after pin on the substrate-lifted
14639 // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
14640 // per-arm predicate: for each variant in the closed accept-set the
14641 // predicate returns `true` iff the variant consumes the paired
14642 // [`Placement::shard_key`] axis under
14643 // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
14644 // partition. Today the accept-set is the singleton `{Sharded}` —
14645 // `Sharded` is the Akka-style hash-keyed distribution arm
14646 // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
14647 // §II.1) and `Replicated` (active-active) refuse the axis through
14648 // [`AplicacaoError::ShardKeyOnNonSharded`].
14649 //
14650 // Pins the per-arm truth-table so a future arm addition (an
14651 // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
14652 // roadmap names, a `WeightedShard` promotion the future M5
14653 // adaptive-placement engine acknowledges) that landed a variant
14654 // without extending this predicate's arm-set would surface as a
14655 // caixa-core build-time exhaustiveness error at the
14656 // `match self { … }` arm-fan below rather than a silent per-consumer
14657 // mis-classification at renderer emit time. The paired
14658 // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
14659 // predicate stays a distinct question — arm-identity (which the
14660 // sibling
14661 // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
14662 // pin already locks) is not cross-slot-invariant consumption; today
14663 // they trip on the same singleton but the pair migrates through
14664 // one caixa-core edit on any future arm addition.
14665 //
14666 // Peer of the sibling per-arm classifier pins
14667 // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
14668 // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
14669 // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
14670 // derived paired predicate on the post-projection typed-view axis
14671 // — same "per-arm semantic-classification predicate paired with
14672 // the arm-identity predicate the derive already emits" discipline
14673 // extended onto the M3 mesh-slot `:placement :estrategia` ↔
14674 // `:placement :shard-key` cross-slot-invariant axis.
14675 let rows: [(PlacementStrategy, bool); 3] = [
14676 (PlacementStrategy::SingleNode, false),
14677 (PlacementStrategy::Replicated, false),
14678 (PlacementStrategy::Sharded, true),
14679 ];
14680 for (variant, expected) in rows {
14681 assert_eq!(
14682 variant.requires_shard_key(),
14683 expected,
14684 "PlacementStrategy::{variant:?}.requires_shard_key() must \
14685 be {expected} (the substrate-canonical cross-slot invariant \
14686 on the :placement :shard-key axis; today `Sharded` is the \
14687 singleton consuming arm — MESH-COMPOSITION §II.4)",
14688 );
14689 }
14690 }
14691
14692 #[test]
14693 fn placement_strategy_requires_shard_key_is_const_fn() {
14694 // The [`PlacementStrategy::requires_shard_key`] cross-slot-
14695 // invariant per-arm predicate is declared `#[must_use] pub const
14696 // fn` — pin the `const`-eval posture here so a future accidental
14697 // downgrade to non-`const` (an added runtime helper reachable
14698 // only from a non-`const` context, a manual hand-rolled `impl`
14699 // that shadows the current three-arm `match self { … }` dispatch)
14700 // trips at caixa-core build time rather than surfacing as a
14701 // downstream `const`-context regression far from the declaration.
14702 // Same shape as the sibling
14703 // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
14704 // the peer [`gen_platform::IsVariant`]-derived arm-identity
14705 // predicate axis, but here the load-bearing assertions live in
14706 // module-scope `const _: () = assert!(…)` items so a violation
14707 // fails at compile time (const-eval trip) rather than test time —
14708 // strictly stronger than the runtime `assert!(CONST)` pattern the
14709 // sibling pin uses, and side-steps the
14710 // `clippy::assertions_on_constants` lint the runtime pattern
14711 // otherwise accumulates on the module baseline.
14712 //
14713 // The test body simply witnesses that the module-scope items
14714 // compiled and the runtime dispatch agrees with the const-eval
14715 // dispatch on every arm — the runtime read gives the test a
14716 // failure surface (rather than an empty test body clippy would
14717 // flag as a no-op).
14718 const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
14719 const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
14720 const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
14721 assert_eq!(
14722 [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
14723 [
14724 PlacementStrategy::SingleNode.requires_shard_key(),
14725 PlacementStrategy::Replicated.requires_shard_key(),
14726 PlacementStrategy::Sharded.requires_shard_key(),
14727 ],
14728 "runtime and const-eval dispatch on \
14729 PlacementStrategy::requires_shard_key must agree on every arm",
14730 );
14731 }
14732
14733 #[test]
14734 fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
14735 // Load-bearing cross-slot-partition pin closing the loop between
14736 // the substrate-lifted
14737 // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
14738 // the closed-set typed enum and the actual
14739 // [`AplicacaoSpec::validate_placement`] runtime behavior across
14740 // the paired `:placement :shard-key` axis: every validated
14741 // [`Placement`] past [`AplicacaoSpec::validate_placement`]
14742 // satisfies `placement.shard_key().is_some() ==
14743 // placement.estrategia().requires_shard_key()`. The four-cell
14744 // shape witness sweeps every combination of (variant in the
14745 // closed accept-set, `:shard-key` Some/None) and pins:
14746 //
14747 // * variant.requires_shard_key() && shard_key.is_some() →
14748 // validate() passes; the paired shape is the sole
14749 // `requires_shard_key` arm-family accepted shape.
14750 // * variant.requires_shard_key() && shard_key.is_none() →
14751 // validate() fails with [`AplicacaoError::ShardedWithoutKey`];
14752 // the paired shape is the refused missing-key shape on
14753 // Sharded-family arms.
14754 // * !variant.requires_shard_key() && shard_key.is_some() →
14755 // validate() fails with
14756 // [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
14757 // is the refused declared-but-inert shape on non-Sharded-
14758 // family arms.
14759 // * !variant.requires_shard_key() && shard_key.is_none() →
14760 // validate() passes; the paired shape is the sole
14761 // non-`requires_shard_key` arm-family accepted shape.
14762 //
14763 // The compile-time-exhaustive `match p.estrategia()` dispatch at
14764 // [`AplicacaoSpec::validate_placement`] preserves its structural
14765 // arm-fan (a future arm addition still surfaces a build-time
14766 // exhaustiveness error there); this pin closes the semantic loop
14767 // between the arm-fan's shape-gate cascades and the substrate-
14768 // canonical predicate every downstream consumer of the paired
14769 // shape reads through. Fail-before-pass-after locally verified by
14770 // mutating the predicate's `Sharded => true` arm to `false` — the
14771 // truthy `expects_ok` cell for `Sharded` + `Some` trips the
14772 // `validate() must pass` assertion; restoring passes. Same "close
14773 // the loop between the typed predicate and the runtime behavior"
14774 // discipline as the sibling
14775 // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
14776 // (7b97d26) cross-projection pin on the peer [`WitTarget`]
14777 // per-arm classifier axis.
14778 for variant in [
14779 PlacementStrategy::SingleNode,
14780 PlacementStrategy::Replicated,
14781 PlacementStrategy::Sharded,
14782 ] {
14783 for present in [false, true] {
14784 let mut spec = three_member_spec();
14785 spec.placement.estrategia = variant;
14786 spec.placement.shard_key = present.then(|| "tenantId".into());
14787 let expects_ok = variant.requires_shard_key() == present;
14788 let result = spec.validate();
14789 match (expects_ok, &result) {
14790 (true, Ok(())) => {}
14791 (false, Err(err)) => {
14792 // Cross-check the refusal diagnostic names the
14793 // right cell of the four-cell shape witness — the
14794 // `requires_shard_key && !present` cell must trip
14795 // [`AplicacaoError::ShardedWithoutKey`]; the
14796 // `!requires_shard_key && present` cell must trip
14797 // [`AplicacaoError::ShardKeyOnNonSharded`].
14798 match (variant.requires_shard_key(), present, err) {
14799 (true, false, AplicacaoError::ShardedWithoutKey) => {}
14800 (
14801 false,
14802 true,
14803 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
14804 ) => {
14805 assert_eq!(
14806 *e, variant,
14807 "ShardKeyOnNonSharded.estrategia must byte-equal \
14808 the paired PlacementStrategy",
14809 );
14810 }
14811 _ => panic!(
14812 "unexpected refusal for estrategia={variant:?} \
14813 present={present}: {err:?}"
14814 ),
14815 }
14816 }
14817 (true, Err(err)) => panic!(
14818 "validate() must pass for estrategia={variant:?} \
14819 present={present} (requires_shard_key={} == present={present}), \
14820 got {err:?}",
14821 variant.requires_shard_key(),
14822 ),
14823 (false, Ok(())) => panic!(
14824 "validate() must fail for estrategia={variant:?} \
14825 present={present} (requires_shard_key={} != present={present})",
14826 variant.requires_shard_key(),
14827 ),
14828 }
14829 }
14830 }
14831 }
14832
14833 #[test]
14834 fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
14835 // Pin the M3 diagnostic template routes through the typed
14836 // [`PlacementStrategy`] Display byte-string (rebound from the
14837 // prior `{estrategia:?}` `Debug` route). Pre-lift the two
14838 // routes emitted identical bytes (the `Debug` derive on a
14839 // unit variant emits the variant name verbatim, exactly what
14840 // `as_str` returns), but the two paths were structurally
14841 // independent — a future `#[serde(rename_all = "…")]`
14842 // attribute or variant rename would coordinate the wire /
14843 // `Display` / `as_str` triple through the lifted const but
14844 // leave the `Debug` route on the compiler-derived variant name,
14845 // silently desynchronizing the diagnostic byte-string from the
14846 // wire byte-string. Rebinding the template onto `Display`
14847 // ties the diagnostic to the same lifted
14848 // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
14849 // emits — drift becomes structurally impossible. Pin the
14850 // byte-string here so a future edit that reverts the template
14851 // to `{estrategia:?}` is caught at caixa-core test time, not
14852 // at consumer dispatch time.
14853 for (variant, expected_scalar) in [
14854 (
14855 PlacementStrategy::SingleNode,
14856 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
14857 ),
14858 (
14859 PlacementStrategy::Replicated,
14860 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
14861 ),
14862 (
14863 PlacementStrategy::Sharded,
14864 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
14865 ),
14866 ] {
14867 let err = AplicacaoError::PlacementWithoutClusters {
14868 estrategia: variant,
14869 };
14870 let msg = err.to_string();
14871 assert!(
14872 msg.starts_with(&format!(":placement {expected_scalar} requires")),
14873 "PlacementWithoutClusters diagnostic for {variant:?} must open \
14874 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
14875 );
14876 }
14877 }
14878
14879 #[test]
14880 fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
14881 // Peer of
14882 // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
14883 // on the second M3 diagnostic that carries the typed
14884 // [`PlacementStrategy`] in its `#[error(…)]` template. Both
14885 // diagnostics now route the strategy scalar through the same
14886 // [`std::fmt::Display`] surface, tying the diagnostic
14887 // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
14888 // const set the wire format also emits. The two non-Sharded
14889 // arms are exercised here (the diagnostic exists to flag a
14890 // `:shard-key` slot the current strategy will never consume);
14891 // the peer `Sharded` arm never reaches this diagnostic (the
14892 // `Sharded` strategy consumes `:shard-key` — the
14893 // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
14894 // slot instead).
14895 for (variant, expected_scalar) in [
14896 (
14897 PlacementStrategy::SingleNode,
14898 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
14899 ),
14900 (
14901 PlacementStrategy::Replicated,
14902 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
14903 ),
14904 ] {
14905 let err = AplicacaoError::ShardKeyOnNonSharded {
14906 estrategia: variant,
14907 shard_key: "$tenantId".into(),
14908 };
14909 let msg = err.to_string();
14910 assert!(
14911 msg.starts_with(&format!(":placement {expected_scalar} carries")),
14912 "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
14913 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
14914 );
14915 }
14916 }
14917
14918 #[test]
14919 fn placement_strategy_all_enumerates_every_variant_once() {
14920 // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
14921 // exhaustive-iteration surface: every variant appears exactly
14922 // once, and the slice length matches the arm count of the
14923 // closed set. Every consumer that walks the accepted-strategy
14924 // set (a future `feira app placement --list` CLI-side surfacing,
14925 // a future M4 admission-webhook's rejection body naming the
14926 // accepted-strategy list, the [`PlacementStrategy::from_wire`]
14927 // reverse-projection consumers that iterate the accept-set for
14928 // a "did you mean" hint) reads through this slice, so a future
14929 // variant addition (an `Anycast` mesh-anycast arm the
14930 // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
14931 // grows the enum but forgets to grow [`Self::ALL`] silently
14932 // truncates every downstream consumer's accept-set at the same
14933 // pre-addition boundary — this pin fails at caixa-core build
14934 // time on the pairwise-distinct + arm-count invariants.
14935 //
14936 // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
14937 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
14938 // pins on the peer closed-set typed-enum axes.
14939 let all: &[PlacementStrategy] = PlacementStrategy::ALL;
14940 assert_eq!(
14941 all.len(),
14942 3,
14943 "PlacementStrategy::ALL must enumerate every variant of the \
14944 three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
14945 );
14946 for (i, a) in all.iter().enumerate() {
14947 for (j, b) in all.iter().enumerate() {
14948 if i != j {
14949 assert_ne!(
14950 a, b,
14951 "PlacementStrategy::ALL must carry every variant exactly \
14952 once — got duplicate {a:?} at indices {i} and {j}"
14953 );
14954 }
14955 }
14956 }
14957 for variant in [
14958 PlacementStrategy::SingleNode,
14959 PlacementStrategy::Replicated,
14960 PlacementStrategy::Sharded,
14961 ] {
14962 assert!(
14963 all.contains(&variant),
14964 "PlacementStrategy::ALL must contain {variant:?} — a future variant \
14965 addition that grows the enum but forgets to grow the ALL slice \
14966 silently truncates every downstream consumer's accept-set at the \
14967 pre-addition boundary"
14968 );
14969 }
14970 }
14971
14972 #[test]
14973 fn placement_strategy_from_wire_accepts_every_lifted_constant() {
14974 // Fail-before-pass-after pin on the forward accept-set of the
14975 // [`PlacementStrategy::from_wire`] reverse projection: every
14976 // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
14977 // constant the [`PlacementStrategy::as_str`] emitter walks
14978 // parses back to its paired variant. Any future arm addition
14979 // that grows the emitter's `as_str` match but forgets to grow
14980 // the parser's `from_str` match silently splits the two halves
14981 // of the round-trip — the wire byte-string one non-serde
14982 // consumer parses from the one the emitter wrote — with the
14983 // failure surfacing at parse time far from the rebrand commit.
14984 // Pinning the three-arm accept-set here catches the drift at
14985 // caixa-core build time.
14986 //
14987 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
14988 // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
14989 // closed-set typed-enum `str → Self` axes.
14990 for (wire, expected) in [
14991 (
14992 crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
14993 PlacementStrategy::SingleNode,
14994 ),
14995 (
14996 crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
14997 PlacementStrategy::Replicated,
14998 ),
14999 (
15000 crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15001 PlacementStrategy::Sharded,
15002 ),
15003 ] {
15004 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
15005 panic!(
15006 "PlacementStrategy::from_wire({wire:?}) must accept every \
15007 M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
15008 lifted canonical byte-string that PlacementStrategy::{expected:?} \
15009 serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
15010 )
15011 });
15012 assert_eq!(
15013 parsed, expected,
15014 "PlacementStrategy::from_wire({wire:?}) must return \
15015 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
15016 );
15017 }
15018 }
15019
15020 #[test]
15021 fn placement_strategy_from_wire_round_trips_through_as_str() {
15022 // Fail-before-pass-after pin on the closed round-trip between
15023 // the forward [`PlacementStrategy::as_str`] emitter and the
15024 // reverse [`PlacementStrategy::from_wire`] parser: for every
15025 // variant in [`PlacementStrategy::ALL`], parsing the emitter's
15026 // output must return exactly the same variant. Any per-arm
15027 // divergence — a future arm added to `as_str` but not
15028 // `from_str`, an accidental copy-paste flip in one but not the
15029 // other — silently splits the emit and parse halves and the
15030 // failure surfaces at consumer parse time far from the drift
15031 // site. The `ALL`-iterating shape means a future variant
15032 // addition picks up the coverage by construction.
15033 //
15034 // Peer of the sibling [`crate::kind::tests`] round-trip pin on
15035 // [`crate::CaixaKind::from_wire`] and the
15036 // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
15037 // sibling round-trip pin on [`RateLimitUnit`].
15038 for &variant in PlacementStrategy::ALL {
15039 let wire = variant.as_str();
15040 let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
15041 panic!(
15042 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
15043 must be Some({variant:?}) — the two halves of the round-trip \
15044 dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
15045 got None on wire byte-string {wire:?}"
15046 )
15047 });
15048 assert_eq!(
15049 parsed, variant,
15050 "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
15051 must round-trip to the same variant; got {parsed:?}"
15052 );
15053 }
15054 }
15055
15056 #[test]
15057 fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
15058 // Fail-before-pass-after pin on the closed-set refusal
15059 // discipline of [`PlacementStrategy::from_wire`]: every
15060 // byte-string outside the three-arm accept-set returns `None`
15061 // rather than silently collapsing onto the [`Default`]
15062 // (`Replicated`) arm or an arbitrary neighbor. The refusal set
15063 // exercised here sweeps the load-bearing drift shapes: the
15064 // empty string (a stripped serde-attribute drift), an all-
15065 // whitespace string (the canonical text-editor accidental
15066 // padding shape), the lowercased kebab-case forms a future
15067 // `#[serde(rename_all = "kebab-case")]` attribute would emit
15068 // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
15069 // coincidentally match the accepted canonical scalars, so only
15070 // `"single-node"` fires as a refusal, but pinning the case-
15071 // sensitivity of the accepted arms via the peer [`SingleNode`]
15072 // assertion in the round-trip pin makes the discipline
15073 // structurally clear), the lowercased single-word forms
15074 // (`"singlenode"`), the padded canonical scalar
15075 // (`" Sharded "`), the trailing-comma / trailing-newline shapes
15076 // (`"Sharded\n"`), and a pointer-different `&'static str` that
15077 // happens to alias a canonical byte-string by content but not
15078 // by identity (validated implicitly by the emitter's routing
15079 // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
15080 // identity a paired [`crate::assert_str_reexport_identity`] pin
15081 // in caixa-core's per-const declaration surface would catch).
15082 //
15083 // Peer of the sibling
15084 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
15085 // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
15086 for bad in [
15087 "",
15088 " ",
15089 "\n",
15090 "\t",
15091 "single-node",
15092 "singlenode",
15093 "SingleNodes",
15094 "single_node",
15095 "single node",
15096 "SINGLENODE",
15097 "SingleNode ",
15098 " SingleNode",
15099 " Sharded ",
15100 "Sharded\n",
15101 "replicated ",
15102 "sharded",
15103 "REPLICATED",
15104 "Anycast",
15105 "Global",
15106 "?",
15107 ] {
15108 assert!(
15109 PlacementStrategy::from_wire(bad).is_none(),
15110 "PlacementStrategy::from_wire({bad:?}) must return None — the \
15111 parser's accept-set is exactly the three PlacementStrategy::as_str \
15112 outputs (SingleNode, Replicated, Sharded), and this byte-string \
15113 is outside that closed set"
15114 );
15115 }
15116 }
15117
15118 #[test]
15119 fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
15120 // Fail-before-pass-after pin on the third path of the four-path
15121 // convergence: `from_str` (the reverse projection) inverts the
15122 // `Serialize` derive's wire byte-string on every variant.
15123 // Together with the pre-existing three-path convergence
15124 // (`Display` + `as_str` + `Serialize` all resolve to the same
15125 // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
15126 // the peer
15127 // [`placement_strategy_display_matches_serialized_wire_byte_string`])
15128 // this closes the round-trip: the wire byte-string the
15129 // `Serialize` derive emits parses back to the same variant
15130 // through `from_str`, so any future serde-attribute or variant-
15131 // rename drift on the emit half now surfaces as a matched drift
15132 // on the parse half at caixa-core build time — the two halves
15133 // migrate as a unit through the lifted consts on any future
15134 // rename, and the round-trip cannot silently split.
15135 //
15136 // Peer of the sibling
15137 // [`placement_strategy_display_matches_serialized_wire_byte_string`]
15138 // wire-format pin — extends the three-path convergence
15139 // (`Display` + `as_str` + `Serialize`) onto the fourth path
15140 // (`from_str`), closing the `str ↔ Self` round-trip on the
15141 // M3 `:placement :estrategia` closed-set axis.
15142 for &variant in PlacementStrategy::ALL {
15143 let wire = serde_json::to_string(&variant).unwrap();
15144 let unquoted = wire
15145 .strip_prefix('"')
15146 .and_then(|s| s.strip_suffix('"'))
15147 .expect("serialized PlacementStrategy is a JSON string");
15148 let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
15149 panic!(
15150 "PlacementStrategy::from_wire({unquoted:?}) must accept the \
15151 Serialize derive's wire byte-string for \
15152 PlacementStrategy::{variant:?} — the four-path convergence \
15153 (Display + as_str + Serialize + from_str) resolves through \
15154 the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
15155 )
15156 });
15157 assert_eq!(
15158 parsed, variant,
15159 "PlacementStrategy::from_wire of the Serialize derive's wire \
15160 byte-string for PlacementStrategy::{variant:?} must round-trip \
15161 to the same variant; got {parsed:?}"
15162 );
15163 }
15164 }
15165
15166 #[test]
15167 fn rejects_zero_policy_timeout() {
15168 let mut s = three_member_spec();
15169 s.politicas.timeout = Some(Duration::ZERO);
15170 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
15171 }
15172
15173 #[test]
15174 fn rejects_zero_policy_retries() {
15175 let mut s = three_member_spec();
15176 s.politicas.retries = Some(0);
15177 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
15178 }
15179
15180 #[test]
15181 fn rejects_policy_retries_above_cap() {
15182 // The fail-before-pass-after pin: `Some(11)` is structurally
15183 // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
15184 // passed validate on every pre-gate codebase because the
15185 // typed slot's only check was the zero-floor arm. The
15186 // thundering-herd amplification vector only surfaced at the
15187 // runtime substrate (Envoy / Cilium L7 retry overlay)
15188 // far from the source caixa.lisp with no field naming the
15189 // offending policy.
15190 let mut s = three_member_spec();
15191 s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
15192 assert_eq!(
15193 s.validate().unwrap_err(),
15194 AplicacaoError::PolicyRetriesExceedsCap {
15195 retries: POLICY_RETRIES_MAX + 1
15196 }
15197 );
15198 }
15199
15200 #[test]
15201 fn rejects_policy_retries_far_above_cap() {
15202 // The `u32::MAX` worst case — the four-billion-retry policy
15203 // a typo (`(:retries 4294967295)`) or struct-literal
15204 // copy-paste lands in the slot. Pin the cap arm's coverage
15205 // explicitly across the full `u32` overflow so a future
15206 // relaxation that drops the upper bound surfaces here.
15207 let mut s = three_member_spec();
15208 s.politicas.retries = Some(u32::MAX);
15209 assert_eq!(
15210 s.validate().unwrap_err(),
15211 AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
15212 );
15213 }
15214
15215 #[test]
15216 fn accepts_policy_retries_at_cap() {
15217 // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
15218 // must validate. The cap is inclusive on the top edge,
15219 // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
15220 // discipline on the sibling [`crate::LimitsSpec::memory`]
15221 // axis. Pin the boundary explicitly so a future off-by-one
15222 // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
15223 // surfaces here as a test failure rather than a silent
15224 // contract narrowing.
15225 let mut s = three_member_spec();
15226 s.politicas.retries = Some(POLICY_RETRIES_MAX);
15227 s.validate()
15228 .expect("retries == POLICY_RETRIES_MAX must validate");
15229 }
15230
15231 #[test]
15232 fn accepts_policy_retries_typical_values() {
15233 // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
15234 // every value in the validated set must pass. The
15235 // Envoy / Istio production-playbook recommendation band
15236 // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
15237 // (`maxRetries ≤ 10`) both lie within this set.
15238 for r in 1..=POLICY_RETRIES_MAX {
15239 let mut s = three_member_spec();
15240 s.politicas.retries = Some(r);
15241 s.validate()
15242 .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
15243 }
15244 }
15245
15246 #[test]
15247 fn policy_retries_zero_takes_precedence_over_cap() {
15248 // The cross-arm ordering pin: `Some(0)` is structurally
15249 // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
15250 // (cap), but the zero-floor diagnostic is the more
15251 // self-locating one (it directly names the omit-axis
15252 // remediation), so the validate gate must fire on zero
15253 // first. Pin the order so a future refactor that reorders
15254 // the arms surfaces here as a test failure rather than a
15255 // silent diagnostic regression. Same shape every other
15256 // zero-then-shape ordering on this surface uses
15257 // ([`AplicacaoError::PolicyTimeoutZero`] then
15258 // [`AplicacaoError::PolicyTimeoutNotCanonical`];
15259 // [`AplicacaoError::PolicyBreakerZeroWindow`] then
15260 // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
15261 let mut s = three_member_spec();
15262 s.politicas.retries = Some(0);
15263 assert_eq!(
15264 s.validate().unwrap_err(),
15265 AplicacaoError::PolicyRetriesZero,
15266 "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
15267 );
15268 }
15269
15270 #[test]
15271 fn policy_retries_cap_diagnostic_carries_offending_value() {
15272 // The diagnostic-shape pin: the offending `u32` is carried
15273 // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
15274 // variant so the surfaced error message names the value the
15275 // author wrote (`":politicas :retries (47) exceeds the
15276 // mesh-policy ceiling …"`), not just the cap. Same
15277 // self-locating diagnostic shape every other typed-cap arm
15278 // on this surface carries
15279 // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
15280 // offending byte count verbatim).
15281 let mut s = three_member_spec();
15282 s.politicas.retries = Some(47);
15283 let err = s.validate().unwrap_err();
15284 assert!(
15285 matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
15286 "got {err:?}"
15287 );
15288 let msg = err.to_string();
15289 assert!(
15290 msg.contains("47"),
15291 ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
15292 );
15293 }
15294
15295 #[test]
15296 fn policy_retries_cap_is_aws_app_mesh_aligned() {
15297 // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
15298 // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
15299 // schema cap — the only upstream mesh-policy schema that
15300 // documents an explicit hard cap. Pinning the literal value
15301 // here surfaces a future drift (a relaxation to 20, a
15302 // tightening to 5) as a deliberate test edit, not a silent
15303 // contract narrowing.
15304 assert_eq!(POLICY_RETRIES_MAX, 10);
15305 }
15306
15307 #[test]
15308 fn rejects_circuit_breaker_zero_max_failures() {
15309 let mut s = three_member_spec();
15310 s.politicas.circuit_breaker = Some(CircuitBreaker {
15311 max_failures: 0,
15312 window: Duration::from_secs(60),
15313 });
15314 assert_eq!(
15315 s.validate().unwrap_err(),
15316 AplicacaoError::PolicyBreakerZeroFailures
15317 );
15318 }
15319
15320 #[test]
15321 fn rejects_circuit_breaker_max_failures_above_cap() {
15322 // The fail-before-pass-after pin: `1001` is structurally one
15323 // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
15324 // silently passed validate on every pre-gate codebase
15325 // because the typed slot's only check was the zero-floor
15326 // arm. The breaker-no-op vector only surfaced at the runtime
15327 // substrate (Envoy / Cilium L7 outlier-detection overlay)
15328 // far from the source caixa.lisp with no field naming the
15329 // offending policy.
15330 let mut s = three_member_spec();
15331 s.politicas.circuit_breaker = Some(CircuitBreaker {
15332 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15333 window: Duration::from_secs(60),
15334 });
15335 assert_eq!(
15336 s.validate().unwrap_err(),
15337 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15338 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15339 }
15340 );
15341 }
15342
15343 #[test]
15344 fn rejects_circuit_breaker_max_failures_far_above_cap() {
15345 // The `u32::MAX` worst case — the four-billion-failure
15346 // threshold a typo (`(:max-failures 4294967295)`) or a
15347 // struct-literal copy-paste lands in the slot. Pin the cap
15348 // arm's coverage explicitly across the full `u32` overflow
15349 // so a future relaxation that drops the upper bound surfaces
15350 // here.
15351 let mut s = three_member_spec();
15352 s.politicas.circuit_breaker = Some(CircuitBreaker {
15353 max_failures: u32::MAX,
15354 window: Duration::from_secs(60),
15355 });
15356 assert_eq!(
15357 s.validate().unwrap_err(),
15358 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15359 max_failures: u32::MAX,
15360 }
15361 );
15362 }
15363
15364 #[test]
15365 fn accepts_circuit_breaker_max_failures_at_cap() {
15366 // The boundary value — exactly
15367 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
15368 // cap is inclusive on the top edge, matching the
15369 // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
15370 // discipline on the sibling capped axes. Pin the boundary
15371 // explicitly so a future off-by-one tightening
15372 // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
15373 // surfaces here as a test failure rather than a silent
15374 // contract narrowing.
15375 let mut s = three_member_spec();
15376 s.politicas.circuit_breaker = Some(CircuitBreaker {
15377 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
15378 window: Duration::from_secs(60),
15379 });
15380 s.validate()
15381 .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
15382 }
15383
15384 #[test]
15385 fn accepts_circuit_breaker_max_failures_typical_values() {
15386 // The documented production-playbook band positive-control
15387 // sweep — every value Hystrix / Istio / Envoy / Polly /
15388 // Resilience4j recommend (5..=50) must pass, plus a sweep
15389 // through the hyperscale band (100, 500, 1000) the cap
15390 // accepts. Pin the inclusive validated set explicitly so a
15391 // future tightening of the ceiling surfaces here.
15392 for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
15393 let mut s = three_member_spec();
15394 s.politicas.circuit_breaker = Some(CircuitBreaker {
15395 max_failures: n,
15396 window: Duration::from_secs(60),
15397 });
15398 s.validate()
15399 .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
15400 }
15401 }
15402
15403 #[test]
15404 fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
15405 // The cross-arm ordering pin: `0` is structurally outside
15406 // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
15407 // (cap), but the zero-floor diagnostic is the more
15408 // self-locating one (it directly names the omit-axis
15409 // remediation), so the validate gate must fire on zero
15410 // first. Same shape every other zero-then-shape ordering on
15411 // this surface uses
15412 // ([`AplicacaoError::PolicyRetriesZero`] then
15413 // [`AplicacaoError::PolicyRetriesExceedsCap`];
15414 // [`AplicacaoError::PolicyTimeoutZero`] then
15415 // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
15416 let mut s = three_member_spec();
15417 s.politicas.circuit_breaker = Some(CircuitBreaker {
15418 max_failures: 0,
15419 window: Duration::from_secs(60),
15420 });
15421 assert_eq!(
15422 s.validate().unwrap_err(),
15423 AplicacaoError::PolicyBreakerZeroFailures,
15424 "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
15425 );
15426 }
15427
15428 #[test]
15429 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
15430 // The cross-arm ordering pin between the cap and the
15431 // sibling `:window` gates (zero-window, canonical-window).
15432 // A breaker carrying both an over-cap `max_failures` AND a
15433 // structurally invalid window (zero, sub-ms) must surface
15434 // the cap diagnostic first — the cap arm is wired
15435 // immediately after the zero-failure arm and strictly
15436 // before the window arms, so the offending value the
15437 // diagnostic names matches the order the author would
15438 // discover the gates by reading top-to-bottom through
15439 // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
15440 // future refactor that reorders the arms surfaces here as a
15441 // test failure rather than a silent diagnostic regression.
15442 let mut s = three_member_spec();
15443 s.politicas.circuit_breaker = Some(CircuitBreaker {
15444 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15445 window: Duration::ZERO,
15446 });
15447 assert_eq!(
15448 s.validate().unwrap_err(),
15449 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15450 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
15451 },
15452 "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
15453 );
15454 }
15455
15456 #[test]
15457 fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
15458 // The diagnostic-shape pin: the offending `u32` is carried
15459 // verbatim into the
15460 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
15461 // variant so the surfaced error message names the value the
15462 // author wrote (`":politicas :circuit-breaker :max-failures
15463 // (50000) exceeds the mesh-policy ceiling …"`), not just
15464 // the cap. Same self-locating diagnostic shape every other
15465 // typed-cap arm on this surface carries
15466 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
15467 // offending retry count verbatim,
15468 // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
15469 // offending byte count verbatim).
15470 let mut s = three_member_spec();
15471 s.politicas.circuit_breaker = Some(CircuitBreaker {
15472 max_failures: 50_000,
15473 window: Duration::from_secs(60),
15474 });
15475 let err = s.validate().unwrap_err();
15476 assert!(
15477 matches!(
15478 err,
15479 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
15480 max_failures: 50_000
15481 }
15482 ),
15483 "got {err:?}"
15484 );
15485 let msg = err.to_string();
15486 assert!(
15487 msg.contains("50000"),
15488 ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
15489 );
15490 }
15491
15492 #[test]
15493 fn policy_breaker_max_failures_cap_pins_canonical_value() {
15494 // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
15495 // value at 1000 — an order of magnitude above every
15496 // documented production-playbook recommendation band
15497 // (Hystrix `requestVolumeThreshold` default 20, Istio
15498 // `outlierDetection.consecutive5xxErrors` default 5, Envoy
15499 // `outlier_detection.consecutive_5xx` default 5, Polly /
15500 // Resilience4j typical 5..=50) and below the
15501 // clearly-pathological "effectively no protection" floor
15502 // (10_000, 100_000, u32::MAX). Pinning the literal value
15503 // here surfaces a future drift (a relaxation to 10_000, a
15504 // tightening to 100) as a deliberate test edit, not a
15505 // silent contract narrowing.
15506 assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
15507 }
15508
15509 #[test]
15510 fn rejects_circuit_breaker_zero_window() {
15511 let mut s = three_member_spec();
15512 s.politicas.circuit_breaker = Some(CircuitBreaker {
15513 max_failures: 5,
15514 window: Duration::ZERO,
15515 });
15516 assert_eq!(
15517 s.validate().unwrap_err(),
15518 AplicacaoError::PolicyBreakerZeroWindow
15519 );
15520 }
15521
15522 #[test]
15523 fn rejects_zero_rate_limit() {
15524 let mut s = three_member_spec();
15525 s.politicas.rate_limit = Some(RateLimit {
15526 rate: 0,
15527 window: Duration::from_secs(1),
15528 });
15529 assert_eq!(
15530 s.validate().unwrap_err(),
15531 AplicacaoError::PolicyRateLimitZero
15532 );
15533 }
15534
15535 #[test]
15536 fn rejects_rate_limit_zero_window() {
15537 // `RateLimit { rate: 100, window: Duration::ZERO }` is
15538 // constructible programmatically (the typed `Duration` field
15539 // imposes no nonzero invariant) but renders through
15540 // `rate_limit_codec::render` as `"100/0s"` — a fragment the
15541 // codec's `parse` rejects as `unknown rate-limit window unit
15542 // "0s"`. Until this validate-time gate landed the typed slot
15543 // accepted the value silently and the round-trip break only
15544 // surfaced at deserialize time (potentially in a downstream
15545 // consumer that never re-validates). Pin the rejection at
15546 // `AplicacaoSpec::validate` so the typed slot's valid set
15547 // matches the codec's round-trippable set structurally.
15548 let mut s = three_member_spec();
15549 s.politicas.rate_limit = Some(RateLimit {
15550 rate: 100,
15551 window: Duration::ZERO,
15552 });
15553 assert_eq!(
15554 s.validate().unwrap_err(),
15555 AplicacaoError::PolicyRateLimitWindowNotCanonical {
15556 window: Duration::ZERO
15557 }
15558 );
15559 }
15560
15561 #[test]
15562 fn rejects_rate_limit_arbitrary_seconds_window() {
15563 // 45 seconds is a valid `Duration` but not one of the three
15564 // canonical rate-limit windows the codec round-trips
15565 // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
15566 // refuses on round-trip — same round-trip-break shape the
15567 // zero-window arm above pins, with a non-zero magnitude to
15568 // guard against a future "reject only zero" half-measure.
15569 let mut s = three_member_spec();
15570 let window = Duration::from_secs(45);
15571 s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
15572 assert_eq!(
15573 s.validate().unwrap_err(),
15574 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
15575 );
15576 }
15577
15578 #[test]
15579 fn rejects_rate_limit_two_minute_window() {
15580 // 120 seconds = 2 minutes is a "looks-canonical" but
15581 // not-canonical window: it's a clean integer multiple of the
15582 // minute unit, but the codec only round-trips the
15583 // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
15584 // A `Duration::from_secs(120)` window renders as `"100/120s"`
15585 // which the parser rejects. Pinning this case rules out a
15586 // future "accept any clean multiple of s/m/h" relaxation
15587 // that would silently break the codec contract.
15588 let mut s = three_member_spec();
15589 let window = Duration::from_secs(120);
15590 s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
15591 assert_eq!(
15592 s.validate().unwrap_err(),
15593 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
15594 );
15595 }
15596
15597 #[test]
15598 fn rejects_rate_limit_subsecond_window() {
15599 // A sub-second window (e.g. 500ms) is a valid `Duration` but
15600 // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
15601 // Pin the rejection so a future relaxation can't silently
15602 // admit fractional-second windows that the codec can't
15603 // round-trip.
15604 let mut s = three_member_spec();
15605 let window = Duration::from_millis(500);
15606 s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
15607 assert_eq!(
15608 s.validate().unwrap_err(),
15609 AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
15610 );
15611 }
15612
15613 #[test]
15614 fn rejects_policy_rate_limit_above_cap() {
15615 // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
15616 // is structurally one past the cap and silently passed
15617 // validate on every pre-gate codebase because the typed slot's
15618 // only `rate` check was the zero-floor arm. The no-op-limiter
15619 // shape only surfaced at the runtime substrate (Envoy's
15620 // `local_rate_limit.token_bucket.max_tokens`, the future
15621 // Cilium L7 rate-limit overlay) far from the source caixa.lisp
15622 // with no field naming the offending policy.
15623 let mut s = three_member_spec();
15624 s.politicas.rate_limit = Some(RateLimit {
15625 rate: POLICY_RATE_LIMIT_MAX + 1,
15626 window: Duration::from_secs(1),
15627 });
15628 assert_eq!(
15629 s.validate().unwrap_err(),
15630 AplicacaoError::PolicyRateLimitExceedsCap {
15631 rate: POLICY_RATE_LIMIT_MAX + 1
15632 }
15633 );
15634 }
15635
15636 #[test]
15637 fn rejects_policy_rate_limit_far_above_cap() {
15638 // The `u32::MAX` worst case — the four-billion-token rate-limit
15639 // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
15640 // copy-paste lands in the slot. Pin the cap arm's coverage
15641 // explicitly across the full `u32` overflow so a future
15642 // relaxation that drops the upper bound surfaces here. Peer to
15643 // `rejects_policy_retries_far_above_cap` on the sibling
15644 // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
15645 // on the sibling `:max-failures` axis.
15646 let mut s = three_member_spec();
15647 s.politicas.rate_limit = Some(RateLimit {
15648 rate: u32::MAX,
15649 window: Duration::from_secs(1),
15650 });
15651 assert_eq!(
15652 s.validate().unwrap_err(),
15653 AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
15654 );
15655 }
15656
15657 #[test]
15658 fn accepts_policy_rate_limit_at_cap() {
15659 // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
15660 // must validate. The cap is inclusive on the top edge, matching
15661 // every other typed upper bound in this crate
15662 // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
15663 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
15664 // across all three canonical windows so a future off-by-one
15665 // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
15666 // window-conditional cap surfaces here as a test failure rather
15667 // than a silent contract narrowing.
15668 for secs in [1u64, 60, 3600] {
15669 let mut s = three_member_spec();
15670 s.politicas.rate_limit = Some(RateLimit {
15671 rate: POLICY_RATE_LIMIT_MAX,
15672 window: Duration::from_secs(secs),
15673 });
15674 s.validate().unwrap_or_else(|e| {
15675 panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
15676 });
15677 }
15678 }
15679
15680 #[test]
15681 fn accepts_policy_rate_limit_typical_values() {
15682 // The documented production-playbook recommendation band —
15683 // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
15684 // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
15685 // Enterprise ~1M per-hour. Every value in the validated set
15686 // must pass; pin the band explicitly so a future tightening
15687 // surfaces here.
15688 for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
15689 for secs in [1u64, 60, 3600] {
15690 let mut s = three_member_spec();
15691 s.politicas.rate_limit = Some(RateLimit {
15692 rate,
15693 window: Duration::from_secs(secs),
15694 });
15695 s.validate().unwrap_or_else(|e| {
15696 panic!("rate={rate} window={secs}s must validate; got {e:?}")
15697 });
15698 }
15699 }
15700 }
15701
15702 #[test]
15703 fn policy_rate_limit_zero_takes_precedence_over_cap() {
15704 // The cross-arm ordering pin: `rate == 0` is structurally
15705 // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
15706 // (cap), but the zero-floor diagnostic is the more
15707 // self-locating one (it directly names the omit-axis
15708 // remediation). Pin the order so a future refactor that
15709 // reorders the arms surfaces here as a test failure rather
15710 // than a silent diagnostic regression. Same shape every other
15711 // zero-then-cap ordering on this surface uses
15712 // ([`AplicacaoError::PolicyRetriesZero`] then
15713 // [`AplicacaoError::PolicyRetriesExceedsCap`];
15714 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
15715 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
15716 let mut s = three_member_spec();
15717 s.politicas.rate_limit = Some(RateLimit {
15718 rate: 0,
15719 window: Duration::from_secs(1),
15720 });
15721 assert_eq!(
15722 s.validate().unwrap_err(),
15723 AplicacaoError::PolicyRateLimitZero,
15724 "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
15725 );
15726 }
15727
15728 #[test]
15729 fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
15730 // Two-axis-bad pin: rate above cap *and* window non-canonical.
15731 // The validate gate must fire on the rate cap first — the
15732 // amplification-shape (no-op limiter) diagnostic is the more
15733 // fundamental one; the window-canonical diagnostic is the
15734 // narrower codec-round-trip shape. Pin the ordering so a future
15735 // refactor that reorders the rate-then-window check arms
15736 // surfaces here as a test failure rather than a silent
15737 // diagnostic regression.
15738 let mut s = three_member_spec();
15739 s.politicas.rate_limit = Some(RateLimit {
15740 rate: POLICY_RATE_LIMIT_MAX + 1,
15741 window: Duration::from_secs(45),
15742 });
15743 assert_eq!(
15744 s.validate().unwrap_err(),
15745 AplicacaoError::PolicyRateLimitExceedsCap {
15746 rate: POLICY_RATE_LIMIT_MAX + 1
15747 },
15748 "above-cap rate must surface the cap diagnostic, not the window diagnostic"
15749 );
15750 }
15751
15752 #[test]
15753 fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
15754 // The diagnostic-shape pin: the offending `u32` is carried
15755 // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
15756 // variant so the surfaced error message names the value the
15757 // author wrote (`":politicas :rate-limit rate (5000000) exceeds
15758 // the mesh-policy ceiling …"`), not just the cap. Same
15759 // self-locating diagnostic shape every other typed-cap arm on
15760 // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
15761 // carries the offending retries count verbatim,
15762 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
15763 // the offending failure count verbatim).
15764 let mut s = three_member_spec();
15765 s.politicas.rate_limit = Some(RateLimit {
15766 rate: 5_000_000,
15767 window: Duration::from_secs(1),
15768 });
15769 let err = s.validate().unwrap_err();
15770 assert!(
15771 matches!(
15772 err,
15773 AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
15774 ),
15775 "got {err:?}"
15776 );
15777 let msg = err.to_string();
15778 assert!(
15779 msg.contains("5000000"),
15780 ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
15781 );
15782 }
15783
15784 #[test]
15785 fn policy_rate_limit_cap_pins_canonical_value() {
15786 // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
15787 // 1_000_000 — two-to-three orders of magnitude above every
15788 // documented production-playbook recommendation band (Envoy /
15789 // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
15790 // Gateway 10_000..=100_000 per-minute) and below the
15791 // clearly-pathological "paste-from-binary blob" floor
15792 // (100_000_000, u32::MAX). Pinning the literal value here
15793 // surfaces a future drift (a relaxation to 10_000_000, a
15794 // tightening to 100_000) as a deliberate test edit, not a
15795 // silent contract narrowing.
15796 assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
15797 }
15798
15799 #[test]
15800 fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
15801 // Both axes are invalid here: rate == 0 *and* window is
15802 // non-canonical. The validate gate must fire on rate first
15803 // (matching the existing `rejects_zero_rate_limit` ordering),
15804 // so the existing diagnostic continues to lead with the
15805 // simpler "zero rate" framing. Pinning the order of checks
15806 // so a future refactor that reorders the arms surfaces here
15807 // as a test failure rather than a silent diagnostic
15808 // regression.
15809 let mut s = three_member_spec();
15810 s.politicas.rate_limit = Some(RateLimit {
15811 rate: 0,
15812 window: Duration::from_secs(45),
15813 });
15814 assert_eq!(
15815 s.validate().unwrap_err(),
15816 AplicacaoError::PolicyRateLimitZero
15817 );
15818 }
15819
15820 #[test]
15821 fn rate_limit_canonical_windows_validate() {
15822 // The three canonical windows the codec round-trips
15823 // losslessly — 1s / 60s / 3600s — must all pass `validate()`
15824 // unchanged. Pin the full canonical set as a positive case
15825 // (the existing `rate_limit_round_trip_seconds` /
15826 // `rate_limit_round_trip_minutes` tests pin the
15827 // serialize-then-deserialize property at the codec layer; this
15828 // test pins the validate-side complement so a future tightening
15829 // of the canonical set — e.g. dropping `:hour` — surfaces here
15830 // as a test failure rather than a silent contract narrowing).
15831 for secs in [1u64, 60, 3600] {
15832 let mut s = three_member_spec();
15833 s.politicas.rate_limit = Some(RateLimit {
15834 rate: 100,
15835 window: Duration::from_secs(secs),
15836 });
15837 s.validate().expect("canonical window must validate");
15838 }
15839 }
15840
15841 #[test]
15842 fn rate_limit_validated_value_round_trips_through_codec() {
15843 // The structural property the validate gate enforces:
15844 // every `RateLimit` past `AplicacaoSpec::validate` round-trips
15845 // losslessly through the `rate_limit_codec` (serialize → string
15846 // → deserialize → equal value). Pin this end-to-end so a future
15847 // change to either side (the validate gate's accepted window
15848 // set, the codec's parse/render unit set) that breaks the
15849 // alignment surfaces here. The previous-state shape (typed
15850 // slot accepts arbitrary `Duration`, codec only round-trips
15851 // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
15852 // window — the validate gate now forecloses that.
15853 for secs in [1u64, 60, 3600] {
15854 let mut s = three_member_spec();
15855 s.politicas.rate_limit = Some(RateLimit {
15856 rate: 250,
15857 window: Duration::from_secs(secs),
15858 });
15859 s.validate().unwrap();
15860 let json = serde_json::to_string(&s.politicas).unwrap();
15861 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15862 assert_eq!(
15863 back.rate_limit, s.politicas.rate_limit,
15864 "every validated :rate-limit must round-trip losslessly through the codec"
15865 );
15866 }
15867 }
15868
15869 #[test]
15870 fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
15871 // The hour-window canonical form (`"<n>/h"`) was missing from
15872 // the prior `rate_limit_round_trip_seconds` / `_minutes` test
15873 // pair. Now that the validate gate pins 3600s as part of the
15874 // canonical set, pin its serialize-side render shape too so
15875 // the third leg of the s/m/h tripod is explicitly tested.
15876 let policy = MeshPolicy {
15877 rate_limit: Some(RateLimit {
15878 rate: 10000,
15879 window: Duration::from_secs(3600),
15880 }),
15881 ..Default::default()
15882 };
15883 let json = serde_json::to_string(&policy).unwrap();
15884 assert!(
15885 json.contains("\"10000/h\""),
15886 "hour-window canonical form must render with `h` suffix (got: {json})"
15887 );
15888 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
15889 assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
15890 }
15891
15892 #[test]
15893 fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
15894 // Pin the substrate-primitive [`RateLimit::canonical_unit`]
15895 // typed accessor's accepted-window set against the codec's
15896 // accepted set explicitly. A future addition to the codec
15897 // (e.g. accepting `:day`/`:week` as authoring units) must be
15898 // accompanied by a parallel addition here, and a regression
15899 // that drops one of the three canonical units from either
15900 // side surfaces as a test failure. The accessor is the
15901 // single source of truth for the canonical-window set —
15902 // [`AplicacaoSpec::validate_politicas`]'s canonical-window
15903 // gate and [`rate_limit_codec::render`]'s canonical arm both
15904 // read through it — this test enshrines that its
15905 // `Duration → Option<RateLimitUnit>` projection matches the
15906 // codec's parse / render arms' accepted-window set exactly.
15907 //
15908 // Predecessor: this pin previously read the module-private
15909 // free helper `is_canonical_rate_limit_window` — a delegate
15910 // that composed [`RateLimitUnit::from_window`] with `.is_some()`
15911 // — but the helper had no production consumers left after the
15912 // validate-gate migration onto [`RateLimit::canonical_unit`]
15913 // and was deleted; the closed-set arm-window bijection now
15914 // lives on exactly one typed dispatch on the substrate
15915 // primitive.
15916 let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
15917 RateLimit { rate: 1, window }.canonical_unit()
15918 };
15919 assert!(canonical_unit(Duration::from_secs(1)).is_some());
15920 assert!(canonical_unit(Duration::from_secs(60)).is_some());
15921 assert!(canonical_unit(Duration::from_secs(3600)).is_some());
15922 // Non-canonical windows the accessor rejects.
15923 assert!(canonical_unit(Duration::ZERO).is_none());
15924 assert!(canonical_unit(Duration::from_secs(2)).is_none());
15925 assert!(canonical_unit(Duration::from_secs(30)).is_none());
15926 assert!(canonical_unit(Duration::from_secs(120)).is_none());
15927 assert!(canonical_unit(Duration::from_secs(86400)).is_none());
15928 // Sub-second windows: even `Duration::from_millis(1000)` is
15929 // exactly 1s and accepted; `Duration::from_millis(500)` is
15930 // sub-second and rejected.
15931 assert!(canonical_unit(Duration::from_millis(1000)).is_some());
15932 assert!(canonical_unit(Duration::from_millis(500)).is_none());
15933 assert!(canonical_unit(Duration::from_millis(1500)).is_none());
15934 }
15935
15936 #[test]
15937 fn rate_limit_unit_table_projections_are_mutual_inverses() {
15938 // Bidirection pin against the closed-set typed enum
15939 // [`RateLimitUnit`] arm-table (the canonical
15940 // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
15941 // of the rate-limit unit surface reads from). The two
15942 // projection directions [`RateLimitUnit::from_suffix`] /
15943 // [`RateLimitUnit::window`] (str → Duration, exposed as one
15944 // typed dispatch through [`RateLimitUnit::window_from_suffix`])
15945 // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
15946 // (Duration → str, exposed as one typed dispatch through
15947 // [`RateLimit::canonical_unit`] composed with
15948 // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
15949 // codec's parse arm ([`rate_limit_codec::parse`] via
15950 // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
15951 // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
15952 // and the validate gate ([`AplicacaoSpec::validate_politicas`]
15953 // via [`RateLimit::canonical_unit`]) all key off. A future
15954 // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
15955 // sub-second window) is one variant + one arm per method on the
15956 // closed-set enum; the compiler-enforced exhaustiveness on
15957 // every consumer's `match self` arms picks it up by
15958 // construction. This pin enshrines that both projection
15959 // directions agree on every canonical arm row and neither
15960 // leaks a spurious entry the other doesn't recognize.
15961 //
15962 // Predecessor: this test previously read the two vestigial
15963 // module-private free helpers `rate_limit_window_unit` and
15964 // `rate_limit_window_from_unit` on the `Duration → &str` and
15965 // `&str → Duration` axes; the former was deleted after its
15966 // sole production consumer ([`rate_limit_codec::render`])
15967 // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
15968 // the latter is folded here into the substrate primitive
15969 // [`RateLimitUnit::window_from_suffix`] so both projection
15970 // directions live on the closed-set enum's arm-table.
15971 for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
15972 let window = super::RateLimitUnit::window_from_suffix(unit)
15973 .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
15974 assert_eq!(
15975 window,
15976 Duration::from_secs(secs),
15977 "unit {unit:?} must resolve to {secs}s"
15978 );
15979 let projected_suffix = RateLimit { rate: 1, window }
15980 .canonical_unit()
15981 .map(super::RateLimitUnit::as_suffix);
15982 assert_eq!(
15983 projected_suffix,
15984 Some(unit),
15985 "Duration({secs}s) must render as {unit:?} \
15986 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
15987 );
15988 }
15989 // Non-table units yield None on the `unit → Duration`
15990 // projection — a future `"d"` addition to the table would
15991 // flip this arm; today it pins the current three-row table's
15992 // rejection semantics.
15993 assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
15994 assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
15995 assert!(super::RateLimitUnit::window_from_suffix("").is_none());
15996 // Non-table Durations yield None on the `Duration → unit`
15997 // projection — pins that the two projections agree on the
15998 // "not in the table" semantic too, so a drift where the
15999 // parse-side accepts a value the render-side can't emit is
16000 // a build error at the two-arm pair, not a silent codec
16001 // round-trip break.
16002 let projected_suffix = |window: Duration| -> Option<&'static str> {
16003 RateLimit { rate: 1, window }
16004 .canonical_unit()
16005 .map(super::RateLimitUnit::as_suffix)
16006 };
16007 assert!(projected_suffix(Duration::from_secs(2)).is_none());
16008 assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
16009 assert!(projected_suffix(Duration::from_millis(1500)).is_none());
16010 }
16011
16012 #[test]
16013 fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
16014 // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
16015 // substrate-primitive `&str → Duration` associated method the
16016 // codec's parse arm ([`rate_limit_codec::parse`]) now routes
16017 // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
16018 // to the same [`Duration`] the two-step composition
16019 // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
16020 // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
16021 // `"MIN"`) must project to [`None`] on both paths. A future
16022 // implementation of `window_from_suffix` that took a shortcut
16023 // through a per-suffix `match` table (bypassing the arm-table's
16024 // `Self::from_suffix` scan and the arm-table's `Self::window`
16025 // dispatch) would silently split the accept-set — the parse
16026 // arm would accept a suffix the enum's arm-table doesn't know,
16027 // or reject a suffix the enum's arm-table does; this pin
16028 // surfaces that drift at caixa-core build time rather than at a
16029 // downstream serde round-trip audit on a live `MeshPolicy`.
16030 //
16031 // Same byte-parity discipline the sibling
16032 // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
16033 // pin carries on the peer `Duration → RateLimitUnit` axis via
16034 // [`RateLimit::canonical_unit`], and the peer
16035 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
16036 // carries on the bidirectional arm-table axis — extended here
16037 // onto the fifth (and last unlifted) projection axis on the
16038 // closed-set enum's arm-table.
16039 let composition = |suffix: &str| -> Option<Duration> {
16040 super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
16041 };
16042 for suffix in ["s", "m", "h"] {
16043 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
16044 let via_composition = composition(suffix);
16045 assert_eq!(
16046 via_method, via_composition,
16047 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
16048 from_suffix({suffix:?}).map(window) — the substrate-primitive \
16049 method must delegate to the arm-table's two typed dispatches, \
16050 not shortcut through a per-suffix match table"
16051 );
16052 assert!(
16053 via_method.is_some(),
16054 "canonical suffix {suffix:?} must resolve to Some(Duration) via \
16055 RateLimitUnit::window_from_suffix"
16056 );
16057 }
16058 for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
16059 let via_method = super::RateLimitUnit::window_from_suffix(suffix);
16060 let via_composition = composition(suffix);
16061 assert_eq!(
16062 via_method, via_composition,
16063 "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
16064 from_suffix({suffix:?}).map(window) on the non-arm rejection \
16065 axis too"
16066 );
16067 assert!(
16068 via_method.is_none(),
16069 "non-arm suffix {suffix:?} must project to None via \
16070 RateLimitUnit::window_from_suffix — a future extension that \
16071 accepted this suffix without a corresponding arm on the enum \
16072 would split the codec's parse-accepted set from the enum's \
16073 arm-table"
16074 );
16075 }
16076 // And the codec's parse arm now reads through this method: a
16077 // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
16078 // the same `Duration` the method returns for its unit, closing
16079 // the two-consumer drift surface (the codec's parse arm and the
16080 // enum's arm-table) with one typed dispatch on the substrate
16081 // primitive.
16082 for suffix in ["s", "m", "h"] {
16083 let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
16084 let mp: MeshPolicy = serde_json::from_str(&wire)
16085 .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
16086 let parsed = mp.rate_limit().expect("rate_limit payload present");
16087 let via_method = super::RateLimitUnit::window_from_suffix(suffix)
16088 .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
16089 assert_eq!(
16090 parsed.window(),
16091 via_method,
16092 "codec parse arm on {wire:?} must resolve the window through \
16093 RateLimitUnit::window_from_suffix, not a divergent path"
16094 );
16095 }
16096 }
16097
16098 #[test]
16099 fn rate_limit_unit_all_enumerates_every_arm_once() {
16100 // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
16101 // enumerate every arm of the closed-set enum exactly once, in
16102 // the canonical shortest-to-longest window order (Second before
16103 // Minute before Hour) — the same order the sibling
16104 // [`crate::supervisor::RestartStrategy`] /
16105 // [`crate::supervisor::RestartPolicy`] /
16106 // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
16107 // typed enums carry (the arm declared first is the arm listed
16108 // first). A future variant addition that extends the enum
16109 // without appending to [`RateLimitUnit::ALL`] leaves the
16110 // exhaustive iteration surface silently short one arm — the
16111 // codec's parse arm would then reject the new suffix even
16112 // though the enum knows it. This pin closes the drift.
16113 assert_eq!(
16114 super::RateLimitUnit::ALL,
16115 &[
16116 super::RateLimitUnit::Second,
16117 super::RateLimitUnit::Minute,
16118 super::RateLimitUnit::Hour,
16119 ],
16120 "RateLimitUnit::ALL must enumerate every arm exactly once, \
16121 in canonical shortest-to-longest window order"
16122 );
16123 }
16124
16125 #[test]
16126 fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
16127 // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
16128 // every arm's [`RateLimitUnit::as_suffix`] output must parse
16129 // back through [`RateLimitUnit::from_suffix`] to the same
16130 // variant. A future arm addition that lands `as_suffix` but
16131 // forgets `from_suffix` (`from_suffix` iterates
16132 // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
16133 // is the load-bearing carrier of the round-trip; the sibling
16134 // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
16135 // the `ALL` half) trips here at caixa-core build time rather
16136 // than surfacing as a codec round-trip miss (a `render` emit
16137 // that lands a suffix the paired `parse` cannot decode).
16138 for unit in super::RateLimitUnit::ALL {
16139 let suffix = unit.as_suffix();
16140 let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
16141 panic!(
16142 "RateLimitUnit::from_suffix({suffix:?}) must accept every \
16143 RateLimitUnit::as_suffix output — got None for {unit:?}"
16144 )
16145 });
16146 assert_eq!(
16147 parsed, *unit,
16148 "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
16149 must return RateLimitUnit::{unit:?}"
16150 );
16151 }
16152 }
16153
16154 #[test]
16155 fn rate_limit_unit_from_window_and_window_round_trip() {
16156 // Total round-trip pin on the `(from_window, window)` pair:
16157 // every arm's [`RateLimitUnit::window`] output must parse back
16158 // through [`RateLimitUnit::from_window`] to the same variant.
16159 // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
16160 // on the peer `Duration` axis — the two round-trip pins
16161 // together enshrine that both projections of the typed
16162 // canonical-unit bijection are total on the arm-set.
16163 for unit in super::RateLimitUnit::ALL {
16164 let window = unit.window();
16165 let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
16166 panic!(
16167 "RateLimitUnit::from_window({window:?}) must accept every \
16168 RateLimitUnit::window output — got None for {unit:?}"
16169 )
16170 });
16171 assert_eq!(
16172 parsed, *unit,
16173 "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
16174 must return RateLimitUnit::{unit:?}"
16175 );
16176 }
16177 }
16178
16179 #[test]
16180 fn rate_limit_unit_projections_are_pairwise_distinct() {
16181 // Distinctness pin: [`RateLimitUnit::as_suffix`] and
16182 // [`RateLimitUnit::window`] outputs must be pairwise distinct
16183 // across every arm — an accidental copy-paste flip that
16184 // reroutes one arm's suffix or window to also match another
16185 // silently collapses two arms onto one, so
16186 // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
16187 // (both using `find` on `Self::ALL`) would return whichever
16188 // arm the linear scan lands on first — a match-arm-ordering-
16189 // dependent outcome the closed-set typed-enum shape is meant
16190 // to rule out structurally. Peer of the sibling
16191 // `caixa_kind_wire_consts_are_pairwise_distinct` /
16192 // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
16193 // other closed-set typed-enum discriminator axes.
16194 let all = super::RateLimitUnit::ALL;
16195 for (i, a) in all.iter().enumerate() {
16196 for (j, b) in all.iter().enumerate() {
16197 if i != j {
16198 assert_ne!(
16199 a.as_suffix(),
16200 b.as_suffix(),
16201 "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
16202 must be distinct — a collision silently collapses two \
16203 arms onto one under from_suffix's linear scan"
16204 );
16205 assert_ne!(
16206 a.window(),
16207 b.window(),
16208 "RateLimitUnit::{a:?}.window() and {b:?}.window() \
16209 must be distinct — a collision silently collapses two \
16210 arms onto one under from_window's linear scan"
16211 );
16212 }
16213 }
16214 }
16215 }
16216
16217 #[test]
16218 fn rate_limit_unit_display_routes_through_as_suffix() {
16219 // Route pin: [`std::fmt::Display`] must byte-equal
16220 // [`RateLimitUnit::as_suffix`] on every arm — the single
16221 // source of truth for the canonical suffix. A future
16222 // reimplementation that hand-rolls the arms instead of
16223 // delegating to [`RateLimitUnit::as_suffix`] would silently
16224 // desynchronize `format!("{u}")` from the codec's parse arm
16225 // (which uses `as_suffix` to compare suffixes). Peer of the
16226 // sibling `caixa_kind_display_routes_through_as_str_helper` /
16227 // `placement_strategy_display_routes_through_as_str_helper`
16228 // pins on the peer closed-set typed-enum Display axes.
16229 for unit in super::RateLimitUnit::ALL {
16230 assert_eq!(
16231 unit.to_string(),
16232 unit.as_suffix(),
16233 "RateLimitUnit::{unit:?} Display must route through \
16234 as_suffix (single source of truth: the canonical suffix \
16235 the codec parses and renders)"
16236 );
16237 }
16238 }
16239
16240 #[test]
16241 fn rate_limit_unit_from_window_rejects_non_canonical() {
16242 // Rejection pin on the parser's accept-set: any Duration
16243 // outside the three-arm [`RateLimitUnit::window`] output set
16244 // (sub-second residue, or a second-magnitude outside `{1, 60,
16245 // 3600}`) must return `None`. A future accidental widening of
16246 // the accept-set (rounding down sub-second residue to the
16247 // nearest arm, admitting `Duration::from_secs(30)` as a
16248 // half-minute unit) would silently drift the parser's accept-
16249 // set from the emitter's — a validated slot with a
16250 // non-canonical window would then round-trip through the
16251 // codec to a canonical form the author never wrote.
16252 assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
16253 assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
16254 assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
16255 assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
16256 assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
16257 assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
16258 assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
16259 }
16260
16261 #[test]
16262 fn rate_limit_unit_from_suffix_rejects_unknown() {
16263 // Rejection pin on the suffix parser's accept-set: any string
16264 // outside the three-arm [`RateLimitUnit::as_suffix`] output
16265 // set must return `None`. Peer of the sibling
16266 // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
16267 // the [`crate::CaixaKind`] `from_wire` accept-set.
16268 for bad in [
16269 "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
16270 " s",
16271 ] {
16272 assert!(
16273 super::RateLimitUnit::from_suffix(bad).is_none(),
16274 "RateLimitUnit::from_suffix({bad:?}) must return None — the \
16275 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
16276 outputs"
16277 );
16278 }
16279 }
16280
16281 #[test]
16282 fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
16283 // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
16284 // every canonical `:window` magnitude the validate gate
16285 // accepts must map to the paired [`RateLimitUnit`] arm through
16286 // this accessor. A future validate-gate rebrand that widened
16287 // the accepted-window set without extending [`RateLimitUnit`]
16288 // would silently split the accessor's `Some`-return set from
16289 // the validate gate's accept-set — a slot that satisfies
16290 // validate would land at the accessor with `None`, so a
16291 // consumer past validate that pattern-matches on the returned
16292 // `Some` would silently miss the newly-accepted magnitude.
16293 for (window_secs, expected) in [
16294 (1u64, super::RateLimitUnit::Second),
16295 (60, super::RateLimitUnit::Minute),
16296 (3600, super::RateLimitUnit::Hour),
16297 ] {
16298 let rl = RateLimit {
16299 rate: 100,
16300 window: Duration::from_secs(window_secs),
16301 };
16302 assert_eq!(
16303 rl.canonical_unit(),
16304 Some(expected),
16305 "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
16306 must return Some({expected:?})"
16307 );
16308 }
16309 // Non-canonical windows the validate gate rejects also return
16310 // None here — the accessor is the typed-enum projection of
16311 // the sibling `is_canonical_rate_limit_window` predicate.
16312 let bad = RateLimit {
16313 rate: 100,
16314 window: Duration::from_secs(30),
16315 };
16316 assert!(
16317 bad.canonical_unit().is_none(),
16318 "RateLimit with a non-canonical window must return None from \
16319 canonical_unit — the validate gate rejects the same set"
16320 );
16321 }
16322
16323 #[test]
16324 fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
16325 // Fail-before-pass-after byte-parity pin: for every canonical
16326 // window the [`rate_limit_codec::render`] arm's emitted string
16327 // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
16328 // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
16329 // the vestigial free helper [`rate_limit_window_unit`] (a
16330 // `find_map`-walked `Duration → &'static str` delegate) onto the
16331 // substrate primitive [`RateLimit::canonical_unit`] typed method
16332 // (a closed-set `match self.window` arm on
16333 // [`RateLimitUnit::from_window`], projected through
16334 // [`RateLimitUnit::as_suffix`] via the enum's
16335 // [`std::fmt::Display`] impl). A future re-routing of the render
16336 // arm through a differently-computed unit projection would break
16337 // this pin at build time rather than as a silent per-consumer
16338 // codec round-trip drift far from the substrate primitive edit.
16339 //
16340 // Sibling to the peer
16341 // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
16342 // on the free-helper axis: that pin locks the two projections
16343 // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
16344 // on the closed-set arm table; this pin locks the codec's render
16345 // arm reads through the typed accessor rather than the free
16346 // helper. Two production consumers of the canonical-unit axis
16347 // now key off one typed dispatch on the substrate primitive.
16348 for (window_secs, unit) in [
16349 (1u64, super::RateLimitUnit::Second),
16350 (60, super::RateLimitUnit::Minute),
16351 (3600, super::RateLimitUnit::Hour),
16352 ] {
16353 let rl = RateLimit {
16354 rate: 42,
16355 window: Duration::from_secs(window_secs),
16356 };
16357 let policy = MeshPolicy {
16358 rate_limit: Some(rl),
16359 ..Default::default()
16360 };
16361 let json = serde_json::to_string(&policy).unwrap();
16362 let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
16363 assert!(
16364 json.contains(&expected),
16365 "rate_limit_codec::render must emit {expected} (via \
16366 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
16367 for a {window_secs}s window; serialized MeshPolicy was: {json}"
16368 );
16369 // And the accessor route resolves to the same typed unit
16370 // the render arm's Display formatting is asked to produce —
16371 // so a future edit that split the two paths (one through
16372 // the accessor, one through a re-introduced free helper)
16373 // trips this pin.
16374 assert_eq!(
16375 rl.canonical_unit(),
16376 Some(unit),
16377 "RateLimit::canonical_unit must return Some({unit:?}) for a \
16378 {window_secs}s window; the codec render arm reads the same \
16379 typed unit through this accessor"
16380 );
16381 }
16382 }
16383
16384 #[test]
16385 fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
16386 // Fail-before-pass-after byte-parity pin on the validate gate's
16387 // canonical-window shape probe: every non-canonical `:window`
16388 // the free-helper predicate [`is_canonical_rate_limit_window`]
16389 // rejects is also rejected by the substrate primitive
16390 // [`RateLimit::canonical_unit`] `.is_none()` route the validate
16391 // gate now reads through, and vice versa on the accepted set
16392 // (the three canonical windows). Locks the migration from the
16393 // free helper onto the substrate primitive: a future re-routing
16394 // of one of the two paths through a differently-computed unit
16395 // projection would silently split the codec's accepted set from
16396 // the validate gate's accepted set — a two-consumer drift the
16397 // codec-round-trip pin
16398 // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
16399 // above closes on the render arm and this pin closes on the
16400 // validate arm.
16401 for canonical_window_secs in [1u64, 60, 3600] {
16402 let mut s = three_member_spec();
16403 let rl = RateLimit {
16404 rate: 100,
16405 window: Duration::from_secs(canonical_window_secs),
16406 };
16407 s.politicas.rate_limit = Some(rl);
16408 assert!(
16409 s.validate().is_ok(),
16410 "canonical {canonical_window_secs}s window must pass \
16411 validate_politicas — the validate gate now reads \
16412 RateLimit::canonical_unit().is_none() and the accessor \
16413 returns Some on every canonical arm"
16414 );
16415 assert!(
16416 rl.canonical_unit().is_some(),
16417 "canonical {canonical_window_secs}s window must resolve to \
16418 Some on RateLimit::canonical_unit — the validate gate reads \
16419 this accessor directly"
16420 );
16421 }
16422 for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
16423 let mut s = three_member_spec();
16424 let rl = RateLimit {
16425 rate: 100,
16426 window: Duration::from_secs(non_canonical_window_secs),
16427 };
16428 s.politicas.rate_limit = Some(rl);
16429 assert_eq!(
16430 s.validate().unwrap_err(),
16431 AplicacaoError::PolicyRateLimitWindowNotCanonical {
16432 window: rl.window(),
16433 },
16434 "non-canonical {non_canonical_window_secs}s window must be \
16435 rejected by validate_politicas — the validate gate now \
16436 keys off RateLimit::canonical_unit().is_none()"
16437 );
16438 assert!(
16439 rl.canonical_unit().is_none(),
16440 "non-canonical {non_canonical_window_secs}s window must \
16441 resolve to None on RateLimit::canonical_unit — the two \
16442 paths (the free helper the validate gate previously read \
16443 and the substrate primitive the validate gate now reads) \
16444 must agree on the same rejected set"
16445 );
16446 }
16447 // And the substrate-primitive [`RateLimit::canonical_unit`]
16448 // accessor's accepted-window set matches the codec's parse arm's
16449 // accepted-suffix set on every canonical / non-canonical shape,
16450 // so a future silent drift between the codec's accepted set and
16451 // the validate gate's accepted set is a build error at test time
16452 // (both consumers key off the same closed-set enum's `match self`
16453 // arms). The predecessor free helper `is_canonical_rate_limit_window`
16454 // — a delegate that composed [`RateLimitUnit::from_window`] with
16455 // `.is_some()` — was deleted after this migration; the
16456 // canonical-window set now lives on exactly one typed dispatch
16457 // on the substrate primitive.
16458 for (secs, expected) in [
16459 (1u64, true),
16460 (60, true),
16461 (3600, true),
16462 (2, false),
16463 (30, false),
16464 (86_400, false),
16465 ] {
16466 let window = Duration::from_secs(secs);
16467 let rl = RateLimit { rate: 1, window };
16468 assert_eq!(
16469 rl.canonical_unit().is_some(),
16470 expected,
16471 "RateLimit::canonical_unit().is_some() must agree with the \
16472 codec-accepted canonical-window set on {secs}s"
16473 );
16474 let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
16475 1 => "s",
16476 60 => "m",
16477 3600 => "h",
16478 _ => return,
16479 })
16480 .is_some_and(|d| d == window);
16481 if expected {
16482 assert!(
16483 suffix_from_axis,
16484 "the codec's `&str → Duration` axis \
16485 ({secs}s) must round-trip to the same Duration the \
16486 substrate primitive's accessor returns Some on"
16487 );
16488 }
16489 }
16490 }
16491
16492 #[test]
16493 fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
16494 // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
16495 // derive: for each of the three variants, exactly one of the
16496 // generated `is_second` / `is_minute` / `is_hour` predicates
16497 // returns `true` and the other two return `false`. Peer of
16498 // the sibling
16499 // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
16500 // sibling `IsVariant`-derived closed-set typed-enum pins.
16501 let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
16502 (super::RateLimitUnit::Second, [true, false, false]),
16503 (super::RateLimitUnit::Minute, [false, true, false]),
16504 (super::RateLimitUnit::Hour, [false, false, true]),
16505 ];
16506 for (variant, expected) in rows {
16507 let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
16508 assert_eq!(
16509 observed, expected,
16510 "RateLimitUnit::{variant:?} is_* predicates must partition \
16511 the arm set (second, minute, hour); got {observed:?}"
16512 );
16513 }
16514 }
16515
16516 #[test]
16517 fn rejects_policy_timeout_sub_millisecond() {
16518 // A purely sub-millisecond `Duration` (`from_micros(500)` =
16519 // 500_000 ns) is not the zero `Duration` — the `is_zero()`
16520 // arm passes — but `as_millis() == 0`, so the shared codec's
16521 // `render` arm returns the literal `"0s"`, which the
16522 // codec's `parse` arm then deserializes as `Duration::ZERO`
16523 // and the `PolicyTimeoutZero` zero-floor gate would reject
16524 // on re-validate. Pin the rejection at the typed slot's
16525 // canonical-floor gate so the round-trip break surfaces at
16526 // validate time, naming the offending `Duration`, rather
16527 // than at the next serialize → deserialize round-trip far
16528 // from the source `caixa.lisp`.
16529 let mut s = three_member_spec();
16530 let timeout = Duration::from_micros(500);
16531 s.politicas.timeout = Some(timeout);
16532 assert_eq!(
16533 s.validate().unwrap_err(),
16534 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
16535 );
16536 }
16537
16538 #[test]
16539 fn rejects_policy_timeout_non_integer_millisecond() {
16540 // A `Duration` with non-integer-millisecond residue
16541 // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
16542 // through the shared codec's `render` arm as `"1ms"` (the
16543 // `as_millis()` floor truncates), which the codec's `parse`
16544 // arm then deserializes as `Duration::from_millis(1)` =
16545 // 1_000_000 ns — silently *different* from the original.
16546 // Pin the rejection so this round-trip break surfaces at
16547 // validate time, where the offending `Duration` is named,
16548 // rather than as a silent value-laundered round-trip on the
16549 // next codec round-trip.
16550 let mut s = three_member_spec();
16551 let timeout = Duration::from_micros(1500);
16552 s.politicas.timeout = Some(timeout);
16553 assert_eq!(
16554 s.validate().unwrap_err(),
16555 AplicacaoError::PolicyTimeoutNotCanonical { timeout }
16556 );
16557 }
16558
16559 #[test]
16560 fn accepts_policy_timeout_integer_millisecond_forms() {
16561 // The codec's accepted set — integer multiples of 1ms — is
16562 // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
16563 // `1h` all pass the canonical gate. Pin the canonical-forms
16564 // sweep so a future tightening of the codec's grammar (e.g.
16565 // dropping `:ms`) surfaces here as a test failure rather
16566 // than a silent contract narrowing on the typed slot.
16567 for timeout in [
16568 Duration::from_millis(1),
16569 Duration::from_millis(500),
16570 Duration::from_millis(1500),
16571 Duration::from_secs(30),
16572 Duration::from_secs(120),
16573 Duration::from_secs(3600),
16574 ] {
16575 let mut s = three_member_spec();
16576 s.politicas.timeout = Some(timeout);
16577 s.validate()
16578 .expect("integer-millisecond :timeout must validate");
16579 }
16580 }
16581
16582 #[test]
16583 fn policy_timeout_zero_takes_precedence_over_canonical() {
16584 // `Duration::ZERO` carries `subsec_nanos() == 0` and would
16585 // pass the canonical-millisecond gate; the more self-locating
16586 // `PolicyTimeoutZero` arm (which names the omit-axis
16587 // remediation directly) must fire first. Pin the ordering so
16588 // a future refactor that reorders the arms surfaces here as a
16589 // test failure rather than a silent diagnostic regression.
16590 let mut s = three_member_spec();
16591 s.politicas.timeout = Some(Duration::ZERO);
16592 assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
16593 }
16594
16595 #[test]
16596 fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
16597 // The diagnostic envelope carries the offending `Duration`
16598 // verbatim so the author can grep their `caixa.lisp` for
16599 // `:timeout "<value>"` and fix it in one edit. Same
16600 // diagnostic shape every other typed-slot canonical-form
16601 // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
16602 // peer `:rate-limit :window` axis.
16603 let mut s = three_member_spec();
16604 let timeout = Duration::from_nanos(1_000_001);
16605 s.politicas.timeout = Some(timeout);
16606 match s.validate().unwrap_err() {
16607 AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
16608 assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
16609 }
16610 other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
16611 }
16612 }
16613
16614 #[test]
16615 fn rejects_policy_timeout_above_cap() {
16616 // The fail-before-pass-after pin: 3601s = 1h + 1s is
16617 // structurally one canonical-tick past the
16618 // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
16619 // integer-millisecond magnitude the canonical-form arm above
16620 // accepts cleanly, that the codec round-trips losslessly as
16621 // `"3601s"`, and that silently passed validate on every
16622 // pre-gate codebase because the typed slot's only checks were
16623 // the zero-floor and canonical-form arms. The mesh-level
16624 // deadline degenerates only at the runtime substrate (Envoy
16625 // / Cilium L7 timeout overlay) far from the source
16626 // `caixa.lisp` with no field naming the offending policy.
16627 let mut s = three_member_spec();
16628 let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
16629 s.politicas.timeout = Some(timeout);
16630 assert_eq!(
16631 s.validate().unwrap_err(),
16632 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
16633 );
16634 }
16635
16636 #[test]
16637 fn rejects_policy_timeout_one_millisecond_above_cap() {
16638 // Boundary case: exactly 1ms past the cap (the granularity
16639 // the canonical-form gate enforces). Catches a future
16640 // "strictly less than" half-measure and pins the diagnostic
16641 // to name the offending `Duration` verbatim. Peer of
16642 // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
16643 // boundary pin on the sibling `:limits :memory` top edge.
16644 let mut s = three_member_spec();
16645 let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
16646 s.politicas.timeout = Some(timeout);
16647 assert_eq!(
16648 s.validate().unwrap_err(),
16649 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
16650 );
16651 }
16652
16653 #[test]
16654 fn rejects_policy_timeout_far_above_cap() {
16655 // The "obvious authoring footgun" case: a `(:timeout "24h")`
16656 // or `(:timeout "86400s")` — values the canonical-form arm
16657 // accepts as integer-millisecond magnitudes, the codec
16658 // round-trips losslessly through serde, but the mesh-level
16659 // policy cannot honor (a 24-hour synchronous-`:contratos`
16660 // deadline is operationally indistinguishable from
16661 // omit-the-axis). Until this gate landed validate accepted
16662 // it. Pin both common above-cap values (24h, 7d) so a future
16663 // relaxation that drops the upper bound surfaces here.
16664 for timeout in [
16665 Duration::from_secs(86_400), // 24h
16666 Duration::from_secs(604_800), // 7d
16667 Duration::from_secs(1_000_000), // ~11.5 days
16668 ] {
16669 let mut s = three_member_spec();
16670 s.politicas.timeout = Some(timeout);
16671 assert_eq!(
16672 s.validate().unwrap_err(),
16673 AplicacaoError::PolicyTimeoutExceedsCap { timeout }
16674 );
16675 }
16676 }
16677
16678 #[test]
16679 fn accepts_policy_timeout_at_cap() {
16680 // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
16681 // must validate. The cap is inclusive on the top edge,
16682 // matching the [`POLICY_RETRIES_MAX`] /
16683 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
16684 // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
16685 // sibling capped axes. Pin the boundary explicitly so a
16686 // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
16687 // instead of `>`) surfaces here as a test failure rather
16688 // than a silent contract narrowing.
16689 let mut s = three_member_spec();
16690 s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
16691 s.validate()
16692 .expect("timeout == POLICY_TIMEOUT_MAX must validate");
16693 }
16694
16695 #[test]
16696 fn accepts_policy_timeout_typical_values() {
16697 // The documented production-playbook band positive-control
16698 // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
16699 // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
16700 // plus a sweep through the long-running-workflow band
16701 // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
16702 // validated set explicitly so a future tightening of the
16703 // ceiling surfaces here as a deliberate test edit, not a
16704 // silent contract narrowing.
16705 for timeout in [
16706 Duration::from_millis(1),
16707 Duration::from_millis(500),
16708 Duration::from_secs(1),
16709 Duration::from_secs(10),
16710 Duration::from_secs(15), // Envoy default
16711 Duration::from_secs(30),
16712 Duration::from_secs(60), // AWS App Mesh typical
16713 Duration::from_secs(300),
16714 Duration::from_secs(900),
16715 Duration::from_secs(1800),
16716 Duration::from_secs(3600), // exactly 1h, the cap
16717 ] {
16718 let mut s = three_member_spec();
16719 s.politicas.timeout = Some(timeout);
16720 s.validate()
16721 .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
16722 }
16723 }
16724
16725 #[test]
16726 fn policy_timeout_zero_takes_precedence_over_cap() {
16727 // The cross-arm ordering pin: `Duration::ZERO` is
16728 // structurally outside both `>= 1ms` (zero-floor) and
16729 // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
16730 // diagnostic is the more self-locating one (it directly
16731 // names the omit-axis remediation), so the validate gate
16732 // must fire on zero first. Same shape every other
16733 // zero-then-shape ordering on this surface uses
16734 // ([`AplicacaoError::PolicyRetriesZero`] then
16735 // [`AplicacaoError::PolicyRetriesExceedsCap`];
16736 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
16737 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
16738 let mut s = three_member_spec();
16739 s.politicas.timeout = Some(Duration::ZERO);
16740 assert_eq!(
16741 s.validate().unwrap_err(),
16742 AplicacaoError::PolicyTimeoutZero,
16743 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
16744 );
16745 }
16746
16747 #[test]
16748 fn policy_timeout_canonical_takes_precedence_over_cap() {
16749 // The cross-arm ordering pin: a `Duration` that is *both*
16750 // sub-millisecond (non-canonical-form) and structurally
16751 // above the cap surfaces the canonical-form diagnostic
16752 // first, because the round-trip-shape break is the more
16753 // fundamental issue (the value can't even round-trip
16754 // through the codec, so the cap diagnostic naming
16755 // `1ms..=1h` would be misleading — there's no integer-ms
16756 // form of the offending value). Pin the order so a future
16757 // refactor that reorders the arms surfaces here as a test
16758 // failure rather than a silent diagnostic regression.
16759 let mut s = three_member_spec();
16760 // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
16761 // *and* total magnitude above the 1h cap.
16762 let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
16763 s.politicas.timeout = Some(timeout);
16764 assert_eq!(
16765 s.validate().unwrap_err(),
16766 AplicacaoError::PolicyTimeoutNotCanonical { timeout },
16767 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
16768 );
16769 }
16770
16771 #[test]
16772 fn policy_timeout_cap_diagnostic_carries_offending_value() {
16773 // The diagnostic-shape pin: the offending `Duration` is
16774 // carried verbatim into the
16775 // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
16776 // surfaced error message names the value the author wrote
16777 // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
16778 // exceeds the mesh-policy ceiling …"`), not just the cap.
16779 // Same self-locating diagnostic shape every other typed-cap
16780 // arm on this surface carries
16781 // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
16782 // offending retry count verbatim).
16783 let mut s = three_member_spec();
16784 let timeout = Duration::from_secs(7200); // 2h
16785 s.politicas.timeout = Some(timeout);
16786 let err = s.validate().unwrap_err();
16787 assert!(
16788 matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
16789 "got {err:?}"
16790 );
16791 let msg = err.to_string();
16792 assert!(
16793 msg.contains("7200"),
16794 ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
16795 );
16796 }
16797
16798 #[test]
16799 fn policy_timeout_cap_pins_canonical_value() {
16800 // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
16801 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
16802 // the shared duration codec emits as a clean canonical
16803 // string (`"<n>h"`). Pinning the literal value here surfaces
16804 // a future drift (a relaxation to 24h, a tightening to 5m)
16805 // as a deliberate test edit, not a silent contract
16806 // narrowing. Same shape every other typed-cap value pin on
16807 // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
16808 assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
16809 assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
16810 }
16811
16812 #[test]
16813 fn policy_timeout_cap_value_round_trips_through_codec() {
16814 // The codec round-trip property the cap arm preserves: the
16815 // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
16816 // the shared duration codec — every value at the cap renders
16817 // to a clean canonical string (`"1h"`) and parses back to
16818 // the same `Duration`. Pin this so a future drift between
16819 // the cap constant and the codec's largest emitted unit
16820 // surfaces here. Same shape every other typed boundary pin
16821 // on this surface uses
16822 // (`wasm32_memory_cap_matches_parsed_4_gib`).
16823 let policy = MeshPolicy {
16824 timeout: Some(POLICY_TIMEOUT_MAX),
16825 ..Default::default()
16826 };
16827 let json = serde_json::to_string(&policy).unwrap();
16828 // The codec emits `"1h"` for the canonical 1-hour magnitude.
16829 assert!(
16830 json.contains("\"1h\""),
16831 "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
16832 );
16833 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
16834 assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
16835 }
16836
16837 #[test]
16838 fn rejects_circuit_breaker_window_sub_millisecond() {
16839 // Peer of the `:timeout` sub-millisecond arm on the second
16840 // typed-`Duration` `:politicas` axis: a purely sub-ms
16841 // `Duration` (`from_micros(500)`) renders through the shared
16842 // codec as `"0s"`, which the codec parses back to
16843 // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
16844 // zero-floor gate then rejects on re-validate.
16845 let mut s = three_member_spec();
16846 let window = Duration::from_micros(500);
16847 s.politicas.circuit_breaker = Some(CircuitBreaker {
16848 max_failures: 5,
16849 window,
16850 });
16851 assert_eq!(
16852 s.validate().unwrap_err(),
16853 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
16854 );
16855 }
16856
16857 #[test]
16858 fn rejects_circuit_breaker_window_non_integer_millisecond() {
16859 // Peer of the `:timeout` non-integer-ms arm: a `Duration`
16860 // with non-integer-millisecond residue renders through the
16861 // shared codec as the truncated `"<n>ms"` form, parsing back
16862 // to a *different* `Duration` on the next round-trip.
16863 let mut s = three_member_spec();
16864 let window = Duration::from_micros(1500);
16865 s.politicas.circuit_breaker = Some(CircuitBreaker {
16866 max_failures: 5,
16867 window,
16868 });
16869 assert_eq!(
16870 s.validate().unwrap_err(),
16871 AplicacaoError::PolicyBreakerWindowNotCanonical { window }
16872 );
16873 }
16874
16875 #[test]
16876 fn accepts_circuit_breaker_window_integer_millisecond_forms() {
16877 // The canonical-forms sweep on the breaker axis: every
16878 // integer-ms multiple the codec round-trips losslessly
16879 // passes the canonical gate.
16880 for window in [
16881 Duration::from_millis(1),
16882 Duration::from_millis(500),
16883 Duration::from_millis(1500),
16884 Duration::from_secs(30),
16885 Duration::from_secs(60),
16886 Duration::from_secs(3600),
16887 ] {
16888 let mut s = three_member_spec();
16889 s.politicas.circuit_breaker = Some(CircuitBreaker {
16890 max_failures: 5,
16891 window,
16892 });
16893 s.validate()
16894 .expect("integer-millisecond :circuit-breaker :window must validate");
16895 }
16896 }
16897
16898 #[test]
16899 fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
16900 // `Duration::ZERO` would pass the canonical-ms gate (the
16901 // sub-ns residue is zero) but must surface the narrower
16902 // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
16903 // remediation.
16904 let mut s = three_member_spec();
16905 s.politicas.circuit_breaker = Some(CircuitBreaker {
16906 max_failures: 5,
16907 window: Duration::ZERO,
16908 });
16909 assert_eq!(
16910 s.validate().unwrap_err(),
16911 AplicacaoError::PolicyBreakerZeroWindow
16912 );
16913 }
16914
16915 #[test]
16916 fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
16917 // Both axes invalid: max_failures == 0 *and* window is
16918 // sub-ms. The validate gate must fire on max_failures first
16919 // (matching the existing ordering pin
16920 // `rejects_circuit_breaker_zero_max_failures` enshrines), so
16921 // the existing diagnostic continues to lead with the simpler
16922 // "zero threshold" framing.
16923 let mut s = three_member_spec();
16924 s.politicas.circuit_breaker = Some(CircuitBreaker {
16925 max_failures: 0,
16926 window: Duration::from_micros(500),
16927 });
16928 assert_eq!(
16929 s.validate().unwrap_err(),
16930 AplicacaoError::PolicyBreakerZeroFailures
16931 );
16932 }
16933
16934 #[test]
16935 fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
16936 let mut s = three_member_spec();
16937 let window = Duration::from_nanos(60_000_000_001);
16938 s.politicas.circuit_breaker = Some(CircuitBreaker {
16939 max_failures: 5,
16940 window,
16941 });
16942 match s.validate().unwrap_err() {
16943 AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
16944 assert_eq!(w, window, "diagnostic must carry the offending Duration");
16945 }
16946 other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
16947 }
16948 }
16949
16950 #[test]
16951 fn rejects_circuit_breaker_window_above_cap() {
16952 // The fail-before-pass-after pin: 3601s = 1h + 1s is
16953 // structurally one canonical-tick past the
16954 // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
16955 // integer-millisecond magnitude the canonical-form arm above
16956 // accepts cleanly, that the codec round-trips losslessly as
16957 // `"3601s"`, and that silently passed validate on every
16958 // pre-gate codebase because the typed slot's only checks were
16959 // the zero-floor and canonical-form arms. The
16960 // rolling-window-to-lifetime-counter degeneration surfaces
16961 // only at the runtime substrate (Envoy's outlier_detection
16962 // interval, the future CiliumClusterwideEnvoyConfig overlay)
16963 // far from the source `caixa.lisp` with no field naming the
16964 // offending policy.
16965 let mut s = three_member_spec();
16966 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
16967 s.politicas.circuit_breaker = Some(CircuitBreaker {
16968 max_failures: 5,
16969 window,
16970 });
16971 assert_eq!(
16972 s.validate().unwrap_err(),
16973 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
16974 );
16975 }
16976
16977 #[test]
16978 fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
16979 // Boundary case: exactly 1ms past the cap (the granularity the
16980 // canonical-form gate enforces). Catches a future "strictly
16981 // less than" half-measure and pins the diagnostic to name the
16982 // offending `Duration` verbatim. Peer of
16983 // `rejects_policy_timeout_one_millisecond_above_cap` on the
16984 // sibling duration-typed `:politicas :timeout` top edge.
16985 let mut s = three_member_spec();
16986 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
16987 s.politicas.circuit_breaker = Some(CircuitBreaker {
16988 max_failures: 5,
16989 window,
16990 });
16991 assert_eq!(
16992 s.validate().unwrap_err(),
16993 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
16994 );
16995 }
16996
16997 #[test]
16998 fn rejects_circuit_breaker_window_far_above_cap() {
16999 // The "obvious authoring footgun" case: a `(:window "24h")` or
17000 // `(:window "86400s")` — values the canonical-form arm
17001 // accepts as integer-millisecond magnitudes, the codec
17002 // round-trips losslessly through serde, but the
17003 // rolling-window breaker contract cannot honor (a 24-hour
17004 // rolling failure window is operationally a lifetime counter).
17005 // Until this gate landed validate accepted it. Pin both common
17006 // above-cap values (24h, 7d) so a future relaxation that
17007 // drops the upper bound surfaces here.
17008 for window in [
17009 Duration::from_secs(86_400), // 24h
17010 Duration::from_secs(604_800), // 7d
17011 Duration::from_secs(1_000_000), // ~11.5 days
17012 ] {
17013 let mut s = three_member_spec();
17014 s.politicas.circuit_breaker = Some(CircuitBreaker {
17015 max_failures: 5,
17016 window,
17017 });
17018 assert_eq!(
17019 s.validate().unwrap_err(),
17020 AplicacaoError::PolicyBreakerWindowExceedsCap { window }
17021 );
17022 }
17023 }
17024
17025 #[test]
17026 fn accepts_circuit_breaker_window_at_cap() {
17027 // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
17028 // (1h) — must validate. The cap is inclusive on the top edge,
17029 // matching the [`POLICY_TIMEOUT_MAX`] /
17030 // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
17031 // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
17032 // sibling capped axes. Pin the boundary explicitly so a
17033 // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
17034 // instead of `>`) surfaces here as a test failure rather than
17035 // a silent contract narrowing.
17036 let mut s = three_member_spec();
17037 s.politicas.circuit_breaker = Some(CircuitBreaker {
17038 max_failures: 5,
17039 window: POLICY_BREAKER_WINDOW_MAX,
17040 });
17041 s.validate()
17042 .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
17043 }
17044
17045 #[test]
17046 fn accepts_circuit_breaker_window_typical_values() {
17047 // The documented production-playbook band positive-control
17048 // sweep — every value Hystrix / resilience4j / Istio / Envoy
17049 // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
17050 // through the long-tail failure-detection band (15m, 30m, 1h)
17051 // the cap accepts. Pin the inclusive validated set explicitly
17052 // so a future tightening of the ceiling surfaces here as a
17053 // deliberate test edit, not a silent contract narrowing.
17054 for window in [
17055 Duration::from_millis(1),
17056 Duration::from_millis(500),
17057 Duration::from_secs(1),
17058 Duration::from_secs(10), // Hystrix / Istio / Envoy default
17059 Duration::from_secs(30),
17060 Duration::from_secs(60), // resilience4j typical
17061 Duration::from_secs(300), // AWS App Mesh typical
17062 Duration::from_secs(900),
17063 Duration::from_secs(1800),
17064 Duration::from_secs(3600), // exactly 1h, the cap
17065 ] {
17066 let mut s = three_member_spec();
17067 s.politicas.circuit_breaker = Some(CircuitBreaker {
17068 max_failures: 5,
17069 window,
17070 });
17071 s.validate()
17072 .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
17073 }
17074 }
17075
17076 #[test]
17077 fn circuit_breaker_zero_window_takes_precedence_over_cap() {
17078 // The cross-arm ordering pin: `Duration::ZERO` is structurally
17079 // outside both `>= 1ms` (zero-floor) and
17080 // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
17081 // diagnostic is the more self-locating one (it directly names
17082 // the omit-axis remediation), so the validate gate must fire
17083 // on zero first. Same shape every other zero-then-cap
17084 // ordering on this surface uses
17085 // ([`AplicacaoError::PolicyTimeoutZero`] then
17086 // [`AplicacaoError::PolicyTimeoutExceedsCap`];
17087 // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17088 // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17089 let mut s = three_member_spec();
17090 s.politicas.circuit_breaker = Some(CircuitBreaker {
17091 max_failures: 5,
17092 window: Duration::ZERO,
17093 });
17094 assert_eq!(
17095 s.validate().unwrap_err(),
17096 AplicacaoError::PolicyBreakerZeroWindow,
17097 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
17098 );
17099 }
17100
17101 #[test]
17102 fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
17103 // The cross-arm ordering pin: a `Duration` that is *both*
17104 // sub-millisecond (non-canonical-form) and structurally above
17105 // the cap surfaces the canonical-form diagnostic first,
17106 // because the round-trip-shape break is the more fundamental
17107 // issue (the value can't even round-trip through the codec, so
17108 // the cap diagnostic naming `1ms..=1h` would be misleading —
17109 // there's no integer-ms form of the offending value). Pin the
17110 // order so a future refactor that reorders the arms surfaces
17111 // here as a test failure rather than a silent diagnostic
17112 // regression. Peer of
17113 // `policy_timeout_canonical_takes_precedence_over_cap` on the
17114 // sibling duration-typed `:politicas :timeout` axis.
17115 let mut s = three_member_spec();
17116 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
17117 s.politicas.circuit_breaker = Some(CircuitBreaker {
17118 max_failures: 5,
17119 window,
17120 });
17121 assert_eq!(
17122 s.validate().unwrap_err(),
17123 AplicacaoError::PolicyBreakerWindowNotCanonical { window },
17124 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
17125 );
17126 }
17127
17128 #[test]
17129 fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
17130 // The cross-arm ordering pin between the two breaker axes: a
17131 // `CircuitBreaker` whose *both* `max_failures` is above its
17132 // cap *and* `window` is above its cap surfaces the
17133 // max-failures cap diagnostic first, because the validate
17134 // gate visits the failures arm before the window arm. Pin the
17135 // order so a future refactor that reorders the breaker arms
17136 // surfaces here.
17137 let mut s = three_member_spec();
17138 let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
17139 s.politicas.circuit_breaker = Some(CircuitBreaker {
17140 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17141 window,
17142 });
17143 assert_eq!(
17144 s.validate().unwrap_err(),
17145 AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17146 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
17147 },
17148 "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
17149 );
17150 }
17151
17152 #[test]
17153 fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
17154 // The diagnostic-shape pin: the offending `Duration` is
17155 // carried verbatim into the
17156 // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
17157 // the surfaced error message names the value the author wrote
17158 // (`":politicas :circuit-breaker :window (Duration { secs:
17159 // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
17160 // just the cap. Same self-locating diagnostic shape every
17161 // other typed-cap arm on this surface carries
17162 // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
17163 // offending `Duration` verbatim).
17164 let mut s = three_member_spec();
17165 let window = Duration::from_secs(7200); // 2h
17166 s.politicas.circuit_breaker = Some(CircuitBreaker {
17167 max_failures: 5,
17168 window,
17169 });
17170 let err = s.validate().unwrap_err();
17171 assert!(
17172 matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
17173 "got {err:?}"
17174 );
17175 let msg = err.to_string();
17176 assert!(
17177 msg.contains("7200"),
17178 ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
17179 );
17180 }
17181
17182 #[test]
17183 fn circuit_breaker_window_cap_pins_canonical_value() {
17184 // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
17185 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
17186 // shared duration codec emits as a clean canonical string
17187 // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
17188 // the sibling duration-typed `:politicas :timeout` axis (the
17189 // two duration-typed `:politicas` axes share a uniform top
17190 // edge). Pinning the literal value here surfaces a future
17191 // drift (a relaxation to 24h, a tightening to 5m) as a
17192 // deliberate test edit, not a silent contract narrowing. Same
17193 // shape every other typed-cap value pin on this surface uses
17194 // (`policy_timeout_cap_pins_canonical_value`).
17195 assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
17196 assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
17197 assert_eq!(
17198 POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
17199 "the two duration-typed `:politicas` caps share the same top edge"
17200 );
17201 }
17202
17203 #[test]
17204 fn circuit_breaker_window_cap_value_round_trips_through_codec() {
17205 // The codec round-trip property the cap arm preserves: the
17206 // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
17207 // through the shared duration codec — every value at the cap
17208 // renders to a clean canonical string (`"1h"`) and parses back
17209 // to the same `Duration`. Pin this so a future drift between
17210 // the cap constant and the codec's largest emitted unit
17211 // surfaces here. Same shape every other typed boundary pin on
17212 // this surface uses
17213 // (`policy_timeout_cap_value_round_trips_through_codec`).
17214 let policy = MeshPolicy {
17215 circuit_breaker: Some(CircuitBreaker {
17216 max_failures: 5,
17217 window: POLICY_BREAKER_WINDOW_MAX,
17218 }),
17219 ..Default::default()
17220 };
17221 let json = serde_json::to_string(&policy).unwrap();
17222 // The codec emits `"1h"` for the canonical 1-hour magnitude.
17223 assert!(
17224 json.contains("\"1h\""),
17225 "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
17226 );
17227 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17228 assert_eq!(
17229 back.circuit_breaker.unwrap().window,
17230 POLICY_BREAKER_WINDOW_MAX
17231 );
17232 }
17233
17234 #[test]
17235 fn is_integer_millisecond_duration_predicate_tracks_codec() {
17236 // Pin the predicate's accepted set against the codec's
17237 // accepted set explicitly. The codec parses
17238 // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
17239 // accepted value is an integer-millisecond multiple — so the
17240 // predicate must accept exactly that set. Same shape every
17241 // other predicate-on-the-typed-slot helper carries
17242 // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
17243 // Read directly from the codec-owned predicate — the crate's
17244 // single source of truth every typed-`Duration` axis now routes
17245 // through via
17246 // [`crate::render::require_positive_canonical_bounded_duration`].
17247 use super::supervisor::duration_codec::is_integer_millisecond_duration;
17248 assert!(is_integer_millisecond_duration(Duration::ZERO));
17249 assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
17250 assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
17251 assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
17252 assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
17253 assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
17254 // Non-integer-millisecond residue: rejected.
17255 assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
17256 assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
17257 assert!(!is_integer_millisecond_duration(Duration::from_micros(
17258 1500
17259 )));
17260 assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
17261 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
17262 999_999
17263 )));
17264 // The 1-ns-past-1ms boundary: rejected (no longer a clean
17265 // integer-millisecond multiple).
17266 assert!(!is_integer_millisecond_duration(Duration::from_nanos(
17267 1_000_001
17268 )));
17269 }
17270
17271 #[test]
17272 fn policy_timeout_validated_value_round_trips_through_codec() {
17273 // The structural property the canonical-ms gate enforces:
17274 // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
17275 // round-trips losslessly through the shared `duration_codec`
17276 // (serialize → string → deserialize → equal value). Pin this
17277 // end-to-end so a future change to either side (the validate
17278 // gate's accepted granularity, the codec's parse/render unit
17279 // set) that breaks the alignment surfaces here. The
17280 // previous-state shape (typed slot accepts arbitrary
17281 // `Duration`, codec only round-trips integer-ms) would fail
17282 // this test for any `Duration::from_micros(1500)` timeout —
17283 // the validate gate now forecloses that.
17284 for timeout in [
17285 Duration::from_millis(1),
17286 Duration::from_millis(1500),
17287 Duration::from_secs(30),
17288 Duration::from_secs(3600),
17289 ] {
17290 let mut s = three_member_spec();
17291 s.politicas.timeout = Some(timeout);
17292 s.validate().unwrap();
17293 let json = serde_json::to_string(&s.politicas).unwrap();
17294 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17295 assert_eq!(
17296 back.timeout, s.politicas.timeout,
17297 "every validated :timeout must round-trip losslessly through the codec"
17298 );
17299 }
17300 }
17301
17302 #[test]
17303 fn circuit_breaker_window_validated_value_round_trips_through_codec() {
17304 // Peer of the `:timeout` round-trip property on the breaker
17305 // axis.
17306 for window in [
17307 Duration::from_millis(1),
17308 Duration::from_millis(1500),
17309 Duration::from_secs(30),
17310 Duration::from_secs(3600),
17311 ] {
17312 let mut s = three_member_spec();
17313 s.politicas.circuit_breaker = Some(CircuitBreaker {
17314 max_failures: 5,
17315 window,
17316 });
17317 s.validate().unwrap();
17318 let json = serde_json::to_string(&s.politicas).unwrap();
17319 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17320 assert_eq!(
17321 back.circuit_breaker.unwrap().window,
17322 window,
17323 "every validated :circuit-breaker :window must round-trip losslessly"
17324 );
17325 }
17326 }
17327
17328 #[test]
17329 fn empty_politicas_validates() {
17330 // Omitting every policy axis is fine — defaults express "no
17331 // policy on this axis", not "policy = 0". The fixture's typical
17332 // values continue to validate; this test pins that
17333 // MeshPolicy::default() is a clean pass through validate().
17334 let mut s = three_member_spec();
17335 s.politicas = MeshPolicy::default();
17336 s.validate().unwrap();
17337 }
17338
17339 #[test]
17340 fn typical_politicas_validates_with_every_axis_set() {
17341 // The full §III.1 example block (timeout + retries + breaker +
17342 // mtls + rate-limit) — every axis nonzero — must remain a
17343 // clean pass.
17344 let mut s = three_member_spec();
17345 s.politicas = MeshPolicy {
17346 timeout: Some(Duration::from_secs(30)),
17347 retries: Some(3),
17348 circuit_breaker: Some(CircuitBreaker {
17349 max_failures: 5,
17350 window: Duration::from_secs(60),
17351 }),
17352 mtls_required: Some(true),
17353 rate_limit: Some(RateLimit {
17354 rate: 100,
17355 window: Duration::from_secs(1),
17356 }),
17357 };
17358 s.validate().unwrap();
17359 }
17360
17361 #[test]
17362 fn rejects_empty_cluster_name() {
17363 let mut s = three_member_spec();
17364 s.placement.clusters = vec!["rio".into(), "".into()];
17365 assert_eq!(
17366 s.validate().unwrap_err(),
17367 AplicacaoError::PlacementClusterEmpty
17368 );
17369 }
17370
17371 #[test]
17372 fn rejects_duplicate_cluster_names() {
17373 let mut s = three_member_spec();
17374 s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
17375 let err = s.validate().unwrap_err();
17376 assert!(
17377 matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
17378 "got {err:?}"
17379 );
17380 }
17381
17382 #[test]
17383 fn rejects_placement_cluster_with_uppercase() {
17384 // The canonical "I copied the cluster's display name verbatim"
17385 // typo — K8s context names are lowercase per DNS-1123 label
17386 // rule, but org docs often round-trip a TitleCase identifier
17387 // (`Rio`, `Mar-East`) from an ADR. Mirrors the
17388 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
17389 // on the peer name axis.
17390 let mut s = three_member_spec();
17391 s.placement.clusters = vec!["Rio".into(), "mar".into()];
17392 let err = s.validate().unwrap_err();
17393 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
17394 panic!("expected PlacementClusterInvalid, got other variant");
17395 };
17396 assert_eq!(cluster, "Rio");
17397 assert!(
17398 reason.contains("uppercase"),
17399 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
17400 );
17401 assert!(
17402 reason.contains("\"rio\""),
17403 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
17404 );
17405 }
17406
17407 #[test]
17408 fn rejects_placement_cluster_with_underscore() {
17409 // The canonical "I'm thinking of an env var / hostname slug"
17410 // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
17411 // schema. K8s context filtering on `my_cluster` silently misses
17412 // the cluster the author intended; the gate moves it to caixa-
17413 // build time. Same shape as `rejects_membro_caixa_with_underscore`
17414 // (3f9d7a0).
17415 let mut s = three_member_spec();
17416 s.placement.clusters = vec!["my_cluster".into()];
17417 let err = s.validate().unwrap_err();
17418 assert!(
17419 matches!(
17420 err,
17421 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
17422 if cluster == "my_cluster" && reason.contains('_')
17423 ),
17424 "got {err:?}"
17425 );
17426 }
17427
17428 #[test]
17429 fn rejects_placement_cluster_with_dot() {
17430 // A `:placement :clusters` entry is a single DNS-1123 *label*,
17431 // not a subdomain — even though K8s context names sometimes
17432 // carry a dotted form via kubeconfig conventions, the strictest
17433 // floor among the use sites (DNS-1035 cluster.x-k8s.io
17434 // `metadata.name`, Cilium identity label values) wins. The "I
17435 // want to namespace my cluster names with `.`" intent is
17436 // expressed via `-` (`mar-east`).
17437 let mut s = three_member_spec();
17438 s.placement.clusters = vec!["team.rio".into()];
17439 let err = s.validate().unwrap_err();
17440 assert!(
17441 matches!(
17442 err,
17443 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
17444 if cluster == "team.rio" && reason.contains('.')
17445 ),
17446 "got {err:?}"
17447 );
17448 }
17449
17450 #[test]
17451 fn rejects_placement_cluster_with_leading_hyphen() {
17452 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
17453 // with an alphanumeric. The K8s apiserver rejects `-rio`
17454 // outright; the rendered fan-out would emit a `metadata.name:
17455 // "-rio"` that fails admission far from the source caixa.lisp.
17456 let mut s = three_member_spec();
17457 s.placement.clusters = vec!["-rio".into()];
17458 let err = s.validate().unwrap_err();
17459 assert!(
17460 matches!(
17461 err,
17462 AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
17463 if cluster == "-rio" && reason.contains("start and end")
17464 ),
17465 "got {err:?}"
17466 );
17467 }
17468
17469 #[test]
17470 fn rejects_placement_cluster_with_trailing_hyphen() {
17471 // The symmetric arm of the boundary rule. Pin separately so
17472 // both ends are covered against a future relaxation that only
17473 // checks one boundary (parallel to
17474 // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
17475 let mut s = three_member_spec();
17476 s.placement.clusters = vec!["rio-".into()];
17477 let err = s.validate().unwrap_err();
17478 assert!(
17479 matches!(
17480 err,
17481 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
17482 if cluster == "rio-"
17483 ),
17484 "got {err:?}"
17485 );
17486 }
17487
17488 #[test]
17489 fn rejects_placement_cluster_with_unicode() {
17490 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
17491 // before it reaches K8s. The byte-by-byte ASCII validity check
17492 // rejects multi-byte UTF-8 sequences by the first byte that
17493 // fails `[a-z0-9-]`.
17494 let mut s = three_member_spec();
17495 s.placement.clusters = vec!["rió".into()];
17496 let err = s.validate().unwrap_err();
17497 assert!(
17498 matches!(
17499 err,
17500 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
17501 if cluster == "rió"
17502 ),
17503 "got {err:?}"
17504 );
17505 }
17506
17507 #[test]
17508 fn rejects_placement_cluster_with_whitespace() {
17509 // Whitespace is the canonical "I pasted from a sketch / doc"
17510 // footgun. The apiserver rejects every cluster `metadata.name`
17511 // value carrying whitespace.
17512 let mut s = three_member_spec();
17513 s.placement.clusters = vec!["rio cluster".into()];
17514 let err = s.validate().unwrap_err();
17515 assert!(
17516 matches!(
17517 err,
17518 AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
17519 if cluster == "rio cluster"
17520 ),
17521 "got {err:?}"
17522 );
17523 }
17524
17525 #[test]
17526 fn rejects_placement_cluster_too_long() {
17527 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
17528 // pin. The diagnostic names both the cap (63) and the actual
17529 // length so the author can shorten in one edit. Mirrors
17530 // `rejects_membro_caixa_too_long` (3f9d7a0).
17531 let mut s = three_member_spec();
17532 let too_long = "a".repeat(64);
17533 s.placement.clusters = vec![too_long.clone()];
17534 let err = s.validate().unwrap_err();
17535 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
17536 panic!("expected PlacementClusterInvalid");
17537 };
17538 assert_eq!(cluster, too_long);
17539 assert!(
17540 reason.contains("63") && reason.contains("64"),
17541 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
17542 );
17543 }
17544
17545 #[test]
17546 fn placement_cluster_max_length_validates() {
17547 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
17548 // future tightening (e.g. dropping to 62) surfaces here as a
17549 // regression, mirroring `membro_caixa_max_length_validates`
17550 // (3f9d7a0).
17551 let mut s = three_member_spec();
17552 s.placement.clusters = vec!["a".repeat(63)];
17553 s.validate().unwrap();
17554 }
17555
17556 #[test]
17557 fn accepts_canonical_placement_cluster_forms() {
17558 // The DNS-1123 label shapes a caixa author is realistically
17559 // going to write for cluster names: single-word lowercase
17560 // (`rio`), regional hyphen-joined (`mar-east`), single
17561 // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
17562 // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
17563 // Pin every leg so a future tightening that bans (e.g.) digit-
17564 // start identifiers surfaces here.
17565 for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
17566 let mut s = three_member_spec();
17567 s.placement.clusters = vec![form.into()];
17568 s.validate().unwrap_or_else(|e| {
17569 panic!("canonical cluster form {form:?} must validate, got {e:?}")
17570 });
17571 }
17572 }
17573
17574 #[test]
17575 fn placement_cluster_empty_takes_precedence_over_invalid() {
17576 // Order pin: the existing `PlacementClusterEmpty` diagnostic
17577 // (which doesn't try to parse) fires before the new
17578 // `PlacementClusterInvalid` parse-side diagnostic, so an empty
17579 // `:clusters` entry keeps its narrower error message — the new
17580 // gate would also reject `""`, but the empty-string arm is the
17581 // more self-locating diagnostic. Mirrors the
17582 // `membro_caixa_empty_takes_precedence_over_invalid` pin
17583 // (3f9d7a0).
17584 let mut s = three_member_spec();
17585 s.placement.clusters = vec!["rio".into(), "".into()];
17586 let err = s.validate().unwrap_err();
17587 assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
17588 }
17589
17590 #[test]
17591 fn placement_cluster_invalid_fires_before_duplicate_check() {
17592 // Order pin: a malformed-shape `:clusters` entry surfaces *its
17593 // own* diagnostic, even when a later entry would otherwise
17594 // collapse onto a duplicate name. The per-entry shape gate runs
17595 // inline before the duplicate-key insert, parallel to
17596 // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
17597 let mut s = three_member_spec();
17598 s.placement.clusters = vec!["Rio".into(), "rio".into()];
17599 let err = s.validate().unwrap_err();
17600 assert!(
17601 matches!(
17602 err,
17603 AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
17604 ),
17605 "got {err:?}"
17606 );
17607 }
17608
17609 #[test]
17610 fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
17611 // The diagnostic-shape pin: the error names the offending
17612 // `:clusters` value verbatim so the author can grep their
17613 // caixa.lisp without re-running the build, and carries a
17614 // non-empty `reason` naming the specific violation. Same shape
17615 // every typed-shape gate enshrines
17616 // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
17617 // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
17618 let mut s = three_member_spec();
17619 s.placement.clusters = vec!["BAD_CLUSTER".into()];
17620 let err = s.validate().unwrap_err();
17621 let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
17622 panic!("expected PlacementClusterInvalid");
17623 };
17624 assert_eq!(cluster, "BAD_CLUSTER");
17625 assert!(
17626 !reason.is_empty(),
17627 "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
17628 );
17629 }
17630
17631 #[test]
17632 fn rejects_sharded_with_empty_clusters() {
17633 // §III.1: Sharded uses :clusters as the shard pool. An empty
17634 // pool means "shard across no clusters" — meaningless, same as
17635 // Replicated with no hosts.
17636 let mut s = three_member_spec();
17637 s.placement.estrategia = PlacementStrategy::Sharded;
17638 s.placement.shard_key = Some("$tenantId".into());
17639 s.placement.clusters = vec![];
17640 assert!(matches!(
17641 s.validate().unwrap_err(),
17642 AplicacaoError::PlacementWithoutClusters {
17643 estrategia: PlacementStrategy::Sharded
17644 }
17645 ));
17646 }
17647
17648 #[test]
17649 fn rejects_sharded_with_empty_shard_key() {
17650 let mut s = three_member_spec();
17651 s.placement.estrategia = PlacementStrategy::Sharded;
17652 s.placement.shard_key = Some("".into());
17653 assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
17654 }
17655
17656 #[test]
17657 fn rejects_shard_key_under_replicated_strategy() {
17658 // The fail-before-pass-after pin: a `:placement (:estrategia
17659 // Replicated :shard-key "tenantId")` manifest carries the
17660 // hash-keyed-distribution slot on a strategy that never consumes
17661 // it. Before the gate the typed slot's value silently vanished
17662 // at the renderer layer (caixa-mesh emits `placement.shardKey`
17663 // verbatim regardless of strategy; the Akka-style cluster-
17664 // sharding reconciler keys off `estrategia == Sharded` and
17665 // ignores the slot otherwise), with no diagnostic. Lifting the
17666 // rejection to a build-time gate makes the
17667 // `shard_key.is_some() == matches!(estrategia, Sharded)`
17668 // partition a structural property of every validated
17669 // [`Placement`].
17670 let mut s = three_member_spec();
17671 // The fixture already uses Replicated; just add a shard-key.
17672 s.placement.shard_key = Some("$tenantId".into());
17673 let err = s.validate().unwrap_err();
17674 let AplicacaoError::ShardKeyOnNonSharded {
17675 estrategia,
17676 shard_key,
17677 } = err
17678 else {
17679 panic!("expected ShardKeyOnNonSharded, got {err:?}");
17680 };
17681 assert_eq!(estrategia, PlacementStrategy::Replicated);
17682 assert_eq!(shard_key, "$tenantId");
17683 }
17684
17685 #[test]
17686 fn rejects_shard_key_under_singlenode_strategy() {
17687 // Peer of the Replicated case above on the SingleNode arm: OTP
17688 // distributed-app takeover (one cluster runs at a time) has no
17689 // hash-keyed routing axis to consume `:shard-key` either, so
17690 // the rejection fires on both non-Sharded arms uniformly.
17691 let mut s = three_member_spec();
17692 s.placement.estrategia = PlacementStrategy::SingleNode;
17693 s.placement.shard_key = Some("$tenantId".into());
17694 let err = s.validate().unwrap_err();
17695 let AplicacaoError::ShardKeyOnNonSharded {
17696 estrategia,
17697 shard_key,
17698 } = err
17699 else {
17700 panic!("expected ShardKeyOnNonSharded, got {err:?}");
17701 };
17702 assert_eq!(estrategia, PlacementStrategy::SingleNode);
17703 assert_eq!(shard_key, "$tenantId");
17704 }
17705
17706 #[test]
17707 fn rejects_empty_shard_key_under_replicated_strategy() {
17708 // The `Some("")` case under non-Sharded is rejected by
17709 // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
17710 // fires before the empty-value gate), not
17711 // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
17712 // the `Sharded` arm). Pin the partition so a future reorder of
17713 // the validate_placement match arms doesn't silently swap which
17714 // diagnostic the author sees — both are author errors, but
17715 // ShardKeyOnNonSharded names which strategy is the actual fix
17716 // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
17717 // only says "pick a non-empty key".
17718 let mut s = three_member_spec();
17719 s.placement.shard_key = Some(String::new());
17720 let err = s.validate().unwrap_err();
17721 assert!(
17722 matches!(
17723 err,
17724 AplicacaoError::ShardKeyOnNonSharded {
17725 estrategia: PlacementStrategy::Replicated,
17726 ref shard_key,
17727 } if shard_key.is_empty()
17728 ),
17729 "got {err:?}"
17730 );
17731 }
17732
17733 #[test]
17734 fn replicated_without_shard_key_validates() {
17735 // The complement of the rejection: `:placement :estrategia
17736 // Replicated` with `:shard-key None` is the canonical happy
17737 // path on every existing fixture. Pin the no-shard-key case so
17738 // the new gate doesn't accidentally fire on `None`.
17739 let mut s = three_member_spec();
17740 assert!(matches!(
17741 s.placement.estrategia,
17742 PlacementStrategy::Replicated
17743 ));
17744 s.placement.shard_key = None;
17745 s.validate().unwrap();
17746 }
17747
17748 #[test]
17749 fn singlenode_without_shard_key_validates() {
17750 // Peer of the Replicated no-shard-key case on the SingleNode
17751 // arm — both non-Sharded strategies must validate cleanly when
17752 // the slot is omitted.
17753 let mut s = three_member_spec();
17754 s.placement.estrategia = PlacementStrategy::SingleNode;
17755 s.placement.shard_key = None;
17756 s.validate().unwrap();
17757 }
17758
17759 fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
17760 // Fixture builder for the `:placement :shard-key` shape gate
17761 // tests: a three-member Aplicacao on the `Sharded` strategy
17762 // with the supplied `:shard-key` slot. Co-locates the
17763 // arm-construction so every test below carries one line of
17764 // setup (the offending `:shard-key` value) and the assertion.
17765 let mut s = three_member_spec();
17766 s.placement.estrategia = PlacementStrategy::Sharded;
17767 s.placement.shard_key = Some(key.into());
17768 s
17769 }
17770
17771 #[test]
17772 fn rejects_shard_key_with_embedded_space() {
17773 // The canonical paste-from-aligned-doc footgun:
17774 // `:shard-key "$tenant Id"` — the Akka-style entity-id
17775 // extractor reads the slot as a single-token reference, and an
17776 // embedded space breaks the token boundary at the runtime
17777 // hash-extractor pass with no diagnostic naming the offending
17778 // entry.
17779 let s = sharded_spec_with_key("$tenant Id");
17780 let err = s.validate().unwrap_err();
17781 assert!(
17782 matches!(
17783 err,
17784 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
17785 if shard_key == "$tenant Id" && reason.contains("space")
17786 ),
17787 "got {err:?}"
17788 );
17789 }
17790
17791 #[test]
17792 fn rejects_shard_key_with_leading_space() {
17793 // Leading-space arm of the embedded-whitespace footgun — the
17794 // paste-from-aligned-doc / paste-from-CSV-cell variant where
17795 // the leading column-padding leaked into the slot.
17796 let s = sharded_spec_with_key(" $tenantId");
17797 let err = s.validate().unwrap_err();
17798 assert!(
17799 matches!(
17800 err,
17801 AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
17802 if shard_key == " $tenantId"
17803 ),
17804 "got {err:?}"
17805 );
17806 }
17807
17808 #[test]
17809 fn rejects_shard_key_with_trailing_newline() {
17810 // The canonical paste-from-shell-heredoc footgun — every
17811 // `<<EOF` heredoc terminator paste leaves a trailing newline
17812 // the YAML emitter then folds away inconsistently across
17813 // emitter implementations.
17814 let s = sharded_spec_with_key("$tenantId\n");
17815 let err = s.validate().unwrap_err();
17816 assert!(
17817 matches!(
17818 err,
17819 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
17820 if shard_key == "$tenantId\n" && reason.contains("0x0a")
17821 ),
17822 "got {err:?}"
17823 );
17824 }
17825
17826 #[test]
17827 fn rejects_shard_key_with_embedded_tab() {
17828 // The paste-from-aligned-doc tab-stop variant — tabs land
17829 // alongside spaces in copy-paste from formatted columns.
17830 let s = sharded_spec_with_key("$tenant\tId");
17831 let err = s.validate().unwrap_err();
17832 assert!(
17833 matches!(
17834 err,
17835 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
17836 if shard_key == "$tenant\tId" && reason.contains("tab")
17837 ),
17838 "got {err:?}"
17839 );
17840 }
17841
17842 #[test]
17843 fn rejects_shard_key_with_control_character() {
17844 // The paste-from-binary / paste-from-screen-cleared-terminal
17845 // footgun — an embedded `\x01` (SOH) byte that some YAML
17846 // emitters silently strip and others escape as ``,
17847 // breaking round-trip across emitter implementations.
17848 let s = sharded_spec_with_key("$tenant\u{0001}Id");
17849 let err = s.validate().unwrap_err();
17850 assert!(
17851 matches!(
17852 err,
17853 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
17854 if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
17855 ),
17856 "got {err:?}"
17857 );
17858 }
17859
17860 #[test]
17861 fn rejects_shard_key_with_non_ascii() {
17862 // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
17863 // footgun — non-ASCII bytes normalize differently between the
17864 // caixa-mesh-side YAML emitter and the in-cluster reconciler's
17865 // YAML parser, the same entity ID can silently map to two
17866 // distinct shards on a re-render.
17867 let s = sharded_spec_with_key("$tenàntId");
17868 let err = s.validate().unwrap_err();
17869 assert!(
17870 matches!(
17871 err,
17872 AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
17873 if shard_key == "$tenàntId" && reason.contains("non-ASCII")
17874 ),
17875 "got {err:?}"
17876 );
17877 }
17878
17879 #[test]
17880 fn rejects_shard_key_too_long() {
17881 // Length cap pin: 64 bytes — one byte over the
17882 // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
17883 // here is a paste-from-doc multi-line blob landing in
17884 // `:shard-key` instead of a single-token extractor expression.
17885 let too_long = "a".repeat(64);
17886 let s = sharded_spec_with_key(&too_long);
17887 let err = s.validate().unwrap_err();
17888 let AplicacaoError::ShardKeyInvalid {
17889 ref shard_key,
17890 ref reason,
17891 } = err
17892 else {
17893 panic!("expected ShardKeyInvalid, got {err:?}");
17894 };
17895 assert_eq!(shard_key, &too_long);
17896 assert!(
17897 reason.contains("63") && reason.contains("64"),
17898 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
17899 );
17900 }
17901
17902 #[test]
17903 fn shard_key_max_length_validates() {
17904 // Boundary pin: 63 bytes exactly — the
17905 // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
17906 // dropping to 62) surfaces here as a regression, mirroring
17907 // `placement_cluster_max_length_validates` /
17908 // `placement_affinity_max_length_validates` on the peer
17909 // identifier-shaped slots.
17910 let s = sharded_spec_with_key(&"a".repeat(63));
17911 s.validate().unwrap();
17912 }
17913
17914 #[test]
17915 fn accepts_canonical_shard_key_forms() {
17916 // The Akka-style entity-id extractor shapes a caixa author is
17917 // realistically going to write — pin every leg so a future
17918 // tightening that bans (e.g.) the `${...}` interpolation
17919 // variant or the `metadata.<field>` JSONPath form surfaces
17920 // here as a regression. The canonical forms span:
17921 //
17922 // - bare property name (`tenantId`, `customerId`)
17923 // - Akka `ExtractEntityId` placeholder (`$tenantId`)
17924 // - JSONPath-style nested reference (`metadata.tenantId`,
17925 // `$.user.id`)
17926 // - interpolation-style template (`${tenant}`)
17927 // - snake_case property name (`customer_id`)
17928 // - kebab-case property name (`customer-id` — accepted
17929 // because the slot is a printable-ASCII single-token
17930 // reference, not a DNS-1123 label like
17931 // `:placement :affinity` / `:clusters`)
17932 // - single character (`a`, `$` — boundary)
17933 for form in [
17934 "tenantId",
17935 "customerId",
17936 "$tenantId",
17937 "metadata.tenantId",
17938 "$.user.id",
17939 "${tenant}",
17940 "customer_id",
17941 "customer-id",
17942 "a",
17943 "$",
17944 ] {
17945 let s = sharded_spec_with_key(form);
17946 s.validate().unwrap_or_else(|e| {
17947 panic!("canonical shard-key form {form:?} must validate, got {e:?}")
17948 });
17949 }
17950 }
17951
17952 #[test]
17953 fn shard_key_empty_takes_precedence_over_invalid() {
17954 // Order pin: the existing `ShardedKeyEmpty` diagnostic
17955 // (reserved for the `Sharded` `Some("")` arm) fires before the
17956 // new `ShardKeyInvalid` parse-side diagnostic, so an empty
17957 // `:shard-key` keeps its narrower error message — the new gate
17958 // would also reject `""` defensively, but the empty-string arm
17959 // is the more self-locating diagnostic. Mirrors the
17960 // `placement_cluster_empty_takes_precedence_over_invalid` pin
17961 // on the peer identifier-shaped slot.
17962 let s = sharded_spec_with_key("");
17963 let err = s.validate().unwrap_err();
17964 assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
17965 }
17966
17967 #[test]
17968 fn shard_key_invalid_diagnostic_carries_offending_value() {
17969 // The diagnostic-shape pin: the error names the offending
17970 // `:shard-key` value verbatim so the author can grep their
17971 // caixa.lisp without re-running the build, and carries a
17972 // parser-shaped `reason:` naming the specific violation —
17973 // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
17974 // on the peer identifier-shaped slot.
17975 let s = sharded_spec_with_key("$tenant Id");
17976 let err = s.validate().unwrap_err();
17977 let AplicacaoError::ShardKeyInvalid {
17978 ref shard_key,
17979 ref reason,
17980 } = err
17981 else {
17982 panic!("expected ShardKeyInvalid, got {err:?}");
17983 };
17984 assert_eq!(shard_key, "$tenant Id");
17985 assert!(
17986 !reason.is_empty(),
17987 "reason must name the specific violation, got empty string"
17988 );
17989 }
17990
17991 #[test]
17992 fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
17993 // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
17994 // `:shard-key` carried on non-Sharded strategies) fires before
17995 // the shape gate, so a malformed `:shard-key` carried on (e.g.)
17996 // a `Replicated` strategy surfaces the more self-locating
17997 // strategy-mismatch diagnostic (naming the actual fix — drop
17998 // the slot, or switch to Sharded) rather than the shape
17999 // diagnostic. The strategy-mismatch arm is the more actionable
18000 // diagnostic: a malformed shard-key on Replicated is "you
18001 // shouldn't have a :shard-key here at all", not "your
18002 // :shard-key value is malformed".
18003 let mut s = three_member_spec();
18004 // Replicated is the default fixture strategy.
18005 s.placement.shard_key = Some("$tenant Id".into());
18006 let err = s.validate().unwrap_err();
18007 assert!(
18008 matches!(
18009 err,
18010 AplicacaoError::ShardKeyOnNonSharded {
18011 estrategia: PlacementStrategy::Replicated,
18012 ..
18013 }
18014 ),
18015 "got {err:?}"
18016 );
18017 }
18018
18019 #[test]
18020 fn rejects_empty_affinity_hint() {
18021 let mut s = three_member_spec();
18022 s.placement.affinity = Some("".into());
18023 assert_eq!(
18024 s.validate().unwrap_err(),
18025 AplicacaoError::PlacementAffinityEmpty
18026 );
18027 }
18028
18029 #[test]
18030 fn placement_without_affinity_validates() {
18031 // Omitting :affinity is fine — the placement engine falls back
18032 // to the default heuristic. Pin the no-hint case so the
18033 // affinity-empty rejection doesn't accidentally fire on `None`.
18034 let mut s = three_member_spec();
18035 s.placement.affinity = None;
18036 s.validate().unwrap();
18037 }
18038
18039 #[test]
18040 fn rejects_placement_affinity_with_uppercase() {
18041 // The canonical "I copied the ADR's display name verbatim" typo
18042 // — placement hints land verbatim in K8s label-selector
18043 // territory, where the apiserver enforces the DNS-1123 label
18044 // rule (lowercase-only) on every identity-keyed admission axis.
18045 // Mirrors `rejects_placement_cluster_with_uppercase` on the
18046 // sibling slot.
18047 let mut s = three_member_spec();
18048 s.placement.affinity = Some("DataLocality".into());
18049 let err = s.validate().unwrap_err();
18050 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18051 panic!("expected PlacementAffinityInvalid, got other variant");
18052 };
18053 assert_eq!(affinity, "DataLocality");
18054 assert!(
18055 reason.contains("uppercase"),
18056 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
18057 );
18058 assert!(
18059 reason.contains("\"datalocality\""),
18060 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
18061 );
18062 }
18063
18064 #[test]
18065 fn rejects_placement_affinity_with_underscore() {
18066 // The canonical "I'm thinking of an env var / Python identifier"
18067 // leak — `_` is forbidden by every DNS-1123 label schema. Same
18068 // shape as `rejects_placement_cluster_with_underscore` on the
18069 // sibling slot.
18070 let mut s = three_member_spec();
18071 s.placement.affinity = Some("data_locality".into());
18072 let err = s.validate().unwrap_err();
18073 assert!(
18074 matches!(
18075 err,
18076 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18077 if affinity == "data_locality" && reason.contains('_')
18078 ),
18079 "got {err:?}"
18080 );
18081 }
18082
18083 #[test]
18084 fn rejects_placement_affinity_with_dot() {
18085 // A `:placement :affinity` value is a single DNS-1123 *label*
18086 // (it lands as a K8s label value selector key), not a subdomain.
18087 // The "I want to namespace my hint with `.`" intent is expressed
18088 // via `-` (`data-locality-east`).
18089 let mut s = three_member_spec();
18090 s.placement.affinity = Some("data.locality".into());
18091 let err = s.validate().unwrap_err();
18092 assert!(
18093 matches!(
18094 err,
18095 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18096 if affinity == "data.locality" && reason.contains('.')
18097 ),
18098 "got {err:?}"
18099 );
18100 }
18101
18102 #[test]
18103 fn rejects_placement_affinity_with_unicode() {
18104 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
18105 // before it reaches K8s. The byte-by-byte ASCII validity check
18106 // rejects multi-byte UTF-8 sequences by the first byte that
18107 // fails `[a-z0-9-]`.
18108 let mut s = three_member_spec();
18109 s.placement.affinity = Some("data-localité".into());
18110 let err = s.validate().unwrap_err();
18111 assert!(
18112 matches!(
18113 err,
18114 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
18115 if affinity == "data-localité"
18116 ),
18117 "got {err:?}"
18118 );
18119 }
18120
18121 #[test]
18122 fn rejects_placement_affinity_with_leading_hyphen() {
18123 // DNS-1123 boundary rule: labels must start with an
18124 // alphanumeric. Pin separately from the trailing-hyphen arm so
18125 // a future relaxation that only checks one boundary surfaces
18126 // here as a regression (parallel to
18127 // `rejects_placement_cluster_with_leading_hyphen`).
18128 let mut s = three_member_spec();
18129 s.placement.affinity = Some("-data-locality".into());
18130 let err = s.validate().unwrap_err();
18131 assert!(
18132 matches!(
18133 err,
18134 AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
18135 if affinity == "-data-locality" && reason.contains("start and end")
18136 ),
18137 "got {err:?}"
18138 );
18139 }
18140
18141 #[test]
18142 fn rejects_placement_affinity_with_trailing_hyphen() {
18143 // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
18144 // ends are covered against a future relaxation.
18145 let mut s = three_member_spec();
18146 s.placement.affinity = Some("data-locality-".into());
18147 let err = s.validate().unwrap_err();
18148 assert!(
18149 matches!(
18150 err,
18151 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
18152 if affinity == "data-locality-"
18153 ),
18154 "got {err:?}"
18155 );
18156 }
18157
18158 #[test]
18159 fn rejects_placement_affinity_with_whitespace() {
18160 // Whitespace is the canonical "I pasted from a sketch / doc"
18161 // footgun. The apiserver rejects every label-selector value
18162 // carrying whitespace.
18163 let mut s = three_member_spec();
18164 s.placement.affinity = Some("data locality".into());
18165 let err = s.validate().unwrap_err();
18166 assert!(
18167 matches!(
18168 err,
18169 AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
18170 if affinity == "data locality"
18171 ),
18172 "got {err:?}"
18173 );
18174 }
18175
18176 #[test]
18177 fn rejects_placement_affinity_too_long() {
18178 // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
18179 // pin. The diagnostic names both the cap (63) and the actual
18180 // length so the author can shorten in one edit. Mirrors
18181 // `rejects_placement_cluster_too_long`.
18182 let mut s = three_member_spec();
18183 let too_long = "a".repeat(64);
18184 s.placement.affinity = Some(too_long.clone());
18185 let err = s.validate().unwrap_err();
18186 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18187 panic!("expected PlacementAffinityInvalid");
18188 };
18189 assert_eq!(affinity, too_long);
18190 assert!(
18191 reason.contains("63") && reason.contains("64"),
18192 "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18193 );
18194 }
18195
18196 #[test]
18197 fn placement_affinity_max_length_validates() {
18198 // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
18199 // future tightening (e.g. dropping to 62) surfaces here as a
18200 // regression, mirroring `placement_cluster_max_length_validates`.
18201 let mut s = three_member_spec();
18202 s.placement.affinity = Some("a".repeat(63));
18203 s.validate().unwrap();
18204 }
18205
18206 #[test]
18207 fn accepts_canonical_placement_affinity_forms() {
18208 // The DNS-1123 label shapes a caixa author is realistically
18209 // going to write for placement hints: the M3 canonical examples
18210 // (`data-locality`, `low-latency`, `anti-affinity`), the
18211 // single-token form (`affinity`), the single-character boundary
18212 // (`a`), the digit-start (DNS-1123 allows this, unlike
18213 // DNS-1035), and a regional-suffixed form. Pin every leg so a
18214 // future tightening that bans (e.g.) digit-start identifiers
18215 // surfaces here.
18216 for form in [
18217 "data-locality",
18218 "low-latency",
18219 "anti-affinity",
18220 "affinity",
18221 "a",
18222 "3-tier",
18223 "locality-east",
18224 ] {
18225 let mut s = three_member_spec();
18226 s.placement.affinity = Some(form.into());
18227 s.validate().unwrap_or_else(|e| {
18228 panic!("canonical affinity form {form:?} must validate, got {e:?}")
18229 });
18230 }
18231 }
18232
18233 #[test]
18234 fn placement_affinity_empty_takes_precedence_over_invalid() {
18235 // Order pin: the existing `PlacementAffinityEmpty` diagnostic
18236 // (which doesn't try to parse) fires before the new
18237 // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
18238 // `:affinity` keeps its narrower error message — the new gate
18239 // would also reject `""`, but the empty-string arm is the more
18240 // self-locating diagnostic. Mirrors the
18241 // `placement_cluster_empty_takes_precedence_over_invalid` pin.
18242 let mut s = three_member_spec();
18243 s.placement.affinity = Some(String::new());
18244 let err = s.validate().unwrap_err();
18245 assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
18246 }
18247
18248 #[test]
18249 fn placement_affinity_invalid_diagnostic_carries_offending_value() {
18250 // The diagnostic shape pin: every rejection carries the offending
18251 // `affinity:` verbatim plus a parser-shaped `reason:` so the
18252 // author can grep their caixa.lisp for `:affinity "<hint>"` and
18253 // fix it in one edit. Mirrors the
18254 // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
18255 // pin on the sibling slot.
18256 let mut s = three_member_spec();
18257 s.placement.affinity = Some("Data_Locality".into());
18258 let err = s.validate().unwrap_err();
18259 let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
18260 panic!("expected PlacementAffinityInvalid");
18261 };
18262 assert_eq!(affinity, "Data_Locality");
18263 assert!(
18264 !reason.is_empty(),
18265 "diagnostic reason must not be empty (got: {reason:?})"
18266 );
18267 }
18268
18269 #[test]
18270 fn singlenode_with_takeover_candidates_validates() {
18271 // OTP distributed-application convention (MESH-COMPOSITION
18272 // §II.1): SingleNode runs on one cluster at a time but the
18273 // :clusters list enumerates the takeover candidates. Multiple
18274 // entries are not a contradiction — they are the failover pool.
18275 let mut s = three_member_spec();
18276 s.placement.estrategia = PlacementStrategy::SingleNode;
18277 s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
18278 s.validate().unwrap();
18279 }
18280
18281 // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
18282
18283 #[test]
18284 fn mesh_policy_default_is_empty() {
18285 // The Default impl carries None on every axis — the typed
18286 // analog of an unset `:politicas (())` slot. Renderers that
18287 // overlay the policy onto a cluster artifact key off this
18288 // predicate to skip the slot entirely; pinning so a future
18289 // axis added to MeshPolicy can't silently break the contract
18290 // (a new field whose Default is non-None would flip is_empty
18291 // to false on every existing caixa, surfacing here).
18292 assert!(MeshPolicy::default().is_empty());
18293 }
18294
18295 #[test]
18296 fn mesh_policy_with_only_timeout_is_not_empty() {
18297 let p = MeshPolicy {
18298 timeout: Some(Duration::from_secs(30)),
18299 ..Default::default()
18300 };
18301 assert!(!p.is_empty());
18302 }
18303
18304 #[test]
18305 fn mesh_policy_with_only_retries_is_not_empty() {
18306 let p = MeshPolicy {
18307 retries: Some(3),
18308 ..Default::default()
18309 };
18310 assert!(!p.is_empty());
18311 }
18312
18313 #[test]
18314 fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
18315 let p = MeshPolicy {
18316 circuit_breaker: Some(CircuitBreaker {
18317 max_failures: 5,
18318 window: Duration::from_secs(60),
18319 }),
18320 ..Default::default()
18321 };
18322 assert!(!p.is_empty());
18323 }
18324
18325 #[test]
18326 fn mesh_policy_with_only_mtls_required_is_not_empty() {
18327 // Even `mtls_required: Some(false)` (an explicit opt-out) is
18328 // not empty — the author *named* the axis, the renderer needs
18329 // to honor that vs. fall back to the cluster default.
18330 let p = MeshPolicy {
18331 mtls_required: Some(false),
18332 ..Default::default()
18333 };
18334 assert!(!p.is_empty());
18335 }
18336
18337 #[test]
18338 fn mesh_policy_with_only_rate_limit_is_not_empty() {
18339 let p = MeshPolicy {
18340 rate_limit: Some(RateLimit {
18341 rate: 100,
18342 window: Duration::from_secs(1),
18343 }),
18344 ..Default::default()
18345 };
18346 assert!(!p.is_empty());
18347 }
18348
18349 #[test]
18350 fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
18351 // The three-member happy-path fixture sets timeout + retries +
18352 // mtls_required — every populated axis must read non-empty.
18353 // Pin the round-trip so the M3.x per-:politicas emitter (the
18354 // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
18355 // on is_empty() to decide whether to emit at all without
18356 // re-deriving the contract from inline field probes.
18357 assert!(!three_member_spec().politicas.is_empty());
18358 }
18359
18360 // ── shared duration codec: cross-slot integer-magnitude gate ──
18361 //
18362 // The integer-magnitude discipline applied to
18363 // `supervisor::duration_codec::parse` lifts onto every typed slot
18364 // that routes through the shared codec — `MeshPolicy::timeout`
18365 // (`:politicas :timeout`) and `CircuitBreaker::window`
18366 // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
18367 // These cross-slot tests pin that the gate fires at the serde
18368 // layer for both typed slots, not just for the supervisor side.
18369
18370 #[test]
18371 fn policy_timeout_serde_rejects_fractional_seconds() {
18372 // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
18373 // so the shared codec's integer-magnitude gate applies on
18374 // deserialize. `"1.5s"` previously parsed to 1500ms and round-
18375 // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
18376 // deserialize with the canonical-form diagnostic naming the
18377 // offending `"1.5"` and the remediation `"1500ms"`.
18378 let payload = r#"{"timeout":"1.5s"}"#;
18379 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18380 let msg = err.to_string();
18381 assert!(
18382 msg.contains("not a non-negative integer"),
18383 "expected integer-magnitude diagnostic in {msg:?}"
18384 );
18385 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
18386 assert!(
18387 msg.contains("\"1500ms\""),
18388 "missing canonical-form remediation in {msg:?}"
18389 );
18390 }
18391
18392 #[test]
18393 fn policy_timeout_serde_rejects_leading_plus_sign() {
18394 // Pin the leading-`+` arm cross-slot — the prior f64 parser
18395 // accepted `"+30s"` silently and round-tripped to `"30s"`.
18396 let payload = r#"{"timeout":"+30s"}"#;
18397 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18398 let msg = err.to_string();
18399 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
18400 }
18401
18402 #[test]
18403 fn circuit_breaker_window_serde_rejects_fractional_minutes() {
18404 // `CircuitBreaker::window` uses `with =
18405 // "supervisor::duration_codec_required"` (the required-Duration
18406 // variant that delegates to the same shared parser). `"0.5m"`
18407 // parsed to 30s and round-tripped to `"30s"` on next emit —
18408 // DRIFT closed.
18409 let payload = format!(
18410 r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
18411 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
18412 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
18413 );
18414 let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
18415 let msg = err.to_string();
18416 assert!(
18417 msg.contains("not a non-negative integer"),
18418 "expected integer-magnitude diagnostic in {msg:?}"
18419 );
18420 assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
18421 assert!(
18422 msg.contains("\"30s\""),
18423 "missing canonical-form remediation in {msg:?}"
18424 );
18425 }
18426
18427 #[test]
18428 fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
18429 // Pin the happy-path on the cross-slot side: every canonical
18430 // author shape `render` ever emits parses cleanly through the
18431 // shared codec on the `CircuitBreaker` slot. The
18432 // codec's accepted set (post-gate) is exactly its emitted set
18433 // for the integer-magnitude class.
18434 for window_lit in ["30s", "500ms", "2m", "1h"] {
18435 let payload = format!(
18436 r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
18437 max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
18438 window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
18439 );
18440 let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
18441 panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
18442 });
18443 assert_eq!(cb.max_failures, 5);
18444 }
18445 }
18446
18447 // ── rate_limit_codec: integer-magnitude gate ──
18448 //
18449 // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
18450 // / 737a676 / d53c922 trajectory landed on every typed-duration /
18451 // typed-byte-size codec in caixa-core lifts onto the fifth typed
18452 // codec — `rate_limit_codec` — through the digit-only magnitude
18453 // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
18454 // These tests pin the gate at the serde layer for `:politicas
18455 // :rate-limit` (the only typed slot the codec backs), and at the
18456 // codec-internal `parse` layer for the canonical positive cases.
18457
18458 #[test]
18459 fn rate_limit_serde_rejects_fractional_rate() {
18460 // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
18461 // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
18462 // wording, which didn't name the canonical-form remediation or
18463 // the round-trip drift the next emit would produce. Now refused
18464 // at deserialize with the canonical-form diagnostic naming the
18465 // offending `"1.5"` magnitude and the round-trip drift wording.
18466 let payload = r#"{"rateLimit":"1.5/s"}"#;
18467 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18468 let msg = err.to_string();
18469 assert!(
18470 msg.contains("not a non-negative integer"),
18471 "expected integer-magnitude diagnostic in {msg:?}"
18472 );
18473 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
18474 assert!(
18475 msg.contains("THEORY.md"),
18476 "missing render-determinism contract citation in {msg:?}"
18477 );
18478 }
18479
18480 #[test]
18481 fn rate_limit_serde_rejects_leading_plus_sign() {
18482 // `u32::from_str("+100")` returns `Ok(100)` (Rust's
18483 // permissive-`+` parse), so `"+100/s"` silently parsed to
18484 // `RateLimit { 100, 1s }` and round-tripped through `render` to
18485 // `"100/s"` — a *different* canonical string on the next emit,
18486 // breaking the THEORY.md Part V render-determinism contract
18487 // exactly the way the peer duration codecs' `"+30s"` case did.
18488 // This is the load-bearing class the digit-only gate closes
18489 // beyond what `u32::from_str`'s strictness covers on its own.
18490 let payload = r#"{"rateLimit":"+100/s"}"#;
18491 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18492 let msg = err.to_string();
18493 assert!(
18494 msg.contains("not a non-negative integer"),
18495 "expected integer-magnitude diagnostic in {msg:?}"
18496 );
18497 assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
18498 }
18499
18500 #[test]
18501 fn rate_limit_serde_rejects_leading_minus_sign() {
18502 // The signed-negative arm: `"-1/s"` lands on the
18503 // non-canonical-but-numeric branch via the `i64` fallback (the
18504 // `f64` parse also succeeds), surfacing the canonical-form
18505 // diagnostic. Replaces the prior value-laundered "not a u32"
18506 // wording with the unified diagnostic across signs.
18507 let payload = r#"{"rateLimit":"-1/s"}"#;
18508 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18509 let msg = err.to_string();
18510 assert!(
18511 msg.contains("not a non-negative integer"),
18512 "expected integer-magnitude diagnostic in {msg:?}"
18513 );
18514 assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
18515 }
18516
18517 #[test]
18518 fn rate_limit_serde_rejects_decimal_shaped_integer() {
18519 // `"100.0/s"` is integer-valued numerically but not in the
18520 // codec's accepted set — `render` emits `"100/s"`, so the
18521 // round-trip would drift. Lifted to the canonical-form
18522 // diagnostic peer with the duration codec's `"1.0s"` case
18523 // (1c55a2a).
18524 let payload = r#"{"rateLimit":"100.0/s"}"#;
18525 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18526 let msg = err.to_string();
18527 assert!(
18528 msg.contains("not a non-negative integer"),
18529 "expected integer-magnitude diagnostic in {msg:?}"
18530 );
18531 assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
18532 }
18533
18534 #[test]
18535 fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
18536 // Non-numeric, non-digit-only input lands on the existing
18537 // narrower `"not a u32"` arm (preserved for diagnostic-shape
18538 // stability on the parser-shape footgun case). Pin this so a
18539 // future relaxation of the numeric-fallback predicate doesn't
18540 // silently collapse garbage onto the canonical-form arm — same
18541 // partition the peer duration codecs draw between
18542 // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
18543 let payload = r#"{"rateLimit":"abc/s"}"#;
18544 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18545 let msg = err.to_string();
18546 assert!(
18547 msg.contains("not a u32"),
18548 "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
18549 );
18550 assert!(
18551 !msg.contains("not a non-negative integer"),
18552 "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
18553 );
18554 }
18555
18556 #[test]
18557 fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
18558 // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
18559 // u32's range. The digit-only gate passes; `u32::from_str`
18560 // fails on overflow. Surface that with the overflow-shaped
18561 // diagnostic naming the offending magnitude verbatim, peer
18562 // with `supervisor::duration_codec`'s overflow arm. Pinning
18563 // the wording so a future refactor doesn't silently collapse
18564 // overflow onto the canonical-form arm.
18565 let payload = r#"{"rateLimit":"4294967296/s"}"#;
18566 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18567 let msg = err.to_string();
18568 assert!(
18569 msg.contains("overflows u32"),
18570 "expected overflow diagnostic in {msg:?}"
18571 );
18572 assert!(
18573 msg.contains("\"4294967296\""),
18574 "missing offending magnitude in {msg:?}"
18575 );
18576 }
18577
18578 #[test]
18579 fn rate_limit_serde_rejects_leading_zero_magnitude() {
18580 // `"0100/s"` is digit-only, so the existing
18581 // non-digit-only / sign / fractional arm doesn't catch it —
18582 // `u32::from_str("0100")` returns `Ok(100)`, so before this
18583 // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
18584 // round-tripped through `render` to `"100/s"` — a *different*
18585 // canonical string on the next emit, breaking the THEORY.md
18586 // Part V render-determinism contract exactly the way the
18587 // peer `"+100/s"` case did before the leading-`+` arm landed.
18588 // This is the load-bearing class the leading-zero gate closes
18589 // beyond what the existing digit-only / sign / fractional
18590 // gates cover, and the peer arm to the leading-`+` test
18591 // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
18592 // canonical-form-drift axis.
18593 let payload = r#"{"rateLimit":"0100/s"}"#;
18594 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18595 let msg = err.to_string();
18596 assert!(
18597 msg.contains("non-canonical leading zero"),
18598 "expected leading-zero diagnostic in {msg:?}"
18599 );
18600 assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
18601 assert!(
18602 msg.contains("THEORY.md"),
18603 "missing render-determinism contract citation in {msg:?}"
18604 );
18605 }
18606
18607 #[test]
18608 fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
18609 // `"00/s"` is the degenerate leading-zero case — every byte
18610 // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
18611 // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
18612 // a *different* canonical string, same render-determinism
18613 // violation. The single-byte `"0/s"` itself is in the
18614 // accepted set (round-trips losslessly through `render`,
18615 // refused downstream by `PolicyRateLimitZero`); the
18616 // multi-byte `"00/s"` is not. Pins the boundary between the
18617 // accepted single-`0` and the rejected leading-zero class.
18618 let payload = r#"{"rateLimit":"00/s"}"#;
18619 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18620 let msg = err.to_string();
18621 assert!(
18622 msg.contains("non-canonical leading zero"),
18623 "expected leading-zero diagnostic in {msg:?}"
18624 );
18625 assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
18626 }
18627
18628 #[test]
18629 fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
18630 // Cross-window pin — the gate is window-agnostic; the
18631 // leading-zero class is a property of the magnitude, not the
18632 // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
18633 // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
18634 // single-window coverage extended across the three canonical
18635 // windows the codec accepts.
18636 let payload = r#"{"rateLimit":"007/h"}"#;
18637 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18638 let msg = err.to_string();
18639 assert!(
18640 msg.contains("non-canonical leading zero"),
18641 "expected leading-zero diagnostic in {msg:?}"
18642 );
18643 assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
18644 }
18645
18646 #[test]
18647 fn rate_limit_serde_rejects_leading_whitespace() {
18648 // `" 100/s"` — the canonical paste-from-aligned-doc /
18649 // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
18650 // the top-level `s.trim()` silently ate the leading space and
18651 // parsed the value to `RateLimit { 100, 1s }`, which then
18652 // round-tripped through `render` to `"100/s"` (a *different*
18653 // canonical string on the next emit) — the exact
18654 // canonical-form-drift class the leading-`+` / leading-zero
18655 // arms already close, extended to the whitespace byte class.
18656 let payload = r#"{"rateLimit":" 100/s"}"#;
18657 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18658 let msg = err.to_string();
18659 assert!(
18660 msg.contains("contains whitespace byte"),
18661 "expected whitespace diagnostic in {msg:?}"
18662 );
18663 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
18664 assert!(
18665 msg.contains("THEORY.md"),
18666 "missing render-determinism contract citation in {msg:?}"
18667 );
18668 }
18669
18670 #[test]
18671 fn rate_limit_serde_rejects_trailing_whitespace() {
18672 // `"100/s "` — the canonical shell-history / trailing-space
18673 // paste footgun. Before this gate the top-level `s.trim()`
18674 // silently ate the trailing space and parsed to
18675 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
18676 // next emit — same canonical-form drift as the leading-space
18677 // sibling, closed on the same whitespace-byte arm.
18678 let payload = r#"{"rateLimit":"100/s "}"#;
18679 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18680 let msg = err.to_string();
18681 assert!(
18682 msg.contains("contains whitespace byte"),
18683 "expected whitespace diagnostic in {msg:?}"
18684 );
18685 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
18686 }
18687
18688 #[test]
18689 fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
18690 // `"100 / s"` — the canonical typographically-spaced author
18691 // shape (the same idiom every prose reference to a rate limit
18692 // renders as, mistakenly retained when the value is pasted
18693 // into a codec-shaped slot). Before this gate the per-part
18694 // `rate_str.trim()` / `unit.trim()` calls silently ate both
18695 // spaces on either side of `/` and parsed to
18696 // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
18697 // codec's *internal* whitespace-tolerance vector, orthogonal
18698 // to the leading / trailing surface but the same canonical-
18699 // form-drift class. Pins the arm as strictly stronger than the
18700 // pre-existing top-level `s.trim()` behavior: it fires on
18701 // whitespace anywhere in the value, not just at the string
18702 // boundary.
18703 let payload = r#"{"rateLimit":"100 / s"}"#;
18704 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18705 let msg = err.to_string();
18706 assert!(
18707 msg.contains("contains whitespace byte"),
18708 "expected whitespace diagnostic in {msg:?}"
18709 );
18710 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
18711 }
18712
18713 #[test]
18714 fn rate_limit_serde_rejects_tab_byte() {
18715 // `"\t100/s"` — the canonical paste-from-indented-doc /
18716 // paste-from-YAML-block-scalar footgun where a tab byte leads
18717 // the magnitude. Pins that the gate covers tab (`0x09`) as
18718 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
18719 // members and both would be silently swallowed by `s.trim()`
18720 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
18721 // space alone to the full ASCII-whitespace set (space `0x20`,
18722 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
18723 // the tab arm as a representative of the non-space members.
18724 let payload = r#"{"rateLimit":"\t100/s"}"#;
18725 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18726 let msg = err.to_string();
18727 assert!(
18728 msg.contains("contains whitespace byte"),
18729 "expected whitespace diagnostic in {msg:?}"
18730 );
18731 assert!(
18732 msg.contains("0x09"),
18733 "missing offending tab byte in {msg:?}"
18734 );
18735 }
18736
18737 // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
18738 //
18739 // Successor to the ASCII-whitespace arm (1ad7755) on
18740 // `rate_limit_codec` — closes the strictly-complementary class the
18741 // byte-scan cannot see, through the lifted
18742 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
18743
18744 #[test]
18745 fn rate_limit_serde_rejects_leading_nbsp() {
18746 // NBSP prefix — paste-from-typography footgun. Byte-scan
18747 // misses, `str::trim` silently strips it, value drifts to
18748 // `"100/s"` on next serialize.
18749 let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
18750 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18751 let msg = err.to_string();
18752 assert!(
18753 msg.contains("non-ASCII Unicode whitespace character"),
18754 "expected non-ASCII whitespace diagnostic in {msg:?}"
18755 );
18756 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
18757 }
18758
18759 #[test]
18760 fn rate_limit_serde_rejects_internal_em_space() {
18761 // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
18762 // paste-from-typography footgun on the `<integer>/<unit>`
18763 // shape.
18764 let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
18765 let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
18766 let msg = err.to_string();
18767 assert!(
18768 msg.contains("non-ASCII Unicode whitespace character"),
18769 "expected non-ASCII whitespace diagnostic in {msg:?}"
18770 );
18771 assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
18772 }
18773
18774 #[test]
18775 fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
18776 // Positive-control pin: every ASCII-only canonical form the
18777 // renderer emits stays accepted through the new arm.
18778 for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
18779 let payload = format!(r#"{{"rateLimit":{lit}}}"#);
18780 let p: MeshPolicy = serde_json::from_str(&payload)
18781 .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
18782 assert!(p.rate_limit.is_some());
18783 }
18784 }
18785
18786 #[test]
18787 fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
18788 // The boundary case — `"0/s"` is the canonical form
18789 // `render(RateLimit { 0, 1s })` emits, so the codec accepts
18790 // it at the parse layer; the downstream
18791 // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
18792 // `rate == 0` at the typed-validate layer above. Pins the
18793 // partition: the leading-zero gate at the codec layer does
18794 // not poach the rate-zero semantic-validation arm at the
18795 // typed-validate layer above (a future stricter codec must
18796 // not reject `"0/s"` here, or it'd collapse the diagnostic
18797 // partitioning that lets `PolicyRateLimitZero` name the
18798 // offending typed slot).
18799 let payload = r#"{"rateLimit":"0/s"}"#;
18800 let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
18801 panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
18802 });
18803 let rl = policy.rate_limit.expect("rate_limit must be Some");
18804 assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
18805 assert_eq!(
18806 rl.window,
18807 Duration::from_secs(1),
18808 "single-`0` magnitude with `s` unit must parse to window=1s"
18809 );
18810 }
18811
18812 #[test]
18813 fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
18814 // The complementary boundary pin — every magnitude
18815 // `render` emits starts with `[1-9]` (or is the single byte
18816 // `"0"`), so the canonical-form predicate is `(len == 1) ||
18817 // (first byte != '0')`. Pinning the `len > 1 && first byte ==
18818 // '1'` case explicitly so a future tightening of the gate
18819 // (e.g. an over-eager "no leading digit < 5" rule, or a
18820 // mistakenly anchored start-of-magnitude byte check) lands
18821 // here before the canonical-forms-iterating test would catch
18822 // it.
18823 let payload = r#"{"rateLimit":"100/s"}"#;
18824 let policy: MeshPolicy = serde_json::from_str(payload)
18825 .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
18826 let rl = policy.rate_limit.expect("rate_limit must be Some");
18827 assert_eq!(
18828 rl.rate, 100,
18829 "canonical-100 magnitude must parse to rate=100"
18830 );
18831 }
18832
18833 #[test]
18834 fn rate_limit_serde_accepts_integer_canonical_forms() {
18835 // Pin the happy-path: every canonical author shape `render`
18836 // ever emits parses cleanly through the codec post-gate. The
18837 // codec's accepted set (post-gate) is exactly its emitted set
18838 // for the integer-magnitude class — same property
18839 // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
18840 // gates guarantee on the peer codecs. Iterating across rate
18841 // magnitudes (including `"0"`, which the codec accepts even
18842 // though `validate_politicas` rejects `rate == 0` at the typed
18843 // layer above) closes the codec contract at the parse layer
18844 // independently of the validate layer.
18845 for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
18846 for unit_lit in ["s", "m", "h"] {
18847 let lit = format!("{rate_lit}/{unit_lit}");
18848 let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
18849 let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
18850 panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
18851 });
18852 let rl = policy.rate_limit.expect("rate_limit must be Some");
18853 assert_eq!(
18854 rl.rate,
18855 rate_lit.parse::<u32>().unwrap(),
18856 "rate mismatch for {lit:?}"
18857 );
18858 }
18859 }
18860 }
18861
18862 #[test]
18863 fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
18864 // The structural property the gate enforces: serialize ∘
18865 // deserialize is the identity on every canonical author shape.
18866 // Peer of `parse_byte_size`'s and `parse_duration`'s
18867 // `_round_trips_through_render_for_every_canonical_form` tests
18868 // on the rate-limit axis. Before the gate, `"+100/s"` violated
18869 // this (`parse` → `RateLimit { 100, 1s }` → `render` →
18870 // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
18871 for rate in [1u32, 100, 5000, 1_000_000] {
18872 for (window, unit) in [
18873 (Duration::from_secs(1), "s"),
18874 (Duration::from_secs(60), "m"),
18875 (Duration::from_secs(3600), "h"),
18876 ] {
18877 let policy = MeshPolicy {
18878 rate_limit: Some(RateLimit { rate, window }),
18879 ..Default::default()
18880 };
18881 let json = serde_json::to_string(&policy).unwrap();
18882 let expected = format!("\"{rate}/{unit}\"");
18883 assert!(
18884 json.contains(&expected),
18885 "expected {expected:?} in {json:?}"
18886 );
18887 let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18888 assert_eq!(
18889 back.rate_limit, policy.rate_limit,
18890 "round-trip for {json:?}"
18891 );
18892 }
18893 }
18894 }
18895
18896 // ── self-membership cross-slot gate ──────────────────────────────
18897
18898 #[test]
18899 fn validate_no_self_membership_rejects_self_named_membro() {
18900 // An Aplicacao whose `:membros` lists its own `:nome` is a
18901 // one-node lacre-closure recursion — rejected, naming the parent.
18902 let membros = vec![
18903 membro("catalog", "^0.1"),
18904 membro("checkout", "^0.1"),
18905 membro("cart", "^0.1"),
18906 ];
18907 let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
18908 assert!(
18909 matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
18910 "got {err:?}"
18911 );
18912 }
18913
18914 #[test]
18915 fn validate_no_self_membership_accepts_distinct_membros() {
18916 // Positive control: distinct member names (including a member
18917 // that is itself an Aplicacao — recursive composition is valid,
18918 // MESH-COMPOSITION §V) pass the gate.
18919 let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
18920 validate_no_self_membership(&membros, "checkout").unwrap();
18921 }
18922
18923 #[test]
18924 fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
18925 // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
18926 // `NoMembros` arm (the more-fundamental "graph must have nodes"
18927 // gate), not by this cross-slot self-edge gate. Keeping the
18928 // self-membership predicate vacuously-ok on the empty input
18929 // matches its supervisor-axis peer
18930 // (`validate_no_self_supervision_empty_children_is_ok`) and
18931 // makes the gate composable from any future call site (an M4
18932 // CR materializer's per-membros validator) without re-checking
18933 // emptiness.
18934 validate_no_self_membership(&[], "checkout").unwrap();
18935 }
18936
18937 #[test]
18938 fn validate_no_self_membership_diagnostic_names_offending_caixa() {
18939 // Pinning the Display: the self-membership diagnostic must name
18940 // the offending caixa verbatim + the "lists itself" framing the
18941 // author can grep for, so the cluster-far failure surfaces at
18942 // build time with one-line remediation. Same diagnostic shape
18943 // as the supervisor-axis `ChildSupervisesSelf` peer.
18944 let membros = vec![membro("orquestra", "^0.1")];
18945 let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
18946 let msg = err.to_string();
18947 assert!(
18948 msg.contains("orquestra"),
18949 "diagnostic must name the offending caixa nome (got: {msg:?})"
18950 );
18951 assert!(
18952 msg.contains("lists itself"),
18953 "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
18954 );
18955 }
18956
18957 #[test]
18958 fn default_servico_port_constant_pins_canonical_8080_literal() {
18959 // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
18960 // at the verbatim `8080` literal both consumers (the
18961 // `Entrada::port` serde default via [`default_port`] and the
18962 // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
18963 // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
18964 // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
18965 // discipline (a085b26) on the per-renderer canonical-K8s-axis
18966 // string-constant axis: a future refactor that drifts the
18967 // constant out from under either consumer surfaces here ahead
18968 // of every per-renderer's first emission. The literal value
18969 // matches the well-known HTTP-alt port the `pleme-computeunit`
18970 // library chart already emits as its `trigger.service.port`
18971 // default — by construction the same value the substrate
18972 // assumes about every Servico's in-cluster L4 listener.
18973 assert_eq!(
18974 DEFAULT_SERVICO_PORT, 8080,
18975 "canonical Servico port literal must remain `8080` verbatim — \
18976 this is the value both the `Entrada::port` serde default and the \
18977 caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
18978 );
18979 }
18980
18981 #[test]
18982 fn default_port_helper_returns_canonical_servico_port_constant() {
18983 // The bridge-arm — pins that the [`default_port`] helper
18984 // [`Entrada::port`]'s `#[serde(default = "default_port")]`
18985 // attribute hooks routes through the lifted
18986 // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
18987 // literal. A future refactor that re-introduces the `8080`
18988 // literal at the helper's return site (silently re-opening
18989 // the drift footgun this lift closed) surfaces here ahead of
18990 // every author-side `(:entrada (:host … :para …))` slot
18991 // without an explicit `:port`. Peer with the
18992 // `default_namespace_re_export_points_at_caixa_core_canonical`
18993 // pin on the caixa-mesh-side re-export axis.
18994 assert_eq!(
18995 default_port(),
18996 DEFAULT_SERVICO_PORT,
18997 "the serde-default helper must route through the lifted constant"
18998 );
18999 }
19000
19001 #[test]
19002 fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
19003 // The end-to-end pin — an author-surface `(:entrada (:host …
19004 // :para …))` without an explicit `:port` slot deserializes to
19005 // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
19006 // verbatim. Routes the canonical lifted constant through both
19007 // the serde-default machinery (the `#[serde(default =
19008 // "default_port")]` attribute) and the typed-value-shape
19009 // contract (the resulting [`Entrada::port`] value). A future
19010 // refactor that drifts either axis — replacing the serde
19011 // hook's helper, changing the typed slot's wire shape — would
19012 // surface here before any per-renderer's CNP / Gateway /
19013 // HTTPRoute emission consumed the drifted default.
19014 let entrada: Entrada =
19015 serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
19016 assert_eq!(
19017 entrada.port, DEFAULT_SERVICO_PORT,
19018 "the serde default must materialize as the lifted canonical Servico port"
19019 );
19020 }
19021
19022 #[test]
19023 fn servico_port_min_pins_canonical_accept_set_floor() {
19024 // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
19025 // verbatim `1` literal every typed `:entrada :port` acceptance
19026 // gate keys off. Peer with the
19027 // [`default_servico_port_constant_pins_canonical_8080_literal`]
19028 // discipline on the canonical-Servico-port-constant axis: a
19029 // future refactor that drifts the accept-set floor out from
19030 // under the sole consumer at [`AplicacaoSpec::validate`]'s
19031 // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
19032 // every per-`:entrada` `EntradaPortZero` diagnostic. The
19033 // literal value matches the IANA-registered TCP/UDP port
19034 // space floor (`1..=65535` — port `0` is the "any ephemeral"
19035 // sentinel, not a well-defined destination the substrate's
19036 // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
19037 // axis can honor).
19038 assert_eq!(
19039 SERVICO_PORT_MIN, 1,
19040 "canonical Servico port accept-set floor must remain `1` verbatim — \
19041 this is the value the `AplicacaoSpec::validate` gate at \
19042 `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
19043 );
19044 }
19045
19046 #[test]
19047 fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
19048 // The cross-const invariant pin — the substrate's canonical
19049 // default port must satisfy its own accept-set floor by
19050 // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
19051 // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
19052 // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
19053 // override the operator pins through a future
19054 // `:placement :default-port` slot that lands out-of-range, a
19055 // per-edition Servico-port migration that lifted the floor
19056 // above the previous default without coordinating the pair —
19057 // would silently invalidate the serde-default emission at
19058 // every author-side `(:entrada (:host … :para …))` slot
19059 // without an explicit `:port`: the default port would fall
19060 // below the accept-set floor, the `AplicacaoSpec::validate`
19061 // gate would reject every default-carrying Aplicacao as
19062 // `EntradaPortZero`, and the substrate's typed
19063 // `(defcaixa … :kind Aplicacao)` surface would fail validate
19064 // on every Aplicacao whose author omitted `:entrada :port`
19065 // for the substrate's chosen default — a class of authoring-
19066 // surface footguns the compile-time pin structurally closes.
19067 // Peer with the
19068 // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
19069 // (27f9b34) cross-const invariant pin discipline on the peer
19070 // canonical-Helm-per-values-block child-chart-enablement-toggle
19071 // axis pair.
19072 assert!(
19073 SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
19074 "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
19075 satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
19076 every default-carrying `(:entrada (:host … :para …))` slot without an \
19077 explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
19078 hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
19079 );
19080 }
19081
19082 #[test]
19083 fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
19084 // The gate-site pin — asserts the `AplicacaoSpec::validate`
19085 // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
19086 // `EntradaPortZero` diagnostic on the below-floor input
19087 // `port: 0` (the only below-floor value the `u16` field can
19088 // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
19089 // is the singleton `{0}`). A future refactor that drifts the
19090 // gate off the lifted const (silently re-introducing an
19091 // inline `if e.port == 0` byte-check) surfaces here — the
19092 // pin cannot distinguish `< 1` from `== 0` on the current
19093 // floor, but it *does* pin that the diagnostic fires on `0`
19094 // through whichever gate is wired, so any future accept-set
19095 // floor migration (a hypothetical unprivileged-only
19096 // migration lifting `SERVICO_PORT_MIN` to `1024`) must
19097 // update this test alongside the const declaration —
19098 // structurally guaranteeing the gate + accept-set + pin
19099 // trio move together. Peer with the
19100 // [`rejects_zero_entrada_port`] behavioral pin on the same
19101 // per-`:entrada :port` axis — that pin asserts the pre-lift
19102 // behavioral contract (`port: 0` → `EntradaPortZero`); this
19103 // pin adds the structural link to the lifted floor const.
19104 assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
19105 let mut s = three_member_spec();
19106 s.entrada.as_mut().unwrap().port = 0;
19107 assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
19108 }
19109
19110 // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
19111
19112 #[test]
19113 fn membro_serde_keys_match_lifted_membro_key_consts() {
19114 // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
19115 // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
19116 // name the exact camelCase JSON keys the
19117 // `#[serde(rename_all = "camelCase")]` attribute on
19118 // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
19119 // that each canonical byte-sequence appears verbatim in the
19120 // JSON — a future accidental `rename_all = "snake_case"` /
19121 // `"kebab-case"` / verbatim-field-name flip at the derive
19122 // attribute (any of which would silently break every downstream
19123 // JSON consumer that reaches for one of the two consts via
19124 // `Value::get(...)`) surfaces here as a build-time test failure
19125 // at `aplicacao.rs`, not as an apply-time
19126 // `.get(<stale-canonical-const>)` returning `None` far from the
19127 // derive-attr drift's commit. Peer with the sibling
19128 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
19129 // (40cc4e5) pin on the M2 supervision-tree top-level axis —
19130 // same discipline the SupervisorSpec top-level lift established,
19131 // extended here to the M3 [`Membro`] per-`:membros` axis.
19132 let m = Membro {
19133 caixa: "catalog".into(),
19134 versao: "^0.1".into(),
19135 };
19136 let json = serde_json::to_string(&m).unwrap();
19137 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
19138 let quoted = format!("\"{key}\"");
19139 assert!(
19140 json.contains("ed),
19141 "serialized Membro must carry the lifted MEMBRO_KEY_* \
19142 byte-sequence {quoted} verbatim in the JSON emission \
19143 (got: {json})",
19144 );
19145 }
19146 }
19147
19148 #[test]
19149 fn membro_key_consts_are_pairwise_distinct() {
19150 // Cross-axis drift-detection pin: a future collapse of the two
19151 // canonical [`Membro`] per-entry byte-strings onto the same
19152 // value (e.g. an accidental copy-paste flip of
19153 // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
19154 // silently reroute every downstream probe on one axis onto the
19155 // sibling axis's overlay entry and pass every propagation-probe
19156 // test that expected only the stale axis's value. Peer of the
19157 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
19158 // (40cc4e5).
19159 let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
19160 for (i, a) in all.iter().enumerate() {
19161 for b in all.iter().skip(i + 1) {
19162 assert_ne!(
19163 a, b,
19164 "MEMBRO_KEY_* consts must be pairwise-distinct \
19165 canonical byte-sequences — got `{a}` == `{b}`",
19166 );
19167 }
19168 }
19169 }
19170
19171 // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
19172 // URL-path fallback resolver every HTTPRoute-aware renderer
19173 // reaching for a per-rule path-list resolution routes through.
19174 // The four pin tests below fix the four-way accept-set the
19175 // resolver must always honor: (:paths-non-empty-verbatim,
19176 // :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
19177 // :paths-preserves-order-across-multiple-entries) — drift on any
19178 // arm surfaces at caixa-core build time rather than at cluster-
19179 // apply time. Peer discipline with `MeshPolicy::is_empty` on the
19180 // sibling `:politicas` typed-primitive dispatch axis.
19181
19182 fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
19183 Entrada {
19184 host: "example.com".into(),
19185 para: "cart".into(),
19186 paths: paths.into_iter().map(String::from).collect(),
19187 port: DEFAULT_SERVICO_PORT,
19188 }
19189 }
19190
19191 #[test]
19192 fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
19193 // The typed `:entrada :paths` slot carries an author-declared
19194 // list — the resolver returns each entry verbatim, no
19195 // catch-all substitution. The canonical "author declared
19196 // paths, honor them verbatim" arm of the path-list dispatch.
19197 let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
19198 assert_eq!(
19199 e.resolved_paths(),
19200 vec!["/api/cart", "/api/products"],
19201 "resolved_paths must return each `:entrada :paths` entry \
19202 verbatim when the typed slot is non-empty (got {:?})",
19203 e.resolved_paths(),
19204 );
19205 }
19206
19207 #[test]
19208 fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
19209 // Empty `:entrada :paths` slot — the resolver substitutes the
19210 // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
19211 // catch-all fallback verbatim. Pins the empty-arm of the
19212 // resolver's four-way accept-set against a future silent
19213 // detour that returned an empty Vec (which would emit an
19214 // HTTPRoute with zero rules — silently dropping every
19215 // external `:entrada` flow at admission time), routed to a
19216 // different fallback shape, or dropped the catch-all
19217 // altogether.
19218 let e = entrada_with_paths(vec![]);
19219 assert_eq!(
19220 e.resolved_paths(),
19221 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
19222 "resolved_paths on empty `:entrada :paths` must fall back \
19223 to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
19224 all — got {:?}",
19225 e.resolved_paths(),
19226 );
19227 }
19228
19229 #[test]
19230 fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
19231 // Single-entry `:entrada :paths` — the resolver returns the
19232 // single declared path verbatim, NOT the catch-all fallback
19233 // (author declared a path, honor it — the empty-arm and the
19234 // len-1 arm are semantically distinct axes of the resolver's
19235 // accept-set). Pins that the resolver treats "author declared
19236 // one path" as authored input, not as the empty case.
19237 let e = entrada_with_paths(vec!["/api/only"]);
19238 assert_eq!(
19239 e.resolved_paths(),
19240 vec!["/api/only"],
19241 "resolved_paths on single-entry `:entrada :paths` must \
19242 return the declared path verbatim, NOT the catch-all \
19243 fallback (got {:?})",
19244 e.resolved_paths(),
19245 );
19246 }
19247
19248 #[test]
19249 fn resolved_paths_preserves_author_declared_order() {
19250 // The `:entrada :paths` list is author-ordered — the resolver
19251 // preserves the author's declaration order verbatim, since
19252 // per-rule dispatch order at the K8s Gateway API HTTPRoute
19253 // consumer is significant (first-match-wins under the
19254 // path-prefix matcher). Pins against a future silent
19255 // re-sort / dedup / normalize detour that reordered author
19256 // input.
19257 let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
19258 assert_eq!(
19259 e.resolved_paths(),
19260 vec!["/z/last", "/a/first", "/m/mid"],
19261 "resolved_paths must preserve author-declared `:entrada \
19262 :paths` order verbatim — got {:?}",
19263 e.resolved_paths(),
19264 );
19265 }
19266
19267 // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
19268 // slot `&[String]` slice accessor every per-`:entrada` consumer
19269 // that must see the author's declaration verbatim (not the
19270 // fallback-applied projection the sibling `resolved_paths`
19271 // returns) routes through. The three pin tests below fix the
19272 // accept-set the accessor must honor: (:non-empty-byte-equal,
19273 // :empty-projects-empty-slice, :preserves-author-declared-order)
19274 // — drift on any arm surfaces at caixa-core build time rather
19275 // than at cluster-apply time. Peer discipline with the sibling
19276 // [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
19277 // peer M3 mesh-slot `Vec<String>`-carry axis.
19278
19279 #[test]
19280 fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
19281 // Byte-equal pin: [`Entrada::paths`] must project the raw
19282 // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
19283 // slice borrowed from the typed slot's own [`Vec<String>`]
19284 // storage — no re-ordering, no dedup, no per-entry normalization,
19285 // no fallback substitution (the fallback-applying projection is
19286 // the sibling [`Entrada::resolved_paths`] resolver). Pins against
19287 // a future silent detour that re-normalized the list, dropped
19288 // duplicates the [`AplicacaoSpec::validate`]
19289 // `EntradaPathDuplicate` refusal already rejects at build time,
19290 // or (most severe) accidentally routed through the fallback-
19291 // applying sibling and returned the substrate catch-all when
19292 // the author declared an empty list — collapsing the raw-slot
19293 // and fallback-applied axes into one and breaking the
19294 // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
19295 //
19296 // Peer of the sibling
19297 // [`Placement::clusters`]-shape byte-equal pin
19298 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
19299 // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
19300 let fixtures: Vec<Vec<String>> = vec![
19301 Vec::new(),
19302 vec!["/api/cart".into()],
19303 vec!["/api/cart".into(), "/api/products".into()],
19304 vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
19305 ];
19306 for paths in fixtures {
19307 let e = Entrada {
19308 host: "example.com".into(),
19309 para: "cart".into(),
19310 paths: paths.clone(),
19311 port: DEFAULT_SERVICO_PORT,
19312 };
19313 assert_eq!(
19314 e.paths(),
19315 paths.as_slice(),
19316 "Entrada::paths must return :entrada :paths verbatim \
19317 (got {:?}, expected {:?})",
19318 e.paths(),
19319 paths.as_slice(),
19320 );
19321 assert_eq!(
19322 e.paths(),
19323 e.paths.as_slice(),
19324 "Entrada::paths accessor and .paths.as_slice() field \
19325 access must byte-equal — the accessor is the substrate-\
19326 primitive typed dispatch every downstream per-`:entrada` \
19327 raw-slot path-list consumer must route through",
19328 );
19329 assert_eq!(
19330 e.paths().len(),
19331 e.paths.len(),
19332 "Entrada::paths().len() must byte-equal self.paths.len() \
19333 — a length drift would silently split the paired \
19334 pre-flight cascade-head `.is_empty()` probe input in \
19335 the sibling [`Entrada::resolved_paths`] resolver from \
19336 the per-entry validate loop's traversal input in \
19337 [`AplicacaoSpec::validate`]",
19338 );
19339 }
19340 }
19341
19342 #[test]
19343 fn resolved_paths_reads_through_lifted_paths_accessor() {
19344 // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
19345 // pre-flight `.paths().is_empty()` cascade-head probe (which
19346 // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
19347 // catch-all fallback arm when the accessor projects the empty
19348 // slice) and the per-entry `.paths().iter().map(String::as_str)`
19349 // projection (which must reach every entry in the same order
19350 // the accessor projects, so the sibling
19351 // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
19352 // per-entry projection stay in lockstep by construction) must
19353 // both key off the lifted accessor. Pins the two-site coherence
19354 // by exercising each production consumer end-to-end: (1) the
19355 // catch-all-fallback arm under the empty slice, (2) the
19356 // author-declared-verbatim arm under a two-entry cohort whose
19357 // per-entry projection must byte-equal the input's per-entry
19358 // author-declared paths in the author's declared order.
19359 //
19360 // Peer of the sibling M3
19361 // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
19362 // `validate_placement_reads_through_lifted_clusters_accessor`
19363 // on the sibling `Placement::clusters` reader-site convergence.
19364 let empty = entrada_with_paths(vec![]);
19365 assert_eq!(
19366 empty.resolved_paths(),
19367 vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
19368 "resolved_paths on empty :entrada :paths must trip the \
19369 lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
19370 catch-all fallback — routing through the lifted paths() \
19371 accessor must not silently drop the fallback arm",
19372 );
19373
19374 let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
19375 assert_eq!(
19376 declared.resolved_paths(),
19377 vec!["/api/cart", "/api/products"],
19378 "resolved_paths on non-empty :entrada :paths must return each \
19379 entry verbatim in the author's declared order — routing \
19380 through the lifted paths() accessor must not silently \
19381 reorder or drop entries",
19382 );
19383 // Byte-equal pin against the raw-slot accessor to keep the
19384 // fallback-applying resolver's per-entry projection input in
19385 // lockstep with the raw-slot accessor's projection.
19386 let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
19387 assert_eq!(
19388 declared.resolved_paths(),
19389 raw_projected,
19390 "resolved_paths non-empty projection must byte-equal the \
19391 lifted paths() accessor's per-entry String::as_str projection \
19392 — the two projections share the same input slice by \
19393 construction, so any drift here would surface a silent \
19394 re-ordering / dedup / normalization detour in the resolver",
19395 );
19396 }
19397
19398 #[test]
19399 fn validate_reads_through_lifted_entrada_paths_accessor() {
19400 // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
19401 // per-entry value-shape gate's `for p in e.paths()` traversal
19402 // (which must reach every entry in the same order the accessor
19403 // projects, so both the per-entry `EntradaPathEmpty` /
19404 // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
19405 // the duplicate-detection HashSet insert that trips
19406 // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
19407 // projection) must route through the lifted accessor. Pins the
19408 // coherence by exercising each production consumer end-to-end:
19409 // (1) the `EntradaPathEmpty` refusal fires on the second entry
19410 // of a two-entry cohort whose head is valid but tail is empty
19411 // (which requires the loop to reach the second entry through
19412 // the accessor), and (2) the `EntradaPathDuplicate` refusal
19413 // fires on the second entry of a two-entry cohort that shares
19414 // a path (which requires the loop to reach both entries — a
19415 // first-entry-only projection would silently pass since the
19416 // dedup HashSet has room for the first insert).
19417 //
19418 // Peer of the sibling
19419 // `validate_placement_reads_through_lifted_clusters_accessor`
19420 // on the sibling `Placement::clusters` reader-site convergence.
19421 let base = crate::AplicacaoSpec {
19422 membros: vec![crate::Membro {
19423 caixa: "cart".into(),
19424 versao: "^0.1".into(),
19425 }],
19426 contratos: Vec::new(),
19427 politicas: crate::MeshPolicy::default(),
19428 placement: crate::Placement {
19429 estrategia: crate::PlacementStrategy::SingleNode,
19430 clusters: vec!["rio".into()],
19431 shard_key: None,
19432 affinity: None,
19433 },
19434 entrada: Some(Entrada {
19435 host: "example.com".into(),
19436 para: "cart".into(),
19437 paths: vec!["/api/cart".into(), String::new()],
19438 port: DEFAULT_SERVICO_PORT,
19439 }),
19440 };
19441 assert_eq!(
19442 base.validate(),
19443 Err(crate::AplicacaoError::EntradaPathEmpty),
19444 "validate must trip EntradaPathEmpty on the second entry of \
19445 a two-entry cohort — routing through the lifted paths() \
19446 accessor must not silently short-circuit the loop at the \
19447 valid head entry",
19448 );
19449
19450 let mut dup = base;
19451 dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
19452 assert_eq!(
19453 dup.validate(),
19454 Err(crate::AplicacaoError::EntradaPathDuplicate {
19455 path: "/api/cart".into(),
19456 }),
19457 "validate must trip EntradaPathDuplicate on the second entry \
19458 of a two-entry cohort that shares a path — routing through \
19459 the lifted paths() accessor must not silently short-circuit \
19460 the dedup HashSet insert at the first entry",
19461 );
19462 }
19463
19464 // ── Entrada::hostname / Entrada::hostnames — the substrate-
19465 // canonical per-`:entrada` DNS-hostname resolver pair every
19466 // Gateway-API-aware renderer reaching for a per-listener
19467 // singular `hostname:` filter (Gateway) or a per-route plural
19468 // `spec.hostnames[]` filter list (HTTPRoute) routes through.
19469 // The three pin tests below fix the two-way accept-set the pair
19470 // must always honor: (:singular-byte-equal-to-host,
19471 // :plural-is-singleton-of-singular, :plural-len-is-one) — drift
19472 // on any arm surfaces at caixa-core build time rather than at
19473 // cluster-apply time when the API server refuses the HTTPRoute
19474 // for non-intersecting hostname filters. Peer discipline with
19475 // the sibling `resolved_paths` accept-set pin block above on the
19476 // per-`:entrada` path-list resolver axis.
19477
19478 fn entrada_with_host(host: &str) -> Entrada {
19479 Entrada {
19480 host: host.into(),
19481 para: "cart".into(),
19482 paths: Vec::new(),
19483 port: DEFAULT_SERVICO_PORT,
19484 }
19485 }
19486
19487 #[test]
19488 fn hostname_returns_entrada_host_byte_equal() {
19489 // The canonical singular-axis pin: [`Entrada::hostname`] must
19490 // return the `:entrada :host` field byte-for-byte, borrowed
19491 // from the typed slot's own [`String`] storage. Pins against a
19492 // future silent detour that re-normalized the host (an
19493 // accidental `.to_lowercase()` — validate_entrada_host already
19494 // enforces lowercase, so any re-normalization is redundant + a
19495 // drift surface between the validator and the accessor), a
19496 // trailing-`.` fully-qualified DNS shape substitution, or a
19497 // Punycode round-trip that lowered a Unicode host through IDNA.
19498 let e = entrada_with_host("checkout.quero.cloud");
19499 assert_eq!(
19500 e.hostname(),
19501 "checkout.quero.cloud",
19502 "Entrada::hostname must return :entrada :host verbatim \
19503 (got {:?})",
19504 e.hostname(),
19505 );
19506 assert_eq!(
19507 e.hostname(),
19508 e.host.as_str(),
19509 "Entrada::hostname must byte-equal the .host field access",
19510 );
19511 }
19512
19513 #[test]
19514 fn hostnames_returns_singleton_of_hostname_accessor() {
19515 // The pair-invariant pin: [`Entrada::hostnames`] must always
19516 // return exactly `vec![hostname()]` — the singleton list whose
19517 // sole entry is the substrate's canonical per-`:entrada`
19518 // singular hostname. Pins the two-consumer coherence axis: the
19519 // Gateway listener's singular `hostname:` filter and the
19520 // HTTPRoute's plural `spec.hostnames[]` filter list must
19521 // agree, else the Gateway API v1.x conformance layer rejects
19522 // the HTTPRoute at attach time with
19523 // `Accepted:False/NoMatchingParent` (the parent Gateway's
19524 // listener hostname doesn't intersect the route's hostname
19525 // filter list) — a divergence whose apply-time symptom is far
19526 // from any single-site commit and never surfaces in the
19527 // emitted YAML. Pinning the pair-invariant here makes any
19528 // future accidental split (an accidental `.to_string() + "."`
19529 // trailing-`.` on the plural side that didn't land on the
19530 // singular side, an accidental prefix stripping on one axis,
19531 // an accidental wildcard prepend the SNI fan-out overlay
19532 // authors on the plural side without a paired singular
19533 // migration) trip at caixa-core build time.
19534 let e = entrada_with_host("checkout.quero.cloud");
19535 assert_eq!(
19536 e.hostnames(),
19537 vec![e.hostname()],
19538 "Entrada::hostnames must return `vec![hostname()]` under \
19539 the pair-invariant — got {:?} vs. singleton {:?}",
19540 e.hostnames(),
19541 vec![e.hostname()],
19542 );
19543 }
19544
19545 #[test]
19546 fn hostnames_is_singleton_under_single_host_author_surface() {
19547 // The singleton-shape pin: under today's single-hostname-per-
19548 // `:entrada` author surface (the `:host` slot is a single
19549 // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
19550 // must always return a list of length exactly one. Pins
19551 // against a future silent detour that returned an empty list
19552 // (which would emit an HTTPRoute with `spec.hostnames: []` —
19553 // matching every incoming Host header regardless of the
19554 // Aplicacao's declared ingress apex, silently over-matching
19555 // every foreign VirtualHost the parent Gateway also fronts) or
19556 // a duplicated entry (which the Gateway API v1.x parser
19557 // accepts as a `[]-length-2 list of equal hostnames]` but
19558 // whose semantics differ from the intended singleton). The
19559 // author-surface extension point ("a future `:entrada
19560 // :alt-hosts` list overlay" the docstring names) is the sole
19561 // future axis that flips this pin — that migration will re-
19562 // author this test to pin the new plural cardinality.
19563 let e = entrada_with_host("checkout.quero.cloud");
19564 assert_eq!(
19565 e.hostnames().len(),
19566 1,
19567 "Entrada::hostnames must be a singleton under today's \
19568 single-hostname-per-`:entrada` author surface — got \
19569 length {}: {:?}",
19570 e.hostnames().len(),
19571 e.hostnames(),
19572 );
19573 }
19574
19575 // ── Entrada::destination — the substrate-canonical per-`:entrada`
19576 // destination-Servico scalar accessor every Gateway-API
19577 // HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
19578 // discriminator arg (HTTPRoute name composer) or a per-rule
19579 // `backendRefs[0].name` axis routes through. The two pin tests
19580 // below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
19581 // either arm surfaces at caixa-core build time rather than at
19582 // cluster-apply time when an HTTPRoute's `metadata.name` and
19583 // `backendRefs[]` silently disagree on which destination Servico
19584 // the ingress fronts. Peer discipline with the sibling
19585 // `resolved_paths` + `hostname` + `hostnames` accept-set pin
19586 // blocks above on the per-`:entrada` path-list / DNS-hostname
19587 // resolver axes.
19588
19589 #[test]
19590 fn destination_returns_entrada_para_byte_equal() {
19591 // The canonical destination-scalar pin: [`Entrada::destination`]
19592 // must return the `:entrada :para` field byte-for-byte, borrowed
19593 // from the typed slot's own [`String`] storage. Pins against a
19594 // future silent detour that re-normalized the destination (an
19595 // accidental `.to_lowercase()` — the destination Servico is
19596 // already validated as a DNS-1123 label upstream, so any
19597 // re-normalization is redundant + a drift surface between the
19598 // validator and the accessor), a namespace-prefix rewrite (an
19599 // accidental `format!("{namespace}/{para}")` per-CR fully-
19600 // qualified rewrite that didn't land on the peer axis), or a
19601 // per-cluster suffix stamp the operator authors on one
19602 // consumer without the other.
19603 for para in ["cart", "checkout", "catalog", "orders-v2"] {
19604 let e = Entrada {
19605 host: "checkout.quero.cloud".into(),
19606 para: para.into(),
19607 paths: Vec::new(),
19608 port: DEFAULT_SERVICO_PORT,
19609 };
19610 assert_eq!(
19611 e.destination(),
19612 para,
19613 "Entrada::destination must return :entrada :para verbatim \
19614 (got {:?}, expected {para:?})",
19615 e.destination(),
19616 );
19617 assert_eq!(
19618 e.destination(),
19619 e.para.as_str(),
19620 "Entrada::destination must byte-equal the .para field access",
19621 );
19622 }
19623 }
19624
19625 #[test]
19626 fn destination_borrows_from_entrada_para_storage() {
19627 // The borrow-not-copy pin: [`Entrada::destination`] must
19628 // return a `&str` slice that borrows from the typed slot's
19629 // own [`String`] storage — same-address invariant with
19630 // `entrada.para.as_str()`. Pins against a future silent detour
19631 // that allocated a fresh `String` (`self.para.clone()` in the
19632 // body would type-check but silently drop the borrow, and
19633 // every downstream consumer that assumed the returned slice
19634 // outlives `&self` would break on a stale-reference use-after-
19635 // free). Peer with the sibling `hostname_returns_entrada_
19636 // host_byte_equal` on the singular-DNS-hostname axis.
19637 let e = entrada_with_host("checkout.quero.cloud");
19638 let dest = e.destination();
19639 let para_slice = e.para.as_str();
19640 assert_eq!(
19641 dest.as_ptr(),
19642 para_slice.as_ptr(),
19643 "Entrada::destination must borrow from the .para String's \
19644 backing storage — a fresh allocation here means the \
19645 accessor no longer names the substrate-primitive typed \
19646 dispatch and every downstream consumer would silently \
19647 carry a detached copy",
19648 );
19649 assert_eq!(
19650 dest.len(),
19651 para_slice.len(),
19652 "Entrada::destination and .para.as_str() must byte-equal in \
19653 length as well as in address",
19654 );
19655 }
19656
19657 #[test]
19658 fn port_returns_entrada_port_verbatim_across_permutations() {
19659 // The canonical L4-port-scalar pin: [`Entrada::port`] must
19660 // return the `:entrada :port` field verbatim as a `u16` across
19661 // every author-declared value in the validated accept-set
19662 // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
19663 // silent detour that clamped the port (an accidental
19664 // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
19665 // land on the peer [`AplicacaoSpec::port_for_destination`]
19666 // resolver), rewrote it through a per-cluster port-remap table
19667 // the operator authors on one consumer without the other, or
19668 // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
19669 // serde-default value (which would silently collapse the
19670 // distinction between "author explicitly declared `:port 8080`"
19671 // and "author omitted the slot and inherited the default" the
19672 // future per-cluster override slot depends on). Peer with the
19673 // sibling `destination_returns_entrada_para_byte_equal` +
19674 // `hostname_returns_entrada_host_byte_equal` pins on the
19675 // per-`:entrada` `&str` scalar axes.
19676 for port in [
19677 SERVICO_PORT_MIN,
19678 DEFAULT_SERVICO_PORT,
19679 8443u16,
19680 9090u16,
19681 u16::MAX,
19682 ] {
19683 let e = Entrada {
19684 host: "checkout.quero.cloud".into(),
19685 para: "cart".into(),
19686 paths: Vec::new(),
19687 port,
19688 };
19689 assert_eq!(
19690 e.port(),
19691 port,
19692 "Entrada::port must return :entrada :port verbatim \
19693 (got {}, expected {port})",
19694 e.port(),
19695 );
19696 assert_eq!(
19697 e.port(),
19698 e.port,
19699 "Entrada::port accessor and .port field access must \
19700 byte-equal — the accessor is the substrate-primitive \
19701 typed dispatch every downstream L4-port consumer must \
19702 route through",
19703 );
19704 }
19705 }
19706
19707 #[test]
19708 fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
19709 // Two-consumer coherence pin: the
19710 // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
19711 // (which reads through [`Entrada::port`] to compare against
19712 // [`SERVICO_PORT_MIN`]) and the
19713 // [`AplicacaoSpec::port_for_destination`] resolver (which reads
19714 // through [`Entrada::port`] to emit the per-destination
19715 // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
19716 // lifted accessor, so any future rebrand on the typed slot's
19717 // reader shape lands at exactly one place. Pins the two-site
19718 // coherence by exercising a below-floor port through validate
19719 // (which must reject) and a validated in-accept-set port through
19720 // port_for_destination (which must emit the same value the
19721 // accessor returns).
19722 let mut spec = three_member_spec();
19723 if let Some(e) = spec.entrada.as_mut() {
19724 e.port = 0;
19725 }
19726 assert_eq!(
19727 spec.validate().unwrap_err(),
19728 AplicacaoError::EntradaPortZero,
19729 "validate must reject `:entrada :port 0` through the lifted \
19730 Entrada::port accessor — port zero lies below \
19731 SERVICO_PORT_MIN and the validator routes through port() \
19732 to name the floor",
19733 );
19734
19735 for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
19736 let mut spec = three_member_spec();
19737 if let Some(e) = spec.entrada.as_mut() {
19738 e.port = port;
19739 }
19740 spec.validate().expect(
19741 "entrada with in-accept-set :port must validate — the \
19742 structural-floor gate reads through Entrada::port",
19743 );
19744 let entrada_ref = spec.entrada().expect(":entrada present");
19745 assert_eq!(
19746 spec.port_for_destination(entrada_ref.destination()),
19747 entrada_ref.port(),
19748 "port_for_destination(entrada.destination()) must equal \
19749 entrada.port() — the two consumers of the per-:entrada \
19750 L4-port axis (validator, per-destination resolver) both \
19751 route through Entrada::port",
19752 );
19753 }
19754 }
19755
19756 #[test]
19757 fn wit_contract_source_returns_de_byte_equal_across_permutations() {
19758 // The canonical caller-Servico-scalar pin: [`WitContract::source`]
19759 // must return the `:contratos :de` field byte-for-byte, borrowed
19760 // from the typed slot's own [`String`] storage. Peer of the
19761 // sibling `destination_returns_entrada_para_byte_equal` pin on
19762 // the per-`:entrada` axis — same "the substrate-primitive
19763 // accessor must byte-equal the raw field access verbatim across
19764 // every author-declared value" discipline extended to the
19765 // per-`:contratos` caller arm. Pins against a future silent
19766 // detour that re-normalized the caller (an accidental
19767 // `.to_lowercase()` — every `:contratos :de` is validated as a
19768 // DNS-1123 label upstream via `validate_contrato_caixa`, so any
19769 // re-normalization is redundant + a drift surface between the
19770 // validator and the accessor), a namespace-prefix rewrite (an
19771 // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
19772 // rewrite that didn't land on the peer axis), or a per-cluster
19773 // suffix stamp the operator authors on one consumer without the
19774 // other.
19775 for de in ["cart", "checkout", "catalog", "orders-v2"] {
19776 let c = WitContract {
19777 de: de.into(),
19778 para: "downstream".into(),
19779 wit: "wasi:http/proxy".into(),
19780 endpoint: Some("/lookup".into()),
19781 subject: None,
19782 slot: None,
19783 };
19784 assert_eq!(
19785 c.source(),
19786 de,
19787 "WitContract::source must return :contratos :de verbatim \
19788 (got {:?}, expected {de:?})",
19789 c.source(),
19790 );
19791 assert_eq!(
19792 c.source(),
19793 c.de.as_str(),
19794 "WitContract::source must byte-equal the .de field access",
19795 );
19796 }
19797 }
19798
19799 #[test]
19800 fn wit_contract_source_borrows_from_de_storage() {
19801 // The borrow-not-copy pin: [`WitContract::source`] must return a
19802 // `&str` slice that borrows from the typed slot's own [`String`]
19803 // storage — same-address invariant with `c.de.as_str()`. Pins
19804 // against a future silent detour that allocated a fresh `String`
19805 // (`self.de.clone()` in the body would type-check but silently
19806 // drop the borrow, and every downstream consumer that assumed
19807 // the returned slice outlives `&self` would break on a stale-
19808 // reference use-after-free). Peer of the sibling
19809 // `destination_borrows_from_entrada_para_storage` on the
19810 // per-`:entrada` axis.
19811 let c = WitContract {
19812 de: "cart".into(),
19813 para: "catalog".into(),
19814 wit: "wasi:http/proxy".into(),
19815 endpoint: Some("/lookup".into()),
19816 subject: None,
19817 slot: None,
19818 };
19819 let src = c.source();
19820 let de_slice = c.de.as_str();
19821 assert_eq!(
19822 src.as_ptr(),
19823 de_slice.as_ptr(),
19824 "WitContract::source must borrow from the .de String's \
19825 backing storage — a fresh allocation here means the \
19826 accessor no longer names the substrate-primitive typed \
19827 dispatch and every downstream consumer would silently \
19828 carry a detached copy",
19829 );
19830 assert_eq!(
19831 src.len(),
19832 de_slice.len(),
19833 "WitContract::source and .de.as_str() must byte-equal in \
19834 length as well as in address",
19835 );
19836 }
19837
19838 #[test]
19839 fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
19840 // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
19841 // must return the `:contratos :para` field byte-for-byte,
19842 // borrowed from the typed slot's own [`String`] storage. Peer of
19843 // the sibling `destination_returns_entrada_para_byte_equal` on
19844 // the per-`:entrada` axis — both accessors name "the destination-
19845 // Servico byte-string" concept on their respective mesh-slot
19846 // atoms (per-ingress apex vs. per-typed-edge callee) and both
19847 // must project the underlying `.para` field verbatim so every
19848 // downstream renderer that composes them with peer accessors
19849 // (e.g. `spec.port_for_destination(c.destination())` at the CNP
19850 // per-edge L4 port emit site) reads the same byte-string the
19851 // author declared.
19852 for para in ["catalog", "payment", "orders", "inventory-v3"] {
19853 let c = WitContract {
19854 de: "cart".into(),
19855 para: para.into(),
19856 wit: "wasi:http/proxy".into(),
19857 endpoint: Some("/lookup".into()),
19858 subject: None,
19859 slot: None,
19860 };
19861 assert_eq!(
19862 c.destination(),
19863 para,
19864 "WitContract::destination must return :contratos :para \
19865 verbatim (got {:?}, expected {para:?})",
19866 c.destination(),
19867 );
19868 assert_eq!(
19869 c.destination(),
19870 c.para.as_str(),
19871 "WitContract::destination must byte-equal the .para \
19872 field access",
19873 );
19874 }
19875 }
19876
19877 #[test]
19878 fn wit_contract_destination_borrows_from_para_storage() {
19879 // The borrow-not-copy pin: [`WitContract::destination`] must
19880 // return a `&str` slice that borrows from the typed slot's own
19881 // [`String`] storage — same-address invariant with
19882 // `c.para.as_str()`. Peer of the sibling
19883 // `destination_borrows_from_entrada_para_storage` on the
19884 // per-`:entrada` axis.
19885 let c = WitContract {
19886 de: "cart".into(),
19887 para: "catalog".into(),
19888 wit: "wasi:http/proxy".into(),
19889 endpoint: Some("/lookup".into()),
19890 subject: None,
19891 slot: None,
19892 };
19893 let dest = c.destination();
19894 let para_slice = c.para.as_str();
19895 assert_eq!(
19896 dest.as_ptr(),
19897 para_slice.as_ptr(),
19898 "WitContract::destination must borrow from the .para \
19899 String's backing storage — a fresh allocation here means \
19900 the accessor no longer names the substrate-primitive typed \
19901 dispatch and every downstream consumer would silently \
19902 carry a detached copy",
19903 );
19904 assert_eq!(
19905 dest.len(),
19906 para_slice.len(),
19907 "WitContract::destination and .para.as_str() must byte-equal \
19908 in length as well as in address",
19909 );
19910 }
19911
19912 #[test]
19913 fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
19914 // The canonical per-`:contratos` WIT-world-reference scalar pin:
19915 // [`WitContract::world_ref`] must return the `:contratos :wit`
19916 // field byte-for-byte, borrowed from the typed slot's own
19917 // [`String`] storage. Sibling of the peer per-`:contratos`
19918 // [`WitContract::source`] / [`WitContract::destination`]
19919 // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
19920 // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
19921 // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
19922 // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
19923 // "the substrate-primitive accessor must byte-equal the raw
19924 // field access verbatim across every author-declared value"
19925 // discipline extended to the per-`:contratos` WIT-world arm.
19926 // Pins against a future silent detour that re-canonicalized the
19927 // WIT world reference (an accidental `.to_lowercase()` pass that
19928 // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
19929 // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
19930 // gate is already lowercase-prefixed so any re-normalization is
19931 // redundant + a drift surface between the validator and the
19932 // accessor), an M4-promotion-shape rewrite that formatted a
19933 // typed WIT-world enum through [`Display`] and silently drifted
19934 // the printer output from the source `caixa.lisp`, or a per-
19935 // cluster WIT-alias rewrite that didn't land on the peer field-
19936 // access sites. Five values sweep the shape-dispatch accept-set
19937 // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
19938 // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
19939 // `wasi:keyvalue/`).
19940 for (wit, endpoint, subject, slot) in [
19941 ("wasi:http/proxy", Some("/lookup"), None, None),
19942 ("http:proxy", Some("/health"), None, None),
19943 ("nats:pub-sub", None, Some("orders.paid"), None),
19944 ("kafka:events", None, Some("checkout-events"), None),
19945 ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
19946 ] {
19947 let c = WitContract {
19948 de: "cart".into(),
19949 para: "downstream".into(),
19950 wit: wit.into(),
19951 endpoint: endpoint.map(str::to_string),
19952 subject: subject.map(str::to_string),
19953 slot: slot.map(str::to_string),
19954 };
19955 assert_eq!(
19956 c.world_ref(),
19957 wit,
19958 "WitContract::world_ref must return :contratos :wit \
19959 verbatim (got {:?}, expected {wit:?})",
19960 c.world_ref(),
19961 );
19962 assert_eq!(
19963 c.world_ref(),
19964 c.wit.as_str(),
19965 "WitContract::world_ref must byte-equal the .wit field \
19966 access",
19967 );
19968 }
19969 }
19970
19971 #[test]
19972 fn wit_contract_world_ref_borrows_from_wit_storage() {
19973 // The borrow-not-copy pin: [`WitContract::world_ref`] must
19974 // return a `&str` slice that borrows from the typed slot's own
19975 // [`String`] storage — same-address invariant with
19976 // `c.wit.as_str()`. Pins against a future silent detour that
19977 // allocated a fresh `String` (`self.wit.clone()` in the body
19978 // would type-check but silently drop the borrow, and every
19979 // downstream consumer that assumed the returned slice outlives
19980 // `&self` would break on a stale-reference use-after-free — the
19981 // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
19982 // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
19983 // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
19984 // / [`is_pubsub`][WitContract::is_pubsub] /
19985 // [`is_store`][WitContract::is_store] methods route through —
19986 // each borrow from the WitContract's own storage and each would
19987 // silently misbehave if this accessor produced a detached copy).
19988 // Peer of the sibling per-`:contratos` [`WitContract::source`] /
19989 // [`WitContract::destination`] and per-`:entrada`
19990 // [`Entrada::destination`] / [`Entrada::hostname`] and
19991 // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
19992 // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
19993 let c = WitContract {
19994 de: "cart".into(),
19995 para: "catalog".into(),
19996 wit: "wasi:http/proxy".into(),
19997 endpoint: Some("/lookup".into()),
19998 subject: None,
19999 slot: None,
20000 };
20001 let world = c.world_ref();
20002 let wit_slice = c.wit.as_str();
20003 assert_eq!(
20004 world.as_ptr(),
20005 wit_slice.as_ptr(),
20006 "WitContract::world_ref must borrow from the .wit String's \
20007 backing storage — a fresh allocation here means the \
20008 accessor no longer names the substrate-primitive typed \
20009 dispatch and every downstream consumer would silently carry \
20010 a detached copy",
20011 );
20012 assert_eq!(
20013 world.len(),
20014 wit_slice.len(),
20015 "WitContract::world_ref and .wit.as_str() must byte-equal in \
20016 length as well as in address",
20017 );
20018 }
20019
20020 #[test]
20021 fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
20022 // Sibling-triple invariant pin composing all three per-`:contratos`
20023 // substrate-primitive typed dispatches — [`WitContract::source`]
20024 // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
20025 // [`WitContract::world_ref`] — at the joint
20026 // `(source(), destination(), world_ref())` call shape every
20027 // renderer that fans on per-edge caller-callee-shape identity
20028 // keys off. The invariant, evaluated per-contract:
20029 //
20030 // (c.source(), c.destination(), c.world_ref())
20031 // == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
20032 //
20033 // Closes the last unlifted per-`:contratos` scalar axis — every
20034 // downstream consumer that reads the triple now routes through
20035 // exactly three typed dispatches on the substrate primitive,
20036 // not two typed + one open-coded field access. A future refactor
20037 // that silently split any one accessor's projection (an
20038 // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
20039 // canonicalization that didn't reach the peer `source`/
20040 // `destination` arms, an accidental `source()` per-cluster
20041 // caller-alias rewrite that didn't land on the `world_ref` peer)
20042 // surfaces at caixa-core build time. Peer of the sibling per-
20043 // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
20044 // per-`:entrada` `(hostname(), destination())` (6db982c /
20045 // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
20046 // axes, extended to the per-`:contratos` triple.
20047 for (de, para, wit, endpoint, subject, slot) in [
20048 (
20049 "cart",
20050 "catalog",
20051 "wasi:http/proxy",
20052 Some("/lookup"),
20053 None,
20054 None,
20055 ),
20056 (
20057 "checkout",
20058 "orders",
20059 "nats:pub-sub",
20060 None,
20061 Some("orders.paid"),
20062 None,
20063 ),
20064 (
20065 "cart",
20066 "kv",
20067 "wasi:keyvalue/store",
20068 None,
20069 None,
20070 Some("carts/{cart_id}"),
20071 ),
20072 (
20073 "orders-v2",
20074 "inventory-v3",
20075 "http:proxy",
20076 Some("/reserve"),
20077 None,
20078 None,
20079 ),
20080 ] {
20081 let c = WitContract {
20082 de: de.into(),
20083 para: para.into(),
20084 wit: wit.into(),
20085 endpoint: endpoint.map(str::to_string),
20086 subject: subject.map(str::to_string),
20087 slot: slot.map(str::to_string),
20088 };
20089 assert_eq!(
20090 (c.source(), c.destination(), c.world_ref()),
20091 (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
20092 "(WitContract::source, ::destination, ::world_ref) must \
20093 project (.de, .para, .wit) verbatim across every author-\
20094 declared triple (got ({:?}, {:?}, {:?}), expected \
20095 ({de:?}, {para:?}, {wit:?}))",
20096 c.source(),
20097 c.destination(),
20098 c.world_ref(),
20099 );
20100 }
20101 }
20102
20103 #[test]
20104 fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
20105 // The canonical per-`:contratos` owned-form caller-callee-pair
20106 // pin: [`WitContract::edge_pair`] must return the
20107 // `(source(), destination())` tuple in owned form byte-for-byte,
20108 // projected through the lifted [`WitContract::source`] /
20109 // [`WitContract::destination`] scalar accessors. Pins the
20110 // composite-projection invariant on the per-`:contratos`
20111 // mesh-slot atom — every author-declared `(de, para)` pair must
20112 // round-trip verbatim through the substrate primitive's typed
20113 // dispatch, so the nine [`AplicacaoError`] diagnostic-
20114 // construction sites the accessor now feeds
20115 // ([`AplicacaoError::EmptyWit`],
20116 // [`AplicacaoError::ContratoEndpointEmpty`],
20117 // [`AplicacaoError::ContratoEndpointNotAbsolute`],
20118 // [`AplicacaoError::ContratoEndpointInvalid`],
20119 // [`AplicacaoError::ContratoSubjectEmpty`],
20120 // [`AplicacaoError::ContratoSubjectInvalid`],
20121 // [`AplicacaoError::ContratoSlotEmpty`],
20122 // [`AplicacaoError::ContratoSlotInvalid`],
20123 // [`AplicacaoError::ContratoDuplicate`]) all read the same
20124 // `(de, para)` label pair every author sees at the source
20125 // `caixa.lisp`. Pins against a future silent detour that swapped
20126 // the `.0` / `.1` arms (an accidental `(destination(),
20127 // source())` re-order in the body would silently invert every
20128 // downstream diagnostic's `de:` / `para:` label pair, silently
20129 // reversing the direction of every operator-facing typed error
20130 // arrow), a fresh-allocation shape drift (an accidental
20131 // `.to_string()` on one arm but not the other would leave the
20132 // owned/borrowed pair mismatched vs. the sibling `source()` /
20133 // `destination()` returns), or an M4 per-cluster caller/callee-
20134 // alias rewrite that landed on `source()` without reaching
20135 // `destination()` (or vice versa). Peer of the sibling per-
20136 // `:contratos` `(source, destination, world_ref)` triple
20137 // pin above on the mesh-slot-atom scalar-value axes, extended
20138 // to the owned-form pair-projection axis.
20139 for (de, para, wit, endpoint, subject, slot) in [
20140 (
20141 "cart",
20142 "catalog",
20143 "wasi:http/proxy",
20144 Some("/lookup"),
20145 None,
20146 None,
20147 ),
20148 (
20149 "checkout",
20150 "orders",
20151 "nats:pub-sub",
20152 None,
20153 Some("orders.paid"),
20154 None,
20155 ),
20156 (
20157 "cart",
20158 "kv",
20159 "wasi:keyvalue/store",
20160 None,
20161 None,
20162 Some("carts/{cart_id}"),
20163 ),
20164 (
20165 "orders-v2",
20166 "inventory-v3",
20167 "http:proxy",
20168 Some("/reserve"),
20169 None,
20170 None,
20171 ),
20172 ] {
20173 let c = WitContract {
20174 de: de.into(),
20175 para: para.into(),
20176 wit: wit.into(),
20177 endpoint: endpoint.map(str::to_string),
20178 subject: subject.map(str::to_string),
20179 slot: slot.map(str::to_string),
20180 };
20181 assert_eq!(
20182 c.edge_pair(),
20183 (de.to_string(), para.to_string()),
20184 "WitContract::edge_pair must return (:contratos :de, \
20185 :contratos :para) as an owned tuple verbatim (got {:?}, \
20186 expected ({de:?}, {para:?}))",
20187 c.edge_pair(),
20188 );
20189 }
20190 }
20191
20192 #[test]
20193 fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
20194 // The composition pin: [`WitContract::edge_pair`] must return
20195 // exactly `(source().to_string(), destination().to_string())` —
20196 // the owned form of the sibling accessor pair — so any future
20197 // refactor that silently re-authored the caller-arm / callee-arm
20198 // projection to bypass the lifted scalar accessors (an accidental
20199 // `(self.de.clone(), self.para.clone())` regression back to the
20200 // raw field-access shape, an M4-typed-caller-enum `Display`
20201 // re-canonicalization on `source()` that didn't reach
20202 // `edge_pair()`, a per-cluster alias rewrite the operator lands
20203 // on `destination()` without reaching this composite projection)
20204 // trips at caixa-core build time. Pins the "typed dispatch
20205 // composes with typed dispatch, not with raw field access"
20206 // discipline every downstream diagnostic-construction site now
20207 // routes through — a `de:` / `para:` label pair whose
20208 // projection silently drifted off the substrate primitive's
20209 // scalar accessors would silently split the diagnostic's self-
20210 // locating signal from the source `caixa.lisp` author's view.
20211 // Peer of the sibling per-`:politicas` `is_empty` /
20212 // `validate_politicas` accessor-routing-pin family on the M3
20213 // mesh-slot family (18575, 18739, 18918, 19140, 19371).
20214 let c = WitContract {
20215 de: "cart".into(),
20216 para: "catalog".into(),
20217 wit: "wasi:http/proxy".into(),
20218 endpoint: Some("/lookup".into()),
20219 subject: None,
20220 slot: None,
20221 };
20222 assert_eq!(
20223 c.edge_pair(),
20224 (c.source().to_string(), c.destination().to_string()),
20225 "WitContract::edge_pair must compose exactly \
20226 (source().to_string(), destination().to_string()) — a \
20227 bypass of either sibling accessor here would silently \
20228 decouple the composite-projection axis from the \
20229 substrate-primitive scalar accessors every downstream \
20230 consumer routes through",
20231 );
20232 }
20233
20234 #[test]
20235 fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
20236 {
20237 // The canonical per-`:contratos` owned-form
20238 // caller-callee-world-ref-triple pin:
20239 // [`WitContract::edge_triple`] must return the
20240 // `(source(), destination(), world_ref())` tuple in owned form
20241 // byte-for-byte, projected through the lifted
20242 // [`WitContract::source`] / [`WitContract::destination`] /
20243 // [`WitContract::world_ref`] scalar accessors. Pins the
20244 // composite-projection invariant on the per-`:contratos`
20245 // mesh-slot atom — every author-declared `(de, para, wit)`
20246 // triple must round-trip verbatim through the substrate
20247 // primitive's typed dispatch, so the nine
20248 // [`AplicacaoError`] diagnostic-construction sites the
20249 // accessor now feeds (the [`WitTarget`]-dispatch's eight
20250 // wrong-target / missing-target / invalid-wit / capability-
20251 // with-payload arms in [`WitContract::target`], plus the
20252 // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
20253 // diagnostic constructor in [`AplicacaoSpec::validate`]) all
20254 // read the same `(de, para, wit)` triple every author sees at
20255 // the source `caixa.lisp`. Pins against a future silent
20256 // detour that swapped any two arms (an accidental `(destination(),
20257 // source(), world_ref())` re-order in the body would silently
20258 // invert every downstream diagnostic's `de:` / `para:` label
20259 // pair, silently reversing the direction of every operator-
20260 // facing typed error arrow), a fresh-allocation shape drift
20261 // (an accidental `.to_string()` skipped on one arm would leave
20262 // the owned/borrowed triple mismatched vs. the sibling
20263 // `source()` / `destination()` / `world_ref()` returns), or an
20264 // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
20265 // canonicalization pass that landed on one accessor without
20266 // reaching the peers. Peer of the sibling per-`:contratos`
20267 // caller-callee-pair
20268 // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
20269 // pin on the mesh-slot-atom composite-projection axis,
20270 // extended to the triple-projection axis.
20271 for (de, para, wit, endpoint, subject, slot) in [
20272 (
20273 "cart",
20274 "catalog",
20275 "wasi:http/proxy",
20276 Some("/lookup"),
20277 None,
20278 None,
20279 ),
20280 (
20281 "checkout",
20282 "orders",
20283 "nats:pub-sub",
20284 None,
20285 Some("orders.paid"),
20286 None,
20287 ),
20288 (
20289 "cart",
20290 "kv",
20291 "wasi:keyvalue/store",
20292 None,
20293 None,
20294 Some("carts/{cart_id}"),
20295 ),
20296 (
20297 "orders-v2",
20298 "inventory-v3",
20299 "http:proxy",
20300 Some("/reserve"),
20301 None,
20302 None,
20303 ),
20304 ] {
20305 let c = WitContract {
20306 de: de.into(),
20307 para: para.into(),
20308 wit: wit.into(),
20309 endpoint: endpoint.map(str::to_string),
20310 subject: subject.map(str::to_string),
20311 slot: slot.map(str::to_string),
20312 };
20313 assert_eq!(
20314 c.edge_triple(),
20315 (de.to_string(), para.to_string(), wit.to_string()),
20316 "WitContract::edge_triple must return (:contratos :de, \
20317 :contratos :para, :contratos :wit) as an owned triple \
20318 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
20319 c.edge_triple(),
20320 );
20321 }
20322 }
20323
20324 #[test]
20325 fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
20326 // The composition pin: [`WitContract::edge_triple`] must return
20327 // exactly `(source().to_string(), destination().to_string(),
20328 // world_ref().to_string())` — the owned form of the sibling
20329 // scalar-accessor triple — so any future refactor that silently
20330 // re-authored one arm's projection to bypass the lifted scalar
20331 // accessors (an accidental `(self.de.clone(), self.para.clone(),
20332 // self.wit.clone())` regression back to the raw field-access
20333 // shape the internal `edge` closure and the ContratoDuplicate
20334 // diagnostic both carried before this lift landed, an
20335 // M4-typed-caller-enum `Display` re-canonicalization on
20336 // `source()` that didn't reach `edge_triple()`, a per-cluster
20337 // alias rewrite the operator lands on `destination()` /
20338 // `world_ref()` without reaching this composite projection)
20339 // trips at caixa-core build time. Pins the "typed dispatch
20340 // composes with typed dispatch, not with raw field access"
20341 // discipline every downstream diagnostic-construction site now
20342 // routes through — a `de:` / `para:` / `wit:` triple whose
20343 // projection silently drifted off the substrate primitive's
20344 // scalar accessors would silently split the diagnostic's self-
20345 // locating signal from the source `caixa.lisp` author's view.
20346 // Peer of the sibling per-`:contratos` edge_pair composition-
20347 // pin above on the mesh-slot-atom composite-projection axis.
20348 let c = WitContract {
20349 de: "cart".into(),
20350 para: "catalog".into(),
20351 wit: "wasi:http/proxy".into(),
20352 endpoint: Some("/lookup".into()),
20353 subject: None,
20354 slot: None,
20355 };
20356 assert_eq!(
20357 c.edge_triple(),
20358 (
20359 c.source().to_string(),
20360 c.destination().to_string(),
20361 c.world_ref().to_string(),
20362 ),
20363 "WitContract::edge_triple must compose exactly \
20364 (source().to_string(), destination().to_string(), \
20365 world_ref().to_string()) — a bypass of any sibling accessor \
20366 here would silently decouple the composite-projection axis \
20367 from the substrate-primitive scalar accessors every \
20368 downstream consumer routes through",
20369 );
20370 }
20371
20372 #[test]
20373 fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
20374 // The canonical semantics-pin: [`WitContract::edge_triple`] must
20375 // project the full `(de, para, wit)` identity of a `:contratos`
20376 // edge — the sub-triple every triple-carrying
20377 // [`AplicacaoError::Contrato*`] diagnostic weaves into its
20378 // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
20379 // missing-target, capability-with-payload, invalid-wit, and the
20380 // duplicate-gate). Rejects a drift in shape (an accidental
20381 // silent detour that returned a `(de, para)` pair or added an
20382 // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
20383 // would trip here because the return type would no longer
20384 // pattern-match the eight `let (de, para, wit) = edge();`
20385 // destructures the [`WitContract::target`] dispatch feeds off
20386 // + the paired duplicate-gate `let (de, para, wit) =
20387 // c.edge_triple();` destructure in
20388 // [`AplicacaoSpec::validate`]). Peer of the sibling per-
20389 // `:contratos` caller-callee-pair pin above extended to the
20390 // triple projection surface: closes the "one composite
20391 // accessor per typed diagnostic-construction sub-tuple"
20392 // discipline on the per-`:contratos` mesh-slot-atom axis.
20393 let c = WitContract {
20394 de: "checkout".into(),
20395 para: "orders".into(),
20396 wit: "nats:pub-sub".into(),
20397 endpoint: None,
20398 subject: Some("orders.paid".into()),
20399 slot: None,
20400 };
20401 let (de, para, wit) = c.edge_triple();
20402 assert_eq!(de, "checkout");
20403 assert_eq!(para, "orders");
20404 assert_eq!(wit, "nats:pub-sub");
20405 }
20406
20407 #[test]
20408 fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
20409 {
20410 // The composition pin: [`WitContract::identity`] must return
20411 // exactly `(source(), destination(), world_ref(), endpoint(),
20412 // subject(), slot())` — the borrowed form of the six-scalar-
20413 // accessor identity axis. Any future refactor that silently
20414 // re-authored one arm's projection to bypass a scalar accessor
20415 // (a `self.de.as_str()` regression back to raw field access on
20416 // any of the three required arms, a `self.endpoint.as_deref()`
20417 // regression on any of the three optional arms, an M4 per-
20418 // cluster caller/callee-alias rewrite the operator lands on
20419 // `source()` / `destination()` without reaching this composite
20420 // projection) trips at caixa-core build time. Sweeps four
20421 // permutations of the WIT-shape × payload lattice — HTTP with
20422 // endpoint, pub-sub with subject, store with slot, payload-less
20423 // capability — so every payload arm is exercised. Peer of the
20424 // sibling per-`:contratos`
20425 // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
20426 // composition pin on the mesh-slot-atom composite-projection
20427 // axis; extends the discipline from the (de, para, wit) prefix
20428 // onto the full-identity axis carrying the three payload arms.
20429 for (de, para, wit, endpoint, subject, slot) in [
20430 (
20431 "cart",
20432 "catalog",
20433 "wasi:http/proxy",
20434 Some("/lookup"),
20435 None,
20436 None,
20437 ),
20438 (
20439 "checkout",
20440 "orders",
20441 "nats:pub-sub",
20442 None,
20443 Some("orders.paid"),
20444 None,
20445 ),
20446 (
20447 "cart",
20448 "kv",
20449 "wasi:keyvalue/store",
20450 None,
20451 None,
20452 Some("carts/{cart_id}"),
20453 ),
20454 ("audit", "sink", "wasi:logging", None, None, None),
20455 ] {
20456 let c = WitContract {
20457 de: de.into(),
20458 para: para.into(),
20459 wit: wit.into(),
20460 endpoint: endpoint.map(str::to_owned),
20461 subject: subject.map(str::to_owned),
20462 slot: slot.map(str::to_owned),
20463 };
20464 assert_eq!(
20465 c.identity(),
20466 (
20467 c.source(),
20468 c.destination(),
20469 c.world_ref(),
20470 c.endpoint(),
20471 c.subject(),
20472 c.slot(),
20473 ),
20474 "WitContract::identity must compose exactly \
20475 (source(), destination(), world_ref(), endpoint(), \
20476 subject(), slot()) — a bypass of any sibling accessor \
20477 here would silently decouple the identity-projection \
20478 axis from the substrate-primitive scalar accessors \
20479 every dedup-key consumer routes through",
20480 );
20481 }
20482 }
20483
20484 #[test]
20485 fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
20486 // The canonical semantics-pin: [`WitContract::identity`] must
20487 // project the six-axis (de, para, wit, endpoint, subject, slot)
20488 // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
20489 // gate keys off — two `WitContract`s that agree on all six axes
20490 // are the same typed edge declared twice, the graph-edge
20491 // analogue of duplicate `:membros` / `:placement :clusters` /
20492 // `:entrada :paths` entries. Rejects a shape drift (an
20493 // accidental silent detour that returned a prefix tuple or
20494 // added an extra field) by pattern-matching the six-arm shape.
20495 // Peer of the sibling per-`:contratos`
20496 // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
20497 // pin extended from the (de, para, wit) prefix onto the full
20498 // six-axis identity that the dedup key rides.
20499 let c = WitContract {
20500 de: "cart".into(),
20501 para: "catalog".into(),
20502 wit: "wasi:http/proxy".into(),
20503 endpoint: Some("/products/:id".into()),
20504 subject: None,
20505 slot: None,
20506 };
20507 let (de, para, wit, endpoint, subject, slot) = c.identity();
20508 assert_eq!(de, "cart");
20509 assert_eq!(para, "catalog");
20510 assert_eq!(wit, "wasi:http/proxy");
20511 assert_eq!(endpoint, Some("/products/:id"));
20512 assert_eq!(subject, None);
20513 assert_eq!(slot, None);
20514
20515 // Two byte-identical contracts must produce equal identities —
20516 // the dedup key's foundational invariant.
20517 let c2 = c.clone();
20518 assert_eq!(c.identity(), c2.identity());
20519
20520 // Any change on any of the six axes must break the identity —
20521 // sweeps by mutating one axis at a time.
20522 let mut mutated = c.clone();
20523 mutated.de = "search".into();
20524 assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
20525 let mut mutated = c.clone();
20526 mutated.para = "warehouse".into();
20527 assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
20528 let mut mutated = c.clone();
20529 mutated.wit = "http:legacy".into();
20530 assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
20531 let mut mutated = c.clone();
20532 mutated.endpoint = Some("/search".into());
20533 assert_ne!(
20534 c.identity(),
20535 mutated.identity(),
20536 "endpoint axis must partition"
20537 );
20538 let mut mutated = c.clone();
20539 mutated.subject = Some("orders.paid".into());
20540 assert_ne!(
20541 c.identity(),
20542 mutated.identity(),
20543 "subject axis must partition"
20544 );
20545 let mut mutated = c;
20546 mutated.slot = Some("carts/{id}".into());
20547 assert_ne!(mutated.identity().5, None, "slot axis must partition");
20548 }
20549
20550 #[test]
20551 fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
20552 // The canonical per-`:contratos` structural-self-edge pin:
20553 // [`WitContract::is_self_loop`] must return `true` when the
20554 // `:de` and `:para` fields agree byte-for-byte, across every
20555 // WIT-shape variant the per-edge shape family carries. Pins
20556 // the shape-agnostic identity-space partition the
20557 // [`AplicacaoSpec::validate`] self-edge gate at
20558 // caixa-core/src/aplicacao.rs:5559 fires against — all four
20559 // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
20560 // under the same one predicate. Four permutations sweep the
20561 // accept-set: HTTP with endpoint, pub-sub with subject, KV
20562 // store with slot, and payload-less capability.
20563 for (nome, wit, endpoint, subject, slot) in [
20564 ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
20565 ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
20566 (
20567 "kv",
20568 "wasi:keyvalue/store",
20569 None,
20570 None,
20571 Some("carts/{cart_id}"),
20572 ),
20573 ("audit", "wasi:logging", None, None, None),
20574 ] {
20575 let c = WitContract {
20576 de: nome.into(),
20577 para: nome.into(),
20578 wit: wit.into(),
20579 endpoint: endpoint.map(str::to_string),
20580 subject: subject.map(str::to_string),
20581 slot: slot.map(str::to_string),
20582 };
20583 assert!(
20584 c.is_self_loop(),
20585 "WitContract::is_self_loop must return true when \
20586 :contratos :de == :contratos :para (got false on \
20587 {nome:?} under {wit:?})",
20588 );
20589 }
20590 }
20591
20592 #[test]
20593 fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
20594 // The complement pin: [`WitContract::is_self_loop`] must return
20595 // `false` on every well-shaped inter-Servico contract (the
20596 // author-intended `:contratos` shape MESH-COMPOSITION §III.1
20597 // names — "Servico A calls Servico B" between two distinct
20598 // graph nodes). Pins against a future silent detour that
20599 // inverted the predicate (an accidental `!= ` swap for `==`
20600 // would silently reject every legitimate inter-Servico edge
20601 // and admit every self-edge — the exact inversion of the
20602 // author-intended shape). Four permutations sweep the same
20603 // WIT-shape accept-set the sibling positive-arm test carries.
20604 for (de, para, wit, endpoint, subject, slot) in [
20605 (
20606 "cart",
20607 "catalog",
20608 "wasi:http/proxy",
20609 Some("/lookup"),
20610 None,
20611 None,
20612 ),
20613 (
20614 "checkout",
20615 "orders",
20616 "nats:pub-sub",
20617 None,
20618 Some("orders.paid"),
20619 None,
20620 ),
20621 (
20622 "cart",
20623 "kv",
20624 "wasi:keyvalue/store",
20625 None,
20626 None,
20627 Some("carts/{cart_id}"),
20628 ),
20629 ("audit", "sink", "wasi:logging", None, None, None),
20630 ] {
20631 let c = WitContract {
20632 de: de.into(),
20633 para: para.into(),
20634 wit: wit.into(),
20635 endpoint: endpoint.map(str::to_string),
20636 subject: subject.map(str::to_string),
20637 slot: slot.map(str::to_string),
20638 };
20639 assert!(
20640 !c.is_self_loop(),
20641 "WitContract::is_self_loop must return false when \
20642 :contratos :de differs from :contratos :para (got true \
20643 on {de:?} → {para:?} under {wit:?})",
20644 );
20645 }
20646 }
20647
20648 #[test]
20649 fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
20650 // The composition pin: [`WitContract::is_self_loop`] must
20651 // resolve to exactly `self.source() == self.destination()` —
20652 // the equality probe of the sibling scalar-accessor pair — so
20653 // any future refactor that silently re-authored the predicate
20654 // to bypass the lifted scalar accessors (an accidental
20655 // `self.de == self.para` regression back to the raw field-
20656 // access shape, an M4-typed-caller-enum identity-comparison
20657 // rule that landed on `source()` without reaching
20658 // `destination()`, a per-cluster alias rewrite the operator
20659 // pins on `destination()` without reaching this predicate)
20660 // trips at caixa-core build time. Pins the "typed dispatch
20661 // composes with typed dispatch, not with raw field access"
20662 // discipline the sibling [`WitContract::edge_pair`] /
20663 // [`WitContract::edge_triple`] composite-projection accessors
20664 // already carry, extended onto the per-edge endpoint-equality
20665 // predicate axis. Positive and complement arms both fire.
20666 let self_edge = WitContract {
20667 de: "cart".into(),
20668 para: "cart".into(),
20669 wit: "wasi:http/proxy".into(),
20670 endpoint: Some("/lookup".into()),
20671 subject: None,
20672 slot: None,
20673 };
20674 assert_eq!(
20675 self_edge.is_self_loop(),
20676 self_edge.source() == self_edge.destination(),
20677 "WitContract::is_self_loop must compose exactly \
20678 `source() == destination()` — a bypass of either sibling \
20679 accessor here would silently decouple the endpoint-\
20680 equality predicate from the substrate-primitive scalar \
20681 accessors every downstream consumer routes through",
20682 );
20683 let inter_edge = WitContract {
20684 de: "cart".into(),
20685 para: "catalog".into(),
20686 wit: "wasi:http/proxy".into(),
20687 endpoint: Some("/lookup".into()),
20688 subject: None,
20689 slot: None,
20690 };
20691 assert_eq!(
20692 inter_edge.is_self_loop(),
20693 inter_edge.source() == inter_edge.destination(),
20694 "WitContract::is_self_loop must compose exactly \
20695 `source() == destination()` on the complement arm too",
20696 );
20697 }
20698
20699 #[test]
20700 fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
20701 // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
20702 // pin: [`WitContract::endpoint`] must return the `:contratos
20703 // :endpoint` field byte-for-byte, borrowed from the typed slot's
20704 // own `Option<String>` storage. Peer of the sibling
20705 // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
20706 // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
20707 // mesh-slot `Option<String>` optional-scalar axes — same "the
20708 // substrate-primitive accessor must byte-equal the raw field
20709 // access verbatim across every author-declared value" discipline
20710 // extended to the per-`:contratos` HTTP-payload-carrier arm.
20711 // Pins against a future silent detour that re-canonicalized the
20712 // endpoint (an accidental percent-encoding pass that didn't
20713 // reach the peer field-access site at the dedup key, a per-CR
20714 // fully-qualified prefix rewrite the operator authors on one
20715 // consumer without the other, or an M4 typed-path-template
20716 // `Display` re-canonicalization that silently drifted the
20717 // printer output from the source `caixa.lisp`). Four values
20718 // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
20719 // gate upstream admits (short root-path, dashed, param-shaped,
20720 // deep-hierarchy).
20721 for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
20722 let c = WitContract {
20723 de: "cart".into(),
20724 para: "catalog".into(),
20725 wit: "wasi:http/proxy".into(),
20726 endpoint: Some(endpoint.into()),
20727 subject: None,
20728 slot: None,
20729 };
20730 assert_eq!(
20731 c.endpoint(),
20732 Some(endpoint),
20733 "WitContract::endpoint must return :contratos :endpoint \
20734 verbatim (got {:?}, expected Some({endpoint:?}))",
20735 c.endpoint(),
20736 );
20737 assert_eq!(
20738 c.endpoint(),
20739 c.endpoint.as_deref(),
20740 "WitContract::endpoint must byte-equal the .endpoint \
20741 field's `.as_deref()` projection",
20742 );
20743 }
20744 }
20745
20746 #[test]
20747 fn wit_contract_endpoint_none_when_field_is_none() {
20748 // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
20749 // payload-carrier accessor pin: when the typed slot is absent —
20750 // the canonical shape under a non-HTTP `:wit` world per the
20751 // [`WitContract::target`]-enforced shape ↔ target partition
20752 // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
20753 // carries `:slot`, [`WitTarget::Capability`] carries none) —
20754 // [`WitContract::endpoint`] must return `None`. Pins against a
20755 // future silent detour that projected the absent slot to a
20756 // `Some("")` empty-string default (the canonical `Option<String>`
20757 // → `String` collapse footgun the sibling M2
20758 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
20759 // emptiness predicates already guard on the peer M2 typed-slot
20760 // surfaces), a `Some("None")` stringified-None round-trip, or a
20761 // `Some` arm whose contents were derived from a sibling slot (an
20762 // accidental fallback to the `:subject` / `:slot` payload that
20763 // read the pub-sub / store payload into the endpoint axis).
20764 // Three contracts sweep the accept-set every non-HTTP `:wit`
20765 // world lands on — pub-sub NATS, key/value, and payload-less
20766 // capability.
20767 for (wit, subject, slot) in [
20768 ("nats:pub-sub", Some("orders.paid"), None),
20769 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
20770 ("wasi:cli/environment", None, None),
20771 ] {
20772 let c = WitContract {
20773 de: "cart".into(),
20774 para: "downstream".into(),
20775 wit: wit.into(),
20776 endpoint: None,
20777 subject: subject.map(str::to_string),
20778 slot: slot.map(str::to_string),
20779 };
20780 assert!(
20781 c.endpoint().is_none(),
20782 "WitContract::endpoint must return None when the typed \
20783 slot is absent under :wit {wit:?} (got {:?})",
20784 c.endpoint(),
20785 );
20786 assert_eq!(
20787 c.endpoint(),
20788 c.endpoint.as_deref(),
20789 "WitContract::endpoint must byte-equal the .endpoint \
20790 field's `.as_deref()` projection in the absent arm",
20791 );
20792 }
20793 }
20794
20795 #[test]
20796 fn wit_contract_endpoint_borrows_from_endpoint_storage() {
20797 // The borrow-not-copy pin: [`WitContract::endpoint`] must return
20798 // an `Option<&str>` whose `Some` arm borrows from the typed
20799 // slot's own [`String`] storage — same-address invariant with
20800 // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
20801 // detour that allocated a fresh `String`
20802 // (`self.endpoint.clone().map(...)` in the body would type-check
20803 // but silently drop the borrow, and every downstream consumer
20804 // that assumed the returned slice outlives `&self` would break
20805 // on a stale-reference use-after-free — the [`WitContract::target`]
20806 // Http-arm payload extraction rebinds the returned `Option<&str>`
20807 // through `.ok_or_else(...)` and threads the `&str` payload into
20808 // [`WitTarget::Http { endpoint: &'a str }`], the
20809 // [`AplicacaoSpec::validate`] duplicate-`:contratos`
20810 // [`ContratoIdentity`] dedup key threads the returned
20811 // `Option<&str>` into the six-tuple's HTTP arm — each borrow
20812 // from the WitContract's own storage and each would silently
20813 // misbehave if this accessor produced a detached copy). Peer of
20814 // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
20815 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
20816 // shaped optional-scalar axes — first extension of the
20817 // `Option<&str>` borrow-not-copy discipline onto the
20818 // per-`:contratos` HTTP-shaped payload-carrier axis.
20819 let c = WitContract {
20820 de: "cart".into(),
20821 para: "catalog".into(),
20822 wit: "wasi:http/proxy".into(),
20823 endpoint: Some("/lookup".into()),
20824 subject: None,
20825 slot: None,
20826 };
20827 let ep = c.endpoint().expect("Some arm");
20828 let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
20829 assert_eq!(
20830 ep.as_ptr(),
20831 storage_slice.as_ptr(),
20832 "WitContract::endpoint must borrow from the .endpoint \
20833 String's backing storage — a fresh allocation here means \
20834 the accessor no longer names the substrate-primitive typed \
20835 dispatch and every downstream consumer would silently \
20836 carry a detached copy",
20837 );
20838 assert_eq!(
20839 ep.len(),
20840 storage_slice.len(),
20841 "WitContract::endpoint and .endpoint.as_deref() must byte-\
20842 equal in length as well as in address",
20843 );
20844 }
20845
20846 #[test]
20847 fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
20848 // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
20849 // pin: [`WitContract::subject`] must return the `:contratos
20850 // :subject` field byte-for-byte, borrowed from the typed slot's
20851 // own `Option<String>` storage. Peer of the sibling per-`:contratos`
20852 // [`WitContract::endpoint`] (7020470) accessor pin on the M3
20853 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
20854 // optional-scalar axis — same "the substrate-primitive accessor
20855 // must byte-equal the raw field access verbatim across every
20856 // author-declared value" discipline extended to the pub-sub arm.
20857 // Pins against a future silent detour that re-canonicalized the
20858 // subject (an accidental `.to_lowercase()` normalization that
20859 // didn't reach the peer field-access site at the dedup key, a
20860 // per-CR fully-qualified prefix rewrite the operator authors on
20861 // one consumer without the other, or an M4 typed-subject-template
20862 // `Display` re-canonicalization that silently drifted the printer
20863 // output from the source `caixa.lisp`). Four values sweep the
20864 // NATS accept-set every pub-sub author-declared subject lands on
20865 // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
20866 for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
20867 let c = WitContract {
20868 de: "cart".into(),
20869 para: "notifier".into(),
20870 wit: "nats:pub-sub".into(),
20871 endpoint: None,
20872 subject: Some(subject.into()),
20873 slot: None,
20874 };
20875 assert_eq!(
20876 c.subject(),
20877 Some(subject),
20878 "WitContract::subject must return :contratos :subject \
20879 verbatim (got {:?}, expected Some({subject:?}))",
20880 c.subject(),
20881 );
20882 assert_eq!(
20883 c.subject(),
20884 c.subject.as_deref(),
20885 "WitContract::subject must byte-equal the .subject \
20886 field's `.as_deref()` projection",
20887 );
20888 }
20889 }
20890
20891 #[test]
20892 fn wit_contract_subject_none_when_field_is_none() {
20893 // The absent-`:subject` arm of the per-`:contratos` pub-sub-
20894 // shaped payload-carrier accessor pin: when the typed slot is
20895 // absent — the canonical shape under a non-pub-sub `:wit` world
20896 // per the [`WitContract::target`]-enforced shape ↔ target
20897 // partition ([`WitTarget::Http`] carries `:endpoint`,
20898 // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
20899 // carries none) — [`WitContract::subject`] must return `None`.
20900 // Pins against a future silent detour that projected the absent
20901 // slot to a `Some("")` empty-string default (the canonical
20902 // `Option<String>` → `String` collapse footgun the sibling M2
20903 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
20904 // emptiness predicates already guard on the peer M2 typed-slot
20905 // surfaces), a `Some("None")` stringified-None round-trip, or a
20906 // `Some` arm whose contents were derived from a sibling slot (an
20907 // accidental fallback to the `:endpoint` / `:slot` payload that
20908 // read the HTTP / store payload into the subject axis). Three
20909 // contracts sweep the accept-set every non-pub-sub `:wit` world
20910 // lands on — HTTP proxy, key/value store, and payload-less
20911 // capability.
20912 for (wit, endpoint, slot) in [
20913 ("wasi:http/proxy", Some("/lookup"), None),
20914 ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
20915 ("wasi:cli/environment", None, None),
20916 ] {
20917 let c = WitContract {
20918 de: "cart".into(),
20919 para: "downstream".into(),
20920 wit: wit.into(),
20921 endpoint: endpoint.map(str::to_string),
20922 subject: None,
20923 slot: slot.map(str::to_string),
20924 };
20925 assert!(
20926 c.subject().is_none(),
20927 "WitContract::subject must return None when the typed \
20928 slot is absent under :wit {wit:?} (got {:?})",
20929 c.subject(),
20930 );
20931 assert_eq!(
20932 c.subject(),
20933 c.subject.as_deref(),
20934 "WitContract::subject must byte-equal the .subject \
20935 field's `.as_deref()` projection in the absent arm",
20936 );
20937 }
20938 }
20939
20940 #[test]
20941 fn wit_contract_subject_borrows_from_subject_storage() {
20942 // The borrow-not-copy pin: [`WitContract::subject`] must return
20943 // an `Option<&str>` whose `Some` arm borrows from the typed
20944 // slot's own [`String`] storage — same-address invariant with
20945 // `c.subject.as_deref().unwrap()`. Pins against a future silent
20946 // detour that allocated a fresh `String`
20947 // (`self.subject.clone().map(...)` in the body would type-check
20948 // but silently drop the borrow, and every downstream consumer
20949 // that assumed the returned slice outlives `&self` would break
20950 // on a stale-reference use-after-free — the [`WitContract::target`]
20951 // PubSub-arm payload extraction rebinds the returned
20952 // `Option<&str>` through `.ok_or_else(...)` and threads the
20953 // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
20954 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
20955 // [`ContratoIdentity`] dedup key threads the returned
20956 // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
20957 // from the WitContract's own storage and each would silently
20958 // misbehave if this accessor produced a detached copy). Peer of
20959 // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
20960 // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
20961 // shaped optional-scalar axis — second extension of the
20962 // `Option<&str>` borrow-not-copy discipline onto the
20963 // per-`:contratos` payload-carrier family, this time on the
20964 // pub-sub arm.
20965 let c = WitContract {
20966 de: "cart".into(),
20967 para: "notifier".into(),
20968 wit: "nats:pub-sub".into(),
20969 endpoint: None,
20970 subject: Some("orders.paid".into()),
20971 slot: None,
20972 };
20973 let sub = c.subject().expect("Some arm");
20974 let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
20975 assert_eq!(
20976 sub.as_ptr(),
20977 storage_slice.as_ptr(),
20978 "WitContract::subject must borrow from the .subject \
20979 String's backing storage — a fresh allocation here means \
20980 the accessor no longer names the substrate-primitive typed \
20981 dispatch and every downstream consumer would silently \
20982 carry a detached copy",
20983 );
20984 assert_eq!(
20985 sub.len(),
20986 storage_slice.len(),
20987 "WitContract::subject and .subject.as_deref() must byte-\
20988 equal in length as well as in address",
20989 );
20990 }
20991
20992 #[test]
20993 fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
20994 // The canonical per-`:contratos` key/value-store-shaped
20995 // `:slot`-scalar pin: [`WitContract::slot`] must return the
20996 // `:contratos :slot` field byte-for-byte, borrowed from the
20997 // typed slot's own `Option<String>` storage. Peer of the
20998 // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
20999 // [`WitContract::subject`] (90de675) accessor pins on the M3
21000 // mesh-slot per-`:contratos` payload-carrier `Option<String>`
21001 // optional-scalar axis — same "the substrate-primitive
21002 // accessor must byte-equal the raw field access verbatim
21003 // across every author-declared value" discipline extended to
21004 // the store arm. Pins against a future silent detour that
21005 // re-canonicalized the slot template (an accidental
21006 // `.to_lowercase()` bucket-prefix normalization that didn't
21007 // reach the peer field-access site at the dedup key, a per-CR
21008 // fully-qualified prefix rewrite the operator authors on one
21009 // consumer without the other, or an M4 typed-key-template
21010 // `Display` re-canonicalization that silently drifted the
21011 // printer output from the source `caixa.lisp`). Four values
21012 // sweep the wasi:keyvalue accept-set every store-shaped
21013 // author-declared slot lands on (flat bucket, single-param
21014 // template, multi-param template, nested-hierarchy template).
21015 for slot in [
21016 "sessions",
21017 "carts/{cart_id}",
21018 "orders/{tenant}/{order_id}",
21019 "cache/tenant-a/orders/{id}",
21020 ] {
21021 let c = WitContract {
21022 de: "cart".into(),
21023 para: "kv".into(),
21024 wit: "wasi:keyvalue/store".into(),
21025 endpoint: None,
21026 subject: None,
21027 slot: Some(slot.into()),
21028 };
21029 assert_eq!(
21030 c.slot(),
21031 Some(slot),
21032 "WitContract::slot must return :contratos :slot \
21033 verbatim (got {:?}, expected Some({slot:?}))",
21034 c.slot(),
21035 );
21036 assert_eq!(
21037 c.slot(),
21038 c.slot.as_deref(),
21039 "WitContract::slot must byte-equal the .slot field's \
21040 `.as_deref()` projection",
21041 );
21042 }
21043 }
21044
21045 #[test]
21046 fn wit_contract_slot_none_when_field_is_none() {
21047 // The absent-`:slot` arm of the per-`:contratos` store-shaped
21048 // payload-carrier accessor pin: when the typed slot is absent —
21049 // the canonical shape under a non-store `:wit` world per the
21050 // [`WitContract::target`]-enforced shape ↔ target partition
21051 // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
21052 // carries `:subject`, [`WitTarget::Capability`] carries none) —
21053 // [`WitContract::slot`] must return `None`. Pins against a
21054 // future silent detour that projected the absent slot to a
21055 // `Some("")` empty-string default (the canonical
21056 // `Option<String>` → `String` collapse footgun the sibling M2
21057 // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
21058 // emptiness predicates already guard on the peer M2 typed-slot
21059 // surfaces), a `Some("None")` stringified-None round-trip, or
21060 // a `Some` arm whose contents were derived from a sibling
21061 // slot (an accidental fallback to the `:endpoint` / `:subject`
21062 // payload that read the HTTP / pub-sub payload into the store
21063 // axis). Three contracts sweep the accept-set every non-store
21064 // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
21065 // payload-less capability.
21066 for (wit, endpoint, subject) in [
21067 ("wasi:http/proxy", Some("/lookup"), None),
21068 ("nats:pub-sub", None, Some("orders.paid")),
21069 ("wasi:cli/environment", None, None),
21070 ] {
21071 let c = WitContract {
21072 de: "cart".into(),
21073 para: "downstream".into(),
21074 wit: wit.into(),
21075 endpoint: endpoint.map(str::to_string),
21076 subject: subject.map(str::to_string),
21077 slot: None,
21078 };
21079 assert!(
21080 c.slot().is_none(),
21081 "WitContract::slot must return None when the typed \
21082 slot is absent under :wit {wit:?} (got {:?})",
21083 c.slot(),
21084 );
21085 assert_eq!(
21086 c.slot(),
21087 c.slot.as_deref(),
21088 "WitContract::slot must byte-equal the .slot field's \
21089 `.as_deref()` projection in the absent arm",
21090 );
21091 }
21092 }
21093
21094 #[test]
21095 fn wit_contract_slot_borrows_from_slot_storage() {
21096 // The borrow-not-copy pin: [`WitContract::slot`] must return
21097 // an `Option<&str>` whose `Some` arm borrows from the typed
21098 // slot's own [`String`] storage — same-address invariant with
21099 // `c.slot.as_deref().unwrap()`. Pins against a future silent
21100 // detour that allocated a fresh `String`
21101 // (`self.slot.clone().map(...)` in the body would type-check
21102 // but silently drop the borrow, and every downstream consumer
21103 // that assumed the returned slice outlives `&self` would
21104 // break on a stale-reference use-after-free — the
21105 // [`WitContract::target`] Store-arm payload extraction rebinds
21106 // the returned `Option<&str>` through `.ok_or_else(...)` and
21107 // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
21108 // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21109 // [`ContratoIdentity`] dedup key threads the returned
21110 // `Option<&str>` into the six-tuple's store arm — each borrow
21111 // from the WitContract's own storage and each would silently
21112 // misbehave if this accessor produced a detached copy). Peer
21113 // of the sibling per-`:contratos` [`WitContract::endpoint`]
21114 // (7020470) / [`WitContract::subject`] (90de675)
21115 // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
21116 // shaped optional-scalar axis — third and final extension of
21117 // the `Option<&str>` borrow-not-copy discipline onto the
21118 // per-`:contratos` payload-carrier family, this time on the
21119 // store arm.
21120 let c = WitContract {
21121 de: "cart".into(),
21122 para: "kv".into(),
21123 wit: "wasi:keyvalue/store".into(),
21124 endpoint: None,
21125 subject: None,
21126 slot: Some("carts/{cart_id}".into()),
21127 };
21128 let slot = c.slot().expect("Some arm");
21129 let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
21130 assert_eq!(
21131 slot.as_ptr(),
21132 storage_slice.as_ptr(),
21133 "WitContract::slot must borrow from the .slot String's \
21134 backing storage — a fresh allocation here means the \
21135 accessor no longer names the substrate-primitive typed \
21136 dispatch and every downstream consumer would silently \
21137 carry a detached copy",
21138 );
21139 assert_eq!(
21140 slot.len(),
21141 storage_slice.len(),
21142 "WitContract::slot and .slot.as_deref() must byte-equal \
21143 in length as well as in address",
21144 );
21145 }
21146
21147 #[test]
21148 fn membro_nome_returns_caixa_byte_equal_across_permutations() {
21149 // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
21150 // [`Membro::nome`] must return the `:membros :caixa` field
21151 // byte-for-byte, borrowed from the typed slot's own [`String`]
21152 // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
21153 // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
21154 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
21155 // slot-atom scalar-value axes — same "the substrate-primitive
21156 // accessor must byte-equal the raw field access verbatim across
21157 // every author-declared value" discipline extended to the
21158 // per-`:membros` member-identity arm. Pins against a future
21159 // silent detour that re-normalized the member identity (an
21160 // accidental `.to_lowercase()` — every `:membros :caixa` is
21161 // validated as a DNS-1123 label upstream via
21162 // [`validate_membro_caixa`], so any re-normalization is
21163 // redundant + a drift surface between the validator and the
21164 // accessor), a namespace-prefix rewrite (an accidental
21165 // `format!("{namespace}/{caixa}")` per-CR fully-qualified
21166 // rewrite that didn't land on the peer axes), or a per-cluster
21167 // alias stamp the operator authors on one consumer without the
21168 // other. Four values sweep the accept-set the DNS-1123 gate
21169 // upstream admits (short single-word / dashed / v-suffixed
21170 // member names).
21171 for name in ["cart", "checkout", "catalog", "orders-v2"] {
21172 let m = Membro {
21173 caixa: name.into(),
21174 versao: "^0.1".into(),
21175 };
21176 assert_eq!(
21177 m.nome(),
21178 name,
21179 "Membro::nome must return :membros :caixa verbatim \
21180 (got {:?}, expected {name:?})",
21181 m.nome(),
21182 );
21183 assert_eq!(
21184 m.nome(),
21185 m.caixa.as_str(),
21186 "Membro::nome must byte-equal the .caixa field access",
21187 );
21188 }
21189 }
21190
21191 #[test]
21192 fn membro_nome_borrows_from_caixa_storage() {
21193 // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
21194 // slice that borrows from the typed slot's own [`String`]
21195 // storage — same-address invariant with `m.caixa.as_str()`. Pins
21196 // against a future silent detour that allocated a fresh `String`
21197 // (`self.caixa.clone()` in the body would type-check but
21198 // silently drop the borrow, and every downstream consumer that
21199 // assumed the returned slice outlives `&self` would break on a
21200 // stale-reference use-after-free — the `HashSet<&str>` collector
21201 // at [`AplicacaoSpec::validate`]'s `names` seed, the
21202 // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
21203 // [`AplicacaoSpec::detect_sync_cycles`], the
21204 // [`crate::render::insert_first_seen`] dedup key at
21205 // [`AplicacaoSpec::validate_membros`] — each borrow from the
21206 // Membro's own storage and each would silently misbehave if
21207 // this accessor produced a detached copy). Peer of the sibling
21208 // per-`:contratos` [`WitContract::source`] /
21209 // [`WitContract::destination`] and per-`:entrada`
21210 // [`Entrada::destination`] borrow-invariant pins on the mesh-
21211 // slot-atom scalar-value axes.
21212 let m = Membro {
21213 caixa: "checkout".into(),
21214 versao: "^0.1".into(),
21215 };
21216 let name = m.nome();
21217 let caixa_slice = m.caixa.as_str();
21218 assert_eq!(
21219 name.as_ptr(),
21220 caixa_slice.as_ptr(),
21221 "Membro::nome must borrow from the .caixa String's backing \
21222 storage — a fresh allocation here means the accessor no \
21223 longer names the substrate-primitive typed dispatch and \
21224 every downstream consumer would silently carry a detached \
21225 copy",
21226 );
21227 assert_eq!(
21228 name.len(),
21229 caixa_slice.len(),
21230 "Membro::nome and .caixa.as_str() must byte-equal in length \
21231 as well as in address",
21232 );
21233 }
21234
21235 #[test]
21236 fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
21237 // The canonical per-`:membros` member-`:versao`-scalar pin:
21238 // [`Membro::versao_requirement`] must return the
21239 // `:membros :versao` field byte-for-byte, borrowed from the typed
21240 // slot's own [`String`] storage. Sibling of the peer
21241 // `membro_nome_returns_caixa_byte_equal_across_permutations`
21242 // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
21243 // — same "the substrate-primitive accessor must byte-equal the
21244 // raw field access verbatim across every author-declared value"
21245 // discipline extended to the per-`:membros` member-`:versao`
21246 // requirement-string arm. Pins against a future silent detour
21247 // that re-canonicalized the requirement (an accidental
21248 // `.to_string()` via [`parse_requirement`] → [`Display`] round-
21249 // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
21250 // drifted the printer output away from the source `caixa.lisp`,
21251 // an accidental whitespace trim on `"^ 0.1"` that no consumer
21252 // ever produced from the field-access side, an accidental
21253 // per-cluster lacre-projected concrete-version rewrite that
21254 // didn't land on the peer field-access sites). Five values sweep
21255 // the accept-set the shared
21256 // [`crate::render::require_valid_versao_requirement`] gate
21257 // admits (caret / tilde / exact / wildcard / bare-major).
21258 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
21259 let m = Membro {
21260 caixa: "cart".into(),
21261 versao: req.into(),
21262 };
21263 assert_eq!(
21264 m.versao_requirement(),
21265 req,
21266 "Membro::versao_requirement must return :membros :versao \
21267 verbatim (got {:?}, expected {req:?})",
21268 m.versao_requirement(),
21269 );
21270 assert_eq!(
21271 m.versao_requirement(),
21272 m.versao.as_str(),
21273 "Membro::versao_requirement must byte-equal the .versao \
21274 field access",
21275 );
21276 }
21277 }
21278
21279 #[test]
21280 fn membro_versao_requirement_borrows_from_versao_storage() {
21281 // The borrow-not-copy pin: [`Membro::versao_requirement`] must
21282 // return a `&str` slice that borrows from the typed slot's own
21283 // [`String`] storage — same-address invariant with
21284 // `m.versao.as_str()`. Pins against a future silent detour that
21285 // allocated a fresh `String` (`self.versao.clone()` in the body
21286 // would type-check but silently drop the borrow, and every
21287 // downstream consumer that assumed the returned slice outlives
21288 // `&self` would break on a stale-reference use-after-free). Peer
21289 // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
21290 // per-`:contratos` [`WitContract::source`] /
21291 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
21292 // [`Entrada::destination`] (6db982c) borrow-invariant pins on
21293 // the mesh-slot-atom scalar-value axes.
21294 let m = Membro {
21295 caixa: "checkout".into(),
21296 versao: "^0.1".into(),
21297 };
21298 let req = m.versao_requirement();
21299 let versao_slice = m.versao.as_str();
21300 assert_eq!(
21301 req.as_ptr(),
21302 versao_slice.as_ptr(),
21303 "Membro::versao_requirement must borrow from the .versao \
21304 String's backing storage — a fresh allocation here means \
21305 the accessor no longer names the substrate-primitive typed \
21306 dispatch and every downstream consumer would silently carry \
21307 a detached copy",
21308 );
21309 assert_eq!(
21310 req.len(),
21311 versao_slice.len(),
21312 "Membro::versao_requirement and .versao.as_str() must byte-\
21313 equal in length as well as in address",
21314 );
21315 }
21316
21317 #[test]
21318 fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
21319 // Sibling-pair invariant pin composing both per-`:membros`
21320 // substrate-primitive typed dispatches — [`Membro::nome`]
21321 // (4a32abf) and [`Membro::versao_requirement`] — at the joint
21322 // `(nome(), versao_requirement())` call shape every renderer
21323 // that fans on per-member identity + version pin keys off. The
21324 // invariant, evaluated per-member:
21325 //
21326 // (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
21327 //
21328 // Closes the last unlifted per-`:membros` scalar axis — every
21329 // downstream consumer that reads the pair now routes through
21330 // exactly two typed dispatches on the substrate primitive, not
21331 // one typed + one open-coded field access. A future refactor
21332 // that silently split either accessor's projection (an
21333 // accidental `nome()` namespace-prefix rewrite that didn't
21334 // reach the peer, an accidental `versao_requirement()` lacre-
21335 // projected concrete-version rewrite that didn't land on the
21336 // `nome()` peer) surfaces at caixa-core build time. Peer of the
21337 // sibling per-`:entrada` `(hostname(), destination())` and
21338 // per-`:contratos` `(source(), destination())` pair invariants
21339 // on the mesh-slot-atom scalar-value axes.
21340 for (caixa, versao) in [
21341 ("cart", "^0.1"),
21342 ("checkout", "~0.1.2"),
21343 ("catalog", "0.1.0"),
21344 ("orders-v2", "*"),
21345 ] {
21346 let m = Membro {
21347 caixa: caixa.into(),
21348 versao: versao.into(),
21349 };
21350 assert_eq!(
21351 (m.nome(), m.versao_requirement()),
21352 (m.caixa.as_str(), m.versao.as_str()),
21353 "(Membro::nome, Membro::versao_requirement) must project \
21354 (.caixa, .versao) verbatim across every author-declared \
21355 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
21356 m.nome(),
21357 m.versao_requirement(),
21358 );
21359 }
21360 }
21361
21362 #[test]
21363 fn validate_membros_empty_gate_routes_through_nome_accessor() {
21364 // Composition pin: [`AplicacaoSpec::validate_membros`]'s
21365 // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
21366 // not the raw `.caixa` field access. Structurally: setting
21367 // ONLY the `.caixa` field to `""` on an otherwise-well-formed
21368 // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
21369 // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
21370 // (i.e. the empty string) — so the emptiness predicate the
21371 // refusal arm reaches under is the accessor-projected value,
21372 // not a peer field that would silently drift under a future
21373 // accessor-side rewrite.
21374 //
21375 // Pins against a future silent detour that (a) re-derived the
21376 // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
21377 // instead of `self.nome().is_empty()`, silently disagreeing with
21378 // every peer consumer (the `validate_membro_caixa(m.nome())`
21379 // call one line below, the dedup-key `insert_first_seen(&mut
21380 // seen, m.nome(), …)` two lines below, the emit-side per-
21381 // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
21382 // (b) accessor-side introduced a per-tenant alias arm the
21383 // caller was unaware of, silently rewriting an author-declared
21384 // `:caixa "checkout"` to `""` — the raw-field-access gate
21385 // would fail-open while the accessor-routed peer consumers
21386 // would fail-closed, splitting the diagnostic from the actual
21387 // failure surface.
21388 //
21389 // Peer of the sibling
21390 // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
21391 // (c0110f1) composition pin — same "the shape-gate predicate
21392 // must route through the substrate-primitive typed dispatch"
21393 // discipline extended onto the per-`:membros` empty-`:caixa`
21394 // refusal-arm axis. Closes the last unlifted `.caixa` production-
21395 // code read site on `Membro` — after this converge every
21396 // caixa-core `.caixa` field access outside the accessor's own
21397 // body is either a test-side field-setter (in-module tests
21398 // constructing invalid-shape inputs) or a doc-comment reference.
21399 let mut s = three_member_spec();
21400 s.membros[1].caixa = String::new();
21401 assert!(
21402 s.membros[1].nome().is_empty(),
21403 "Membro::nome must byte-equal the .caixa field access — an \
21404 accessor-side detour that no longer projects the raw field \
21405 would silently split this drift-detection test from the \
21406 validate() refusal arm",
21407 );
21408 assert_eq!(
21409 s.membros[1].nome(),
21410 s.membros[1].caixa.as_str(),
21411 "Membro::nome and .caixa.as_str() must byte-equal on an \
21412 empty-`:caixa` entry — the emptiness gate keys off the \
21413 accessor by construction",
21414 );
21415 assert_eq!(
21416 s.validate().unwrap_err(),
21417 AplicacaoError::MembroCaixaEmpty,
21418 "validate_membros' emptiness gate must fire MembroCaixaEmpty \
21419 on an entry whose accessor-projected `nome()` is empty",
21420 );
21421 }
21422
21423 #[test]
21424 fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
21425 // The canonical per-`:placement` Akka-cluster-sharding
21426 // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
21427 // the `:placement :shard-key` field byte-for-byte, borrowed
21428 // from the typed slot's own `Option<String>` storage. Peer of
21429 // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
21430 // per-`:contratos` [`WitContract::source`] /
21431 // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
21432 // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
21433 // slot-atom scalar-value axes — same "the substrate-primitive
21434 // accessor must byte-equal the raw field access verbatim across
21435 // every author-declared value" discipline extended to the
21436 // per-`:placement` Akka-cluster-sharding key extractor arm.
21437 // Pins against a future silent detour that re-normalized the
21438 // key (an accidental `.to_lowercase()` — every non-empty
21439 // `:shard-key` is validated as a printable-ASCII single-token
21440 // reference upstream via [`validate_placement_shard_key`], so
21441 // any re-normalization is redundant + a drift surface between
21442 // the validator and the accessor), a per-cluster alias rewrite
21443 // the operator authors on one consumer without the other, or an
21444 // accidental variable-prefix strip (`$tenantId` → `tenantId`)
21445 // that didn't land on the peer field-access sites. Four values
21446 // sweep the accept-set the shape gate admits — bare identifier,
21447 // `$`-prefixed variable, dotted path, `${}`-quoted variable —
21448 // the four canonical Akka-style entity-id extractor shapes the
21449 // future M4 cluster-sharding reconciler hashes.
21450 for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
21451 let p = Placement {
21452 estrategia: PlacementStrategy::Sharded,
21453 clusters: vec!["rio".into()],
21454 affinity: None,
21455 shard_key: Some(key.into()),
21456 };
21457 assert_eq!(
21458 p.shard_key(),
21459 Some(key),
21460 "Placement::shard_key must return :placement :shard-key \
21461 verbatim (got {:?}, expected Some({key:?}))",
21462 p.shard_key(),
21463 );
21464 assert_eq!(
21465 p.shard_key(),
21466 p.shard_key.as_deref(),
21467 "Placement::shard_key must byte-equal the .shard_key \
21468 field's `.as_deref()` projection",
21469 );
21470 }
21471 }
21472
21473 #[test]
21474 fn placement_shard_key_none_when_field_is_none() {
21475 // The absent-`:shard-key` arm of the per-`:placement`
21476 // Akka-cluster-sharding accessor pin: when the typed slot is
21477 // absent — the canonical shape under `:estrategia Replicated` /
21478 // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
21479 // enforced `shard_key.is_some() == matches!(estrategia,
21480 // Sharded)` partition — [`Placement::shard_key`] must return
21481 // `None`. Pins against a future silent detour that projected
21482 // the absent slot to a `Some("")` empty-string default (the
21483 // canonical `Option<String>` → `String` collapse footgun the
21484 // sibling M2 [`crate::LimitsSpec::is_empty`] /
21485 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
21486 // already guard on the peer M2 typed-slot surfaces), a
21487 // `Some("None")` stringified-None round-trip, or a `Some` arm
21488 // whose contents were derived from a sibling slot (an
21489 // accidental fallback to `estrategia.as_str()` that read the
21490 // strategy discriminator into the key axis). Two placements
21491 // sweep the accept-set every `validate`-passing non-`Sharded`
21492 // shape lands on — `Replicated` (Erlang/OTP distributed-app
21493 // takeover) and `SingleNode` (single-node hosting).
21494 for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
21495 let p = Placement {
21496 estrategia,
21497 clusters: vec!["rio".into()],
21498 affinity: None,
21499 shard_key: None,
21500 };
21501 assert!(
21502 p.shard_key().is_none(),
21503 "Placement::shard_key must return None when the typed \
21504 slot is absent under :estrategia {estrategia:?} (got {:?})",
21505 p.shard_key(),
21506 );
21507 assert_eq!(
21508 p.shard_key(),
21509 p.shard_key.as_deref(),
21510 "Placement::shard_key must byte-equal the .shard_key \
21511 field's `.as_deref()` projection in the absent arm",
21512 );
21513 }
21514 }
21515
21516 #[test]
21517 fn placement_shard_key_borrows_from_shard_key_storage() {
21518 // The borrow-not-copy pin: [`Placement::shard_key`] must return
21519 // an `Option<&str>` whose `Some` arm borrows from the typed
21520 // slot's own [`String`] storage — same-address invariant with
21521 // `p.shard_key.as_deref().unwrap()`. Pins against a future
21522 // silent detour that allocated a fresh `String`
21523 // (`self.shard_key.clone().map(...)` in the body would type-
21524 // check but silently drop the borrow, and every downstream
21525 // consumer that assumed the returned slice outlives `&self`
21526 // would break on a stale-reference use-after-free — the
21527 // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
21528 // gate's `Some(k)`-bound match arm reads `k: &str` under the
21529 // accessor's return type and would silently misbehave if this
21530 // accessor produced a detached copy). Peer of the sibling
21531 // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
21532 // [`WitContract::source`] / [`WitContract::destination`]
21533 // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
21534 // (6db982c) borrow-invariant pins on the mesh-slot-atom
21535 // scalar-value axes — first extension of the discipline onto
21536 // an `Option<String>`-shaped optional-scalar axis.
21537 let p = Placement {
21538 estrategia: PlacementStrategy::Sharded,
21539 clusters: vec!["rio".into()],
21540 affinity: None,
21541 shard_key: Some("tenantId".into()),
21542 };
21543 let key = p.shard_key().expect("Some arm");
21544 let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
21545 assert_eq!(
21546 key.as_ptr(),
21547 storage_slice.as_ptr(),
21548 "Placement::shard_key must borrow from the .shard_key \
21549 String's backing storage — a fresh allocation here means \
21550 the accessor no longer names the substrate-primitive typed \
21551 dispatch and every downstream consumer would silently \
21552 carry a detached copy",
21553 );
21554 assert_eq!(
21555 key.len(),
21556 storage_slice.len(),
21557 "Placement::shard_key and .shard_key.as_deref() must byte-\
21558 equal in length as well as in address",
21559 );
21560 }
21561
21562 #[test]
21563 fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
21564 // The canonical per-`:placement` M3-Adaptive-compression-hint
21565 // scalar pin: [`Placement::affinity`] must return the
21566 // `:placement :affinity` field byte-for-byte, borrowed from the
21567 // typed slot's own `Option<String>` storage. Peer of the sibling
21568 // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
21569 // pin on the sibling `Option<&str>` optional-scalar axis — same
21570 // "the substrate-primitive accessor must byte-equal the raw
21571 // field access verbatim across every author-declared value"
21572 // discipline extended to the peer per-`:placement` M3-Adaptive-
21573 // compression-hint arm. Pins against a future silent detour
21574 // that re-normalized the hint (an accidental `.to_lowercase()`
21575 // — every `:affinity` is already validated as a DNS-1123 label
21576 // upstream via [`validate_placement_affinity`], so any re-
21577 // normalization is redundant + a drift surface between the
21578 // validator and the accessor), a per-cluster alias rewrite the
21579 // operator authors on one consumer without the other, or an
21580 // accidental hint-family collapse (`low-latency` → `latency`
21581 // that dropped the qualifier prefix). Four values sweep the
21582 // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
21583 // canonical adaptive-compression-weight biases the future M4
21584 // placement engine reads.
21585 for hint in [
21586 "data-locality",
21587 "low-latency",
21588 "high-throughput",
21589 "cost-optimized",
21590 ] {
21591 let p = Placement {
21592 estrategia: PlacementStrategy::Replicated,
21593 clusters: vec!["rio".into()],
21594 affinity: Some(hint.into()),
21595 shard_key: None,
21596 };
21597 assert_eq!(
21598 p.affinity(),
21599 Some(hint),
21600 "Placement::affinity must return :placement :affinity \
21601 verbatim (got {:?}, expected Some({hint:?}))",
21602 p.affinity(),
21603 );
21604 assert_eq!(
21605 p.affinity(),
21606 p.affinity.as_deref(),
21607 "Placement::affinity must byte-equal the .affinity \
21608 field's `.as_deref()` projection",
21609 );
21610 }
21611 }
21612
21613 #[test]
21614 fn placement_affinity_none_when_field_is_none() {
21615 // The absent-`:affinity` arm of the per-`:placement`
21616 // M3-Adaptive-compression-hint accessor pin: when the typed
21617 // slot is absent — the canonical shape of an Aplicacao that
21618 // leaves the compression weighting up to the placement engine's
21619 // cluster-default arm — [`Placement::affinity`] must return
21620 // `None`. Pins against a future silent detour that projected
21621 // the absent slot to a `Some("")` empty-string default (the
21622 // canonical `Option<String>` → `String` collapse footgun the
21623 // sibling M2 [`crate::LimitsSpec::is_empty`] /
21624 // [`crate::BehaviorSpec::is_empty`] emptiness predicates
21625 // already guard on the peer M2 typed-slot surfaces), a
21626 // `Some("None")` stringified-None round-trip, a `Some` arm
21627 // whose contents were derived from a sibling slot (an
21628 // accidental fallback to `estrategia.as_str()` that read the
21629 // strategy discriminator into the hint axis), or a
21630 // `Some("default")` implicit-default that would silently biases
21631 // the routing without the author having written one. Three
21632 // placements sweep the accept-set every `validate`-passing
21633 // `:affinity None` shape lands on — one per PlacementStrategy
21634 // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
21635 // with a shard-key), since `:affinity` is orthogonal to
21636 // `:estrategia` in the typed grammar.
21637 for (estrategia, shard_key) in [
21638 (PlacementStrategy::SingleNode, None),
21639 (PlacementStrategy::Replicated, None),
21640 (PlacementStrategy::Sharded, Some("tenantId".to_string())),
21641 ] {
21642 let p = Placement {
21643 estrategia,
21644 clusters: vec!["rio".into()],
21645 affinity: None,
21646 shard_key,
21647 };
21648 assert!(
21649 p.affinity().is_none(),
21650 "Placement::affinity must return None when the typed \
21651 slot is absent under :estrategia {estrategia:?} (got {:?})",
21652 p.affinity(),
21653 );
21654 assert_eq!(
21655 p.affinity(),
21656 p.affinity.as_deref(),
21657 "Placement::affinity must byte-equal the .affinity \
21658 field's `.as_deref()` projection in the absent arm",
21659 );
21660 }
21661 }
21662
21663 #[test]
21664 fn placement_affinity_borrows_from_affinity_storage() {
21665 // The borrow-not-copy pin: [`Placement::affinity`] must return
21666 // an `Option<&str>` whose `Some` arm borrows from the typed
21667 // slot's own [`String`] storage — same-address invariant with
21668 // `p.affinity.as_deref().unwrap()`. Pins against a future
21669 // silent detour that allocated a fresh `String`
21670 // (`self.affinity.clone().map(...)` in the body would type-
21671 // check but silently drop the borrow, and every downstream
21672 // consumer that assumed the returned slice outlives `&self`
21673 // would break on a stale-reference use-after-free — the
21674 // [`AplicacaoSpec::validate_placement`] per-hint value-shape
21675 // gate reads the accessor's `&str` return through the
21676 // [`validate_placement_affinity`] `&str` parameter and would
21677 // silently misbehave if this accessor produced a detached
21678 // copy). Peer of the sibling per-`:placement`
21679 // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
21680 // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
21681 // extends the discipline onto the sibling per-`:placement`
21682 // M3-Adaptive-compression-hint arm.
21683 let p = Placement {
21684 estrategia: PlacementStrategy::Replicated,
21685 clusters: vec!["rio".into()],
21686 affinity: Some("data-locality".into()),
21687 shard_key: None,
21688 };
21689 let hint = p.affinity().expect("Some arm");
21690 let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
21691 assert_eq!(
21692 hint.as_ptr(),
21693 storage_slice.as_ptr(),
21694 "Placement::affinity must borrow from the .affinity \
21695 String's backing storage — a fresh allocation here means \
21696 the accessor no longer names the substrate-primitive typed \
21697 dispatch and every downstream consumer would silently \
21698 carry a detached copy",
21699 );
21700 assert_eq!(
21701 hint.len(),
21702 storage_slice.len(),
21703 "Placement::affinity and .affinity.as_deref() must byte-\
21704 equal in length as well as in address",
21705 );
21706 }
21707
21708 #[test]
21709 fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
21710 // The canonical per-`:placement` distribution-strategy-scalar
21711 // pin: [`Placement::estrategia`] must return the `:placement
21712 // :estrategia` field verbatim as a [`PlacementStrategy`],
21713 // `Copy`-projected from the typed slot's own `PlacementStrategy`
21714 // storage across every variant in the closed accept-set
21715 // (`SingleNode` — Erlang/OTP distributed-app takeover;
21716 // `Replicated` — active-active across every named cluster;
21717 // `Sharded` — Akka-style hash-keyed entity distribution). Pins
21718 // against a future silent detour that re-derived the strategy
21719 // from a peer axis (an accidental fallback to
21720 // `if shard_key.is_some() { Sharded } else { Replicated }`
21721 // collapse that read the shard-key axis into the strategy
21722 // discriminator), a variant remap the operator authors on one
21723 // consumer without the other, or a stale-derive detour that
21724 // substituted [`PlacementStrategy::default`] when the field
21725 // held any explicit variant (which would silently collapse the
21726 // distinction between "author explicitly declared `:estrategia
21727 // Replicated`" and "author omitted the slot and inherited the
21728 // default" the future per-cluster override slot depends on).
21729 // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
21730 // pin on the `Copy`-return `u16` scalar axis — same "the
21731 // substrate-primitive accessor must byte-equal the raw field
21732 // access verbatim across every author-declared value" discipline
21733 // extended onto the per-`:placement` distribution-strategy
21734 // `Copy`-composite-enum scalar axis.
21735 for estrategia in [
21736 PlacementStrategy::SingleNode,
21737 PlacementStrategy::Replicated,
21738 PlacementStrategy::Sharded,
21739 ] {
21740 // Route the paired `:shard-key` fixture-builder through the
21741 // typed cross-slot invariant predicate
21742 // [`PlacementStrategy::requires_shard_key`] rather than the
21743 // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
21744 // arm-identity predicate — same discipline the sibling
21745 // `placement_strategy_variants_round_trip` fixture builder now
21746 // reads through.
21747 let shard_key = estrategia
21748 .requires_shard_key()
21749 .then(|| "tenantId".to_string());
21750 let p = Placement {
21751 estrategia,
21752 clusters: vec!["rio".into()],
21753 affinity: None,
21754 shard_key,
21755 };
21756 assert_eq!(
21757 p.estrategia(),
21758 estrategia,
21759 "Placement::estrategia must return :placement :estrategia \
21760 verbatim (got {:?}, expected {estrategia:?})",
21761 p.estrategia(),
21762 );
21763 assert_eq!(
21764 p.estrategia(),
21765 p.estrategia,
21766 "Placement::estrategia accessor and .estrategia field \
21767 access must byte-equal — the accessor is the substrate-\
21768 primitive typed dispatch every downstream distribution-\
21769 strategy consumer must route through",
21770 );
21771 }
21772 }
21773
21774 #[test]
21775 fn validate_placement_reads_through_lifted_estrategia_accessor() {
21776 // Three-consumer coherence pin: the
21777 // [`AplicacaoSpec::validate_placement`]
21778 // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
21779 // `estrategia:` field (which reads through
21780 // [`Placement::estrategia`] to name the strategy the empty
21781 // `:clusters` list was declared against), the same method's
21782 // `Sharded ↔ non-Sharded` `match` partition dispatch (which
21783 // reads through [`Placement::estrategia`] to fan across the
21784 // shape-gate cascades), and the non-`Sharded`-arm
21785 // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
21786 // `estrategia:` field (which reads through
21787 // [`Placement::estrategia`] to name the strategy the declared-
21788 // but-inert `:shard-key` was authored under) must all key off
21789 // the lifted accessor, so any future rebrand on the typed
21790 // slot's reader shape lands at exactly one place. Pins the
21791 // three-site coherence by exercising each error surface end-
21792 // to-end and asserting the surfaced `estrategia:` field byte-
21793 // equals the accessor's return. Peer of the sibling per-
21794 // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
21795 // pin on the M3 mesh-slot `Copy`-return scalar axis.
21796
21797 // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
21798 // whose `estrategia:` field must byte-equal the accessor's return
21799 // for every variant in the closed accept-set.
21800 for estrategia in [
21801 PlacementStrategy::SingleNode,
21802 PlacementStrategy::Replicated,
21803 PlacementStrategy::Sharded,
21804 ] {
21805 let mut spec = three_member_spec();
21806 spec.placement.estrategia = estrategia;
21807 spec.placement.clusters = Vec::new();
21808 // Route the paired `:shard-key` spec-mutator through the typed
21809 // cross-slot invariant predicate
21810 // [`PlacementStrategy::requires_shard_key`] rather than the
21811 // [`gen_platform::IsVariant`]-derived
21812 // [`PlacementStrategy::is_sharded`] arm-identity predicate —
21813 // same discipline the sibling
21814 // `placement_strategy_variants_round_trip` and
21815 // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
21816 // fixture builders now read through.
21817 spec.placement.shard_key = estrategia
21818 .requires_shard_key()
21819 .then(|| "tenantId".to_string());
21820 let err = spec.validate().unwrap_err();
21821 match err {
21822 AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
21823 assert_eq!(
21824 e,
21825 spec.placement.estrategia(),
21826 "PlacementWithoutClusters.estrategia must byte-equal \
21827 Placement::estrategia() — the error carrier reads \
21828 through the lifted accessor",
21829 );
21830 }
21831 other => panic!(
21832 "expected PlacementWithoutClusters, got {other:?} for \
21833 estrategia={estrategia:?}"
21834 ),
21835 }
21836 }
21837
21838 // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
21839 // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
21840 // must byte-equal the accessor's return for both non-`Sharded`
21841 // strategies.
21842 for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
21843 let mut spec = three_member_spec();
21844 spec.placement.estrategia = estrategia;
21845 spec.placement.shard_key = Some("tenantId".into());
21846 let err = spec.validate().unwrap_err();
21847 match err {
21848 AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
21849 assert_eq!(
21850 e,
21851 spec.placement.estrategia(),
21852 "ShardKeyOnNonSharded.estrategia must byte-equal \
21853 Placement::estrategia() — the non-Sharded-arm \
21854 refusal reads through the lifted accessor",
21855 );
21856 }
21857 other => panic!(
21858 "expected ShardKeyOnNonSharded, got {other:?} for \
21859 estrategia={estrategia:?}"
21860 ),
21861 }
21862 }
21863 }
21864
21865 // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
21866 //
21867 // The [`Placement::clusters`] accessor lift is the second slice-return
21868 // (`&[T]`) accessor on any typed slot — sibling to the seed M2
21869 // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
21870 // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
21871 // below cover (1) the accessor's byte-equal projection against the raw
21872 // field access across the empty / singleton / cohort fixtures the
21873 // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
21874 // and the per-cluster validate loop fan between, and (2) the two-
21875 // consumer coherence of the paired pre-flight refusal probe and the
21876 // per-cluster validate loop routing through the accessor on both arms.
21877
21878 #[test]
21879 fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
21880 // The canonical per-`:placement` cluster-pool-scalar-shape pin:
21881 // [`Placement::clusters`] must return the `:placement :clusters`
21882 // typed `Vec<String>` verbatim as a `&[String]` slice-view over
21883 // the same backing buffer the raw `self.clusters.as_slice()`
21884 // field access borrows from, byte-equal across every
21885 // representative fixture in the accept-set — the empty slice
21886 // (the pre-validation sentinel every
21887 // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
21888 // the singleton slice (the minimal `SingleNode`-shape cohort),
21889 // and multi-entry cohorts (the peer `Replicated` / `Sharded`
21890 // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
21891 //
21892 // Pins against a future silent detour that returned
21893 // `&Vec<String>` (which would type-check but leak the storage-
21894 // side `Vec`'s grow/push/reserve surface no consumer of the
21895 // typed view reaches for), a fresh-allocated `Vec<String>` copy
21896 // (which would type-check via a coercion but silently break
21897 // every downstream caller that relied on the slice sharing the
21898 // backing buffer's identity), or an out-of-order or length-
21899 // drifted projection (which would silently split the paired
21900 // pre-flight `.is_empty()` refusal probe's input from the per-
21901 // cluster validate loop's traversal input).
21902 //
21903 // Peer of the sibling M2
21904 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
21905 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
21906 // `:supervisor` static-child-list axis, extended onto the M3
21907 // per-`:placement` distribution-target-list `Vec`-carry axis.
21908 let fixtures: Vec<Vec<String>> = vec![
21909 Vec::new(),
21910 vec!["rio".into()],
21911 vec!["rio".into(), "mar".into()],
21912 vec!["rio".into(), "mar".into(), "plo".into()],
21913 ];
21914 for clusters in fixtures {
21915 let p = Placement {
21916 clusters: clusters.clone(),
21917 ..Placement::default()
21918 };
21919 assert_eq!(
21920 p.clusters(),
21921 clusters.as_slice(),
21922 "Placement::clusters must return :placement :clusters \
21923 verbatim (got {:?}, expected {:?})",
21924 p.clusters(),
21925 clusters.as_slice(),
21926 );
21927 assert_eq!(
21928 p.clusters(),
21929 p.clusters.as_slice(),
21930 "Placement::clusters accessor and .clusters.as_slice() \
21931 field access must byte-equal — the accessor is the \
21932 substrate-primitive typed dispatch every downstream \
21933 cluster-pool consumer must route through",
21934 );
21935 assert_eq!(
21936 p.clusters().len(),
21937 p.clusters.len(),
21938 "Placement::clusters().len() must byte-equal \
21939 self.clusters.len() — a length-drift would silently \
21940 split the paired pre-flight `.is_empty()` refusal \
21941 probe input from the per-cluster validate loop's \
21942 traversal input",
21943 );
21944 }
21945 }
21946
21947 #[test]
21948 fn validate_placement_reads_through_lifted_clusters_accessor() {
21949 // Two-consumer coherence pin: the
21950 // [`AplicacaoSpec::validate_placement`] pre-flight
21951 // `self.placement.clusters().is_empty()` refusal probe (which
21952 // must trip [`AplicacaoError::PlacementWithoutClusters`] when
21953 // the accessor projects the empty slice) and the per-cluster
21954 // validate loop's `for c in self.placement.clusters()`
21955 // traversal (which must reach every entry in the same order
21956 // the accessor projects, so both the per-entry value-shape
21957 // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
21958 // and the duplicate-detection HashSet insert that trips
21959 // [`AplicacaoError::PlacementClusterDuplicate`] key off the
21960 // accessor's projection) must both key off the lifted
21961 // accessor, so any future rebrand on the typed slot's reader
21962 // shape lands at exactly one place. Pins the two-site
21963 // coherence by exercising each production consumer end-to-end:
21964 // (1) the `PlacementWithoutClusters` refusal under the empty
21965 // slice, (2) the `PlacementClusterInvalid` refusal fires on
21966 // the second entry of a two-cluster cohort whose head is
21967 // valid but tail is not (which requires the loop to reach the
21968 // second entry through the accessor), and (3) the
21969 // `PlacementClusterDuplicate` refusal fires on the second
21970 // entry of a two-cluster cohort that shares a name (which
21971 // requires the loop to reach both entries — a first-entry-only
21972 // projection would silently pass since the dedup HashSet has
21973 // room for the first insert).
21974 //
21975 // Peer of the sibling M2
21976 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
21977 // (bc92bce) coherence pin on the per-`:supervisor` static-
21978 // child-list axis, extended onto the M3 per-`:placement`
21979 // distribution-target-list `Vec`-carry axis.
21980
21981 // (1) Pre-flight `.is_empty()` probe: the empty slice must
21982 // trip `PlacementWithoutClusters`.
21983 let mut spec = three_member_spec();
21984 spec.placement.clusters = Vec::new();
21985 match spec.validate().unwrap_err() {
21986 AplicacaoError::PlacementWithoutClusters { .. } => {}
21987 other => panic!("expected PlacementWithoutClusters, got {other:?}"),
21988 }
21989 assert!(
21990 spec.placement.clusters().is_empty(),
21991 "the pre-flight refusal input must be the empty slice per \
21992 the accessor's projection",
21993 );
21994
21995 // (2) Per-cluster validate loop: a two-cluster cohort with an
21996 // invalid tail entry must trip `PlacementClusterInvalid` on
21997 // the tail — the loop must reach the second entry through
21998 // the accessor.
21999 let mut spec = three_member_spec();
22000 spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
22001 match spec.validate().unwrap_err() {
22002 AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
22003 assert_eq!(
22004 cluster, "BAD_CLUSTER",
22005 "PlacementClusterInvalid.cluster must carry the \
22006 tail entry the loop reached through the accessor",
22007 );
22008 }
22009 other => panic!("expected PlacementClusterInvalid, got {other:?}"),
22010 }
22011 assert_eq!(
22012 spec.placement.clusters().len(),
22013 2,
22014 "the per-cluster validate loop's traversal input must be \
22015 a two-element slice per the accessor's projection",
22016 );
22017
22018 // (3) Per-cluster validate loop: a two-cluster cohort that
22019 // shares a name must trip `PlacementClusterDuplicate` on the
22020 // second entry — the loop must reach both entries through the
22021 // accessor for the dedup HashSet's second insert to collide.
22022 let mut spec = three_member_spec();
22023 spec.placement.clusters = vec!["rio".into(), "rio".into()];
22024 match spec.validate().unwrap_err() {
22025 AplicacaoError::PlacementClusterDuplicate { cluster } => {
22026 assert_eq!(
22027 cluster, "rio",
22028 "PlacementClusterDuplicate.cluster must carry the \
22029 shared cluster name verbatim",
22030 );
22031 }
22032 other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
22033 }
22034 assert_eq!(
22035 spec.placement.clusters().len(),
22036 2,
22037 "the per-cluster validate loop's traversal input must be \
22038 a two-element slice per the accessor's projection",
22039 );
22040 }
22041
22042 #[test]
22043 fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
22044 // The canonical per-`:membros` member-list-slice-shape pin:
22045 // [`AplicacaoSpec::membros`] must return the `:membros` typed
22046 // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
22047 // same backing buffer the raw `self.membros.as_slice()` field
22048 // access borrows from, byte-equal across every representative
22049 // fixture in the accept-set — the empty slice (the pre-
22050 // validation sentinel every [`AplicacaoError::NoMembros`]
22051 // refusal keys off), the singleton slice (the minimal one-
22052 // Servico Aplicacao shape), and multi-entry cohorts (the peer
22053 // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
22054 // load-bearing identity of the application graph).
22055 //
22056 // Pins against a future silent detour that returned
22057 // `&Vec<Membro>` (which would type-check but leak the storage-
22058 // side `Vec`'s grow/push/reserve surface no consumer of the
22059 // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
22060 // (which would type-check via a coercion but silently break
22061 // every downstream caller that relied on the slice sharing the
22062 // backing buffer's identity), or an out-of-order or length-
22063 // drifted projection (which would silently split the paired
22064 // `HashSet<&str>` name-set seed's collect input from the
22065 // pre-flight `.is_empty()` refusal probe's input from the per-
22066 // member validate loop's traversal input from the
22067 // programs.yaml emitter's per-entry fan-out loop's input from
22068 // the `feira app graph` per-member print traversal's input).
22069 //
22070 // Peer of the sibling M2
22071 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22072 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22073 // `:supervisor` static-child-list axis and the sibling M3
22074 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
22075 // (a6e18d7) `&[String]` byte-equal pin on the per-
22076 // `:placement` distribution-target-list axis — extends the
22077 // slice-return-accessor byte-equal-projection discipline onto
22078 // the outermost M3 mesh-slot type's per-Aplicacao member-list
22079 // `Vec`-carry axis.
22080 let fixtures: Vec<Vec<Membro>> = vec![
22081 Vec::new(),
22082 vec![membro("catalog", "^0.1")],
22083 vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
22084 vec![
22085 membro("catalog", "^0.1"),
22086 membro("cart", "^0.1"),
22087 membro("payment", "^0.2"),
22088 ],
22089 ];
22090 for membros in fixtures {
22091 let s = AplicacaoSpec {
22092 membros: membros.clone(),
22093 contratos: Vec::new(),
22094 politicas: MeshPolicy::default(),
22095 placement: Placement::default(),
22096 entrada: None,
22097 };
22098 assert_eq!(
22099 s.membros(),
22100 membros.as_slice(),
22101 "AplicacaoSpec::membros must return :membros verbatim \
22102 (got {:?}, expected {:?})",
22103 s.membros(),
22104 membros.as_slice(),
22105 );
22106 assert_eq!(
22107 s.membros(),
22108 s.membros.as_slice(),
22109 "AplicacaoSpec::membros accessor and .membros.as_slice() \
22110 field access must byte-equal — the accessor is the \
22111 substrate-primitive typed dispatch every downstream \
22112 member-list consumer must route through",
22113 );
22114 assert_eq!(
22115 s.membros().len(),
22116 s.membros.len(),
22117 "AplicacaoSpec::membros().len() must byte-equal \
22118 self.membros.len() — a length-drift would silently \
22119 split the paired `HashSet<&str>` name-set seed's \
22120 collect input from the pre-flight `.is_empty()` \
22121 refusal probe input from the per-member validate \
22122 loop's traversal input",
22123 );
22124 }
22125 }
22126
22127 #[test]
22128 fn validate_reads_through_lifted_membros_accessor() {
22129 // Three-consumer coherence pin: the
22130 // [`AplicacaoSpec::validate_membros`] pre-flight
22131 // `self.membros().is_empty()` refusal probe (which must trip
22132 // [`AplicacaoError::NoMembros`] when the accessor projects the
22133 // empty slice), the same method's per-member validate loop's
22134 // `for m in self.membros()` traversal (which must reach every
22135 // entry in the same order the accessor projects, so both the
22136 // per-entry empty-`:caixa` gate that trips
22137 // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
22138 // detection `insert_first_seen` that trips
22139 // [`AplicacaoError::MembroDuplicate`] key off the accessor's
22140 // projection), and the peer [`AplicacaoSpec::validate`]'s
22141 // `HashSet<&str>` name-set seed's
22142 // `self.membros().iter().map(Membro::nome).collect()` collect
22143 // input (which every `:contratos` `:de` / `:para` membership
22144 // lookup rejects an unknown name against) must all three key
22145 // off the lifted accessor, so any future rebrand on the typed
22146 // slot's reader shape lands at exactly one place. Pins the
22147 // three-site coherence by exercising each production consumer
22148 // end-to-end: (1) the `NoMembros` refusal under the empty
22149 // slice, (2) the `MembroCaixaEmpty` refusal fires on the
22150 // second entry of a two-member cohort whose head is valid but
22151 // tail has an empty `:caixa` (which requires the loop to
22152 // reach the second entry through the accessor), and (3) the
22153 // `MembroDuplicate` refusal fires on the second entry of a
22154 // two-member cohort that shares a `:caixa` name (which
22155 // requires the loop to reach both entries through the
22156 // accessor for the dedup HashSet's second insert to collide).
22157 //
22158 // Peer of the sibling M2
22159 // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
22160 // (bc92bce) coherence pin on the per-`:supervisor` static-
22161 // child-list axis and the sibling M3
22162 // `validate_placement_reads_through_lifted_clusters_accessor`
22163 // (a6e18d7) coherence pin on the per-`:placement` distribution-
22164 // target-list axis — extends the slice-return-accessor
22165 // multi-consumer coherence discipline onto the outermost M3
22166 // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
22167
22168 // (1) Pre-flight `.is_empty()` probe: the empty slice must
22169 // trip `NoMembros`.
22170 let mut spec = three_member_spec();
22171 spec.membros = Vec::new();
22172 assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
22173 assert!(
22174 spec.membros().is_empty(),
22175 "the pre-flight refusal input must be the empty slice per \
22176 the accessor's projection",
22177 );
22178
22179 // (2) Per-member validate loop: a two-member cohort with an
22180 // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
22181 // the tail — the loop must reach the second entry through
22182 // the accessor.
22183 let mut spec = three_member_spec();
22184 spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
22185 assert_eq!(
22186 spec.validate().unwrap_err(),
22187 AplicacaoError::MembroCaixaEmpty,
22188 );
22189 assert_eq!(
22190 spec.membros().len(),
22191 2,
22192 "the per-member validate loop's traversal input must be \
22193 a two-element slice per the accessor's projection",
22194 );
22195
22196 // (3) Per-member validate loop: a two-member cohort that
22197 // shares a `:caixa` name must trip `MembroDuplicate` on the
22198 // second entry — the loop must reach both entries through the
22199 // accessor for the dedup HashSet's second insert to collide.
22200 let mut spec = three_member_spec();
22201 spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
22202 match spec.validate().unwrap_err() {
22203 AplicacaoError::MembroDuplicate { caixa } => {
22204 assert_eq!(
22205 caixa, "catalog",
22206 "MembroDuplicate.caixa must carry the shared \
22207 member name verbatim",
22208 );
22209 }
22210 other => panic!("expected MembroDuplicate, got {other:?}"),
22211 }
22212 assert_eq!(
22213 spec.membros().len(),
22214 2,
22215 "the per-member validate loop's traversal input must be \
22216 a two-element slice per the accessor's projection",
22217 );
22218 }
22219
22220 #[test]
22221 fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
22222 // The canonical per-`:contratos` contract-list-slice-shape pin:
22223 // [`AplicacaoSpec::contratos`] must return the `:contratos`
22224 // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
22225 // slice-view over the same backing buffer the raw
22226 // `self.contratos.as_slice()` field access borrows from, byte-
22227 // equal across every representative fixture in the accept-set —
22228 // the empty slice (the pre-validation "internal-only mesh" shape
22229 // an Aplicacao whose members exchange no typed edges renders
22230 // through), the singleton slice (the minimal one-edge Aplicacao
22231 // shape), and multi-entry cohorts (the peer multi-edge shapes
22232 // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
22233 // of the application graph).
22234 //
22235 // Pins against a future silent detour that returned
22236 // `&Vec<WitContract>` (which would type-check but leak the
22237 // storage-side `Vec`'s grow/push/reserve surface no consumer of
22238 // the typed view reaches for), a fresh-allocated
22239 // `Vec<WitContract>` copy (which would type-check via a coercion
22240 // but silently break every downstream caller that relied on the
22241 // slice sharing the backing buffer's identity), or an out-of-
22242 // order or length-drifted projection (which would silently split
22243 // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
22244 // seed's traversal input from the `detect_sync_cycles` per-edge
22245 // adjacency-list seed's traversal input from the
22246 // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
22247 // BTreeMap grouping loop's traversal input from the
22248 // `feira app graph` per-contract print traversal's input).
22249 //
22250 // Peer of the immediately-adjacent sibling M3
22251 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
22252 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
22253 // node-list axis, the sibling M3
22254 // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
22255 // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
22256 // distribution-target-list axis, and the sibling M2
22257 // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
22258 // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
22259 // `:supervisor` static-child-list axis — extends the slice-
22260 // return-accessor byte-equal-projection discipline onto the
22261 // outermost M3 mesh-slot type's per-Aplicacao contract-list
22262 // `Vec`-carry axis, closing the last unlifted per-
22263 // `AplicacaoSpec` `Vec`-carry axis.
22264 let fixtures: Vec<Vec<WitContract>> = vec![
22265 Vec::new(),
22266 vec![contract_http("cart", "catalog", "/products/:id")],
22267 vec![
22268 contract_http("cart", "catalog", "/products/:id"),
22269 contract_http("cart", "payment", "/charge"),
22270 ],
22271 vec![
22272 contract_http("cart", "catalog", "/products/:id"),
22273 contract_http("cart", "payment", "/charge"),
22274 contract_http("payment", "catalog", "/audit"),
22275 ],
22276 ];
22277 for contratos in fixtures {
22278 let s = AplicacaoSpec {
22279 membros: vec![
22280 membro("catalog", "^0.1"),
22281 membro("cart", "^0.1"),
22282 membro("payment", "^0.2"),
22283 ],
22284 contratos: contratos.clone(),
22285 politicas: MeshPolicy::default(),
22286 placement: Placement::default(),
22287 entrada: None,
22288 };
22289 assert_eq!(
22290 s.contratos(),
22291 contratos.as_slice(),
22292 "AplicacaoSpec::contratos must return :contratos verbatim \
22293 (got {:?}, expected {:?})",
22294 s.contratos(),
22295 contratos.as_slice(),
22296 );
22297 assert_eq!(
22298 s.contratos(),
22299 s.contratos.as_slice(),
22300 "AplicacaoSpec::contratos accessor and \
22301 .contratos.as_slice() field access must byte-equal — \
22302 the accessor is the substrate-primitive typed dispatch \
22303 every downstream contract-list consumer must route \
22304 through",
22305 );
22306 assert_eq!(
22307 s.contratos().len(),
22308 s.contratos.len(),
22309 "AplicacaoSpec::contratos().len() must byte-equal \
22310 self.contratos.len() — a length-drift would silently \
22311 split the paired per-edge validate-loop's traversal \
22312 input from the sync-cycle adjacency-list seed's \
22313 traversal input from the cilium_network_policies \
22314 per-`(:de, :para)` BTreeMap grouping loop's traversal \
22315 input from the `feira app graph` per-contract print \
22316 traversal's input",
22317 );
22318 }
22319 }
22320
22321 #[test]
22322 fn validate_reads_through_lifted_contratos_accessor() {
22323 // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
22324 // per-`:contratos` validate-loop's `for c in self.contratos()`
22325 // traversal (which must reach every entry in the same order the
22326 // accessor projects, so both the per-entry
22327 // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
22328 // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
22329 // dedup `HashSet` insert key off the accessor's projection),
22330 // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
22331 // `for c in self.contratos()` adjacency-list seed (which drives
22332 // the sync-subgraph deadlock-detection gate via
22333 // [`AplicacaoError::SyncCycle`]), and the peer
22334 // [`caixa_mesh::cilium_network_policies`]'s
22335 // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
22336 // grouping loop (which drives the per-CNP fan-out) must all
22337 // three key off the lifted accessor, so any future rebrand on
22338 // the typed slot's reader shape lands at exactly one place. Pins
22339 // the three-site coherence by exercising the two caixa-core
22340 // production consumers end-to-end: (1) the empty-`:contratos`
22341 // slice must validate without a per-edge diagnostic (the
22342 // per-edge loop is a no-op under the empty projection), (2) the
22343 // `ContratoMemberMissing` refusal fires on the second entry of a
22344 // two-edge cohort whose head references a valid member but tail
22345 // references a phantom name (which requires the loop to reach
22346 // the second entry through the accessor), and (3) the
22347 // `SyncCycle` refusal fires on a self-referential two-edge
22348 // cohort through the sync-cycle detector's peer projection
22349 // (which requires the detector to iterate the accessor's
22350 // projection to add the back-edge to its adjacency list).
22351 //
22352 // Peer of the sibling M3
22353 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
22354 // three-consumer coherence pin on the per-`:membros` node-list
22355 // axis and the sibling M3
22356 // `validate_placement_reads_through_lifted_clusters_accessor`
22357 // (a6e18d7) coherence pin on the per-`:placement` distribution-
22358 // target-list axis — extends the slice-return-accessor multi-
22359 // consumer coherence discipline onto the outermost M3 mesh-slot
22360 // type's per-Aplicacao contract-list `Vec`-carry axis.
22361
22362 // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
22363 // and no per-edge diagnostic surfaces. Validate succeeds on
22364 // the well-formed `:membros` head.
22365 let mut spec = three_member_spec();
22366 spec.contratos = Vec::new();
22367 assert!(
22368 spec.validate().is_ok(),
22369 "empty :contratos must validate — the per-edge loop is a \
22370 no-op under the accessor's empty projection",
22371 );
22372 assert!(
22373 spec.contratos().is_empty(),
22374 "the per-edge validate loop's traversal input must be the \
22375 empty slice per the accessor's projection",
22376 );
22377
22378 // (2) Per-edge validate loop: a two-edge cohort whose tail
22379 // references a phantom `:para` member must trip
22380 // `ContratoMemberMissing` on the tail — the loop must reach
22381 // the second entry through the accessor for the membership
22382 // lookup to fail on the phantom name.
22383 let mut spec = three_member_spec();
22384 spec.contratos = vec![
22385 contract_http("cart", "catalog", "/products/:id"),
22386 contract_http("cart", "phantom", "/x"),
22387 ];
22388 let err = spec.validate().unwrap_err();
22389 assert!(
22390 matches!(
22391 err,
22392 AplicacaoError::ContratoMemberMissing { ref caixa }
22393 if caixa == "phantom"
22394 ),
22395 "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
22396 );
22397 assert_eq!(
22398 spec.contratos().len(),
22399 2,
22400 "the per-edge validate loop's traversal input must be \
22401 a two-element slice per the accessor's projection",
22402 );
22403
22404 // (3) Sync-cycle detector: a two-edge synchronous cohort
22405 // whose second edge closes the sync-subgraph back onto the
22406 // first must trip [`AplicacaoError::ContratoCycle`] — the
22407 // detector must iterate the accessor's projection to add
22408 // both edges to its adjacency list, so a length-drift on
22409 // the accessor's projection would silently disagree with
22410 // the sync-cycle detector on which edge closes the loop.
22411 // Peer projection to the `validate` per-edge loop above:
22412 // the sync-cycle detector routes through the same lifted
22413 // accessor, so a rebrand of the reader shape lands at one
22414 // place. Uses a two-edge cohort (cart → catalog → cart)
22415 // because the per-edge `ContratoSelfLoop` gate fires before
22416 // the sync-cycle detector on a single self-referential edge
22417 // (`cart → cart`) — the cycle-detector's input must be a
22418 // multi-edge cohort for its per-edge traversal input to be
22419 // observably wider than the per-edge validate loop's input.
22420 let mut spec = three_member_spec();
22421 spec.contratos = vec![
22422 contract_http("cart", "catalog", "/products/:id"),
22423 contract_http("catalog", "cart", "/callback"),
22424 ];
22425 let err = spec.validate().unwrap_err();
22426 assert!(
22427 matches!(err, AplicacaoError::ContratoCycle { .. }),
22428 "expected ContratoCycle from the sync-cycle detector on a \
22429 two-edge back-edge cohort, got {err:?}",
22430 );
22431 assert_eq!(
22432 spec.contratos().len(),
22433 2,
22434 "the sync-cycle detector's traversal input must be a \
22435 two-element slice per the accessor's projection",
22436 );
22437 }
22438
22439 #[test]
22440 fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
22441 // The canonical per-`:politicas` outer-composite-reference-shape
22442 // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
22443 // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
22444 // the same backing storage the raw `&self.politicas` field
22445 // access borrows from, byte-equal across every representative
22446 // fixture in the accept-set — the default `MeshPolicy` (the
22447 // author-empty "no policy on any axis" shape whose
22448 // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
22449 // shapes carrying one axis at a time
22450 // (`{mtls_required, timeout, retries, circuit_breaker,
22451 // rate_limit}` — the minimal five-axis fan-out over the
22452 // per-axis lifted accessor family every downstream mesh-artifact
22453 // emitter dispatches on), and the multi-axis composite (the
22454 // canonical `three_member_spec` fixture's `{timeout, retries,
22455 // mtls_required}` triple — the load-bearing shape every
22456 // Aplicacao-scoped fixture in this suite constructs).
22457 //
22458 // Pins against a future silent detour that returned a fresh-
22459 // cloned `MeshPolicy` copy (which would type-check via a `Clone`
22460 // impl but silently break every downstream caller that relied
22461 // on the reference sharing the composite's backing identity), a
22462 // reference to an operator-resolved overlay (the future
22463 // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
22464 // acknowledges — its resolution must land at exactly this
22465 // accessor body, not silently divert the raw slot away from a
22466 // second consumer), or an axis-shuffled projection (a future
22467 // detour that swapped `timeout` and `retries` through the
22468 // accessor would silently split the paired `validate_politicas`
22469 // per-axis bracket-dispatch's traversal input from the peer
22470 // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
22471 // emitter's fan-out input from the peer
22472 // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
22473 // overlay emitter's fan-out input).
22474 //
22475 // Peer of the sibling M3
22476 // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
22477 // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
22478 // node-list `Vec`-carry axis and the sibling M3
22479 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
22480 // (0dcc926) `&[WitContract]` byte-equal pin on the per-
22481 // `:contratos` edge-list `Vec`-carry axis — extends the outer-
22482 // accessor byte-equal-projection discipline onto the outermost
22483 // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
22484 // reference axis, the first `&Composite`-return accessor on the
22485 // outer [`AplicacaoSpec`] type.
22486 let fixtures: Vec<MeshPolicy> = vec![
22487 MeshPolicy::default(),
22488 MeshPolicy {
22489 mtls_required: Some(true),
22490 ..MeshPolicy::default()
22491 },
22492 MeshPolicy {
22493 mtls_required: Some(false),
22494 ..MeshPolicy::default()
22495 },
22496 MeshPolicy {
22497 timeout: Some(Duration::from_secs(30)),
22498 ..MeshPolicy::default()
22499 },
22500 MeshPolicy {
22501 retries: Some(3),
22502 ..MeshPolicy::default()
22503 },
22504 MeshPolicy {
22505 circuit_breaker: Some(CircuitBreaker {
22506 max_failures: 5,
22507 window: Duration::from_secs(30),
22508 }),
22509 ..MeshPolicy::default()
22510 },
22511 MeshPolicy {
22512 rate_limit: Some(RateLimit {
22513 rate: 100,
22514 window: Duration::from_secs(1),
22515 }),
22516 ..MeshPolicy::default()
22517 },
22518 MeshPolicy {
22519 timeout: Some(Duration::from_secs(30)),
22520 retries: Some(3),
22521 mtls_required: Some(true),
22522 ..MeshPolicy::default()
22523 },
22524 ];
22525 for politicas in fixtures {
22526 let s = AplicacaoSpec {
22527 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
22528 contratos: Vec::new(),
22529 politicas: politicas.clone(),
22530 placement: Placement::default(),
22531 entrada: None,
22532 };
22533 assert_eq!(
22534 *s.politicas(),
22535 politicas,
22536 "AplicacaoSpec::politicas must return :politicas verbatim \
22537 (got {:?}, expected {:?})",
22538 s.politicas(),
22539 politicas,
22540 );
22541 assert!(
22542 std::ptr::eq(s.politicas(), &s.politicas),
22543 "AplicacaoSpec::politicas accessor and &self.politicas \
22544 field access must borrow the same backing storage — \
22545 the accessor is the substrate-primitive typed dispatch \
22546 every downstream mesh-policy composite consumer must \
22547 route through, and a reference-identity split would \
22548 silently break every consumer that relied on the \
22549 borrow sharing the composite's storage",
22550 );
22551 assert_eq!(
22552 s.politicas().is_empty(),
22553 s.politicas.is_empty(),
22554 "AplicacaoSpec::politicas().is_empty() must byte-equal \
22555 self.politicas.is_empty() — an emptiness-drift would \
22556 silently split the paired `validate_politicas` \
22557 per-axis bracket-dispatch's seed from the peer \
22558 caixa-mesh CNP mTLS-overlay emitter's key from the \
22559 peer caixa-mesh HTTPRoute timeout+retry overlay \
22560 emitter's key",
22561 );
22562 }
22563 }
22564
22565 #[test]
22566 fn validate_politicas_reads_through_lifted_politicas_accessor() {
22567 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
22568 // per-axis bracket-dispatch seed (`let p = self.politicas();`,
22569 // followed by the per-axis fan-out `p.timeout()` /
22570 // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
22571 // the lifted axis-level accessor family) must key off the
22572 // lifted outer accessor, so any future rebrand on the typed
22573 // slot's outer-composite reader shape lands at exactly one
22574 // place. Pins the multi-axis coherence by exercising each
22575 // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
22576 // a `Some(Duration::ZERO)` timeout under the outer accessor's
22577 // reference projection, (2) `PolicyRetriesZero` fires on a
22578 // `Some(0)` retries under the same projection, and (3) an
22579 // empty [`MeshPolicy::default`] passes `validate_politicas` —
22580 // the outer accessor's reference-projection reaches every
22581 // per-axis branch without silently short-circuiting any.
22582 //
22583 // Peer of the sibling M3
22584 // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
22585 // three-consumer coherence pin on the per-`:membros` node-list
22586 // axis and the sibling M3
22587 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
22588 // three-consumer coherence pin on the per-`:contratos`
22589 // edge-list axis — extends the multi-consumer coherence
22590 // discipline onto the outermost M3 mesh-slot type's per-
22591 // Aplicacao mesh-policy composite-reference axis, the first
22592 // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
22593 // type.
22594
22595 // (1) `PolicyTimeoutZero` refusal under the outer accessor's
22596 // reference projection: a `Some(Duration::ZERO)` timeout must
22597 // trip the zero-floor gate. The bracket-dispatch's first arm
22598 // reads `p.timeout()` on the reference returned by the outer
22599 // accessor.
22600 let mut spec = three_member_spec();
22601 spec.politicas.timeout = Some(Duration::ZERO);
22602 spec.politicas.retries = None;
22603 spec.politicas.circuit_breaker = None;
22604 spec.politicas.rate_limit = None;
22605 assert_eq!(
22606 spec.validate().unwrap_err(),
22607 AplicacaoError::PolicyTimeoutZero,
22608 );
22609 assert!(
22610 std::ptr::eq(spec.politicas(), &spec.politicas),
22611 "the `validate_politicas` per-axis bracket-dispatch's \
22612 traversal input must be the same backing composite the \
22613 accessor's reference projection borrows from",
22614 );
22615
22616 // (2) `PolicyRetriesZero` refusal under the outer accessor's
22617 // reference projection: a `Some(0)` retries must trip the
22618 // zero-floor gate. The bracket-dispatch's second arm reads
22619 // `p.retries()` on the reference returned by the outer accessor.
22620 let mut spec = three_member_spec();
22621 spec.politicas.timeout = None;
22622 spec.politicas.retries = Some(0);
22623 spec.politicas.circuit_breaker = None;
22624 spec.politicas.rate_limit = None;
22625 assert_eq!(
22626 spec.validate().unwrap_err(),
22627 AplicacaoError::PolicyRetriesZero,
22628 );
22629
22630 // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
22631 // — every per-axis arm short-circuits on `None`, so the outer
22632 // accessor's reference projection reaches the fall-through
22633 // `Ok(())` without any per-axis refusal firing.
22634 let mut spec = three_member_spec();
22635 spec.politicas = MeshPolicy::default();
22636 assert!(
22637 spec.validate().is_ok(),
22638 "an empty `MeshPolicy` must pass `validate_politicas` — \
22639 every per-axis arm short-circuits on `None` under the \
22640 outer accessor's reference projection",
22641 );
22642 assert!(
22643 spec.politicas().is_empty(),
22644 "the outer accessor's reference projection must be the \
22645 empty composite per the `MeshPolicy::default()` fixture",
22646 );
22647 }
22648
22649 #[test]
22650 #[allow(clippy::too_many_lines)]
22651 fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
22652 // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
22653 // per-axis bracket-dispatch's `:timeout` and `:retries` arms
22654 // must both key off the lifted axis-level accessors
22655 // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
22656 // the peer `:circuit-breaker` / `:rate-limit` arms already
22657 // routing through [`MeshPolicy::circuit_breaker`] /
22658 // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
22659 // per axis on the substrate primitive" shape at the fan-out
22660 // (four axes, four accessors, no raw-field-access site
22661 // anywhere on the bracket-dispatch). Pins the per-axis
22662 // coherence at the accept-set boundaries the bracket carves:
22663 // 1. accessor byte-equal to raw field on every representative
22664 // accept-set value (`None`, sub-cap, at-cap, past-cap
22665 // sentinel) — a future accessor drift that no longer
22666 // shipped the raw slot verbatim would surface here,
22667 // 2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
22668 // routed through the accessor's projection, proving the
22669 // first arm reads through the accessor rather than a
22670 // silent-detour peer-axis field access,
22671 // 3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
22672 // through the accessor's projection, proving the second
22673 // arm reads through the accessor,
22674 // 4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
22675 // passes validate under the accessor projection (paired
22676 // with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
22677 // sibling axis), pinning the upper-boundary accept-arm
22678 // also routes through the accessor.
22679 //
22680 // Peer of the sibling M3
22681 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
22682 // outer-composite-reference coherence pin (which asserts the
22683 // `let p = self.politicas()` seed); extends the discipline onto
22684 // the per-axis fan-out layer that consumes the seed's
22685 // reference. Same shape as
22686 // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
22687 // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
22688 // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
22689 // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
22690
22691 // (1) Accessor byte-equal to raw field on the `:timeout` axis
22692 // across the accept-set boundaries the bracket dispatch's
22693 // three-arm gate carves out
22694 // ([`crate::render::require_positive_canonical_bounded_duration`]
22695 // — zero-floor + canonical-form + upper-cap).
22696 for timeout in [
22697 None,
22698 Some(Duration::ZERO),
22699 Some(Duration::from_millis(1)),
22700 Some(POLICY_TIMEOUT_MAX),
22701 ] {
22702 let p = MeshPolicy {
22703 timeout,
22704 ..MeshPolicy::default()
22705 };
22706 assert_eq!(
22707 p.timeout(),
22708 p.timeout,
22709 "MeshPolicy::timeout accessor must byte-equal the raw \
22710 .timeout field across every accept-set boundary the \
22711 validate_politicas :timeout arm carves out — a drift \
22712 here would silently split the validate bracket's arm \
22713 from the peer caixa-mesh HTTPRoute timeout-overlay \
22714 emitter's read",
22715 );
22716 }
22717
22718 // (2) Accessor byte-equal to raw field on the `:retries` axis
22719 // across the accept-set boundaries the bracket dispatch's
22720 // two-arm gate carves out
22721 // ([`crate::render::require_positive_bounded_u32`] — zero-floor
22722 // + upper-cap).
22723 for retries in [
22724 None,
22725 Some(0u32),
22726 Some(1u32),
22727 Some(POLICY_RETRIES_MAX),
22728 Some(POLICY_RETRIES_MAX + 1),
22729 Some(u32::MAX),
22730 ] {
22731 let p = MeshPolicy {
22732 retries,
22733 ..MeshPolicy::default()
22734 };
22735 assert_eq!(
22736 p.retries(),
22737 p.retries,
22738 "MeshPolicy::retries accessor must byte-equal the raw \
22739 .retries field across every accept-set boundary the \
22740 validate_politicas :retries arm carves out — a drift \
22741 here would silently split the validate bracket's arm \
22742 from the peer caixa-mesh HTTPRoute retry-overlay \
22743 emitter's read",
22744 );
22745 }
22746
22747 // (3) `PolicyTimeoutZero` fires on the accessor-projected
22748 // zero-floor boundary. A silent detour that no longer read
22749 // through `p.timeout()` (a peer-axis field read, an accidental
22750 // Option::and-then chain that collapsed the None arm to Some,
22751 // an accessor rebrand that clamped the return through the
22752 // upper cap) would fail to refuse here.
22753 let mut spec = three_member_spec();
22754 spec.politicas.timeout = Some(Duration::ZERO);
22755 spec.politicas.retries = None;
22756 spec.politicas.circuit_breaker = None;
22757 spec.politicas.rate_limit = None;
22758 assert_eq!(
22759 spec.politicas().timeout(),
22760 Some(Duration::ZERO),
22761 "the accessor projection must reflect the fixture's \
22762 `Some(Duration::ZERO)` :timeout verbatim",
22763 );
22764 assert_eq!(
22765 spec.validate().unwrap_err(),
22766 AplicacaoError::PolicyTimeoutZero,
22767 "the validate_politicas :timeout zero-floor arm must fire \
22768 through the lifted accessor's projection — a silent \
22769 detour to a peer-axis field would fail to refuse",
22770 );
22771
22772 // (4) `PolicyRetriesZero` fires on the accessor-projected
22773 // zero-floor boundary on the sibling `:retries` axis.
22774 let mut spec = three_member_spec();
22775 spec.politicas.timeout = None;
22776 spec.politicas.retries = Some(0);
22777 spec.politicas.circuit_breaker = None;
22778 spec.politicas.rate_limit = None;
22779 assert_eq!(
22780 spec.politicas().retries(),
22781 Some(0),
22782 "the accessor projection must reflect the fixture's \
22783 `Some(0)` :retries verbatim",
22784 );
22785 assert_eq!(
22786 spec.validate().unwrap_err(),
22787 AplicacaoError::PolicyRetriesZero,
22788 "the validate_politicas :retries zero-floor arm must fire \
22789 through the lifted accessor's projection — a silent \
22790 detour to a peer-axis field would fail to refuse",
22791 );
22792
22793 // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
22794 // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
22795 // must pass validate under the accessor projection — pins the
22796 // upper-boundary accept-arm also routes through the lifted
22797 // accessor (a drift that clamped or short-circuited at the
22798 // upper boundary would fail the whole-spec validate here).
22799 let mut spec = three_member_spec();
22800 spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
22801 spec.politicas.retries = Some(POLICY_RETRIES_MAX);
22802 spec.politicas.circuit_breaker = None;
22803 spec.politicas.rate_limit = None;
22804 assert_eq!(
22805 spec.politicas().timeout(),
22806 Some(POLICY_TIMEOUT_MAX),
22807 "the accessor projection must reflect the fixture's \
22808 at-cap :timeout verbatim",
22809 );
22810 assert_eq!(
22811 spec.politicas().retries(),
22812 Some(POLICY_RETRIES_MAX),
22813 "the accessor projection must reflect the fixture's \
22814 at-cap :retries verbatim",
22815 );
22816 assert!(
22817 spec.validate().is_ok(),
22818 "at-cap :timeout + :retries must pass validate under the \
22819 accessor projection — the upper-boundary accept-arm on \
22820 both axes routes through the lifted accessor",
22821 );
22822 }
22823
22824 #[test]
22825 fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
22826 // The canonical per-`:placement` outer-composite-reference-shape
22827 // pin: [`AplicacaoSpec::placement`] must return the `:placement`
22828 // typed `Placement` verbatim as a `&Placement` reference over the
22829 // same backing storage the raw `&self.placement` field access
22830 // borrows from, byte-equal across every representative fixture in
22831 // the accept-set — the default `Placement` (the substrate seed
22832 // shape whose [`PlacementStrategy::default`] evaluates to
22833 // `SingleNode` with an empty `:clusters` pool and both
22834 // optional-scalar axes `None`), and every canonical strategy /
22835 // cluster-pool / optional-scalar combination the
22836 // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
22837 // three [`PlacementStrategy`] variants — `SingleNode`,
22838 // `Replicated`, `Sharded` — cross-projected with a non-empty
22839 // `:clusters` pool and, on the `Sharded` arm, a non-empty
22840 // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
22841 // canonical `three_member_spec` `Replicated` fixture's
22842 // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
22843 //
22844 // Pins against a future silent detour that returned a fresh-
22845 // cloned `Placement` copy (which would type-check via a `Clone`
22846 // impl but silently break every downstream caller that relied on
22847 // the reference sharing the composite's backing identity), a
22848 // reference to an operator-resolved overlay (the future per-
22849 // cluster `:placement-overrides` slot MESH-COMPOSITION §V
22850 // acknowledges — its resolution must land at exactly this
22851 // accessor body, not silently divert the raw slot away from a
22852 // second consumer), or an axis-shuffled projection (a future
22853 // detour that swapped `clusters` and `affinity` through the
22854 // accessor would silently split the paired `validate_placement`
22855 // per-axis bracket-dispatch's traversal input from the peer
22856 // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
22857 // programs.yaml distribution-annotation emitter's fan-out input
22858 // from the peer `feira app graph` per-Aplicacao print line's
22859 // input).
22860 //
22861 // Peer of the sibling M3
22862 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
22863 // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
22864 // outer mesh-policy composite-reference axis, and of the sibling
22865 // slice-return `aplicacao_spec_membros_returns_membros_slice_
22866 // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
22867 // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
22868 // across_permutations` (0dcc926) `&[WitContract]` pins — extends
22869 // the outer-accessor byte-equal-projection discipline onto the
22870 // outermost M3 mesh-slot type's per-Aplicacao distribution
22871 // composite-reference axis, the second `&Composite`-return
22872 // accessor on the outer [`AplicacaoSpec`] type.
22873 let fixtures: Vec<Placement> = vec![
22874 Placement::default(),
22875 Placement {
22876 estrategia: PlacementStrategy::SingleNode,
22877 clusters: vec!["rio".into()],
22878 affinity: None,
22879 shard_key: None,
22880 },
22881 Placement {
22882 estrategia: PlacementStrategy::Replicated,
22883 clusters: vec!["rio".into(), "mar".into()],
22884 affinity: None,
22885 shard_key: None,
22886 },
22887 Placement {
22888 estrategia: PlacementStrategy::Replicated,
22889 clusters: vec!["rio".into(), "mar".into()],
22890 affinity: Some("data-locality".into()),
22891 shard_key: None,
22892 },
22893 Placement {
22894 estrategia: PlacementStrategy::Sharded,
22895 clusters: vec!["rio".into(), "mar".into()],
22896 affinity: None,
22897 shard_key: Some("tenantId".into()),
22898 },
22899 Placement {
22900 estrategia: PlacementStrategy::Sharded,
22901 clusters: vec!["rio".into(), "mar".into(), "sol".into()],
22902 affinity: Some("low-latency".into()),
22903 shard_key: Some("metadata.tenantId".into()),
22904 },
22905 ];
22906 for placement in fixtures {
22907 let s = AplicacaoSpec {
22908 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
22909 contratos: Vec::new(),
22910 politicas: MeshPolicy::default(),
22911 placement: placement.clone(),
22912 entrada: None,
22913 };
22914 assert_eq!(
22915 *s.placement(),
22916 placement,
22917 "AplicacaoSpec::placement must return :placement verbatim \
22918 (got {:?}, expected {:?})",
22919 s.placement(),
22920 placement,
22921 );
22922 assert!(
22923 std::ptr::eq(s.placement(), &s.placement),
22924 "AplicacaoSpec::placement accessor and &self.placement \
22925 field access must borrow the same backing storage — the \
22926 accessor is the substrate-primitive typed dispatch every \
22927 downstream distribution-composite consumer must route \
22928 through, and a reference-identity split would silently \
22929 break every consumer that relied on the borrow sharing \
22930 the composite's storage",
22931 );
22932 assert_eq!(
22933 s.placement().estrategia(),
22934 s.placement.estrategia,
22935 "AplicacaoSpec::placement().estrategia() must byte-equal \
22936 self.placement.estrategia — a strategy-drift would \
22937 silently split the paired `validate_placement` \
22938 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
22939 peer caixa-mesh programs.yaml `placement.estrategia` \
22940 emitter's key from the peer `feira app graph` printer's \
22941 strategy label",
22942 );
22943 assert_eq!(
22944 s.placement().clusters(),
22945 s.placement.clusters.as_slice(),
22946 "AplicacaoSpec::placement().clusters() must byte-equal \
22947 self.placement.clusters — a cluster-pool drift would \
22948 silently split the paired `validate_placement` \
22949 pre-flight `.is_empty()` refusal probe's traversal from \
22950 the peer caixa-mesh programs.yaml `placement.clusters` \
22951 emitter's fan-out from the peer `feira app graph` \
22952 printer's cluster list",
22953 );
22954 }
22955 }
22956
22957 #[test]
22958 fn validate_placement_reads_through_lifted_placement_accessor() {
22959 // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
22960 // per-axis bracket-dispatch seed (`let p = self.placement();`,
22961 // followed by the per-axis fan-out `p.clusters()` /
22962 // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
22963 // lifted axis-level accessor family) must key off the lifted
22964 // outer accessor, so any future rebrand on the typed slot's
22965 // outer-composite reader shape lands at exactly one place. Pins
22966 // the multi-axis coherence by exercising each per-axis refusal
22967 // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
22968 // `:clusters` pool under the outer accessor's reference
22969 // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
22970 // strategy with a `None` `:shard-key` under the same projection,
22971 // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
22972 // with a `Some` `:shard-key` under the same projection, and
22973 // (4) the canonical `three_member_spec` `Replicated` fixture
22974 // passes `validate_placement` under the outer accessor's
22975 // reference projection — the accessor's reference-projection
22976 // reaches every per-axis branch (cluster-pool refusal, `Sharded`
22977 // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
22978 // without silently short-circuiting any.
22979 //
22980 // Peer of the sibling M3
22981 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
22982 // (534dc21) multi-axis coherence pin on the per-`:politicas`
22983 // outer mesh-policy composite-reference axis — extends the
22984 // multi-consumer coherence discipline onto the outermost M3
22985 // mesh-slot type's per-Aplicacao distribution composite-
22986 // reference axis, the second `&Composite`-return accessor on
22987 // the outer [`AplicacaoSpec`] type.
22988
22989 // (1) `PlacementWithoutClusters` refusal under the outer
22990 // accessor's reference projection: an empty `:clusters` pool
22991 // must trip the pre-flight refusal probe. The bracket-dispatch's
22992 // first arm reads `p.clusters()` on the reference returned by
22993 // the outer accessor.
22994 let mut spec = three_member_spec();
22995 spec.placement.clusters = Vec::new();
22996 assert_eq!(
22997 spec.validate().unwrap_err(),
22998 AplicacaoError::PlacementWithoutClusters {
22999 estrategia: PlacementStrategy::Replicated,
23000 },
23001 );
23002 assert!(
23003 std::ptr::eq(spec.placement(), &spec.placement),
23004 "the `validate_placement` per-axis bracket-dispatch's \
23005 traversal input must be the same backing composite the \
23006 accessor's reference projection borrows from",
23007 );
23008
23009 // (2) `ShardedWithoutKey` refusal under the outer accessor's
23010 // reference projection: a `Sharded` strategy with a `None`
23011 // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
23012 // The bracket-dispatch's third arm reads `p.estrategia()` for
23013 // the match scrutinee then `p.shard_key()` for the cascade
23014 // scrutinee, both on the reference returned by the outer
23015 // accessor.
23016 let mut spec = three_member_spec();
23017 spec.placement.estrategia = PlacementStrategy::Sharded;
23018 spec.placement.shard_key = None;
23019 assert_eq!(
23020 spec.validate().unwrap_err(),
23021 AplicacaoError::ShardedWithoutKey,
23022 );
23023
23024 // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
23025 // reference projection: a non-`Sharded` strategy with a `Some`
23026 // `:shard-key` must trip the declared-but-inert refusal. The
23027 // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
23028 // + `p.estrategia()` for the diagnostic on the reference
23029 // returned by the outer accessor.
23030 let mut spec = three_member_spec();
23031 spec.placement.estrategia = PlacementStrategy::Replicated;
23032 spec.placement.shard_key = Some("tenantId".into());
23033 assert_eq!(
23034 spec.validate().unwrap_err(),
23035 AplicacaoError::ShardKeyOnNonSharded {
23036 estrategia: PlacementStrategy::Replicated,
23037 shard_key: "tenantId".into(),
23038 },
23039 );
23040
23041 // (4) Canonical `three_member_spec` `Replicated` fixture passes
23042 // `validate_placement` — every per-axis arm reaches the fall-
23043 // through `Ok(())` without any per-axis refusal firing under the
23044 // outer accessor's reference projection.
23045 let spec = three_member_spec();
23046 assert!(
23047 spec.validate().is_ok(),
23048 "the canonical Replicated placement fixture must pass \
23049 `validate_placement` — every per-axis arm short-circuits on \
23050 valid input under the outer accessor's reference projection",
23051 );
23052 assert_eq!(
23053 spec.placement().estrategia(),
23054 PlacementStrategy::Replicated,
23055 "the outer accessor's reference projection must be the \
23056 canonical Replicated fixture's strategy",
23057 );
23058 assert_eq!(
23059 spec.placement().clusters(),
23060 &["rio", "mar"],
23061 "the outer accessor's reference projection must be the \
23062 canonical Replicated fixture's cluster pool",
23063 );
23064 }
23065
23066 #[test]
23067 fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
23068 // The canonical per-`:entrada` outer-composite-optional-
23069 // reference-shape pin: [`AplicacaoSpec::entrada`] must return
23070 // the `:entrada` typed `Option<Entrada>` verbatim as an
23071 // `Option<&Entrada>` reference over the same backing storage
23072 // the raw `self.entrada.as_ref()` field access borrows from,
23073 // byte-equal across every representative fixture in the
23074 // accept-set — the author-omitted `None` shape (the
23075 // "internal-only mesh" partition every downstream external-
23076 // gateway emitter treats as "emit nothing"), the minimal
23077 // singleton `:entrada` composite (host + destination + empty
23078 // paths + default port), the paths-carrying composite (the
23079 // canonical `three_member_spec` fixture's ["/api" "/health"]
23080 // path-list shape every HTTPRoute per-rule fan-out emitter
23081 // reads), and the non-default port composite (the canonical
23082 // custom-port shape the port-fallback resolver reads).
23083 //
23084 // Pins against a future silent detour that returned a fresh-
23085 // cloned `Entrada` copy (which would type-check via a `Clone`
23086 // impl but silently break every downstream caller that
23087 // relied on the reference sharing the composite's backing
23088 // identity), a reference to an operator-resolved overlay
23089 // (the future per-cluster `:entrada-overrides` slot the
23090 // MESH-COMPOSITION §V federation roadmap acknowledges — its
23091 // resolution must land at exactly this accessor body, not
23092 // silently divert the raw slot away from a second consumer),
23093 // a `None` → `Some(Entrada::default)` cluster-default
23094 // projection (which would collapse the load-bearing
23095 // "author-omitted `:entrada` ⇒ internal-only mesh" partition
23096 // the peer `gateway_routes` early-return + `feira app graph`
23097 // internal-only-mesh partition both read), or an axis-
23098 // shuffled projection (a future detour that swapped
23099 // `host` and `para` through the accessor would silently
23100 // split the paired `validate` per-`:entrada` shape-and-
23101 // membership gate's traversal input from the peer
23102 // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
23103 // fan-out input from the peer `feira app graph` external-
23104 // gateway summary line).
23105 //
23106 // Peer of the sibling M3
23107 // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
23108 // (534dc21) `&MeshPolicy` byte-equal pin on the per-
23109 // `:politicas` outer mesh-policy composite-reference axis
23110 // and of the sibling M3
23111 // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
23112 // (9abb8f0) `&Placement` byte-equal pin on the per-
23113 // `:placement` outer distribution-composite composite-
23114 // reference axis — extends the outer-accessor byte-equal-
23115 // projection discipline onto the last unlifted outermost M3
23116 // mesh-slot type's per-Aplicacao external-gateway composite-
23117 // reference axis, the third and final `&Composite`-return
23118 // accessor on the outer [`AplicacaoSpec`] type.
23119 let fixtures: Vec<Option<Entrada>> = vec![
23120 None,
23121 Some(Entrada {
23122 host: "checkout.quero.cloud".into(),
23123 para: "cart".into(),
23124 paths: Vec::new(),
23125 port: DEFAULT_SERVICO_PORT,
23126 }),
23127 Some(Entrada {
23128 host: "checkout.quero.cloud".into(),
23129 para: "cart".into(),
23130 paths: vec!["/api".into(), "/health".into()],
23131 port: DEFAULT_SERVICO_PORT,
23132 }),
23133 Some(Entrada {
23134 host: "checkout.quero.cloud".into(),
23135 para: "cart".into(),
23136 paths: vec!["/api".into()],
23137 port: 9443,
23138 }),
23139 ];
23140 for entrada in fixtures {
23141 let s = AplicacaoSpec {
23142 membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23143 contratos: Vec::new(),
23144 politicas: MeshPolicy::default(),
23145 placement: Placement::default(),
23146 entrada: entrada.clone(),
23147 };
23148 assert_eq!(
23149 s.entrada(),
23150 entrada.as_ref(),
23151 "AplicacaoSpec::entrada must return :entrada verbatim \
23152 (got {:?}, expected {:?})",
23153 s.entrada(),
23154 entrada.as_ref(),
23155 );
23156 match (s.entrada(), s.entrada.as_ref()) {
23157 (Some(a), Some(b)) => assert!(
23158 std::ptr::eq(a, b),
23159 "AplicacaoSpec::entrada accessor and \
23160 self.entrada.as_ref() field access must borrow \
23161 the same backing storage — the accessor is the \
23162 substrate-primitive typed dispatch every \
23163 downstream external-gateway composite consumer \
23164 must route through, and a reference-identity \
23165 split would silently break every consumer that \
23166 relied on the borrow sharing the composite's \
23167 storage",
23168 ),
23169 (None, None) => {}
23170 _ => panic!(
23171 "AplicacaoSpec::entrada presence bit must byte-\
23172 equal self.entrada.is_some() — a presence-bit \
23173 drift would silently split the paired `validate` \
23174 per-`:entrada` shape-and-membership gate's \
23175 traversal head from the peer \
23176 caixa-mesh gateway_routes early-return partition \
23177 from the peer `feira app graph` internal-only-\
23178 mesh partition",
23179 ),
23180 }
23181 assert_eq!(
23182 s.entrada().is_some(),
23183 s.entrada.is_some(),
23184 "AplicacaoSpec::entrada().is_some() must byte-equal \
23185 self.entrada.is_some() — a presence-bit drift would \
23186 silently split every downstream `Option<&Entrada>` \
23187 consumer's partition on the internal-only-mesh arm",
23188 );
23189 }
23190 }
23191
23192 #[test]
23193 fn validate_reads_through_lifted_entrada_accessor() {
23194 // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
23195 // per-`:entrada` shape-and-membership gate (`if let Some(e) =
23196 // self.entrada() { … }`, followed by the per-axis fan-out
23197 // `validate_entrada_para(&e.para)` /
23198 // `EntradaMemberMissing` membership lookup /
23199 // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
23200 // per-`e.paths` `validate_entrada_path` traversal) must key
23201 // off the lifted outer accessor, so any future rebrand on
23202 // the typed slot's outer-composite reader shape lands at
23203 // exactly one place. Pins the multi-axis coherence by
23204 // exercising each per-axis refusal end-to-end: (1) the
23205 // author-omitted `None` shape short-circuits past every
23206 // per-`:entrada` refusal (the internal-only mesh partition
23207 // the accessor's `None` arm names), (2) `EntradaMemberMissing`
23208 // fires on a well-shaped but phantom `:para` under the outer
23209 // accessor's reference projection, and (3) the canonical
23210 // `three_member_spec` `:entrada` fixture passes `validate`
23211 // under the outer accessor's reference projection.
23212 //
23213 // Peer of the sibling M3
23214 // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23215 // (534dc21) multi-axis coherence pin on the per-`:politicas`
23216 // outer mesh-policy composite-reference axis and the sibling
23217 // M3
23218 // [`validate_placement_reads_through_lifted_placement_accessor`]
23219 // (9abb8f0) multi-axis coherence pin on the per-`:placement`
23220 // outer distribution-composite composite-reference axis —
23221 // extends the multi-consumer coherence discipline onto the
23222 // last unlifted outermost M3 mesh-slot type's per-Aplicacao
23223 // external-gateway composite-reference axis, the third and
23224 // final `&Composite`-return accessor on the outer
23225 // [`AplicacaoSpec`] type.
23226
23227 // (1) `None` :entrada — the internal-only-mesh partition
23228 // short-circuits past every per-`:entrada` refusal. The outer
23229 // accessor's reference projection reaches the fall-through
23230 // `Ok(())` on the `None` arm without any per-axis refusal
23231 // firing.
23232 let mut spec = three_member_spec();
23233 spec.entrada = None;
23234 assert!(
23235 spec.validate().is_ok(),
23236 "an author-omitted `:entrada` must pass `validate` — the \
23237 internal-only-mesh partition short-circuits past every \
23238 per-`:entrada` refusal under the outer accessor's \
23239 reference projection",
23240 );
23241 assert!(
23242 spec.entrada().is_none(),
23243 "the outer accessor's reference projection must name the \
23244 internal-only-mesh partition per the `None` fixture",
23245 );
23246
23247 // (2) `EntradaMemberMissing` refusal under the outer accessor's
23248 // reference projection: a well-shaped but phantom `:para` must
23249 // trip the membership-lookup refusal. The gate's second arm
23250 // reads `e.para` on the reference returned by the outer
23251 // accessor.
23252 let mut spec = three_member_spec();
23253 if let Some(e) = spec.entrada.as_mut() {
23254 e.para = "phantom".into();
23255 }
23256 assert_eq!(
23257 spec.validate().unwrap_err(),
23258 AplicacaoError::EntradaMemberMissing {
23259 para: "phantom".into(),
23260 },
23261 );
23262 match (spec.entrada(), spec.entrada.as_ref()) {
23263 (Some(a), Some(b)) => assert!(
23264 std::ptr::eq(a, b),
23265 "the `validate` per-`:entrada` gate's traversal head \
23266 must be the same backing composite the accessor's \
23267 reference projection borrows from",
23268 ),
23269 _ => panic!("fixture must carry Some(:entrada)"),
23270 }
23271
23272 // (3) Canonical `three_member_spec` `:entrada` fixture passes
23273 // `validate` — every per-axis arm reaches the fall-through
23274 // `Ok(())` without any per-axis refusal firing under the
23275 // outer accessor's reference projection.
23276 let spec = three_member_spec();
23277 assert!(
23278 spec.validate().is_ok(),
23279 "the canonical `:entrada` fixture must pass `validate` — \
23280 every per-axis arm short-circuits on valid input under \
23281 the outer accessor's reference projection",
23282 );
23283 assert!(
23284 spec.entrada().is_some(),
23285 "the outer accessor's reference projection must be the \
23286 canonical `:entrada` fixture's composite",
23287 );
23288 }
23289
23290 #[test]
23291 fn port_for_destination_reads_through_lifted_entrada_accessor() {
23292 // Peer coherence pin: the
23293 // [`AplicacaoSpec::port_for_destination`] per-destination
23294 // L4-port fallback resolver's composite-projection seed
23295 // (`self.entrada().filter(…).map_or(…)`) must key off the
23296 // lifted outer accessor. Pins the coherence by exercising
23297 // the resolver end-to-end: (1) the `None` `:entrada` shape
23298 // falls through to `DEFAULT_SERVICO_PORT` under the outer
23299 // accessor's reference projection, (2) a non-matching
23300 // destination falls through to `DEFAULT_SERVICO_PORT` under
23301 // the outer accessor's reference projection, and (3) the
23302 // matching destination resolves to the `:entrada :port`
23303 // value under the outer accessor's reference projection.
23304 //
23305 // Peer of the sibling
23306 // [`validate_reads_through_lifted_entrada_accessor`] multi-
23307 // consumer coherence pin on the same per-`:entrada` outer-
23308 // composite axis — extends the multi-consumer coherence
23309 // discipline onto the second per-`:entrada` production
23310 // consumer, the L4-port fallback resolver.
23311
23312 // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
23313 // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
23314 // arm under the outer accessor's reference projection.
23315 let mut spec = three_member_spec();
23316 spec.entrada = None;
23317 assert_eq!(
23318 spec.port_for_destination("cart"),
23319 DEFAULT_SERVICO_PORT,
23320 "the port-fallback resolver must fall through to \
23321 DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
23322 under the outer accessor's reference projection",
23323 );
23324
23325 // (2) Non-matching destination — the resolver's `filter(…)`
23326 // arm rejects a mismatched destination and falls through
23327 // to `DEFAULT_SERVICO_PORT` under the outer accessor's
23328 // reference projection.
23329 let mut spec = three_member_spec();
23330 if let Some(e) = spec.entrada.as_mut() {
23331 e.para = "cart".into();
23332 e.port = 9443;
23333 }
23334 assert_eq!(
23335 spec.port_for_destination("catalog"),
23336 DEFAULT_SERVICO_PORT,
23337 "the port-fallback resolver must fall through to \
23338 DEFAULT_SERVICO_PORT on a non-matching destination \
23339 under the outer accessor's reference projection",
23340 );
23341
23342 // (3) Matching destination — the resolver's `map_or(…)` arm
23343 // returns the `:entrada :port` value under the outer
23344 // accessor's reference projection.
23345 let mut spec = three_member_spec();
23346 if let Some(e) = spec.entrada.as_mut() {
23347 e.para = "cart".into();
23348 e.port = 9443;
23349 }
23350 assert_eq!(
23351 spec.port_for_destination("cart"),
23352 9443,
23353 "the port-fallback resolver must return the \
23354 `:entrada :port` value on a matching destination \
23355 under the outer accessor's reference projection",
23356 );
23357 }
23358
23359 #[test]
23360 fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
23361 // The canonical per-`:politicas` `:mtls-required` mTLS-
23362 // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
23363 // must return the `:politicas :mtls-required` typed bool
23364 // verbatim as an `Option<bool>`, byte-equal to the raw field
23365 // access across every value in the three-way accept-set —
23366 // `None` (cluster default applies), `Some(true)` (mTLS
23367 // handshake enforced — the sandboxing-by-default arm the
23368 // MeshPolicy's docstring names), `Some(false)` (handshake
23369 // skipped — the explicit debug-edge opt-out).
23370 //
23371 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
23372 // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
23373 // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
23374 // shape — first `Option<Copy-T>`-return accessor on the M3
23375 // mesh-slot family. Pins against a future silent detour that
23376 // re-derived the toggle from a peer axis (an accidental
23377 // `.circuit_breaker.is_some()` collapse that assumed mTLS on
23378 // whenever a breaker is set), a `None` → `Some(false)` cluster-
23379 // default projection (the canonical `Option<bool>` → `bool`
23380 // collapse footgun the surrounding `is_empty()` predicate
23381 // guards on the peer emptiness axis), or a `Some(true)` /
23382 // `Some(false)` variant swap that landed on one consumer
23383 // without the other.
23384 for required in [None, Some(true), Some(false)] {
23385 let p = MeshPolicy {
23386 mtls_required: required,
23387 ..MeshPolicy::default()
23388 };
23389 assert_eq!(
23390 p.mtls_required(),
23391 required,
23392 "MeshPolicy::mtls_required must return :politicas \
23393 :mtls-required verbatim (got {:?}, expected {required:?})",
23394 p.mtls_required(),
23395 );
23396 assert_eq!(
23397 p.mtls_required(),
23398 p.mtls_required,
23399 "MeshPolicy::mtls_required must byte-equal the raw \
23400 .mtls_required field access across every value in the \
23401 three-way accept-set",
23402 );
23403 }
23404 }
23405
23406 #[test]
23407 fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
23408 // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
23409 // arm must key off [`MeshPolicy::mtls_required`], not the raw
23410 // `.mtls_required` field access. Structurally: toggling ONLY
23411 // the `mtls_required` slot on an otherwise-default MeshPolicy
23412 // must flip `is_empty()` from `true` (all-`None`) to `false`
23413 // (one axis carries a value); the flip must be observed for
23414 // both `Some(true)` and `Some(false)` since the emptiness
23415 // semantic reads "any axis carries a value" — not "any axis
23416 // carries a truthy value" — the same non-collapsing shape the
23417 // sibling M2 [`crate::LimitsSpec::is_empty`] /
23418 // [`crate::BehaviorSpec::is_empty`] predicates carry on their
23419 // peer `Option<T>`-typed slot surfaces.
23420 //
23421 // Pins against a future silent detour that re-derived the
23422 // emptiness predicate off a peer axis (an accidental
23423 // `.rate_limit.is_none()`-only chain that dropped the
23424 // `mtls_required` arm entirely), a `mtls_required == Some(_)`
23425 // collapse to a truthy-only check (which would silently
23426 // classify `Some(false)` as empty), or an accessor-side
23427 // detour that no longer names the substrate-primitive typed
23428 // dispatch (an accidental `self.mtls_required.unwrap_or(false)
23429 // == false` fallback in the accessor that would silently
23430 // classify both `None` and `Some(false)` as the same value).
23431 //
23432 // Peer of the sibling per-`:placement` [`Placement::shard_key`]
23433 // (7cd2a28) accessor-composition pin on the sibling optional-
23434 // scalar axis — same "the emptiness / shape-gate predicate
23435 // must route through the substrate-primitive typed dispatch"
23436 // discipline extended onto the peer per-`:politicas` emptiness
23437 // predicate.
23438 let empty = MeshPolicy::default();
23439 assert!(
23440 empty.is_empty(),
23441 "MeshPolicy::default() must be is_empty() — every axis \
23442 defaults to None",
23443 );
23444 for required in [Some(true), Some(false)] {
23445 let p = MeshPolicy {
23446 mtls_required: required,
23447 ..MeshPolicy::default()
23448 };
23449 assert!(
23450 !p.is_empty(),
23451 "MeshPolicy::is_empty must return false when \
23452 :mtls-required is {required:?} — the emptiness \
23453 predicate reads \"any axis carries a value\", not \
23454 \"any axis carries a truthy value\"",
23455 );
23456 assert_eq!(
23457 p.mtls_required().is_none(),
23458 p.is_empty(),
23459 "when :mtls-required is the only set axis, \
23460 is_empty() must equal mtls_required().is_none() — \
23461 the accessor and the emptiness predicate must \
23462 route through the same substrate-primitive typed \
23463 dispatch on the :mtls-required arm",
23464 );
23465 }
23466 }
23467
23468 #[test]
23469 fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
23470 // The by-copy pin: [`MeshPolicy::mtls_required`] returns
23471 // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
23472 // accessor must return by value, not by reference. Peer of the
23473 // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
23474 // borrow-invariant pin on the sibling `Option<String>` slot,
23475 // but extended onto the peer `Option<bool>` copy-invariant
23476 // shape — the accessor's returned `Option<bool>` must outlive
23477 // `&self` (multiple calls must return equal values from a
23478 // dropped-`&self` copy, since the returned Option carries no
23479 // borrow), and calling the accessor twice on the same
23480 // MeshPolicy must yield the same `Option<bool>` verbatim
23481 // (idempotent, no side effects on `&self`).
23482 //
23483 // Pins against a future silent detour that returned
23484 // `Option<&bool>` (which would type-check but silently break
23485 // every downstream caller — [`single_field_overlay`]'s first
23486 // parameter is `Option<T: Clone>`, and `&bool` would fold to a
23487 // detached copy at the call site), an accidental
23488 // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
23489 // would also type-check but return `Option<&bool>`), or a
23490 // one-arm-only accessor that reads `Some(*b)` in the Some arm
23491 // but reads a fresh Default::default() in the None arm.
23492 for required in [None, Some(true), Some(false)] {
23493 let p = MeshPolicy {
23494 mtls_required: required,
23495 ..MeshPolicy::default()
23496 };
23497 let first = p.mtls_required();
23498 let second = p.mtls_required();
23499 assert_eq!(
23500 first, second,
23501 "MeshPolicy::mtls_required must be idempotent — two \
23502 successive calls on the same &self must return the \
23503 same Option<bool>",
23504 );
23505 assert_eq!(
23506 first, required,
23507 "MeshPolicy::mtls_required must return :politicas \
23508 :mtls-required verbatim by copy — got {first:?}, \
23509 expected {required:?}",
23510 );
23511 }
23512 }
23513
23514 #[test]
23515 fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
23516 // The canonical per-`:politicas` `:retries` transient-failure-
23517 // retry-budget scalar pin: [`MeshPolicy::retries`] must return
23518 // the `:politicas :retries` typed `u32` verbatim as an
23519 // `Option<u32>`, byte-equal to the raw field access across every
23520 // representative value in the accept-set — `None` (cluster
23521 // default applies — typically "no retries beyond a single
23522 // dispatch attempt" the caixa-mesh `retry_overlay` builder
23523 // documents), `Some(1)` (the lower boundary of the
23524 // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
23525 // `AplicacaoSpec::validate_politicas` gate carves out on the
23526 // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
23527 // (the upper boundary the same gate carves out on the sibling
23528 // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
23529 // past-the-guard sentinel that pins the accessor doesn't perform
23530 // a silent bounds-collapse at the return path).
23531 //
23532 // Sibling of the peer per-`:politicas`
23533 // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
23534 // sibling `Option<Copy-T>` optional-scalar axis, extended to the
23535 // peer per-`:politicas` `Option<u32>` shape — second
23536 // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
23537 // Pins against a future silent detour that re-derived the retry
23538 // cap from a peer axis (an accidental `.circuit_breaker
23539 // .as_ref().map(|b| b.max_failures)` collapse that read the
23540 // breaker's max-failure count as a retry budget), a
23541 // `None → Some(0)` cluster-default projection (which would
23542 // silently re-introduce the `PolicyRetriesZero` refusal case at
23543 // the emit boundary), or a bounds-collapsing accessor that
23544 // clamped the return through `POLICY_RETRIES_MAX` (the
23545 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
23546 // must ship the raw slot verbatim so a validate-time gate
23547 // regression surfaces at the emit boundary rather than being
23548 // silently absorbed).
23549 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
23550 let p = MeshPolicy {
23551 retries,
23552 ..MeshPolicy::default()
23553 };
23554 assert_eq!(
23555 p.retries(),
23556 retries,
23557 "MeshPolicy::retries must return :politicas :retries \
23558 verbatim (got {:?}, expected {retries:?})",
23559 p.retries(),
23560 );
23561 assert_eq!(
23562 p.retries(),
23563 p.retries,
23564 "MeshPolicy::retries must byte-equal the raw .retries \
23565 field access across every value in the accept-set",
23566 );
23567 }
23568 }
23569
23570 #[test]
23571 fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
23572 // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
23573 // must key off [`MeshPolicy::retries`], not the raw `.retries`
23574 // field access. Structurally: toggling ONLY the `retries` slot
23575 // on an otherwise-default MeshPolicy must flip `is_empty()`
23576 // from `true` (all-`None`) to `false` (one axis carries a
23577 // value); the flip must be observed for every value in the
23578 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
23579 // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
23580 // the emptiness semantic reads "any axis carries a value" —
23581 // not "any axis carries a value the validate gate accepts" —
23582 // the same non-collapsing shape the peer M2
23583 // [`crate::LimitsSpec::is_empty`] /
23584 // [`crate::BehaviorSpec::is_empty`] predicates carry.
23585 //
23586 // Pins against a future silent detour that re-derived the
23587 // emptiness predicate off a peer axis (an accidental
23588 // `.rate_limit.is_none()`-only chain that dropped the
23589 // `retries` arm entirely), a `retries == Some(_)` collapse
23590 // that key-off a validate-gate-clamped bounds check (which
23591 // would silently classify a past-the-guard `Some(u32::MAX)`
23592 // as empty because it fails the `1..=POLICY_RETRIES_MAX`
23593 // check), or an accessor-side detour that no longer names the
23594 // substrate-primitive typed dispatch.
23595 //
23596 // Sibling of the peer per-`:politicas`
23597 // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
23598 // pin on the sibling `Option<Copy-T>` optional-scalar axis —
23599 // same "the emptiness predicate must route through the
23600 // substrate-primitive typed dispatch" discipline extended onto
23601 // the peer per-`:politicas` `Option<u32>` axis.
23602 let empty = MeshPolicy::default();
23603 assert!(
23604 empty.is_empty(),
23605 "MeshPolicy::default() must be is_empty() — every axis \
23606 defaults to None",
23607 );
23608 for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
23609 let p = MeshPolicy {
23610 retries,
23611 ..MeshPolicy::default()
23612 };
23613 assert!(
23614 !p.is_empty(),
23615 "MeshPolicy::is_empty must return false when \
23616 :retries is {retries:?} — the emptiness \
23617 predicate reads \"any axis carries a value\", not \
23618 \"any axis carries a value the validate gate \
23619 accepts\"",
23620 );
23621 assert_eq!(
23622 p.retries().is_none(),
23623 p.is_empty(),
23624 "when :retries is the only set axis, is_empty() \
23625 must equal retries().is_none() — the accessor and \
23626 the emptiness predicate must route through the same \
23627 substrate-primitive typed dispatch on the :retries \
23628 arm",
23629 );
23630 }
23631 }
23632
23633 #[test]
23634 fn mesh_policy_retries_projects_option_u32_by_copy() {
23635 // The by-copy pin: [`MeshPolicy::retries`] returns
23636 // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
23637 // accessor must return by value, not by reference. Sibling of
23638 // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
23639 // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
23640 // extended onto the sibling `Option<u32>` copy-invariant
23641 // shape — the accessor's returned `Option<u32>` must outlive
23642 // `&self` (multiple calls must return equal values from a
23643 // dropped-`&self` copy, since the returned Option carries no
23644 // borrow), and calling the accessor twice on the same
23645 // MeshPolicy must yield the same `Option<u32>` verbatim
23646 // (idempotent, no side effects on `&self`).
23647 //
23648 // Pins against a future silent detour that returned
23649 // `Option<&u32>` (which would type-check but silently break
23650 // every downstream caller — [`crate::render::single_field_overlay`]'s
23651 // first parameter is `Option<T: Clone>`, and `&u32` would
23652 // fold to a detached copy at the call site), an accidental
23653 // `Option::as_ref()` projection (`self.retries.as_ref()` would
23654 // also type-check but return `Option<&u32>`), or a one-arm-
23655 // only accessor that reads `Some(*n)` in the Some arm but
23656 // reads a fresh `Default::default()` (`0_u32`) in the None
23657 // arm.
23658 for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
23659 let p = MeshPolicy {
23660 retries,
23661 ..MeshPolicy::default()
23662 };
23663 let first = p.retries();
23664 let second = p.retries();
23665 assert_eq!(
23666 first, second,
23667 "MeshPolicy::retries must be idempotent — two \
23668 successive calls on the same &self must return the \
23669 same Option<u32>",
23670 );
23671 assert_eq!(
23672 first, retries,
23673 "MeshPolicy::retries must return :politicas :retries \
23674 verbatim by copy — got {first:?}, expected {retries:?}",
23675 );
23676 }
23677 }
23678
23679 #[test]
23680 fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
23681 // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
23682 // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
23683 // return the `:politicas :timeout` typed [`Duration`] verbatim
23684 // as an `Option<Duration>`, byte-equal to the raw field access
23685 // across every representative value in the accept-set — `None`
23686 // (cluster default applies — typically the gateway class's
23687 // implementation-side per-request wall-clock cap the caixa-mesh
23688 // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
23689 // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
23690 // set the surrounding `AplicacaoSpec::validate_politicas` gate
23691 // carves out on the sibling `PolicyTimeoutZero` /
23692 // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
23693 // (the upper boundary the same gate carves out on the sibling
23694 // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
23695 // (a past-the-guard sentinel that pins the accessor doesn't
23696 // perform a silent bounds-collapse into `None` on the zero-
23697 // Duration arm — validate rejects zero but the accessor must
23698 // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
23699 // past-the-guard sentinel that pins the accessor doesn't
23700 // perform a silent bounds-collapse at the return path).
23701 //
23702 // Sibling of the peer per-`:politicas`
23703 // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
23704 // `Option<u32>` optional-scalar axis and the peer per-
23705 // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
23706 // pin on the sibling `Option<bool>` optional-scalar axis,
23707 // extended onto the peer per-`:politicas` `Option<Duration>`
23708 // shape — third `Option<Copy-T>`-return accessor on the M3
23709 // mesh-slot family. Pins against a future silent detour that
23710 // re-derived the per-call cap from a peer axis (an accidental
23711 // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
23712 // read the breaker's rolling-window duration as a per-call
23713 // deadline), a `None → Some(Duration::MAX)` cluster-default
23714 // projection (which would silently re-introduce the
23715 // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
23716 // blocking" arm at the emit boundary), or a bounds-collapsing
23717 // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
23718 // (the `AplicacaoSpec::validate` gate owns the bounds; the
23719 // accessor must ship the raw slot verbatim so a validate-time
23720 // gate regression surfaces at the emit boundary rather than
23721 // being silently absorbed).
23722 for timeout in [
23723 None,
23724 Some(Duration::from_millis(1)),
23725 Some(POLICY_TIMEOUT_MAX),
23726 Some(Duration::ZERO),
23727 Some(Duration::MAX),
23728 ] {
23729 let p = MeshPolicy {
23730 timeout,
23731 ..MeshPolicy::default()
23732 };
23733 assert_eq!(
23734 p.timeout(),
23735 timeout,
23736 "MeshPolicy::timeout must return :politicas :timeout \
23737 verbatim (got {:?}, expected {timeout:?})",
23738 p.timeout(),
23739 );
23740 assert_eq!(
23741 p.timeout(),
23742 p.timeout,
23743 "MeshPolicy::timeout must byte-equal the raw .timeout \
23744 field access across every value in the accept-set",
23745 );
23746 }
23747 }
23748
23749 #[test]
23750 fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
23751 // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
23752 // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
23753 // field access. Structurally: toggling ONLY the `timeout` slot
23754 // on an otherwise-default MeshPolicy must flip `is_empty()`
23755 // from `true` (all-`None`) to `false` (one axis carries a
23756 // value); the flip must be observed for every value in the
23757 // accept-set the surrounding `AplicacaoSpec::validate_politicas`
23758 // gate accepts (`Some(Duration::from_millis(1))`,
23759 // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
23760 // reads "any axis carries a value" — not "any axis carries a
23761 // value the validate gate accepts" — the same non-collapsing
23762 // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
23763 // [`crate::BehaviorSpec::is_empty`] predicates carry.
23764 //
23765 // Pins against a future silent detour that re-derived the
23766 // emptiness predicate off a peer axis (an accidental
23767 // `.rate_limit.is_none()`-only chain that dropped the
23768 // `timeout` arm entirely), a `timeout == Some(_)` collapse
23769 // that key-off a validate-gate-clamped bounds check (which
23770 // would silently classify a past-the-guard `Some(Duration::MAX)`
23771 // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
23772 // check), or an accessor-side detour that no longer names the
23773 // substrate-primitive typed dispatch.
23774 //
23775 // Sibling of the peer per-`:politicas`
23776 // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
23777 // the sibling `Option<u32>` optional-scalar axis and the peer
23778 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
23779 // accessor-composition pin on the sibling `Option<bool>`
23780 // optional-scalar axis — same "the emptiness predicate must
23781 // route through the substrate-primitive typed dispatch"
23782 // discipline extended onto the peer per-`:politicas`
23783 // `Option<Duration>` axis.
23784 let empty = MeshPolicy::default();
23785 assert!(
23786 empty.is_empty(),
23787 "MeshPolicy::default() must be is_empty() — every axis \
23788 defaults to None",
23789 );
23790 for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
23791 let p = MeshPolicy {
23792 timeout,
23793 ..MeshPolicy::default()
23794 };
23795 assert!(
23796 !p.is_empty(),
23797 "MeshPolicy::is_empty must return false when \
23798 :timeout is {timeout:?} — the emptiness \
23799 predicate reads \"any axis carries a value\", not \
23800 \"any axis carries a value the validate gate \
23801 accepts\"",
23802 );
23803 assert_eq!(
23804 p.timeout().is_none(),
23805 p.is_empty(),
23806 "when :timeout is the only set axis, is_empty() \
23807 must equal timeout().is_none() — the accessor and \
23808 the emptiness predicate must route through the same \
23809 substrate-primitive typed dispatch on the :timeout \
23810 arm",
23811 );
23812 }
23813 }
23814
23815 #[test]
23816 fn mesh_policy_timeout_projects_option_duration_by_copy() {
23817 // The by-copy pin: [`MeshPolicy::timeout`] returns
23818 // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
23819 // and the accessor must return by value, not by reference.
23820 // Sibling of the peer per-`:politicas`
23821 // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
23822 // sibling `Option<u32>` optional-scalar axis and the peer
23823 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
23824 // by-copy pin on the sibling `Option<bool>` optional-scalar
23825 // axis, extended onto the peer per-`:politicas`
23826 // `Option<Duration>` copy-invariant shape — the accessor's
23827 // returned `Option<Duration>` must outlive `&self` (multiple
23828 // calls must return equal values from a dropped-`&self`
23829 // copy, since the returned Option carries no borrow), and
23830 // calling the accessor twice on the same MeshPolicy must
23831 // yield the same `Option<Duration>` verbatim (idempotent, no
23832 // side effects on `&self`).
23833 //
23834 // Pins against a future silent detour that returned
23835 // `Option<&Duration>` (which would type-check but silently
23836 // break every downstream caller — [`crate::render::single_field_overlay`]'s
23837 // first parameter is `Option<T: Clone>`, and `&Duration`
23838 // would fold to a detached copy at the call site), an
23839 // accidental `Option::as_ref()` projection
23840 // (`self.timeout.as_ref()` would also type-check but return
23841 // `Option<&Duration>`), or a one-arm-only accessor that
23842 // reads `Some(*d)` in the Some arm but reads a fresh
23843 // `Default::default()` (`Duration::ZERO`) in the None arm
23844 // (which would silently re-classify every unset `:timeout`
23845 // as the `PolicyTimeoutZero`-refused zero-Duration value at
23846 // the accessor boundary).
23847 for timeout in [
23848 None,
23849 Some(Duration::from_millis(1)),
23850 Some(POLICY_TIMEOUT_MAX),
23851 Some(Duration::ZERO),
23852 Some(Duration::MAX),
23853 ] {
23854 let p = MeshPolicy {
23855 timeout,
23856 ..MeshPolicy::default()
23857 };
23858 let first = p.timeout();
23859 let second = p.timeout();
23860 assert_eq!(
23861 first, second,
23862 "MeshPolicy::timeout must be idempotent — two \
23863 successive calls on the same &self must return the \
23864 same Option<Duration>",
23865 );
23866 assert_eq!(
23867 first, timeout,
23868 "MeshPolicy::timeout must return :politicas :timeout \
23869 verbatim by copy — got {first:?}, expected {timeout:?}",
23870 );
23871 }
23872 }
23873
23874 #[test]
23875 fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
23876 // The canonical per-`:politicas` `:rate-limit` Envoy-
23877 // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
23878 // [`MeshPolicy::rate_limit`] must return the `:politicas
23879 // :rate-limit` typed [`RateLimit`] verbatim as an
23880 // `Option<RateLimit>`, byte-equal to the raw field access
23881 // across every representative value in the accept-set — `None`
23882 // (cluster default applies — no per-Aplicacao rate declaration,
23883 // the gateway-class per-listener default arm the future caixa-
23884 // mesh `local_rate_limit_overlay` emitter documents),
23885 // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
23886 // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
23887 // accept-set the surrounding
23888 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
23889 // sibling `PolicyRateLimitZero` refusal, paired with the
23890 // canonical-window "1 second" arm of the three-unit
23891 // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
23892 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
23893 // (the upper boundary the same gate carves out on the sibling
23894 // `PolicyRateLimitExceedsCap` refusal, paired with the
23895 // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
23896 // (a past-the-guard sentinel that pins the accessor doesn't
23897 // perform a silent bounds-collapse into `None` on the
23898 // zero-rate/zero-window arm — validate rejects zero but the
23899 // accessor must ship the raw slot verbatim so a validate-time
23900 // gate regression surfaces at the emit boundary rather than
23901 // being silently absorbed), and
23902 // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
23903 // (a past-the-guard sentinel that pins the accessor doesn't
23904 // perform a silent bounds-collapse at the return path).
23905 //
23906 // First `Option<Copy-composite-T>`-return accessor pin on the
23907 // M3 mesh-slot family (peer of the sibling per-`:politicas`
23908 // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
23909 // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
23910 // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
23911 // Copy accessor pins, extended onto the peer per-`:politicas`
23912 // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
23913 // and the accessor returns by value). Pins against a future
23914 // silent detour that re-derived the rate declaration from a
23915 // peer axis (an accidental
23916 // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
23917 // collapse that read the breaker's trip threshold + rolling
23918 // window as a rate declaration), a `None → Some(default())`
23919 // cluster-default projection (which would silently re-
23920 // introduce a "cluster default is 0/s" arm the emit boundary
23921 // would take as "declared but inert" — the canonical
23922 // declared-but-inert footgun the sibling
23923 // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
23924 // amplification-shape axis), a bounds-collapsing accessor
23925 // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
23926 // clamped `rl.window` through [`is_canonical_rate_limit_window`]
23927 // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
23928 // accessor must ship the raw slot verbatim), or a
23929 // by-reference detour (`Option<&RateLimit>`) that broke every
23930 // downstream consumer keying off `Option<RateLimit>` by-copy.
23931 for rl in [
23932 None,
23933 Some(RateLimit {
23934 rate: 1,
23935 window: Duration::from_secs(1),
23936 }),
23937 Some(RateLimit {
23938 rate: POLICY_RATE_LIMIT_MAX,
23939 window: Duration::from_secs(3600),
23940 }),
23941 Some(RateLimit {
23942 rate: 0,
23943 window: Duration::ZERO,
23944 }),
23945 Some(RateLimit {
23946 rate: u32::MAX,
23947 window: Duration::MAX,
23948 }),
23949 ] {
23950 let p = MeshPolicy {
23951 rate_limit: rl,
23952 ..MeshPolicy::default()
23953 };
23954 assert_eq!(
23955 p.rate_limit(),
23956 rl,
23957 "MeshPolicy::rate_limit must return :politicas :rate-limit \
23958 verbatim (got {:?}, expected {rl:?})",
23959 p.rate_limit(),
23960 );
23961 assert_eq!(
23962 p.rate_limit(),
23963 p.rate_limit,
23964 "MeshPolicy::rate_limit must byte-equal the raw \
23965 .rate_limit field access across every value in the \
23966 accept-set",
23967 );
23968 }
23969 }
23970
23971 #[test]
23972 fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
23973 // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
23974 // must key off [`MeshPolicy::rate_limit`], not the raw
23975 // `.rate_limit` field access. Structurally: toggling ONLY the
23976 // `rate_limit` slot on an otherwise-default MeshPolicy must
23977 // flip `is_empty()` from `true` (all-`None`) to `false` (one
23978 // axis carries a value); the flip must be observed for every
23979 // representative value in the accept-set the surrounding
23980 // [`AplicacaoSpec::validate_politicas`] gate accepts
23981 // (`Some(RateLimit { rate: 1, window: 1s })`,
23982 // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
23983 // since the emptiness semantic reads "any axis carries a
23984 // value" — not "any axis carries a value the validate gate
23985 // accepts" — the same non-collapsing shape the peer M2
23986 // [`crate::LimitsSpec::is_empty`] /
23987 // [`crate::BehaviorSpec::is_empty`] predicates carry.
23988 //
23989 // Pins against a future silent detour that re-derived the
23990 // emptiness predicate off a peer axis (an accidental
23991 // `.timeout.is_none()`-only chain that dropped the
23992 // `rate_limit` arm entirely — the last unlifted inline field
23993 // access on `is_empty` before this lift), a `rate_limit ==
23994 // Some(_)` collapse that key-off a validate-gate-clamped
23995 // bounds check (which would silently classify a past-the-
23996 // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
23997 // because it fails the value-shape gate), or an accessor-
23998 // side detour that no longer names the substrate-primitive
23999 // typed dispatch.
24000 //
24001 // Fourth "the emptiness predicate must route through the
24002 // substrate-primitive typed dispatch" composition pin on the
24003 // M3 mesh-slot family — closes the last unlifted composition
24004 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
24005 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
24006 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
24007 // 7073d0f is_empty-composition pins on the sibling primitive-
24008 // Copy axes, extended onto the peer per-`:politicas`
24009 // composite-Copy `Option<RateLimit>` axis).
24010 let empty = MeshPolicy::default();
24011 assert!(
24012 empty.is_empty(),
24013 "MeshPolicy::default() must be is_empty() — every axis \
24014 defaults to None",
24015 );
24016 for rl in [
24017 RateLimit {
24018 rate: 1,
24019 window: Duration::from_secs(1),
24020 },
24021 RateLimit {
24022 rate: POLICY_RATE_LIMIT_MAX,
24023 window: Duration::from_secs(3600),
24024 },
24025 ] {
24026 let p = MeshPolicy {
24027 rate_limit: Some(rl),
24028 ..MeshPolicy::default()
24029 };
24030 assert!(
24031 !p.is_empty(),
24032 "MeshPolicy::is_empty must return false when \
24033 :rate-limit is {rl:?} — the emptiness predicate \
24034 reads \"any axis carries a value\", not \"any axis \
24035 carries a value the validate gate accepts\"",
24036 );
24037 assert_eq!(
24038 p.rate_limit().is_none(),
24039 p.is_empty(),
24040 "when :rate-limit is the only set axis, is_empty() \
24041 must equal rate_limit().is_none() — the accessor \
24042 and the emptiness predicate must route through the \
24043 same substrate-primitive typed dispatch on the \
24044 :rate-limit arm",
24045 );
24046 }
24047 }
24048
24049 #[test]
24050 fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
24051 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24052 // `:rate-limit` value-shape gate must key off
24053 // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
24054 // field bind. Structurally: a `MeshPolicy` whose only set
24055 // axis is a `Some(RateLimit { rate: 0, .. })` must surface
24056 // the `PolicyRateLimitZero` refusal exactly, and the same
24057 // MeshPolicy with the rate at the canonical lower boundary
24058 // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
24059 // The pair jointly pins the accessor + validate-gate
24060 // composition: any future silent detour that had the accessor
24061 // omit the `Some(RateLimit { rate: 0, .. })` arm (a
24062 // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
24063 // silently absorb the `PolicyRateLimitZero` refusal at the
24064 // accessor boundary — the composition pin catches that at
24065 // caixa-core build time.
24066 //
24067 // Sibling of the peer [`validate_politicas`]
24068 // `:mtls-required` / `:retries` / `:timeout` composition pins
24069 // on the sibling primitive-Copy optional-scalar axes — same
24070 // "the validate / shape-gate predicate must route through the
24071 // substrate-primitive typed dispatch" discipline extended
24072 // onto the peer per-`:politicas` composite-Copy
24073 // `Option<RateLimit>` axis. Second composition-with-accessor
24074 // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
24075 // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
24076 let mut spec = three_member_spec();
24077 spec.politicas = MeshPolicy {
24078 rate_limit: Some(RateLimit {
24079 rate: 0,
24080 window: Duration::from_secs(1),
24081 }),
24082 ..MeshPolicy::default()
24083 };
24084 assert!(
24085 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
24086 "validate_politicas must reject rate == 0 with \
24087 PolicyRateLimitZero — the accessor and the validate gate \
24088 must route through the same substrate-primitive typed \
24089 dispatch on the :rate-limit zero-floor arm",
24090 );
24091 spec.politicas = MeshPolicy {
24092 rate_limit: Some(RateLimit {
24093 rate: 1,
24094 window: Duration::from_secs(1),
24095 }),
24096 ..MeshPolicy::default()
24097 };
24098 assert!(
24099 spec.validate().is_ok(),
24100 "validate_politicas must accept rate == 1 (the canonical \
24101 lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
24102 set) with a canonical 1s window",
24103 );
24104 }
24105
24106 #[test]
24107 fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
24108 // The canonical per-`:politicas` `:circuit-breaker` Envoy-
24109 // `outlier_detection`-mesh consecutive-failure-ejection scalar
24110 // pin: [`MeshPolicy::circuit_breaker`] must return the
24111 // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
24112 // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
24113 // raw field access across every representative value in the
24114 // accept-set — `None` (cluster default applies — no
24115 // per-Aplicacao breaker declaration, the gateway-class per-
24116 // listener default arm the future caixa-mesh
24117 // `outlier_detection_overlay` emitter documents),
24118 // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
24119 // (the lower boundary of the accept-set the surrounding
24120 // [`AplicacaoSpec::validate_politicas`] gate carves out on the
24121 // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
24122 // refusals),
24123 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
24124 // (the upper boundary the same gate carves out on the sibling
24125 // `PolicyBreakerMaxFailuresExceedsCap` /
24126 // `PolicyBreakerWindowExceedsCap` refusals),
24127 // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
24128 // (a past-the-guard sentinel that pins the accessor doesn't
24129 // perform a silent bounds-collapse into `None` on the
24130 // zero-failures/zero-window arm — validate rejects zero but
24131 // the accessor must ship the raw slot verbatim so a validate-
24132 // time gate regression surfaces at the emit boundary rather
24133 // than being silently absorbed), and
24134 // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
24135 // (a past-the-guard sentinel that pins the accessor doesn't
24136 // perform a silent bounds-collapse at the return path).
24137 //
24138 // Second `Option<Copy-composite-T>`-return accessor pin on the
24139 // M3 mesh-slot family (peer of the sibling per-`:politicas`
24140 // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
24141 // composite-Copy accessor pin, and of the sibling per-
24142 // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
24143 // [`MeshPolicy::retries`] bdfb399 /
24144 // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
24145 // accessor pins). Pins against a future silent detour that
24146 // re-derived the breaker declaration from a peer axis (an
24147 // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
24148 // collapse that read the rate-limit's bucket capacity + refill
24149 // period as a breaker declaration), a `None → Some(default())`
24150 // cluster-default projection (which would silently re-
24151 // introduce the `PolicyBreakerZeroFailures` /
24152 // `PolicyBreakerZeroWindow` refusal cases at the emit
24153 // boundary), a bounds-collapsing accessor that clamped
24154 // `cb.max_failures` through
24155 // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
24156 // through [`POLICY_BREAKER_WINDOW_MAX`] (the
24157 // [`AplicacaoSpec::validate`] gate owns the bounds; the
24158 // accessor must ship the raw slot verbatim), or a
24159 // by-reference detour (`Option<&CircuitBreaker>`) that broke
24160 // every downstream consumer keying off `Option<CircuitBreaker>`
24161 // by-copy.
24162 for cb in [
24163 None,
24164 Some(CircuitBreaker {
24165 max_failures: 1,
24166 window: Duration::from_millis(1),
24167 }),
24168 Some(CircuitBreaker {
24169 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
24170 window: POLICY_BREAKER_WINDOW_MAX,
24171 }),
24172 Some(CircuitBreaker {
24173 max_failures: 0,
24174 window: Duration::ZERO,
24175 }),
24176 Some(CircuitBreaker {
24177 max_failures: u32::MAX,
24178 window: Duration::MAX,
24179 }),
24180 ] {
24181 let p = MeshPolicy {
24182 circuit_breaker: cb,
24183 ..MeshPolicy::default()
24184 };
24185 assert_eq!(
24186 p.circuit_breaker(),
24187 cb,
24188 "MeshPolicy::circuit_breaker must return :politicas \
24189 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
24190 p.circuit_breaker(),
24191 );
24192 assert_eq!(
24193 p.circuit_breaker(),
24194 p.circuit_breaker,
24195 "MeshPolicy::circuit_breaker must byte-equal the raw \
24196 .circuit_breaker field access across every value in \
24197 the accept-set",
24198 );
24199 }
24200 }
24201
24202 #[test]
24203 fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
24204 // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
24205 // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
24206 // `.circuit_breaker` field access. Structurally: toggling ONLY
24207 // the `circuit_breaker` slot on an otherwise-default MeshPolicy
24208 // must flip `is_empty()` from `true` (all-`None`) to `false`
24209 // (one axis carries a value); the flip must be observed for
24210 // every representative value in the accept-set the surrounding
24211 // [`AplicacaoSpec::validate_politicas`] gate accepts
24212 // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
24213 // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
24214 // since the emptiness semantic reads "any axis carries a
24215 // value" — not "any axis carries a value the validate gate
24216 // accepts" — the same non-collapsing shape the peer M2
24217 // [`crate::LimitsSpec::is_empty`] /
24218 // [`crate::BehaviorSpec::is_empty`] predicates carry.
24219 //
24220 // Pins against a future silent detour that re-derived the
24221 // emptiness predicate off a peer axis (an accidental
24222 // `.rate_limit.is_none()`-only chain that dropped the
24223 // `circuit_breaker` arm entirely — the last unlifted inline
24224 // field access on `is_empty` before this lift), a
24225 // `circuit_breaker == Some(_)` collapse that key-off a
24226 // validate-gate-clamped bounds check (which would silently
24227 // classify a past-the-guard `Some(CircuitBreaker { max_failures:
24228 // 0, window: 0s })` as empty because it fails the value-shape
24229 // gate), or an accessor-side detour that no longer names the
24230 // substrate-primitive typed dispatch.
24231 //
24232 // Fifth "the emptiness predicate must route through the
24233 // substrate-primitive typed dispatch" composition pin on the
24234 // M3 mesh-slot family — closes the last unlifted composition
24235 // arm on [`MeshPolicy::is_empty`] (peer of the sibling
24236 // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
24237 // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
24238 // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
24239 // composition pins on the sibling primitive-Copy + composite-
24240 // Copy axes, extended onto the peer per-`:politicas`
24241 // composite-Copy `Option<CircuitBreaker>` axis).
24242 let empty = MeshPolicy::default();
24243 assert!(
24244 empty.is_empty(),
24245 "MeshPolicy::default() must be is_empty() — every axis \
24246 defaults to None",
24247 );
24248 for cb in [
24249 CircuitBreaker {
24250 max_failures: 1,
24251 window: Duration::from_millis(1),
24252 },
24253 CircuitBreaker {
24254 max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
24255 window: POLICY_BREAKER_WINDOW_MAX,
24256 },
24257 ] {
24258 let p = MeshPolicy {
24259 circuit_breaker: Some(cb),
24260 ..MeshPolicy::default()
24261 };
24262 assert!(
24263 !p.is_empty(),
24264 "MeshPolicy::is_empty must return false when \
24265 :circuit-breaker is {cb:?} — the emptiness predicate \
24266 reads \"any axis carries a value\", not \"any axis \
24267 carries a value the validate gate accepts\"",
24268 );
24269 assert_eq!(
24270 p.circuit_breaker().is_none(),
24271 p.is_empty(),
24272 "when :circuit-breaker is the only set axis, \
24273 is_empty() must equal circuit_breaker().is_none() — \
24274 the accessor and the emptiness predicate must route \
24275 through the same substrate-primitive typed dispatch \
24276 on the :circuit-breaker arm",
24277 );
24278 }
24279 }
24280
24281 #[test]
24282 fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
24283 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24284 // `:circuit-breaker` value-shape gate must key off
24285 // [`MeshPolicy::circuit_breaker`], not the raw
24286 // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
24287 // whose only set axis is a `Some(CircuitBreaker { max_failures:
24288 // 0, .. })` must surface the `PolicyBreakerZeroFailures`
24289 // refusal exactly, and the same MeshPolicy with the breaker at
24290 // the canonical lower boundary
24291 // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
24292 // pass validate. The pair jointly pins the accessor +
24293 // validate-gate composition: any future silent detour that had
24294 // the accessor omit the `Some(CircuitBreaker { max_failures:
24295 // 0, .. })` arm (a
24296 // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
24297 // collapse) would silently absorb the
24298 // `PolicyBreakerZeroFailures` refusal at the accessor
24299 // boundary — the composition pin catches that at caixa-core
24300 // build time.
24301 //
24302 // Sibling of the peer [`validate_politicas`]
24303 // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
24304 // composition pins on the sibling primitive-Copy + composite-
24305 // Copy optional-scalar axes — same "the validate / shape-gate
24306 // predicate must route through the substrate-primitive typed
24307 // dispatch" discipline extended onto the peer per-`:politicas`
24308 // composite-Copy `Option<CircuitBreaker>` axis. Second
24309 // composition-with-accessor pin on the M3 mesh-slot
24310 // `Option<CircuitBreaker>` arm alongside the
24311 // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
24312 let mut spec = three_member_spec();
24313 spec.politicas = MeshPolicy {
24314 circuit_breaker: Some(CircuitBreaker {
24315 max_failures: 0,
24316 window: Duration::from_millis(1),
24317 }),
24318 ..MeshPolicy::default()
24319 };
24320 assert!(
24321 matches!(
24322 spec.validate(),
24323 Err(AplicacaoError::PolicyBreakerZeroFailures)
24324 ),
24325 "validate_politicas must reject max_failures == 0 with \
24326 PolicyBreakerZeroFailures — the accessor and the validate \
24327 gate must route through the same substrate-primitive \
24328 typed dispatch on the :circuit-breaker zero-floor arm",
24329 );
24330 spec.politicas = MeshPolicy {
24331 circuit_breaker: Some(CircuitBreaker {
24332 max_failures: 1,
24333 window: Duration::from_millis(1),
24334 }),
24335 ..MeshPolicy::default()
24336 };
24337 assert!(
24338 spec.validate().is_ok(),
24339 "validate_politicas must accept a CircuitBreaker at the \
24340 canonical lower boundary (max_failures = 1, window = \
24341 1ms) — the accessor and the validate gate must route \
24342 through the same substrate-primitive typed dispatch on \
24343 the :circuit-breaker arm",
24344 );
24345 }
24346
24347 #[test]
24348 fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
24349 // The canonical per-`:politicas :circuit-breaker` `:max-failures`
24350 // Envoy-outlier-detection trip-threshold scalar pin:
24351 // [`CircuitBreaker::max_failures`] must return the
24352 // `:politicas :circuit-breaker :max-failures` typed `u32`
24353 // verbatim, byte-equal to the raw field access across every
24354 // representative value in the accept-set — `1` (the lower
24355 // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
24356 // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
24357 // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
24358 // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
24359 // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
24360 // refusal), `0` (a past-the-guard sentinel that pins the accessor
24361 // doesn't perform a silent bounds-collapse into `1` on the zero
24362 // arm — validate rejects zero but the accessor must ship the
24363 // raw slot verbatim so a validate-time gate regression surfaces
24364 // at the emit boundary rather than being silently absorbed),
24365 // `u32::MAX` (a past-the-guard sentinel that pins the accessor
24366 // doesn't perform a silent bounds-collapse through
24367 // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
24368 //
24369 // First sub-struct required-scalar accessor pin on the M3
24370 // mesh-slot family — sibling in shape to the peer per-`:membros`
24371 // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
24372 // (a40b0e3) required-`String`-carry accessor pins and the peer
24373 // per-`:contratos` [`WitContract::source`] /
24374 // [`WitContract::destination`] (7f0fd43) required-`String`-carry
24375 // accessor pins, extended onto the peer per-`CircuitBreaker`
24376 // required-`u32` scalar-value axis. Pins against a future silent
24377 // detour that re-derived the trip threshold from a peer axis (an
24378 // accidental `self.window.as_secs() as u32` collapse that read
24379 // the breaker's rolling-window duration as a failure count), a
24380 // `0 → 1` cluster-default projection (which would silently absorb
24381 // the `PolicyBreakerZeroFailures` refusal case at the accessor
24382 // boundary), or a bounds-collapsing accessor that clamped the
24383 // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
24384 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
24385 // must ship the raw slot verbatim).
24386 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
24387 let cb = CircuitBreaker {
24388 max_failures,
24389 window: Duration::from_secs(60),
24390 };
24391 assert_eq!(
24392 cb.max_failures(),
24393 max_failures,
24394 "CircuitBreaker::max_failures must return :politicas \
24395 :circuit-breaker :max-failures verbatim (got {}, \
24396 expected {max_failures})",
24397 cb.max_failures(),
24398 );
24399 assert_eq!(
24400 cb.max_failures(),
24401 cb.max_failures,
24402 "CircuitBreaker::max_failures must byte-equal the raw \
24403 .max_failures field access across every value in the \
24404 u32 accept-set",
24405 );
24406 }
24407 }
24408
24409 #[test]
24410 fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
24411 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24412 // `:circuit-breaker :max-failures` zero-floor arm must key off
24413 // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
24414 // field access. Structurally: a `CircuitBreaker { max_failures:
24415 // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
24416 // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
24417 // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
24418 // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
24419 // pass validate. The pair jointly pins the accessor +
24420 // validate-gate composition: any future silent detour that had
24421 // the accessor return a fresh `1` on the zero arm (a
24422 // `.max_failures().max(1)` collapse) would silently absorb the
24423 // `PolicyBreakerZeroFailures` refusal at the accessor boundary
24424 // and the validate gate would accept a struct-literal
24425 // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
24426 // catches that at caixa-core build time.
24427 //
24428 // Peer of the sibling per-`:politicas`
24429 // [`MeshPolicy::mtls_required`] (c0110f1) /
24430 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
24431 // (7073d0f) accessor-composition pins on the sibling optional-
24432 // scalar axes — same "the validate / shape-gate predicate must
24433 // route through the substrate-primitive typed dispatch"
24434 // discipline extended onto the peer per-`CircuitBreaker`
24435 // required-scalar composition axis.
24436 let mut spec = three_member_spec();
24437 spec.politicas = MeshPolicy {
24438 circuit_breaker: Some(CircuitBreaker {
24439 max_failures: 0,
24440 window: Duration::from_secs(60),
24441 }),
24442 ..MeshPolicy::default()
24443 };
24444 assert!(
24445 matches!(
24446 spec.validate(),
24447 Err(AplicacaoError::PolicyBreakerZeroFailures)
24448 ),
24449 "validate_politicas must reject max_failures == 0 with \
24450 PolicyBreakerZeroFailures — the accessor and the validate \
24451 gate must route through the same substrate-primitive typed \
24452 dispatch on the :max-failures zero-floor arm",
24453 );
24454 spec.politicas = MeshPolicy {
24455 circuit_breaker: Some(CircuitBreaker {
24456 max_failures: 1,
24457 window: Duration::from_secs(60),
24458 }),
24459 ..MeshPolicy::default()
24460 };
24461 assert!(
24462 spec.validate().is_ok(),
24463 "validate_politicas must accept max_failures == 1 (the \
24464 lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
24465 accept-set)",
24466 );
24467 }
24468
24469 #[test]
24470 fn circuit_breaker_max_failures_projects_u32_by_copy() {
24471 // The by-copy pin: [`CircuitBreaker::max_failures`] returns
24472 // `u32` by copy — `u32` is `Copy` and the accessor must return
24473 // by value, not by reference. Peer of the sibling
24474 // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
24475 // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
24476 // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
24477 // optional-scalar axes, extended onto the peer
24478 // per-`CircuitBreaker` required-`u32` copy-invariant shape —
24479 // the accessor's returned `u32` must outlive `&self` (multiple
24480 // calls must return equal values from a dropped-`&self` copy,
24481 // since the returned scalar carries no borrow), and calling
24482 // the accessor twice on the same CircuitBreaker must yield the
24483 // same `u32` verbatim (idempotent, no side effects on `&self`).
24484 //
24485 // Pins against a future silent detour that returned `&u32`
24486 // (which would type-check but silently break every downstream
24487 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
24488 // first parameter is `u32`, and `&u32` would fold to a detached
24489 // copy at the call site with a `*` deref the sibling accessors
24490 // don't need), an accidental `.max_failures.wrapping_add(0)`
24491 // detour that returned a fresh copy through an arithmetic
24492 // no-op (breaking a future `const fn` regression), or a
24493 // one-arm-only accessor that returned a saturating value on
24494 // some sentinel input (breaking the pass-through invariant the
24495 // sibling required-scalar accessors carry).
24496 for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
24497 let cb = CircuitBreaker {
24498 max_failures,
24499 window: Duration::from_secs(60),
24500 };
24501 let first = cb.max_failures();
24502 let second = cb.max_failures();
24503 assert_eq!(
24504 first, second,
24505 "CircuitBreaker::max_failures must be idempotent — two \
24506 successive calls on the same &self must return the \
24507 same u32",
24508 );
24509 assert_eq!(
24510 first, max_failures,
24511 "CircuitBreaker::max_failures must return :politicas \
24512 :circuit-breaker :max-failures verbatim by copy — \
24513 got {first}, expected {max_failures}",
24514 );
24515 }
24516 }
24517
24518 #[test]
24519 fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
24520 // The canonical per-`:politicas :circuit-breaker` `:window`
24521 // Envoy-outlier-detection rolling-observation-interval scalar
24522 // pin: [`CircuitBreaker::window`] must return the
24523 // `:politicas :circuit-breaker :window` typed `Duration`
24524 // verbatim, byte-equal to the raw field access across every
24525 // representative value in the accept-set — `Duration::from_millis(1)`
24526 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
24527 // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
24528 // gate carves out on the sibling `PolicyBreakerZeroWindow`
24529 // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
24530 // same gate carves out on the sibling
24531 // `PolicyBreakerWindowExceedsCap` refusal),
24532 // `Duration::ZERO` (a past-the-guard sentinel that pins the
24533 // accessor doesn't perform a silent bounds-collapse into
24534 // `Duration::from_millis(1)` on the zero arm — validate rejects
24535 // zero but the accessor must ship the raw slot verbatim so a
24536 // validate-time gate regression surfaces at the emit boundary
24537 // rather than being silently absorbed),
24538 // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
24539 // far above the 1h cap — that pins the accessor doesn't perform
24540 // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
24541 // at the return path).
24542 //
24543 // Second sub-struct required-scalar accessor pin on the M3
24544 // mesh-slot family — sibling in shape to the just-landed
24545 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
24546 // (3a74062) required-`u32` accessor pin on the peer
24547 // per-`CircuitBreaker` required-axis, extended onto the
24548 // per-sub-struct required-`Duration` axis. Pins against a
24549 // future silent detour that re-derived the observation window
24550 // from a peer axis (an accidental
24551 // `Duration::from_secs(self.max_failures as u64)` collapse that
24552 // read the breaker's trip count as an observation-interval
24553 // duration), a `Duration::ZERO → Duration::from_millis(1)`
24554 // cluster-default projection (which would silently absorb the
24555 // `PolicyBreakerZeroWindow` refusal case at the accessor
24556 // boundary), or a bounds-collapsing accessor that clamped the
24557 // return through `POLICY_BREAKER_WINDOW_MAX` (the
24558 // `AplicacaoSpec::validate` gate owns the bounds; the accessor
24559 // must ship the raw slot verbatim).
24560 for window in [
24561 Duration::from_millis(1),
24562 POLICY_BREAKER_WINDOW_MAX,
24563 Duration::ZERO,
24564 Duration::from_secs(86_400),
24565 ] {
24566 let cb = CircuitBreaker {
24567 max_failures: 5,
24568 window,
24569 };
24570 assert_eq!(
24571 cb.window(),
24572 window,
24573 "CircuitBreaker::window must return :politicas \
24574 :circuit-breaker :window verbatim (got {:?}, \
24575 expected {window:?})",
24576 cb.window(),
24577 );
24578 assert_eq!(
24579 cb.window(),
24580 cb.window,
24581 "CircuitBreaker::window must byte-equal the raw \
24582 .window field access across every value in the \
24583 Duration accept-set",
24584 );
24585 }
24586 }
24587
24588 #[test]
24589 fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
24590 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
24591 // `:circuit-breaker :window` zero-floor arm must key off
24592 // [`CircuitBreaker::window`], not the raw `.window` field
24593 // access. Structurally: a `CircuitBreaker { window:
24594 // Duration::ZERO, .. }` embedded in a
24595 // `:politicas :circuit-breaker` slot must surface the
24596 // `PolicyBreakerZeroWindow` refusal exactly, and a
24597 // `CircuitBreaker { window: Duration::from_millis(1), .. }`
24598 // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
24599 // accept-set) must pass validate. The pair jointly pins the
24600 // accessor + validate-gate composition: any future silent
24601 // detour that had the accessor return a fresh
24602 // `Duration::from_millis(1)` on the zero arm (a
24603 // `.window().max(Duration::from_millis(1))` collapse) would
24604 // silently absorb the `PolicyBreakerZeroWindow` refusal at the
24605 // accessor boundary and the validate gate would accept a
24606 // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
24607 // — the composition pin catches that at caixa-core build time.
24608 //
24609 // Peer of the sibling per-`CircuitBreaker`
24610 // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
24611 // pin on the peer required-scalar `:max-failures` axis — same
24612 // "the validate / shape-gate predicate must route through the
24613 // substrate-primitive typed dispatch" discipline extended onto
24614 // the peer per-`CircuitBreaker` required-`Duration` composition
24615 // axis.
24616 let mut spec = three_member_spec();
24617 spec.politicas = MeshPolicy {
24618 circuit_breaker: Some(CircuitBreaker {
24619 max_failures: 5,
24620 window: Duration::ZERO,
24621 }),
24622 ..MeshPolicy::default()
24623 };
24624 assert!(
24625 matches!(
24626 spec.validate(),
24627 Err(AplicacaoError::PolicyBreakerZeroWindow)
24628 ),
24629 "validate_politicas must reject window == Duration::ZERO \
24630 with PolicyBreakerZeroWindow — the accessor and the \
24631 validate gate must route through the same substrate-\
24632 primitive typed dispatch on the :window zero-floor arm",
24633 );
24634 spec.politicas = MeshPolicy {
24635 circuit_breaker: Some(CircuitBreaker {
24636 max_failures: 5,
24637 window: Duration::from_millis(1),
24638 }),
24639 ..MeshPolicy::default()
24640 };
24641 assert!(
24642 spec.validate().is_ok(),
24643 "validate_politicas must accept window == \
24644 Duration::from_millis(1) (the lower boundary of the \
24645 1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
24646 );
24647 }
24648
24649 #[test]
24650 fn circuit_breaker_window_projects_duration_by_copy() {
24651 // The by-copy pin: [`CircuitBreaker::window`] returns
24652 // `Duration` by copy — `Duration` is `Copy` and the accessor
24653 // must return by value, not by reference. Peer of the sibling
24654 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
24655 // (3a74062) by-copy pin on the peer required-scalar
24656 // `:max-failures` axis, extended onto the peer
24657 // per-`CircuitBreaker` required-`Duration` copy-invariant shape
24658 // — the accessor's returned `Duration` must outlive `&self`
24659 // (multiple calls must return equal values from a
24660 // dropped-`&self` copy, since the returned scalar carries no
24661 // borrow), and calling the accessor twice on the same
24662 // CircuitBreaker must yield the same `Duration` verbatim
24663 // (idempotent, no side effects on `&self`).
24664 //
24665 // Pins against a future silent detour that returned
24666 // `&Duration` (which would type-check but silently break every
24667 // downstream `Duration`-by-value consumer —
24668 // [`crate::render::require_positive_canonical_bounded_duration`]'s
24669 // first parameter is `Duration`, and `&Duration` would fold to
24670 // a detached copy at the call site with a `*` deref the sibling
24671 // accessors don't need), an accidental `.window + Duration::ZERO`
24672 // detour that returned a fresh copy through an arithmetic
24673 // no-op (breaking a future `const fn` regression), or a
24674 // one-arm-only accessor that returned a saturating value on
24675 // some sentinel input (breaking the pass-through invariant the
24676 // sibling required-scalar accessors carry).
24677 for window in [
24678 Duration::from_millis(1),
24679 POLICY_BREAKER_WINDOW_MAX,
24680 Duration::ZERO,
24681 Duration::from_secs(86_400),
24682 ] {
24683 let cb = CircuitBreaker {
24684 max_failures: 5,
24685 window,
24686 };
24687 let first = cb.window();
24688 let second = cb.window();
24689 assert_eq!(
24690 first, second,
24691 "CircuitBreaker::window must be idempotent — two \
24692 successive calls on the same &self must return the \
24693 same Duration",
24694 );
24695 assert_eq!(
24696 first, window,
24697 "CircuitBreaker::window must return :politicas \
24698 :circuit-breaker :window verbatim by copy — \
24699 got {first:?}, expected {window:?}",
24700 );
24701 }
24702 }
24703
24704 #[test]
24705 fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
24706 // Apex-identity pair-invariant pin composing both substrate-
24707 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
24708 // and [`WitContract::destination`] — at the emit-side call shape
24709 // every per-`(:de, :para)` CNP L4 port reader now takes. The
24710 // invariant, evaluated per-edge:
24711 //
24712 // spec.port_for_destination(c.destination()) == expected_port
24713 //
24714 // where `expected_port` is `entrada.port` when
24715 // `c.destination() == entrada.destination()` and
24716 // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
24717 // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
24718 // pin on the per-`:entrada` axis — that pin encodes the apex
24719 // ingress L4 identity via `entrada.destination()`; this pin
24720 // encodes the per-edge L4 identity via `c.destination()`, and
24721 // both compose on the same substrate-primitive resolver so a
24722 // future refactor that silently split either accessor's apex
24723 // behavior surfaces at caixa-core build time.
24724 let mut spec = three_member_spec();
24725 if let Some(e) = spec.entrada.as_mut() {
24726 e.para = "cart".into();
24727 e.port = 8443;
24728 }
24729 let apex_contract = WitContract {
24730 de: "checkout".into(),
24731 para: "cart".into(),
24732 wit: "wasi:http/proxy".into(),
24733 endpoint: Some("/hello".into()),
24734 subject: None,
24735 slot: None,
24736 };
24737 assert_eq!(
24738 spec.port_for_destination(apex_contract.destination()),
24739 8443,
24740 "`spec.port_for_destination(c.destination())` must equal \
24741 `entrada.port` when the contract callee names the ingress \
24742 apex — the CNP per-edge L4 port and the HTTPRoute apex \
24743 backendRef port share this substrate-primitive resolver.",
24744 );
24745 let non_apex_contract = WitContract {
24746 de: "cart".into(),
24747 para: "payment".into(),
24748 wit: "wasi:http/proxy".into(),
24749 endpoint: Some("/charge".into()),
24750 subject: None,
24751 slot: None,
24752 };
24753 assert_eq!(
24754 spec.port_for_destination(non_apex_contract.destination()),
24755 DEFAULT_SERVICO_PORT,
24756 "`spec.port_for_destination(c.destination())` must fall back \
24757 to the substrate-canonical port floor when the contract \
24758 callee is not the ingress apex — the resolver's non-apex \
24759 arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
24760 );
24761 }
24762
24763 #[test]
24764 fn membro_key_consts_are_lower_camel_case_shape() {
24765 // Shape-pin: every `MEMBRO_KEY_*` const must be a
24766 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
24767 // `kebab-case` hyphens, no leading colon, no `PascalCase`
24768 // leading capital, no whitespace / dots) — the canonical shape
24769 // the `#[serde(rename_all = "camelCase")]` derive produces on
24770 // [`Membro`]. A future flip to a non-camelCase attribute at
24771 // the derive surfaces both here (this test fails on the
24772 // stale-constant shape) and at
24773 // `membro_serde_keys_match_lifted_membro_key_consts` (that test
24774 // fails on the mismatch between const and derive). Peer with
24775 // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
24776 // on the sibling `SupervisorSpec` top-level axis.
24777 for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
24778 assert!(
24779 !key.is_empty(),
24780 "MEMBRO_KEY_* must be non-empty (got {key:?})"
24781 );
24782 let first = key.chars().next().unwrap();
24783 assert!(
24784 first.is_ascii_lowercase(),
24785 "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
24786 (got {key:?}, leads with {first:?})",
24787 );
24788 assert!(
24789 key.chars().all(|c| c.is_ascii_alphanumeric()),
24790 "MEMBRO_KEY_* must be ASCII-alphanumeric only \
24791 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
24792 );
24793 }
24794 }
24795
24796 // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
24797
24798 #[test]
24799 fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
24800 // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
24801 // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
24802 // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
24803 // keys the `#[serde(rename_all = "camelCase")]` attribute on
24804 // [`WitContract`] emits for the required-triad. The three
24805 // sibling payload-arm keys already pin under
24806 // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
24807 // `STORE_FIELD_NAME` — pin all six alongside so a future
24808 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
24809 // verbatim-field-name flip at the derive attribute (any of which
24810 // would silently break every downstream JSON consumer that
24811 // reaches for one of the six via `Value::get(...)`) surfaces
24812 // here as a build-time test failure at `aplicacao.rs`, not as an
24813 // apply-time `.get(<stale-canonical-const>)` returning `None`
24814 // far from the derive-attr drift's commit. Peer with the sibling
24815 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
24816 // pin on the M3 `:membros` per-entry axis — same discipline the
24817 // `Membro` per-entry lift established, extended here to the
24818 // sibling M3 `WitContract` per-`:contratos` entry axis, the last
24819 // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
24820 // axis on the Aplicacao surface without a lifted serde-key peer.
24821 let c = WitContract {
24822 de: "cart".into(),
24823 para: "catalog".into(),
24824 wit: "wasi:http/proxy".into(),
24825 endpoint: Some("/lookup".into()),
24826 subject: None,
24827 slot: None,
24828 };
24829 let json = serde_json::to_string(&c).unwrap();
24830 for key in [
24831 crate::CONTRATO_KEY_DE,
24832 crate::CONTRATO_KEY_PARA,
24833 crate::CONTRATO_KEY_WIT,
24834 WitTarget::HTTP_FIELD_NAME,
24835 ] {
24836 let quoted = format!("\"{key}\"");
24837 assert!(
24838 json.contains("ed),
24839 "serialized WitContract must carry the lifted \
24840 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
24841 {quoted} verbatim in the JSON emission (got: {json})",
24842 );
24843 }
24844
24845 // Pin the two remaining payload-arm keys by round-tripping a
24846 // `WitContract` under each payload-shape (pub-sub, store) — the
24847 // required-triad appears on every emission but the payload arms
24848 // only surface when their `Option<String>` field is `Some`.
24849 let pubsub = WitContract {
24850 de: "cart".into(),
24851 para: "events".into(),
24852 wit: "nats:pub-sub".into(),
24853 endpoint: None,
24854 subject: Some("orders.placed".into()),
24855 slot: None,
24856 };
24857 let pubsub_json = serde_json::to_string(&pubsub).unwrap();
24858 let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
24859 assert!(
24860 pubsub_json.contains(&pubsub_quoted),
24861 "serialized pub-sub WitContract must carry the lifted \
24862 WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
24863 verbatim in the JSON emission (got: {pubsub_json})",
24864 );
24865 let store = WitContract {
24866 de: "cart".into(),
24867 para: "sessions".into(),
24868 wit: "wasi:keyvalue/store".into(),
24869 endpoint: None,
24870 subject: None,
24871 slot: Some("cart/$id".into()),
24872 };
24873 let store_json = serde_json::to_string(&store).unwrap();
24874 let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
24875 assert!(
24876 store_json.contains(&store_quoted),
24877 "serialized store WitContract must carry the lifted \
24878 WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
24879 verbatim in the JSON emission (got: {store_json})",
24880 );
24881 }
24882
24883 #[test]
24884 fn contrato_key_consts_are_pairwise_distinct() {
24885 // Cross-axis drift-detection pin: a future collapse of the six
24886 // canonical [`WitContract`] per-entry byte-strings onto the same
24887 // value (e.g. an accidental copy-paste flip of
24888 // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
24889 // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
24890 // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
24891 // every downstream probe on one axis onto the sibling axis's
24892 // overlay entry and pass every propagation-probe test that
24893 // expected only the stale axis's value. Peer of the sibling
24894 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
24895 // widened here to the six-way axis the `WitContract`
24896 // required-triad + `WitTarget` payload-triad jointly cover.
24897 let all = [
24898 crate::CONTRATO_KEY_DE,
24899 crate::CONTRATO_KEY_PARA,
24900 crate::CONTRATO_KEY_WIT,
24901 WitTarget::HTTP_FIELD_NAME,
24902 WitTarget::PUBSUB_FIELD_NAME,
24903 WitTarget::STORE_FIELD_NAME,
24904 ];
24905 for (i, a) in all.iter().enumerate() {
24906 for b in all.iter().skip(i + 1) {
24907 assert_ne!(
24908 a, b,
24909 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
24910 must be pairwise-distinct canonical byte-sequences \
24911 — got `{a}` == `{b}`",
24912 );
24913 }
24914 }
24915 }
24916
24917 #[test]
24918 fn contrato_key_consts_are_lower_camel_case_shape() {
24919 // Shape-pin: every `CONTRATO_KEY_*` (and every peer
24920 // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
24921 // byte-sequence (no `snake_case` underscores, no `kebab-case`
24922 // hyphens, no leading colon, no `PascalCase` leading capital, no
24923 // whitespace / dots) — the canonical shape the
24924 // `#[serde(rename_all = "camelCase")]` derive produces on
24925 // [`WitContract`]. A future flip to a non-camelCase attribute at
24926 // the derive surfaces both here (this test fails on the
24927 // stale-constant shape) and at
24928 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
24929 // (that test fails on the mismatch between const and derive).
24930 // Peer with `membro_key_consts_are_lower_camel_case_shape`
24931 // (ce80ca0) on the sibling `Membro` per-entry axis.
24932 for key in [
24933 crate::CONTRATO_KEY_DE,
24934 crate::CONTRATO_KEY_PARA,
24935 crate::CONTRATO_KEY_WIT,
24936 WitTarget::HTTP_FIELD_NAME,
24937 WitTarget::PUBSUB_FIELD_NAME,
24938 WitTarget::STORE_FIELD_NAME,
24939 ] {
24940 assert!(
24941 !key.is_empty(),
24942 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
24943 non-empty (got {key:?})"
24944 );
24945 let first = key.chars().next().unwrap();
24946 assert!(
24947 first.is_ascii_lowercase(),
24948 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
24949 with an ASCII-lowercase byte (got {key:?}, leads with \
24950 {first:?})",
24951 );
24952 assert!(
24953 key.chars().all(|c| c.is_ascii_alphanumeric()),
24954 "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
24955 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
24956 whitespace (got {key:?})",
24957 );
24958 }
24959 }
24960
24961 // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
24962
24963 #[test]
24964 fn entrada_serde_keys_match_lifted_entrada_key_consts() {
24965 // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
24966 // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
24967 // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
24968 // name the exact camelCase JSON keys the
24969 // `#[serde(rename_all = "camelCase")]` attribute on
24970 // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
24971 // pin that each canonical byte-sequence appears verbatim in the
24972 // JSON — a future accidental `rename_all = "snake_case"` /
24973 // `"kebab-case"` / verbatim-field-name flip at the derive
24974 // attribute (any of which would silently break every downstream
24975 // JSON consumer that reaches for one of the four consts via
24976 // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
24977 // emitter's per-Aplicacao hostname/paths/port projection, the
24978 // future `app-operator` reconciler's per-Aplicacao ingress
24979 // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
24980 // materializer's admission-time cross-check) surfaces here as
24981 // a build-time test failure at `aplicacao.rs`, not as an
24982 // apply-time `.get(<stale-canonical-const>)` returning `None`
24983 // far from the derive-attr drift's commit. Peer with the
24984 // sibling
24985 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
24986 // (ca463a4) and
24987 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
24988 // pins on the M3 collection-slot atom axes — same discipline
24989 // both collection-slot lifts established, extended here to the
24990 // singleton `:entrada` mesh-slot atom axis, the last M3
24991 // typed-struct top-level `#[serde(rename_all = "camelCase")]`
24992 // axis on the Aplicacao surface without a lifted serde-key
24993 // peer.
24994 let e = Entrada {
24995 host: "checkout.quero.cloud".into(),
24996 para: "cart".into(),
24997 paths: vec!["/cart".into()],
24998 port: 8080,
24999 };
25000 let json = serde_json::to_string(&e).unwrap();
25001 for key in [
25002 crate::ENTRADA_KEY_HOST,
25003 crate::ENTRADA_KEY_PARA,
25004 crate::ENTRADA_KEY_PATHS,
25005 crate::ENTRADA_KEY_PORT,
25006 ] {
25007 let quoted = format!("\"{key}\"");
25008 assert!(
25009 json.contains("ed),
25010 "serialized Entrada must carry the lifted ENTRADA_KEY_* \
25011 byte-sequence {quoted} verbatim in the JSON emission \
25012 (got: {json})",
25013 );
25014 }
25015 }
25016
25017 #[test]
25018 fn entrada_key_consts_are_pairwise_distinct() {
25019 // Cross-axis drift-detection pin: a future collapse of the four
25020 // canonical [`Entrada`] singleton byte-strings onto the same
25021 // value (e.g. an accidental copy-paste flip of
25022 // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
25023 // silently reroute every downstream probe on one axis onto the
25024 // sibling axis's overlay entry and pass every propagation-probe
25025 // test that expected only the stale axis's value — the
25026 // Gateway/HTTPRoute emitter would read the hostname string
25027 // where the destination-Servico name was expected (or vice
25028 // versa), the admission-webhook cross-check would compare the
25029 // wrong pair of values, and the resulting Gateway resource
25030 // would either be admitted with garbage or rejected at the
25031 // controller far from the rebrand commit's source. Peer of the
25032 // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
25033 // tetrad (40cc4e5), the two-way distinct pin on the
25034 // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
25035 // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
25036 // triad (ca463a4).
25037 let all = [
25038 crate::ENTRADA_KEY_HOST,
25039 crate::ENTRADA_KEY_PARA,
25040 crate::ENTRADA_KEY_PATHS,
25041 crate::ENTRADA_KEY_PORT,
25042 ];
25043 for (i, a) in all.iter().enumerate() {
25044 for b in all.iter().skip(i + 1) {
25045 assert_ne!(
25046 a, b,
25047 "ENTRADA_KEY_* consts must be pairwise-distinct \
25048 canonical byte-sequences — got `{a}` == `{b}`",
25049 );
25050 }
25051 }
25052 }
25053
25054 #[test]
25055 fn entrada_key_consts_are_lower_camel_case_shape() {
25056 // Shape-pin: every `ENTRADA_KEY_*` const must be a
25057 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25058 // `kebab-case` hyphens, no leading colon, no `PascalCase`
25059 // leading capital, no whitespace / dots) — the canonical shape
25060 // the `#[serde(rename_all = "camelCase")]` derive produces on
25061 // [`Entrada`]. A future flip to a non-camelCase attribute at
25062 // the derive surfaces both here (this test fails on the
25063 // stale-constant shape) and at
25064 // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
25065 // test fails on the mismatch between const and derive). Peer
25066 // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
25067 // and `contrato_key_consts_are_lower_camel_case_shape`
25068 // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
25069 // entry axes.
25070 for key in [
25071 crate::ENTRADA_KEY_HOST,
25072 crate::ENTRADA_KEY_PARA,
25073 crate::ENTRADA_KEY_PATHS,
25074 crate::ENTRADA_KEY_PORT,
25075 ] {
25076 assert!(
25077 !key.is_empty(),
25078 "ENTRADA_KEY_* must be non-empty (got {key:?})"
25079 );
25080 let first = key.chars().next().unwrap();
25081 assert!(
25082 first.is_ascii_lowercase(),
25083 "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
25084 (got {key:?}, leads with {first:?})",
25085 );
25086 assert!(
25087 key.chars().all(|c| c.is_ascii_alphanumeric()),
25088 "ENTRADA_KEY_* must be ASCII-alphanumeric only \
25089 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25090 );
25091 }
25092 }
25093
25094 // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
25095
25096 #[test]
25097 fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
25098 // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
25099 // ([`crate::POLITICAS_KEY_TIMEOUT`] /
25100 // [`crate::POLITICAS_KEY_RETRIES`] /
25101 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
25102 // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
25103 // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
25104 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
25105 // on [`MeshPolicy`] emits. Three of the five axes
25106 // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
25107 // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
25108 // camelCase transforms — the derive-attribute is load-bearing
25109 // on those, unlike the sibling `Entrada` / `Membro` /
25110 // `WitContract` structs whose fields are all lowercase-single-
25111 // word and where the derive is a no-op on every axis.
25112 // Serialize a fully-populated [`MeshPolicy`] (every axis
25113 // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
25114 // on none of the five slots) and pin that each canonical
25115 // byte-sequence appears verbatim in the JSON — a future
25116 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
25117 // verbatim-field-name flip at the derive attribute (any of
25118 // which would silently break every downstream JSON consumer
25119 // that reaches for one of the five consts via
25120 // `Value::get(...)` — the future M4 per-edge `:politicas`
25121 // overlay projection onto Cilium `L7Rules` and Gateway API
25122 // `HTTPRoute` backend timeouts, the future
25123 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
25124 // admission-time mesh-policy cross-check, the future
25125 // `feira lint` per-`:politicas` bound-check gate) surfaces here
25126 // as a build-time test failure at `aplicacao.rs`, not as an
25127 // apply-time `.get(<stale-canonical-const>)` returning `None`
25128 // far from the derive-attr drift's commit. Peer with the
25129 // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
25130 // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25131 // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
25132 // (ce80ca0) pins on the M3 collection-slot / singleton-slot
25133 // atom axes — same discipline every M3 sibling lift
25134 // established, extended here to the singleton `:politicas`
25135 // mesh-slot atom axis, closing the last M3 typed-struct
25136 // top-level `#[serde(rename_all = "camelCase")]` axis on the
25137 // Aplicacao surface without a lifted serde-key peer.
25138 let p = MeshPolicy {
25139 timeout: Some(Duration::from_secs(30)),
25140 retries: Some(3),
25141 circuit_breaker: Some(CircuitBreaker {
25142 max_failures: 5,
25143 window: Duration::from_secs(60),
25144 }),
25145 mtls_required: Some(true),
25146 rate_limit: Some(RateLimit {
25147 rate: 100,
25148 window: Duration::from_secs(1),
25149 }),
25150 };
25151 let json = serde_json::to_string(&p).unwrap();
25152 for key in [
25153 crate::POLITICAS_KEY_TIMEOUT,
25154 crate::POLITICAS_KEY_RETRIES,
25155 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
25156 crate::POLITICAS_KEY_MTLS_REQUIRED,
25157 crate::POLITICAS_KEY_RATE_LIMIT,
25158 ] {
25159 let quoted = format!("\"{key}\"");
25160 assert!(
25161 json.contains("ed),
25162 "serialized MeshPolicy must carry the lifted \
25163 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
25164 JSON emission (got: {json})",
25165 );
25166 }
25167 }
25168
25169 #[test]
25170 fn politicas_key_consts_are_pairwise_distinct() {
25171 // Cross-axis drift-detection pin: a future collapse of the five
25172 // canonical [`MeshPolicy`] singleton byte-strings onto the same
25173 // value (e.g. an accidental copy-paste flip of
25174 // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
25175 // would silently reroute every downstream probe on one axis
25176 // onto the sibling axis's overlay entry and pass every
25177 // propagation-probe test that expected only the stale axis's
25178 // value — the M4 per-edge `:politicas` overlay projection would
25179 // read the retry-count string where the timeout duration was
25180 // expected (or vice versa), the CR materializer's admission
25181 // cross-check would compare the wrong pair of values, and the
25182 // resulting mesh reconciler would either bind the wrong axis
25183 // or reject the resource at reconcile far from the rebrand
25184 // commit's source. Peer of the sibling four-way distinct pin
25185 // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
25186 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
25187 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
25188 // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
25189 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
25190 let all = [
25191 crate::POLITICAS_KEY_TIMEOUT,
25192 crate::POLITICAS_KEY_RETRIES,
25193 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
25194 crate::POLITICAS_KEY_MTLS_REQUIRED,
25195 crate::POLITICAS_KEY_RATE_LIMIT,
25196 ];
25197 for (i, a) in all.iter().enumerate() {
25198 for b in all.iter().skip(i + 1) {
25199 assert_ne!(
25200 a, b,
25201 "POLITICAS_KEY_* consts must be pairwise-distinct \
25202 canonical byte-sequences — got `{a}` == `{b}`",
25203 );
25204 }
25205 }
25206 }
25207
25208 #[test]
25209 fn politicas_key_consts_are_lower_camel_case_shape() {
25210 // Shape-pin: every `POLITICAS_KEY_*` const must be a
25211 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25212 // `kebab-case` hyphens, no leading colon, no `PascalCase`
25213 // leading capital, no whitespace / dots) — the canonical shape
25214 // the `#[serde(rename_all = "camelCase")]` derive produces on
25215 // [`MeshPolicy`]. A future flip to a non-camelCase attribute
25216 // at the derive surfaces both here (this test fails on the
25217 // stale-constant shape) and at
25218 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
25219 // (that test fails on the mismatch between const and derive).
25220 // Peer with `entrada_key_consts_are_lower_camel_case_shape`
25221 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
25222 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
25223 // (ca463a4) on the sibling M3 typed-struct axes.
25224 for key in [
25225 crate::POLITICAS_KEY_TIMEOUT,
25226 crate::POLITICAS_KEY_RETRIES,
25227 crate::POLITICAS_KEY_CIRCUIT_BREAKER,
25228 crate::POLITICAS_KEY_MTLS_REQUIRED,
25229 crate::POLITICAS_KEY_RATE_LIMIT,
25230 ] {
25231 assert!(
25232 !key.is_empty(),
25233 "POLITICAS_KEY_* must be non-empty (got {key:?})"
25234 );
25235 let first = key.chars().next().unwrap();
25236 assert!(
25237 first.is_ascii_lowercase(),
25238 "POLITICAS_KEY_* must lead with an ASCII-lowercase \
25239 byte (got {key:?}, leads with {first:?})",
25240 );
25241 assert!(
25242 key.chars().all(|c| c.is_ascii_alphanumeric()),
25243 "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
25244 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25245 );
25246 }
25247 }
25248
25249 // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
25250
25251 #[test]
25252 fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
25253 // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
25254 // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
25255 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
25256 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
25257 // [`CircuitBreaker`] emits inside the
25258 // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
25259 // two axes (`max_failures` → `maxFailures`) is a non-trivial
25260 // camelCase transform — the derive-attribute is load-bearing on
25261 // that axis, unlike the sibling `window` field where the derive
25262 // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
25263 // pin that each canonical byte-sequence appears verbatim in the
25264 // JSON — a future accidental `rename_all = "snake_case"` /
25265 // `"kebab-case"` / verbatim-field-name flip at the derive
25266 // attribute (any of which would silently break every downstream
25267 // JSON consumer that reaches for one of the two consts via
25268 // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
25269 // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
25270 // per-edge `:politicas` overlay projection onto the mesh's
25271 // per-backend consecutive-failure-counter tripping threshold, the
25272 // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
25273 // admission-time breaker cross-check, the future `feira lint`
25274 // per-`:politicas :circuit-breaker` bound-check gate) surfaces
25275 // here as a build-time test failure at `aplicacao.rs`, not as an
25276 // apply-time `.get(<stale-canonical-const>)` returning `None`
25277 // far from the derive-attr drift's commit. Peer with the sibling
25278 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
25279 // (b55cca7) parent-axis pin — that test pins the outer
25280 // sub-block key the derive on [`MeshPolicy`] emits, this test
25281 // pins the inner keys the derive on the payload type emits, so
25282 // the two together lock the whole [`MeshPolicy`] breaker-tuning
25283 // shape end-to-end at build time.
25284 let cb = CircuitBreaker {
25285 max_failures: 5,
25286 window: Duration::from_secs(60),
25287 };
25288 let json = serde_json::to_string(&cb).unwrap();
25289 for key in [
25290 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
25291 crate::CIRCUIT_BREAKER_KEY_WINDOW,
25292 ] {
25293 let quoted = format!("\"{key}\"");
25294 assert!(
25295 json.contains("ed),
25296 "serialized CircuitBreaker must carry the lifted \
25297 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
25298 in the JSON emission (got: {json})",
25299 );
25300 }
25301 }
25302
25303 #[test]
25304 fn circuit_breaker_key_consts_are_pairwise_distinct() {
25305 // Cross-axis drift-detection pin: a future collapse of the two
25306 // canonical [`CircuitBreaker`] sub-block byte-strings onto the
25307 // same value (e.g. an accidental copy-paste flip of
25308 // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
25309 // `"maxFailures"`) would silently reroute every downstream
25310 // probe on one axis onto the sibling axis's overlay entry and
25311 // pass every propagation-probe test that expected only the
25312 // stale axis's value — the M4 per-edge `:politicas` overlay
25313 // projection would read the failure-count where the window
25314 // duration was expected (or vice versa), the CR materializer's
25315 // admission cross-check would compare the wrong pair of values,
25316 // and the resulting mesh reconciler would either bind the wrong
25317 // axis or reject the resource at reconcile far from the rebrand
25318 // commit's source. Peer of the sibling five-way distinct pin on
25319 // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
25320 // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
25321 // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
25322 // six-way distinct pin on the `CONTRATO_KEY_*` triad +
25323 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
25324 let all = [
25325 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
25326 crate::CIRCUIT_BREAKER_KEY_WINDOW,
25327 ];
25328 for (i, a) in all.iter().enumerate() {
25329 for b in all.iter().skip(i + 1) {
25330 assert_ne!(
25331 a, b,
25332 "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
25333 canonical byte-sequences — got `{a}` == `{b}`",
25334 );
25335 }
25336 }
25337 }
25338
25339 #[test]
25340 fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
25341 // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
25342 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25343 // `kebab-case` hyphens, no leading colon, no `PascalCase`
25344 // leading capital, no whitespace / dots) — the canonical shape
25345 // the `#[serde(rename_all = "camelCase")]` derive produces on
25346 // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
25347 // at the derive surfaces both here (this test fails on the
25348 // stale-constant shape) and at
25349 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
25350 // (that test fails on the mismatch between const and derive).
25351 // Peer with `politicas_key_consts_are_lower_camel_case_shape`
25352 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
25353 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
25354 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
25355 // (ca463a4) on the sibling M3 typed-struct axes.
25356 for key in [
25357 crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
25358 crate::CIRCUIT_BREAKER_KEY_WINDOW,
25359 ] {
25360 assert!(
25361 !key.is_empty(),
25362 "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
25363 );
25364 let first = key.chars().next().unwrap();
25365 assert!(
25366 first.is_ascii_lowercase(),
25367 "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
25368 byte (got {key:?}, leads with {first:?})",
25369 );
25370 assert!(
25371 key.chars().all(|c| c.is_ascii_alphanumeric()),
25372 "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
25373 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25374 );
25375 }
25376 }
25377
25378 // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
25379
25380 #[test]
25381 fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
25382 // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
25383 // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
25384 // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
25385 // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
25386 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
25387 // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
25388 // [`Placement`] emits. One of the four axes (`shard_key` →
25389 // `shardKey`) is a non-trivial camelCase transform — the
25390 // derive-attribute is load-bearing on that axis, unlike the
25391 // sibling `estrategia` / `clusters` / `affinity` axes whose
25392 // source-side field names carry no `_` and where the derive is a
25393 // no-op. Serialize a fully-populated [`Placement`] (both
25394 // `Option`-carrying axes `Some(_)` so
25395 // `skip_serializing_if = "Option::is_none"` fires on neither of
25396 // the two optional slots) and pin that each canonical
25397 // byte-sequence appears verbatim in the JSON — a future
25398 // accidental `rename_all = "snake_case"` / `"kebab-case"` /
25399 // verbatim-field-name flip at the derive attribute (any of which
25400 // would silently break every downstream consumer that reaches
25401 // for one of the four consts via
25402 // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
25403 // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
25404 // aggregator's per-cluster fanout filter keying off
25405 // `placement.clusters`, the M3 shard-pool dispatch materializer
25406 // keying off `placement.shardKey`, the M3 Adaptive compression
25407 // pass weighting off `placement.affinity`, every downstream
25408 // dispatcher branching on `placement.estrategia`, the future
25409 // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
25410 // admission-time placement cross-check, the future `feira lint`
25411 // per-`:placement` bound-check gate) surfaces here as a
25412 // build-time test failure at `aplicacao.rs`, not as an
25413 // apply-time `.get(<stale-canonical-const>)` returning `None`
25414 // far from the derive-attr drift's commit. Peer with the sibling
25415 // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
25416 // (b55cca7),
25417 // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
25418 // (468e959),
25419 // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
25420 // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
25421 // (ca463a4), and
25422 // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
25423 // pins on the M3 collection-slot / singleton-slot atom axes —
25424 // closes the last M3 typed-struct top-level
25425 // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
25426 // surface without a drift-detection pin.
25427 let p = Placement {
25428 estrategia: PlacementStrategy::Sharded,
25429 clusters: vec!["rio".into(), "mar".into()],
25430 affinity: Some("data-locality".into()),
25431 shard_key: Some("$tenantId".into()),
25432 };
25433 let json = serde_json::to_string(&p).unwrap();
25434 for key in [
25435 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
25436 crate::M3_PLACEMENT_KEY_CLUSTERS,
25437 crate::M3_PLACEMENT_KEY_AFFINITY,
25438 crate::M3_PLACEMENT_KEY_SHARD_KEY,
25439 ] {
25440 let quoted = format!("\"{key}\"");
25441 assert!(
25442 json.contains("ed),
25443 "serialized Placement must carry the lifted \
25444 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
25445 the JSON emission (got: {json})",
25446 );
25447 }
25448 }
25449
25450 #[test]
25451 fn m3_placement_key_consts_are_pairwise_distinct() {
25452 // Cross-axis drift-detection pin: a future collapse of the four
25453 // canonical [`Placement`] sub-block byte-strings onto the same
25454 // value (e.g. an accidental copy-paste flip of
25455 // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
25456 // `"affinity"`) would silently reroute every downstream probe on
25457 // one axis onto the sibling axis's overlay entry and pass every
25458 // propagation-probe test that expected only the stale axis's
25459 // value — the M3 shard-pool dispatch materializer would read the
25460 // affinity placement-hint where the shard-selection template was
25461 // expected (or vice versa), the M3 Adaptive compression pass's
25462 // cross-check would compare the wrong pair of values, and the
25463 // resulting placement engine would either bind the wrong axis or
25464 // reject the resource at reconcile far from the rebrand commit's
25465 // source. Peer of the sibling two-way distinct pin on the
25466 // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
25467 // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
25468 // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
25469 // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
25470 // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
25471 // `WitTarget::*_FIELD_NAME` triad (ca463a4).
25472 let all = [
25473 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
25474 crate::M3_PLACEMENT_KEY_CLUSTERS,
25475 crate::M3_PLACEMENT_KEY_AFFINITY,
25476 crate::M3_PLACEMENT_KEY_SHARD_KEY,
25477 ];
25478 for (i, a) in all.iter().enumerate() {
25479 for b in all.iter().skip(i + 1) {
25480 assert_ne!(
25481 a, b,
25482 "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
25483 canonical byte-sequences — got `{a}` == `{b}`",
25484 );
25485 }
25486 }
25487 }
25488
25489 #[test]
25490 fn m3_placement_key_consts_are_lower_camel_case_shape() {
25491 // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
25492 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
25493 // `kebab-case` hyphens, no leading colon, no `PascalCase`
25494 // leading capital, no whitespace / dots) — the canonical shape
25495 // the `#[serde(rename_all = "camelCase")]` derive produces on
25496 // [`Placement`]. A future flip to a non-camelCase attribute at
25497 // the derive surfaces both here (this test fails on the stale-
25498 // constant shape) and at
25499 // `placement_serde_keys_match_lifted_m3_placement_key_consts`
25500 // (that test fails on the mismatch between const and derive).
25501 // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
25502 // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
25503 // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
25504 // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
25505 // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
25506 // (ca463a4) on the sibling M3 typed-struct axes.
25507 for key in [
25508 crate::M3_PLACEMENT_KEY_ESTRATEGIA,
25509 crate::M3_PLACEMENT_KEY_CLUSTERS,
25510 crate::M3_PLACEMENT_KEY_AFFINITY,
25511 crate::M3_PLACEMENT_KEY_SHARD_KEY,
25512 ] {
25513 assert!(
25514 !key.is_empty(),
25515 "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
25516 );
25517 let first = key.chars().next().unwrap();
25518 assert!(
25519 first.is_ascii_lowercase(),
25520 "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
25521 byte (got {key:?}, leads with {first:?})",
25522 );
25523 assert!(
25524 key.chars().all(|c| c.is_ascii_alphanumeric()),
25525 "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
25526 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
25527 );
25528 }
25529 }
25530
25531 // ── AplicacaoSpec::port_for_destination — the substrate-canonical
25532 // destination-facing L4 port resolver every per-Aplicacao renderer
25533 // reaching for a per-destination Servico TCP port axis routes
25534 // through. The four pin tests below fix the four-way accept-set
25535 // the resolver must always honor: (:entrada-para-matches,
25536 // :entrada-para-mismatches, :entrada-none-so-fallback,
25537 // :entrada-port-non-default-honored) — drift on any arm surfaces
25538 // at caixa-core build time rather than at cluster-apply time.
25539
25540 #[test]
25541 fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
25542 // The typed `:entrada` block's `:para "cart"` matches the
25543 // queried destination, so the resolver returns the author-
25544 // declared `:port` scalar verbatim — the canonical "the
25545 // destination Servico IS the ingress apex, honor the typed
25546 // listener port" arm of the port-resolution dispatch.
25547 let mut spec = three_member_spec();
25548 if let Some(e) = spec.entrada.as_mut() {
25549 e.para = "cart".into();
25550 e.port = 9090;
25551 }
25552 assert_eq!(
25553 spec.port_for_destination("cart"),
25554 9090,
25555 "port_for_destination(entrada.para) must return entrada.port \
25556 verbatim, not the DEFAULT_SERVICO_PORT fallback"
25557 );
25558 }
25559
25560 #[test]
25561 fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
25562 // The typed `:entrada` block names `:para "cart"`, but the
25563 // queried destination is `"payment"` — a Servico that
25564 // participates in the mesh graph but is not the ingress apex.
25565 // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
25566 // canonical port floor, closing the "non-apex destination reads
25567 // the substrate default" arm. Same fixture the peer
25568 // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
25569 // pin at caixa-mesh exercises through the CNP emit-side path;
25570 // this pin exercises the shared underlying resolver directly.
25571 let spec = three_member_spec();
25572 assert_eq!(
25573 spec.port_for_destination("payment"),
25574 DEFAULT_SERVICO_PORT,
25575 "port_for_destination(non-apex-destination) must route \
25576 through the lifted DEFAULT_SERVICO_PORT canonical port floor"
25577 );
25578 }
25579
25580 #[test]
25581 fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
25582 // Internal-only Aplicacao — no `:entrada` block declared. Every
25583 // per-destination port query falls back to the lifted
25584 // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
25585 // the Aplicacao surface admits `:entrada None` (internal mesh
25586 // with no external gateway); every downstream renderer's per-
25587 // destination port axis must still resolve to a well-defined
25588 // scalar even without an ingress apex.
25589 let mut spec = three_member_spec();
25590 spec.entrada = None;
25591 assert_eq!(
25592 spec.port_for_destination("cart"),
25593 DEFAULT_SERVICO_PORT,
25594 "port_for_destination on an internal-only Aplicacao must \
25595 fall back to the lifted DEFAULT_SERVICO_PORT floor for \
25596 every destination"
25597 );
25598 assert_eq!(
25599 spec.port_for_destination("payment"),
25600 DEFAULT_SERVICO_PORT,
25601 "port_for_destination on an internal-only Aplicacao must \
25602 fall back uniformly across every destination — the fallback \
25603 is not entrada-shape-conditional"
25604 );
25605 }
25606
25607 #[test]
25608 fn port_for_destination_honors_non_default_entrada_port_verbatim() {
25609 // Structural pin against a hypothetical future refactor that
25610 // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
25611 // the resolver (a "normalize to the default when the author's
25612 // port matches the substrate default" collapse) — that would
25613 // break renderer sites that carry meaning on the emitted port
25614 // value beyond bare equality (a future per-cluster listener-
25615 // audit that keys off the author-declared port, not the
25616 // resolved-with-fallback port). Pin that a non-default
25617 // entrada.port is returned verbatim so drift here surfaces at
25618 // caixa-core build time.
25619 let mut spec = three_member_spec();
25620 if let Some(e) = spec.entrada.as_mut() {
25621 e.para = "cart".into();
25622 e.port = 8443;
25623 }
25624 assert_ne!(
25625 8443, DEFAULT_SERVICO_PORT,
25626 "test fixture must probe a port distinct from \
25627 DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
25628 );
25629 assert_eq!(
25630 spec.port_for_destination("cart"),
25631 8443,
25632 "port_for_destination(entrada.para) must return entrada.port \
25633 verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
25634 );
25635 }
25636
25637 #[test]
25638 fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
25639 // Apex-identity pair-invariant pin composing both substrate-
25640 // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
25641 // and [`Entrada::destination`] — at the emit-side call shape
25642 // every per-Aplicacao renderer's ingress-apex L4 port reader
25643 // now takes. The invariant:
25644 //
25645 // spec.port_for_destination(entrada.destination()) == entrada.port
25646 //
25647 // holds by construction under today's single-destination
25648 // `:entrada` slot (`destination()` returns `entrada.para`, and
25649 // the resolver's apex arm matches `para == destination` and
25650 // returns `entrada.port`), and every downstream consumer that
25651 // composes the two accessors at the ingress apex — the
25652 // `caixa_mesh::gateway_routes` HTTPRoute per-rule
25653 // `backendRefs[0].port` emit-site path, the peer future M4 CR
25654 // materializer's admission-webhook that promotes the scalar to
25655 // a per-CR override overlay, every future per-Aplicacao snapshot
25656 // renderer's apex-facing L4 port reader — reaches through the
25657 // same composition. Pin the identity across four permutations
25658 // (`:para` × `:port` including a non-default port to exercise
25659 // the honor-verbatim arm and a non-cart `:para` to exercise
25660 // destination-agnostic identity) so a future refactor that
25661 // silently split either accessor's apex behavior surfaces at
25662 // caixa-core build time — a subtle `destination()` renaming
25663 // that returned `entrada.host.as_str()` instead of
25664 // `entrada.para.as_str()` would blow this pin loudly, closing
25665 // the last quiet failure mode the two lifts admit in composition.
25666 //
25667 // Peer discipline with the sibling caixa-mesh cross-crate pin
25668 // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
25669 // on the two-renderer pair-invariant axis; this pin encodes the
25670 // same two-consumer coherence rule at the substrate-primitive
25671 // level so the invariant survives even if every renderer is
25672 // deleted.
25673 for (para, port) in [
25674 ("cart", DEFAULT_SERVICO_PORT),
25675 ("cart", 8443u16),
25676 ("payment", 9090u16),
25677 ("catalog", 443u16),
25678 ] {
25679 let mut spec = three_member_spec();
25680 if let Some(e) = spec.entrada.as_mut() {
25681 e.para = para.into();
25682 e.port = port;
25683 }
25684 let expected_port = spec
25685 .entrada()
25686 .expect("three_member_spec carries a typed `:entrada` block")
25687 .port();
25688 let composed_port = {
25689 let entrada = spec.entrada().expect("entrada present");
25690 spec.port_for_destination(entrada.destination())
25691 };
25692 assert_eq!(
25693 composed_port, expected_port,
25694 "`spec.port_for_destination(entrada.destination())` must \
25695 equal `entrada.port` under today's single-destination \
25696 `:entrada` slot — this is the apex-identity contract \
25697 every downstream ingress-apex L4 port reader relies on. \
25698 Input :entrada :para: {para:?}, :entrada :port: {port}"
25699 );
25700 }
25701 }
25702
25703 #[test]
25704 fn port_for_destination_apex_arm_routes_through_destination_accessor() {
25705 // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
25706 // per-`:entrada` apex-arm membership probe must key off
25707 // [`Entrada::destination`], not the raw `.para` field access.
25708 // Structurally: setting ONLY the `:entrada :para` field to a
25709 // fresh non-cart destination on an otherwise-well-formed
25710 // Aplicacao must (1) leave `e.destination()` byte-equal to
25711 // `e.para.as_str()` (the accessor is byte-projective by
25712 // definition), and (2) cause the resolver's apex arm to fire
25713 // and return `entrada.port` at exactly that new destination
25714 // while every other destination string falls through to
25715 // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
25716 // membership check. Pins against a future silent detour that
25717 // (a) re-derived the apex-arm membership probe off
25718 // `e.para == destination` in `port_for_destination` instead of
25719 // `e.destination() == destination`, silently disagreeing with
25720 // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
25721 // consumers (`entrada.destination()` at
25722 // caixa-mesh/src/lib.rs:3173, `c.destination()` at
25723 // caixa-mesh/src/lib.rs:2739) that already reach through the
25724 // accessor, (b) accessor-side introduced a per-tenant alias
25725 // arm the caller was unaware of, silently rewriting an
25726 // author-declared `:para "cart"` value to a canary-aliased
25727 // form — the raw-field-access resolver would fall through to
25728 // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
25729 // while the peer emit-site consumers landed on the aliased
25730 // destination, splitting the ingress-apex L4 port at
25731 // cluster-apply time.
25732 //
25733 // Peer of the sibling
25734 // [`validate_membros_empty_gate_routes_through_nome_accessor`]
25735 // (d0de220) composition pin on the per-`:membros` refusal-arm
25736 // axis — same "the shape-gate predicate must route through the
25737 // substrate-primitive typed dispatch" discipline extended onto
25738 // the per-`:entrada` apex-arm membership-probe axis. Closes
25739 // the last unlifted `.para` production-code read site on
25740 // `Entrada` in `caixa-core` — after this converge every
25741 // `caixa-core` `.para` field access outside the accessor's own
25742 // body and outside the `WitContract` per-`:contratos` sibling
25743 // axis is either a test-side field-setter or a doc-comment
25744 // reference.
25745 for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
25746 let mut spec = three_member_spec();
25747 if let Some(e) = spec.entrada.as_mut() {
25748 e.para = para.into();
25749 e.port = port;
25750 }
25751 let e = spec
25752 .entrada
25753 .as_ref()
25754 .expect("three_member_spec carries a typed `:entrada` block");
25755 assert_eq!(
25756 e.destination(),
25757 e.para.as_str(),
25758 "Entrada::destination must byte-equal the .para field \
25759 access — an accessor-side detour that no longer \
25760 projects the raw field would silently split this \
25761 drift-detection test from the port_for_destination \
25762 apex-arm membership probe",
25763 );
25764 assert_eq!(
25765 spec.port_for_destination(para),
25766 port,
25767 "port_for_destination must key off the accessor-projected \
25768 destination and return `entrada.port` on the apex arm — \
25769 input :entrada :para: {para:?}, :entrada :port: {port}",
25770 );
25771 assert_eq!(
25772 spec.port_for_destination("ghost-destination-never-a-member"),
25773 DEFAULT_SERVICO_PORT,
25774 "port_for_destination must fall through to \
25775 DEFAULT_SERVICO_PORT on a non-matching destination \
25776 under the accessor-projected membership check — input \
25777 :entrada :para: {para:?}, :entrada :port: {port}",
25778 );
25779 }
25780 }
25781
25782 #[test]
25783 fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
25784 // The canonical per-`:politicas :rate-limit` `:rate`
25785 // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
25786 // [`RateLimit::rate`] must return the `:politicas :rate-limit`
25787 // typed `u32` verbatim, byte-equal to the raw field access
25788 // across every representative value in the accept-set — `1` (the
25789 // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
25790 // the surrounding [`AplicacaoSpec::validate_politicas`] gate
25791 // carves out on the sibling `PolicyRateLimitZero` refusal),
25792 // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
25793 // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
25794 // `0` (a past-the-guard sentinel that pins the accessor doesn't
25795 // perform a silent bounds-collapse into `1` on the zero arm —
25796 // validate rejects zero but the accessor must ship the raw slot
25797 // verbatim so a validate-time gate regression surfaces at the
25798 // emit boundary rather than being silently absorbed), `u32::MAX`
25799 // (a past-the-guard sentinel that pins the accessor doesn't
25800 // perform a silent bounds-collapse through
25801 // `POLICY_RATE_LIMIT_MAX` at the return path).
25802 //
25803 // First sub-struct required-scalar accessor pin on the
25804 // `RateLimit` axis — sibling in shape to the peer
25805 // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
25806 // required-`u32` accessor pin on the peer per-sub-struct
25807 // required-axis. Pins against a future silent detour that
25808 // re-derived the token capacity from a peer axis (an accidental
25809 // `self.window.as_secs() as u32` collapse that read the
25810 // rate-limit window duration as a token count), a `0 → 1`
25811 // cluster-default projection (which would silently absorb the
25812 // `PolicyRateLimitZero` refusal case at the accessor boundary),
25813 // or a bounds-collapsing accessor that clamped the return
25814 // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
25815 // gate owns the bounds; the accessor must ship the raw slot
25816 // verbatim).
25817 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
25818 let rl = RateLimit {
25819 rate,
25820 window: Duration::from_secs(1),
25821 };
25822 assert_eq!(
25823 rl.rate(),
25824 rate,
25825 "RateLimit::rate must return :politicas :rate-limit :rate \
25826 verbatim (got {}, expected {rate})",
25827 rl.rate(),
25828 );
25829 assert_eq!(
25830 rl.rate(),
25831 rl.rate,
25832 "RateLimit::rate must byte-equal the raw .rate field \
25833 access across every value in the u32 accept-set",
25834 );
25835 }
25836 }
25837
25838 #[test]
25839 fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
25840 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25841 // `:rate-limit :rate` zero-floor arm must key off
25842 // [`RateLimit::rate`], not the raw `.rate` field access.
25843 // Structurally: a `RateLimit { rate: 0, window:
25844 // Duration::from_secs(1) }` embedded in a `:politicas
25845 // :rate-limit` slot must surface the `PolicyRateLimitZero`
25846 // refusal exactly, and a `RateLimit { rate: 1, window:
25847 // Duration::from_secs(1) }` (the lower boundary of the
25848 // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
25849 // The pair jointly pins the accessor + validate-gate composition:
25850 // any future silent detour that had the accessor return a fresh
25851 // `1` on the zero arm (a `.rate().max(1)` collapse) would
25852 // silently absorb the `PolicyRateLimitZero` refusal at the
25853 // accessor boundary and the validate gate would accept a
25854 // struct-literal `RateLimit { rate: 0, .. }` — the composition
25855 // pin catches that at caixa-core build time.
25856 //
25857 // Peer of the sibling per-`CircuitBreaker`
25858 // [`CircuitBreaker::max_failures`] (3a74062) /
25859 // [`CircuitBreaker::window`] (373957f) accessor-composition
25860 // pins on the peer required-scalar axes — same "the validate /
25861 // shape-gate predicate must route through the substrate-primitive
25862 // typed dispatch" discipline extended onto the peer
25863 // per-`RateLimit` required-`u32` composition axis.
25864 let mut spec = three_member_spec();
25865 spec.politicas = MeshPolicy {
25866 rate_limit: Some(RateLimit {
25867 rate: 0,
25868 window: Duration::from_secs(1),
25869 }),
25870 ..MeshPolicy::default()
25871 };
25872 assert!(
25873 matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
25874 "validate_politicas must reject rate == 0 with \
25875 PolicyRateLimitZero — the accessor and the validate gate \
25876 must route through the same substrate-primitive typed \
25877 dispatch on the :rate zero-floor arm",
25878 );
25879 spec.politicas = MeshPolicy {
25880 rate_limit: Some(RateLimit {
25881 rate: 1,
25882 window: Duration::from_secs(1),
25883 }),
25884 ..MeshPolicy::default()
25885 };
25886 assert!(
25887 spec.validate().is_ok(),
25888 "validate_politicas must accept rate == 1 (the lower \
25889 boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
25890 );
25891 }
25892
25893 #[test]
25894 fn rate_limit_rate_projects_u32_by_copy() {
25895 // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
25896 // `u32` is `Copy` and the accessor must return by value, not by
25897 // reference. Peer of the sibling per-`CircuitBreaker`
25898 // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
25899 // peer required-scalar `:max-failures` axis, extended onto the
25900 // peer per-`RateLimit` required-`u32` copy-invariant shape —
25901 // the accessor's returned `u32` must outlive `&self` (multiple
25902 // calls must return equal values from a dropped-`&self` copy,
25903 // since the returned scalar carries no borrow), and calling the
25904 // accessor twice on the same RateLimit must yield the same
25905 // `u32` verbatim (idempotent, no side effects on `&self`).
25906 //
25907 // Pins against a future silent detour that returned `&u32`
25908 // (which would type-check but silently break every downstream
25909 // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
25910 // first parameter is `u32`, and `&u32` would fold to a detached
25911 // copy at the call site with a `*` deref the sibling accessors
25912 // don't need), an accidental `.rate.wrapping_add(0)` detour that
25913 // returned a fresh copy through an arithmetic no-op (breaking a
25914 // future `const fn` regression), or a one-arm-only accessor
25915 // that returned a saturating value on some sentinel input
25916 // (breaking the pass-through invariant the sibling required-
25917 // scalar accessors carry).
25918 for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
25919 let rl = RateLimit {
25920 rate,
25921 window: Duration::from_secs(1),
25922 };
25923 let first = rl.rate();
25924 let second = rl.rate();
25925 assert_eq!(
25926 first, second,
25927 "RateLimit::rate must be idempotent — two successive \
25928 calls on the same &self must return the same u32",
25929 );
25930 assert_eq!(
25931 first, rate,
25932 "RateLimit::rate must return :politicas :rate-limit :rate \
25933 verbatim by copy — got {first}, expected {rate}",
25934 );
25935 }
25936 }
25937
25938 #[test]
25939 fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
25940 // The canonical per-`:politicas :rate-limit` `:window`
25941 // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
25942 // pin: [`RateLimit::window`] must return the
25943 // `:politicas :rate-limit :window` typed `Duration` verbatim,
25944 // byte-equal to the raw field access across every
25945 // representative value in the accept-set — `Duration::from_secs(1)`
25946 // (the `"s"` canonical window, the lower row of
25947 // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
25948 // [`AplicacaoSpec::validate_politicas`] gate accepts via
25949 // [`is_canonical_rate_limit_window`]),
25950 // `Duration::from_secs(60)` (the `"m"` canonical window, the
25951 // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
25952 // window, the upper row), `Duration::ZERO` (a past-the-guard
25953 // sentinel that pins the accessor doesn't perform a silent
25954 // bounds-collapse into `Duration::from_secs(1)` on the zero
25955 // arm — validate rejects an off-set window through
25956 // `PolicyRateLimitWindowNotCanonical` but the accessor must
25957 // ship the raw slot verbatim so a validate-time gate
25958 // regression surfaces at the emit boundary rather than being
25959 // silently absorbed), `Duration::from_millis(500)` (a
25960 // sub-canonical past-the-guard sentinel that pins the accessor
25961 // doesn't silently normalize a non-canonical fractional
25962 // magnitude onto the nearest canonical row).
25963 //
25964 // Second sub-struct required-scalar accessor pin on the
25965 // `RateLimit` axis — sibling in shape to the just-landed
25966 // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
25967 // accessor pin on the peer per-sub-struct required-axis,
25968 // extended onto the per-`RateLimit` required-`Duration` axis.
25969 // Pins against a future silent detour that re-derived the
25970 // refill period from a peer axis (an accidental
25971 // `Duration::from_secs(self.rate as u64)` collapse that read
25972 // the rate-limit token capacity as a refill-interval
25973 // duration), a `Duration::ZERO → Duration::from_secs(1)`
25974 // canonical-default projection (which would silently absorb
25975 // the `PolicyRateLimitWindowNotCanonical` refusal case at the
25976 // accessor boundary), or a canonical-set-collapsing accessor
25977 // that clamped the return through [`rate_limit_window_unit`]
25978 // (the `AplicacaoSpec::validate` gate owns the canonical-set
25979 // membership; the accessor must ship the raw slot verbatim).
25980 for window in [
25981 Duration::from_secs(1),
25982 Duration::from_secs(60),
25983 Duration::from_secs(3600),
25984 Duration::ZERO,
25985 Duration::from_millis(500),
25986 ] {
25987 let rl = RateLimit { rate: 100, window };
25988 assert_eq!(
25989 rl.window(),
25990 window,
25991 "RateLimit::window must return :politicas :rate-limit :window \
25992 verbatim (got {:?}, expected {window:?})",
25993 rl.window(),
25994 );
25995 assert_eq!(
25996 rl.window(),
25997 rl.window,
25998 "RateLimit::window must byte-equal the raw .window field \
25999 access across every value in the Duration accept-set",
26000 );
26001 }
26002 }
26003
26004 #[test]
26005 fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
26006 // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26007 // `:rate-limit :window` canonical-set arm must key off
26008 // [`RateLimit::window`], not the raw `.window` field access.
26009 // Structurally: a `RateLimit { window: Duration::from_millis(500),
26010 // .. }` embedded in a `:politicas :rate-limit` slot must
26011 // surface the `PolicyRateLimitWindowNotCanonical` refusal
26012 // exactly (with the sub-canonical `Duration::from_millis(500)`
26013 // magnitude carried through verbatim), and a `RateLimit
26014 // { window: Duration::from_secs(1), .. }` (the lower row of
26015 // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
26016 // The pair jointly pins the accessor + validate-gate
26017 // composition: any future silent detour that had the accessor
26018 // normalize the off-set window to the nearest canonical row
26019 // (a `.window().max(Duration::from_secs(1))` collapse, or a
26020 // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
26021 // collapse) would silently absorb the
26022 // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
26023 // boundary — including a drift in the error's `window` payload
26024 // (the emit-side diagnostic reader keys off the offending
26025 // magnitude verbatim, so a normalization at the accessor
26026 // boundary would silently pin the wrong magnitude in the
26027 // refusal). The composition pin catches that at caixa-core
26028 // build time.
26029 //
26030 // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
26031 // (7f81a60) accessor-composition pin on the peer required-
26032 // scalar `:rate` axis — same "the validate / shape-gate
26033 // predicate must route through the substrate-primitive typed
26034 // dispatch, and the error payload must project through the
26035 // same accessor" discipline extended onto the peer
26036 // per-`RateLimit` required-`Duration` composition axis.
26037 let mut spec = three_member_spec();
26038 spec.politicas = MeshPolicy {
26039 rate_limit: Some(RateLimit {
26040 rate: 100,
26041 window: Duration::from_millis(500),
26042 }),
26043 ..MeshPolicy::default()
26044 };
26045 match spec.validate() {
26046 Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
26047 assert_eq!(
26048 window,
26049 Duration::from_millis(500),
26050 "PolicyRateLimitWindowNotCanonical must carry the \
26051 offending :window magnitude verbatim through the \
26052 accessor — got {window:?}, expected 500ms",
26053 );
26054 }
26055 other => panic!(
26056 "validate_politicas must reject non-canonical :window \
26057 with PolicyRateLimitWindowNotCanonical — the accessor \
26058 and the validate gate must route through the same \
26059 substrate-primitive typed dispatch on the :window \
26060 canonical-set arm; got {other:?}",
26061 ),
26062 }
26063 spec.politicas = MeshPolicy {
26064 rate_limit: Some(RateLimit {
26065 rate: 100,
26066 window: Duration::from_secs(1),
26067 }),
26068 ..MeshPolicy::default()
26069 };
26070 assert!(
26071 spec.validate().is_ok(),
26072 "validate_politicas must accept window == Duration::from_secs(1) \
26073 (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
26074 );
26075 }
26076
26077 #[test]
26078 fn rate_limit_window_projects_duration_by_copy() {
26079 // The by-copy pin: [`RateLimit::window`] returns `Duration`
26080 // by copy — `Duration` is `Copy` and the accessor must return
26081 // by value, not by reference. Peer of the sibling per-`RateLimit`
26082 // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
26083 // required-scalar `:rate` axis, extended onto the peer
26084 // per-`RateLimit` required-`Duration` copy-invariant shape —
26085 // the accessor's returned `Duration` must outlive `&self`
26086 // (multiple calls must return equal values from a
26087 // dropped-`&self` copy, since the returned scalar carries no
26088 // borrow), and calling the accessor twice on the same
26089 // RateLimit must yield the same `Duration` verbatim
26090 // (idempotent, no side effects on `&self`).
26091 //
26092 // Pins against a future silent detour that returned
26093 // `&Duration` (which would type-check but silently break every
26094 // downstream `Duration`-by-value consumer —
26095 // [`is_canonical_rate_limit_window`]'s first parameter is
26096 // `Duration`, and `&Duration` would fold to a detached copy at
26097 // the call site with a `*` deref the sibling accessors don't
26098 // need), an accidental `.window + Duration::ZERO` detour that
26099 // returned a fresh copy through an arithmetic no-op (breaking
26100 // a future `const fn` regression), or a one-arm-only accessor
26101 // that returned a canonical fallback on some sentinel input
26102 // (breaking the pass-through invariant the sibling required-
26103 // scalar accessors carry).
26104 for window in [
26105 Duration::from_secs(1),
26106 Duration::from_secs(60),
26107 Duration::from_secs(3600),
26108 Duration::ZERO,
26109 Duration::from_millis(500),
26110 ] {
26111 let rl = RateLimit { rate: 100, window };
26112 let first = rl.window();
26113 let second = rl.window();
26114 assert_eq!(
26115 first, second,
26116 "RateLimit::window must be idempotent — two successive \
26117 calls on the same &self must return the same Duration",
26118 );
26119 assert_eq!(
26120 first, window,
26121 "RateLimit::window must return :politicas :rate-limit :window \
26122 verbatim by copy — got {first:?}, expected {window:?}",
26123 );
26124 }
26125 }
26126}